-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1581 lines (1295 loc) · 52.3 KB
/
main.py
File metadata and controls
1581 lines (1295 loc) · 52.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import typer
import asyncio
import json
import os
from typing import List, Optional
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from src.search import JobSearcher
from src.enhanced_search import EnhancedJobSearcher
from src.parser import JobParser, batch_process
from src.tagger import JobTagger
from src.scorer import JobScorer
from src.operator_cli import discover_app, profile_app, draft_app, feedback_app
app = typer.Typer()
console = Console()
app.add_typer(discover_app, name="discover")
app.add_typer(profile_app, name="profile")
app.add_typer(draft_app, name="draft")
app.add_typer(feedback_app, name="feedback")
HISTORY_FILE = "search_history.json"
def load_history() -> set:
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, "r") as f:
return set(json.load(f))
except:
return set()
return set()
def save_history(urls: set):
with open(HISTORY_FILE, "w") as f:
json.dump(list(urls), f)
@app.command()
def start():
"""🎯 Interactive wizard to find jobs (RECOMMENDED)"""
console.print("[bold blue]🔍 Welcome to Dork Hunter![/bold blue]")
console.print("Let's find your perfect job! 🚀\n")
# Step 1: Role
role = typer.prompt(
"💼 What job role are you looking for?", default="Software Engineer"
)
# Step 2: Region
console.print("\n🌍 Which region interests you?")
console.print("1. LATAM (Latin America)")
console.print("2. EUROPE (European Union + UK)")
console.print("3. USA (United States + Canada)")
console.print("4. ANY (Global search)")
region_choice = typer.prompt("Choose region (1-4)", default="4")
region_map = {"1": "LATAM", "2": "EUROPE", "3": "USA", "4": "any"}
region = region_map.get(region_choice, "any")
# Step 3: Countries (if region selected)
countries = []
if region != "any":
from src.regional_platforms import REGIONAL_PLATFORMS
available_countries = list(REGIONAL_PLATFORMS[region]["countries"].keys())
console.print(
f"\n🏳️ Available countries in {region}: {', '.join(available_countries)}"
)
country_input = typer.prompt(
"Specific countries? (comma-separated, or press Enter for all)", default=""
)
if country_input.strip():
countries = [c.strip().lower() for c in country_input.split(",")]
# Step 4: Remote preference
console.print("\n🏠 Remote work preference?")
console.print("1. Strict remote only")
console.print("2. Hybrid/flexible")
console.print("3. Any (including onsite)")
remote_choice = typer.prompt("Choose remote type (1-3)", default="1")
remote_map = {"1": "strict", "2": "hybrid", "3": "any"}
remote = remote_map.get(remote_choice, "strict")
# Step 5: Platform exclusions
exclude_input = typer.prompt(
"\n🚫 Exclude any platforms? (e.g., linkedin,indeed or press Enter for none)",
default="",
)
exclude = [p.strip() for p in exclude_input.split(",") if p.strip()]
# Confirmation
console.print(f"\n[bold green]🎯 Search Summary:[/bold green]")
console.print(f"Role: {role}")
console.print(f"Region: {region}")
console.print(f"Countries: {', '.join(countries) if countries else 'All'}")
console.print(f"Remote: {remote}")
console.print(f"Excluded: {', '.join(exclude) if exclude else 'None'}")
if typer.confirm("\n🚀 Start the search?", default=True):
console.print("\n[bold blue]🔍 Starting job discovery...[/bold blue]")
console.print("💡 Tip: This may take a few minutes. Grab some coffee! ☕")
else:
console.print("👋 Search cancelled. Run again anytime!")
@app.command()
def search(
role: str = typer.Option(..., "--role", "-r"),
regions: List[str] = typer.Option(
None, "--region", "-R", help="Target regions: USA, EUROPE, LATAM"
),
countries: List[str] = typer.Option(
None, "--country", "-c", help="Specific countries: germany, colombia, brazil"
),
exclude_platforms: List[str] = typer.Option(
None, "--exclude", "-x", help="Exclude platforms: linkedin, indeed"
),
provider: str = typer.Option(
"duckduckgo",
"--provider",
"-p",
help="Search provider: duckduckgo, tavily, google, bing, serpapi, hybrid",
),
output: str = typer.Option("raw_jobs.json", "--output", "-o"),
):
"""Phase 1: DISCOVER raw URLs with enhanced filtering and observability."""
from src.enhanced_search import EnhancedJobSearcher
from src.job_observer import JobObserver
# Start observability
observer = JobObserver()
run_id = observer.start_run(role, regions, provider)
try:
searcher = EnhancedJobSearcher(provider=provider)
console.print(f"[bold green]Discovering jobs for:[/bold green] {role}")
if regions:
console.print(f"[cyan]Regions:[/cyan] {', '.join(regions)}")
if countries:
console.print(f"[cyan]Countries:[/cyan] {', '.join(countries)}")
if exclude_platforms:
console.print(
f"[yellow]Excluding platforms:[/yellow] {', '.join(exclude_platforms)}"
)
raw_results = searcher.search(
role=role,
regions=regions,
countries=countries,
exclude_platforms=exclude_platforms,
)
# Log search results
query_count = len(
searcher.build_queries(role, regions, countries, exclude_platforms)
)
observer.log_search_results(query_count, len(raw_results))
with open(output, "w") as f:
json.dump(raw_results, f, indent=4)
console.print(
f"[bold green]Saved {len(raw_results)} raw results to {output}[/bold green]"
)
except Exception as e:
observer.log_error(str(e), "search")
console.print(f"[red]Search failed: {e}[/red]")
finally:
observer.finish_run()
@app.command()
def process(
input_file: str = typer.Argument(..., help="Raw JSON from search"),
role: str = typer.Option(..., "--role", "-r", help="The role to match against"),
output: str = typer.Option("curated_jobs.json", "--output", "-o"),
min_confidence: float = typer.Option(0.3, "--min-confidence"),
):
"""Phase 2-4: PARSE, CLASSIFY, TAG, SCORE."""
if not os.path.exists(input_file):
console.print(f"[red]Input file {input_file} not found.[/red]")
return
with open(input_file, "r") as f:
raw_data = json.load(f)
urls = [item["url"] for item in raw_data if item.get("url")]
history = load_history()
new_urls = [u for u in urls if u not in history]
console.print(
f"Found {len(new_urls)} new URLs to process (skipped {len(urls) - len(new_urls)} already seen)."
)
if not new_urls:
return
console.print(f"[bold blue]Processing {len(new_urls)} URLs...[/bold blue]")
processed_jobs = asyncio.run(batch_process(new_urls))
# Phase 4: Tagging & Phase 5: Scoring
tagger = JobTagger()
scorer = JobScorer(target_role=role)
final_jobs = []
for job in processed_jobs:
tagged_job = tagger.tag_regions(job)
scored_job = scorer.calculate_score(tagged_job)
if scored_job["confidence"] >= min_confidence:
final_jobs.append(scored_job)
history.add(job["url"])
elif (
scored_job.get("remote_type") in ["strict", "hybrid"]
and scored_job.get("match_score", 0) >= 70
):
# Include high-scoring remote jobs even with low confidence
scored_job["confidence"] = 0.5 # Boost confidence for good remote matches
final_jobs.append(scored_job)
history.add(job["url"])
save_history(history)
# Sort by score
final_jobs.sort(key=lambda x: x["match_score"], reverse=True)
with open(output, "w") as f:
json.dump(final_jobs, f, indent=4)
console.print(
f"[bold green]Saved {len(final_jobs)} curated and scored jobs to {output}[/bold green]"
)
@app.command()
def run(
role: str = typer.Option(..., "--role", "-r"),
region: str = typer.Option("any", "--region", "-R"),
remote: str = typer.Option("any", "--remote"),
):
"""Phase 1-5: Full Pipeline + Filter."""
raw_file = "temp_raw.json"
curated_file = "temp_curated.json"
# 1. Search
search(role=role, output=raw_file)
# 2. Process & Tag
process(input_file=raw_file, role=role, output=curated_file)
# 3. Filter (Phase 5)
if not os.path.exists(curated_file):
console.print("[yellow]No new jobs found to display.[/yellow]")
return
with open(curated_file, "r") as f:
jobs = json.load(f)
filtered = []
for job in jobs:
# Remote Filter
if remote == "strict" and job["remote_type"] != "strict":
continue
# Region Filter
if region != "any":
target_region = region.upper()
if (
target_region not in job["regions_allowed"]
and "GLOBAL" not in job["regions_allowed"]
):
continue
filtered.append(job)
# Display Results
if not filtered:
console.print("[yellow]No jobs matched your filters.[/yellow]")
else:
table = Table(title=f"Matched Jobs for {role}")
table.add_column("Score", style="white")
table.add_column("Company", style="cyan")
table.add_column("Title", style="magenta")
table.add_column("Regions", style="yellow")
table.add_column("Remote", style="blue")
for j in filtered:
score_color = "green" if j.get("match_score", 0) > 80 else "yellow"
table.add_row(
f"[{score_color}]{j.get('match_score', 0)}%[/{score_color}]",
j.get("company", "N/A"),
j.get("title", "N/A")[:40],
", ".join(j.get("regions_allowed", [])),
j.get("remote_type", "N/A"),
)
console.print(table)
console.print(
f"\n[bold green]Found {len(filtered)} matching jobs![/bold green]"
)
# Cleanup
if os.path.exists(raw_file):
os.remove(raw_file)
if os.path.exists(curated_file):
os.remove(curated_file)
@app.command()
def start():
"""
Interactive Mode: Enhanced Job Hunter Wizard.
"""
from rich.prompt import Prompt, Confirm
from rich.columns import Columns
from rich.panel import Panel
console.print(
Panel(
"[bold yellow]Welcome to Dork Hunter![/bold yellow]\nLet's find you a job.",
title="Interactive Mode",
border_style="yellow",
)
)
# 1. Get Role
role = Prompt.ask(
"[bold cyan]What role are you looking for?[/bold cyan]",
default="Software Engineer",
)
# 2. Get Region
region_choices = ["LATAM", "EUROPE", "USA", "ANY"]
region = Prompt.ask(
"[bold cyan]Target Region?[/bold cyan]", choices=region_choices, default="ANY"
)
# 3. Specific Countries (optional)
countries = []
if Confirm.ask("[cyan]Want to target specific countries?[/cyan]"):
country_options = {
"LATAM": ["colombia", "brazil", "mexico", "argentina", "chile"],
"EUROPE": ["germany", "spain", "uk", "france", "netherlands"],
"USA": ["usa", "canada"],
}
available_countries = country_options.get(
region,
country_options["LATAM"]
+ country_options["EUROPE"]
+ country_options["USA"],
)
console.print(f"[dim]Available: {', '.join(available_countries)}[/dim]")
while True:
country = Prompt.ask("[cyan]Add country (or 'done')[/cyan]")
if country.lower() == "done":
break
if country.lower() in available_countries:
countries.append(country.lower())
console.print(f"[green]Added: {country}[/green]")
else:
console.print("[red]Invalid country. Try again.[/red]")
# 4. Platform Selection
exclude_platforms = []
if Confirm.ask("[cyan]Want to exclude any job platforms?[/cyan]"):
platforms = [
"linkedin",
"indeed",
"glassdoor",
"greenhouse",
"lever",
"workable",
"ashby",
]
console.print(f"[dim]Available: {', '.join(platforms)}[/dim]")
while True:
platform = Prompt.ask("[cyan]Exclude platform (or 'done')[/cyan]")
if platform.lower() == "done":
break
if platform.lower() in platforms:
exclude_platforms.append(platform.lower())
console.print(f"[yellow]Excluded: {platform}[/yellow]")
else:
console.print("[red]Invalid platform. Try again.[/red]")
# 5. Get Remote Preference
remote_choices = ["strict", "hybrid", "any"]
remote = Prompt.ask(
"[bold cyan]Remote Preference?[/bold cyan]",
choices=remote_choices,
default="strict",
)
# 6. Summary & Confirmation
console.print(f"\n[bold green]Ready to search![/bold green]")
console.print(f"Role: [cyan]{role}[/cyan]")
console.print(f"Region: [cyan]{region}[/cyan]")
if countries:
console.print(f"Countries: [cyan]{', '.join(countries)}[/cyan]")
if exclude_platforms:
console.print(f"Excluded: [yellow]{', '.join(exclude_platforms)}[/yellow]")
console.print(f"Remote: [cyan]{remote}[/cyan]")
if not Confirm.ask("Start the hunt?"):
console.print("[red]Aborted.[/red]")
return
# Run enhanced search
from src.enhanced_search import EnhancedJobSearcher
searcher = EnhancedJobSearcher()
raw_results = searcher.search(
role=role,
regions=[region] if region != "ANY" else None,
countries=countries if countries else None,
exclude_platforms=exclude_platforms if exclude_platforms else None,
)
# Save and process
raw_file = "temp_raw.json"
curated_file = "temp_curated.json"
with open(raw_file, "w") as f:
json.dump(raw_results, f, indent=4)
process(input_file=raw_file, role=role, output=curated_file, min_confidence=0.3)
# Filter and display results
if not os.path.exists(curated_file):
console.print("[yellow]No new jobs found.[/yellow]")
return
with open(curated_file, "r") as f:
jobs = json.load(f)
filtered = []
for job in jobs:
if remote == "strict" and job["remote_type"] != "strict":
continue
if region != "ANY":
target_region = region.upper()
if (
target_region not in job["regions_allowed"]
and "GLOBAL" not in job["regions_allowed"]
):
continue
filtered.append(job)
if not filtered:
console.print("[yellow]No jobs matched your filters.[/yellow]")
else:
table = Table(title=f"Jobs for {role}")
table.add_column("Platform", style="blue")
table.add_column("Company", style="cyan")
table.add_column("Title", style="magenta")
table.add_column("Location", style="green")
table.add_column("Remote", style="yellow")
for j in filtered[:20]: # Show top 20
table.add_row(
j.get("ats", "N/A"),
j.get("company", "N/A")[:20] if j.get("company") else "N/A",
j.get("title", "N/A")[:30] if j.get("title") else "N/A",
j.get("location_raw", "N/A")[:25] if j.get("location_raw") else "N/A",
j.get("remote_type", "N/A"),
)
console.print(table)
console.print(
f"\n[bold green]Found {len(filtered)} matching jobs![/bold green]"
)
if len(filtered) > 20:
console.print(f"[dim]Showing top 20 of {len(filtered)} results[/dim]")
# Cleanup
if os.path.exists(raw_file):
os.remove(raw_file)
if os.path.exists(curated_file):
os.remove(curated_file)
@app.command()
def dedupe(
input_file: str = typer.Option("filtered_jobs.json", help="Input job file"),
output_file: str = typer.Option(
"unique_jobs.json", help="Output file for unique jobs"
),
threshold: int = typer.Option(
85, "--threshold", "-t", help="Similarity threshold (0-100)"
),
):
"""Senior-level deduplication using multi-field matching"""
from src.deduplicator import JobDeduplicator
if not os.path.exists(input_file):
console.print(f"[red]File {input_file} not found[/red]")
return
with open(input_file) as f:
jobs = json.load(f)
console.print(
f"[cyan]Deduplicating {len(jobs)} jobs with threshold {threshold}%...[/cyan]"
)
console.print(
"[dim]Dedup key: (company, normalized_title, normalized_location)[/dim]"
)
deduplicator = JobDeduplicator(similarity_threshold=threshold)
unique_jobs, duplicates = deduplicator.remove_duplicates(jobs)
# Save unique jobs
with open(output_file, "w") as f:
json.dump(unique_jobs, f, indent=2)
# Display results
from rich.table import Table
stats = deduplicator.get_dedup_stats(duplicates)
table = Table(title="Senior-Level Deduplication Results")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="white")
table.add_row("Original jobs", str(len(jobs)))
table.add_row("Unique jobs", str(len(unique_jobs)))
table.add_row("Duplicates removed", str(len(duplicates)))
table.add_row("Deduplication rate", f"{(len(duplicates) / len(jobs) * 100):.1f}%")
if duplicates:
table.add_row("Avg similarity", f"{stats['avg_similarity']:.1f}%")
console.print(table)
# Pass condition check: Same job never appears twice
dedup_keys = [deduplicator.generate_dedup_key(job) for job in unique_jobs]
unique_keys = set(dedup_keys)
if len(unique_keys) == len(unique_jobs):
console.print(
f"\n[bold green]✅ Pass Condition Met: Same job never appears twice in final output[/bold green]"
)
else:
console.print(
f"\n[bold red]❌ Pass Condition Failed: {len(unique_jobs) - len(unique_keys)} duplicate keys found[/bold red]"
)
# Show sample duplicates
if duplicates:
console.print(f"\n[bold yellow]Sample Duplicates Found:[/bold yellow]")
for i, dup in enumerate(duplicates[:3], 1):
console.print(
f"{i}. {dup['duplicate_job'].get('title', 'No title')[:50]}..."
)
console.print(
f" Company: {dup['duplicate_job'].get('company', 'Unknown')}"
)
console.print(f" Similarity: {dup['similarity']:.1f}%")
console.print(
f" Preferred: {'Newer' if dup['preferred'] == dup['duplicate_job'] else 'Existing'}"
)
console.print()
console.print(
f"[bold green]Saved {len(unique_jobs)} unique jobs to {output_file}[/bold green]"
)
@app.command()
def export(
format: str = typer.Option("csv", help="Export format: csv, xlsx, json"),
output: str = typer.Option("jobs_export", help="Output filename"),
):
"""Export jobs to different formats"""
import glob
# Load latest jobs
job_files = glob.glob("*jobs*.json")
if not job_files:
console.print("[red]No job files found[/red]")
return
latest_file = max(job_files, key=lambda f: os.path.getmtime(f))
with open(latest_file) as f:
jobs = json.load(f)
if format == "csv":
import csv
filename = f"{output}.csv"
with open(filename, "w", newline="") as f:
if jobs:
writer = csv.DictWriter(f, fieldnames=jobs[0].keys())
writer.writeheader()
writer.writerows(jobs)
console.print(f"✅ Exported {len(jobs)} jobs to {filename}")
elif format == "json":
filename = f"{output}.json"
with open(filename, "w") as f:
json.dump(jobs, f, indent=2)
console.print(f"✅ Exported {len(jobs)} jobs to {filename}")
@app.command()
def stats():
"""Show job search statistics"""
from collections import Counter
import glob
# Load all job files
all_jobs = []
for file in glob.glob("*jobs*.json"):
try:
with open(file) as f:
jobs = json.load(f)
if isinstance(jobs, list):
all_jobs.extend(jobs)
except:
continue
if not all_jobs:
console.print("[red]No job data found[/red]")
return
# Calculate stats
total_jobs = len(all_jobs)
companies = Counter(job.get("company", "Unknown") for job in all_jobs)
remote_types = Counter(job.get("remote_type", "Unknown") for job in all_jobs)
regions = Counter()
for job in all_jobs:
for region in job.get("regions", []):
regions[region] += 1
# Display stats
console.print(f"[bold blue]📊 Job Statistics[/bold blue]")
console.print(f"Total Jobs: {total_jobs}")
console.print(f"\n[cyan]Top Companies:[/cyan]")
for company, count in companies.most_common(5):
console.print(f" {company}: {count}")
console.print(f"\n[cyan]Remote Types:[/cyan]")
for remote_type, count in remote_types.most_common():
console.print(f" {remote_type}: {count}")
console.print(f"\n[cyan]Regions:[/cyan]")
for region, count in regions.most_common():
console.print(f" {region}: {count}")
@app.command()
def platforms(
region: str = typer.Option(None, help="Show platforms for specific region"),
):
"""Show available platforms by region"""
from src.regional_platforms import REGIONAL_PLATFORMS, get_platforms_for_region
if region:
platforms = get_platforms_for_region(region.upper())
console.print(f"[bold blue]Platforms for {region.upper()}:[/bold blue]")
for platform in platforms:
console.print(f" • {platform}")
else:
console.print("[bold blue]Available Regions & Platforms:[/bold blue]")
for region_name, data in REGIONAL_PLATFORMS.items():
console.print(f"\n[cyan]{region_name}:[/cyan]")
for platform in data["platforms"]:
console.print(f" • {platform}")
console.print(
f" [dim]Countries: {', '.join(data['countries'].keys())}[/dim]"
)
@app.command()
def add_role(
role: str = typer.Argument(..., help="Role name to add synonyms for"),
synonyms: List[str] = typer.Argument(..., help="List of synonyms for the role"),
):
"""Add role synonyms dynamically without rewriting search logic"""
searcher = EnhancedJobSearcher()
searcher.add_role_synonyms(role, synonyms)
# Show coverage
coverage = searcher.get_role_coverage(role)
console.print(
f"[bold green]✅ Role '{role}' now has {coverage['coverage']} variants:[/bold green]"
)
for variant in coverage["variants"]:
console.print(f" • {variant}")
console.print(
f"\n[bold blue]Pass condition met:[/bold blue] Added new role without rewriting search logic!"
)
@app.command()
def test_queries(
role: str = typer.Argument(..., help="Role to test query generation for"),
max_queries: int = typer.Option(5, help="Maximum queries to generate"),
):
"""Test dynamic query generation for a role"""
from src.dynamic_query_builder import DynamicQueryBuilder
builder = DynamicQueryBuilder()
domains = ["boards.greenhouse.io", "jobs.lever.co"]
variants = builder.get_progressive_queries(role, domains, max_queries)
table = Table(title=f"Dynamic Queries for '{role}'")
table.add_column("Priority", style="cyan")
table.add_column("Query", style="white")
table.add_column("Strategy", style="yellow")
for variant in variants:
strategy = {
1: "High precision",
2: "Medium precision",
3: "Broad coverage",
}.get(variant.priority, "Unknown")
table.add_row(
str(variant.priority),
variant.query[:100] + "..." if len(variant.query) > 100 else variant.query,
strategy,
)
console.print(table)
@app.command()
def add_role(
role: str = typer.Argument(..., help="Role name (e.g., 'rust', 'golang')"),
synonyms: List[str] = typer.Argument(
..., help="Role synonyms (e.g., 'rust developer' 'systems engineer')"
),
):
"""Add new role synonyms without changing code - senior level feature"""
from src.dynamic_query_builder import DynamicQueryBuilder
builder = DynamicQueryBuilder()
builder.add_role_synonyms(role, synonyms)
console.print(f"[bold green]✅ Added role '{role}' with synonyms:[/bold green]")
for synonym in synonyms:
console.print(f" • {synonym}")
console.print(f"\n[dim]Saved to roles_config.json for persistence[/dim]")
@app.command()
def list_roles():
"""List all available job roles in the system"""
from src.dynamic_query_builder import DynamicQueryBuilder
from rich.table import Table
from rich.columns import Columns
from rich.panel import Panel
builder = DynamicQueryBuilder()
console.print(
Panel("[bold blue]Available Job Roles[/bold blue]", border_style="blue")
)
console.print(f"[dim]Total roles: {len(builder.role_synonyms)}[/dim]\n")
# Group roles by category for better display
categories = {
"Software Development": [
"python",
"javascript",
"react",
"node",
"fullstack",
"java",
"c++",
"golang",
"rust",
"mobile",
"backend-engineer",
"integration-engineer",
],
"Data & Analytics": [
"data",
"data-clerk",
"junior-analyst",
"reporting-analyst",
"business-analyst",
"operations-analyst",
"mis-analyst",
"data-quality",
"bi-analyst",
"data-operations",
"product-analyst",
"program-analyst",
"revenue-analyst",
"risk-analyst",
"technical-analyst",
"support-analyst",
"qa-analyst",
"data-engineer",
"analytics-engineer",
"internal-tools",
],
"Infrastructure & DevOps": [
"devops",
"security",
"platform-engineer",
"cloud-engineer",
"automation-engineer",
],
"QA & Testing": [
"qa",
"qa-engineer",
"qa-analyst",
"test-automation",
],
"Project & Program Management": [
"project-manager",
"operations-coordinator",
"program-analyst",
"tpm",
],
"Product Management": [
"product",
"associate-pm",
"product-ops",
],
"Design": ["design"],
"Solutions & Implementation": [
"solutions-engineer",
"implementation-engineer",
],
}
for category, role_keys in categories.items():
console.print(f"\n[bold cyan]{category}:[/bold cyan]")
table = Table(show_header=True, header_style="bold", box=None)
table.add_column("Role Key", style="green", width=20)
table.add_column("Search Variants", style="white", width=60)
for role_key in role_keys:
if role_key in builder.role_synonyms:
synonyms = builder.role_synonyms[role_key]
synonyms_str = ", ".join(synonyms[:5])
if len(synonyms) > 5:
synonyms_str += f" [dim](+{len(synonyms) - 5} more)[/dim]"
table.add_row(role_key, synonyms_str)
console.print(table)
console.print("\n[bold yellow]Usage:[/bold yellow]")
console.print(" Search by role key: uv run python main.py search --role python")
console.print(
" Or use any synonym: uv run python main.py search --role 'data clerk'"
)
console.print(
"\n[dim]Tip: Use 'test-queries' to preview generated search queries for any role[/dim]"
)
@app.command()
def list_platforms():
"""List all available job platforms in the system"""
from src.platforms import JobPlatforms
from rich.table import Table
from rich.panel import Panel
platforms = JobPlatforms.PLATFORMS
console.print(
Panel("[bold blue]Available Job Platforms[/bold blue]", border_style="blue")
)
console.print(f"[dim]Total platforms: {len(platforms)}[/dim]\n")
# Group platforms by type
categories = {
"ATS (Applicant Tracking Systems)": [],
"Major Job Boards": [],
"Remote-First Platforms": [],
"Startup Platforms": [],
"Product & Tech": [],
"Regional Platforms": [],
}
for name, config in platforms.items():
platform_type = config.get("type", "other")
category = config.get("category", "")
if platform_type == "ats":
categories["ATS (Applicant Tracking Systems)"].append((name, config))
elif platform_type == "job_board":
categories["Major Job Boards"].append((name, config))
elif platform_type == "remote":
categories["Remote-First Platforms"].append((name, config))
elif platform_type == "startup":
categories["Startup Platforms"].append((name, config))
elif platform_type == "specialized":
categories["Product & Tech"].append((name, config))
elif platform_type == "regional":
categories["Regional Platforms"].append((name, config))
for category_name, platform_list in categories.items():
if not platform_list:
continue
console.print(f"\n[bold cyan]{category_name}:[/bold cyan]")
table = Table(show_header=True, header_style="bold", box=None)
table.add_column("Platform", style="green", width=20)
table.add_column("Domains", style="white", width=50)
table.add_column("Status", style="yellow", width=10)
for name, config in platform_list:
domains = config.get("domains", [])
domains_str = ", ".join(domains[:2])
if len(domains) > 2:
domains_str += f" [dim](+{len(domains) - 2} more)[/dim]"
status = "✓ Enabled" if config.get("enabled", False) else "✗ Disabled"
table.add_row(name, domains_str, status)
console.print(table)
console.print("\n[bold yellow]Usage:[/bold yellow]")
console.print(
" Search specific platforms: uv run python main.py search --role python --region USA"
)
console.print(
" Exclude platforms: uv run python main.py search --role python --exclude linkedin --exclude indeed"
)
console.print(
"\n[dim]Tip: Use 'platforms --region LATAM' to see region-specific platforms[/dim]"
)
@app.command()
def test_queries(
role: str = typer.Argument(..., help="Role to test query generation for"),
domains: List[str] = typer.Option(
["boards.greenhouse.io"], "--domain", "-d", help="Test domains"
),
max_queries: int = typer.Option(8, "--max", "-m", help="Maximum queries to show"),
):
"""Test dynamic query generation for any role - preview before searching"""
from src.dynamic_query_builder import DynamicQueryBuilder
builder = DynamicQueryBuilder()
variants = builder.get_progressive_queries(role, domains, max_queries)
if not variants:
console.print(f"[red]No query variants generated for role: {role}[/red]")
console.print("[yellow]Try adding role synonyms first with: add-role[/yellow]")
return
table = Table(title=f"Dynamic Query Variants for '{role}'")
table.add_column("Priority", style="cyan", width=8)
table.add_column("Strategy", style="yellow", width=20)
table.add_column("Query", style="white")
table.add_column("Role Terms", style="green", width=25)
for variant in variants:
role_terms_str = ", ".join(variant.role_terms[:2]) + (
"..." if len(variant.role_terms) > 2 else ""
)
table.add_row(
str(variant.priority),
variant.strategy,
variant.query[:80] + "..." if len(variant.query) > 80 else variant.query,
role_terms_str,
)
console.print(table)
console.print(
f"\n[dim]Generated {len(variants)} query variants using progressive widening strategy[/dim]"
)
@app.command()
def query_demo(
role: str = typer.Option("python", "--role", "-r", help="Role to demonstrate"),
):
"""Demonstrate senior-level query strategy vs basic approach"""
from src.dynamic_query_builder import DynamicQueryBuilder
console.print(f"[bold blue]Query Strategy Demo: {role}[/bold blue]\n")
# Show basic approach