-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
680 lines (583 loc) · 26.2 KB
/
Copy pathmain.py
File metadata and controls
680 lines (583 loc) · 26.2 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
#!/usr/bin/env python3
"""
YC Cofounder Matcher - Automated candidate discovery and outreach.
Main entry point and orchestration.
"""
import argparse
import sys
from rich.console import Console
from rich.panel import Panel
from config import Config
from session_manager import SessionManager
from browser import BrowserManager
from api_client import YCCofounderAPI
from evaluator import GeminiEvaluator
from interactive import InteractiveReviewer, AutoModeRunner
from logger import InvitationLogger, setup_error_logger
console = Console()
class CofounderMatcher:
"""Main orchestrator for the cofounder matching automation."""
def __init__(self, config: Config, mode: str):
"""Initialize matcher with configuration and mode."""
self.config = config
self.mode = mode # 'auth', 'interactive', 'auto', 'dry-run'
# Initialize components
self.session_manager = SessionManager(config.storage_state_path)
self.browser_manager = BrowserManager(config)
self.api_client = YCCofounderAPI()
self.evaluator = GeminiEvaluator(config)
self.logger = InvitationLogger(config.logs_dir)
self.error_logger = setup_error_logger(config.logs_dir)
# Mode-specific components
if mode == 'interactive':
self.reviewer = InteractiveReviewer(config.interactive_timeout)
elif mode == 'auto':
self.auto_runner = AutoModeRunner()
# Statistics
self.stats = {
'evaluated': 0,
'sent': 0,
'sent_custom': 0,
'skipped_manual': 0,
'skipped_threshold': 0,
'skipped_location': 0,
'skipped_timeout': 0,
'errors': 0
}
# Error tracking
self.consecutive_errors = 0
self.max_consecutive_errors = 5
def run(self):
"""Main execution flow."""
try:
# Display header
self._display_header()
# Validate configuration
errors = self.config.validate()
if errors:
for error in errors:
console.print(f"[red]✗ {error}[/red]")
return 1
# Handle auth mode
if self.mode == 'auth':
return self._run_auth_mode()
# Handle matching modes
return self._run_matching_mode()
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted by user[/yellow]")
self._display_summary()
return 130
except Exception as e:
console.print(f"\n[red]Fatal error: {e}[/red]")
self.error_logger.exception("Fatal error in main execution")
return 1
finally:
# Cleanup
if hasattr(self, 'browser_manager'):
self.browser_manager.close()
def _display_header(self):
"""Display application header."""
title = "YC Cofounder Matcher"
if self.mode == 'interactive':
title += " - Interactive Mode"
elif self.mode == 'auto':
title += " - Auto Mode"
elif self.mode == 'dry-run':
title += " - Dry Run"
elif self.mode == 'auth':
title += " - Authentication"
console.print(Panel(title, style="bold cyan"))
def _run_auth_mode(self):
"""Run authentication mode."""
console.print("\n[bold]Starting authentication flow...[/bold]\n")
# Force headless=False for auth mode
original_headless = self.config.headless
self.config.headless = False
try:
# Launch browser (non-headless for auth)
browser, context = self.browser_manager.launch()
page = context.new_page()
# Perform authentication
self.session_manager.authenticate(page, context)
console.print("\n[green]✓ Authentication complete![/green]")
console.print("You can now run: [cyan]python main.py --interactive[/cyan]\n")
return 0
except Exception as e:
console.print(f"\n[red]Authentication failed: {e}[/red]")
console.print("\n[yellow]Troubleshooting tips:[/yellow]")
console.print("1. Make sure Chromium is properly installed: [cyan]playwright install chromium[/cyan]")
console.print("2. Try with a different browser: Update browser.py to use firefox or webkit")
console.print("3. Check if you have permission issues or security software blocking Chromium")
return 1
finally:
# Restore original setting
self.config.headless = original_headless
def _run_matching_mode(self):
"""Run candidate matching (interactive, auto, or dry-run)."""
# Check for existing session
if not self.session_manager.session_exists():
console.print("[red]✗ No saved session found[/red]")
console.print("Please run: [cyan]python main.py --auth[/cyan]\n")
return 1
# Load session and launch browser
console.print("[dim]Loading saved session...[/dim]")
storage_state = self.session_manager.load_session()
browser, context = self.browser_manager.launch(storage_state)
# Create feed page
feed_page = context.new_page()
# Validate session
console.print("[dim]Validating session...[/dim]")
if not self.session_manager.validate_session(feed_page):
console.print("[red]✗ Session expired[/red]")
console.print("Please re-authenticate: [cyan]python main.py --auth[/cyan]\n")
return 1
console.print("[green]✓[/green] Session valid\n")
# Start discovery using API
console.print("[bold]Starting discovery...[/bold]\n")
# Process candidates one by one
invites_sent = 0
idx = 0
while invites_sent < self.config.max_invites_per_run:
idx += 1
# Check error threshold
if self.consecutive_errors >= self.max_consecutive_errors:
console.print(f"\n[red]Too many consecutive errors ({self.consecutive_errors}). Stopping.[/red]")
break
# Get next candidate from API
console.print(f"\n[bold cyan]Candidate {idx}[/bold cyan]")
candidate = self.api_client.get_next_candidate(feed_page)
if not candidate:
console.print("[yellow]No more candidates available[/yellow]")
break
# Show invites remaining
if candidate.get('invites_remaining') is not None:
console.print(f"[dim]Invites remaining: {candidate['invites_remaining']}[/dim]")
# Process candidate
try:
result = self._process_candidate_api(feed_page, candidate, idx)
if result == 'sent':
invites_sent += 1
self.consecutive_errors = 0
elif result == 'quit':
console.print("\n[yellow]User requested quit[/yellow]")
break
elif result == 'error':
self.consecutive_errors += 1
else:
self.consecutive_errors = 0
except Exception as e:
console.print(f"[red]Error processing candidate: {e}[/red]")
self.error_logger.exception(f"Error processing {candidate.get('slug', 'unknown')}")
self.stats['errors'] += 1
self.consecutive_errors += 1
# Random delay before next candidate
self.browser_manager.random_delay()
# Display summary
self._display_summary()
return 0
def _process_candidate_api(self, page, candidate, idx):
"""
Process a single candidate using API data.
Returns: 'sent', 'skipped', 'error', or 'quit'
"""
candidate_slug = candidate['slug']
candidate_name = candidate['name']
console.print(f"[bold]{candidate_name}[/bold] ({candidate['location']})")
try:
# Evaluate candidate
try:
evaluation = self.evaluator.evaluate_candidate(candidate)
score = evaluation['score']
reasoning = evaluation['reasoning']
self.stats['evaluated'] += 1
except Exception as e:
console.print(f"[red]Evaluation failed: {e}[/red]")
self.logger.log_action(
candidate_slug, candidate_name, 0, str(e),
'error', '', self.mode
)
return 'error'
# Check threshold
if score < self.config.evaluation_threshold:
console.print(f"[yellow]Score {score}/10 - Below threshold ({self.config.evaluation_threshold})[/yellow]")
console.print(f"[dim]{reasoning}[/dim]")
if self.mode == 'auto':
self.auto_runner.log_evaluation(idx, 999, candidate_slug,
candidate_name, score, reasoning)
self.auto_runner.log_action('skipped-threshold')
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'skipped-threshold', '', self.mode
)
self.stats['skipped_threshold'] += 1
return 'skipped'
# Dry-run mode: just log evaluation
if self.mode == 'dry-run':
console.print(f" Score: {score}/10 - {reasoning}")
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'dry-run', '', 'dry-run'
)
return 'skipped'
# Generate invitation message
try:
message = self.evaluator.generate_invitation(candidate)
except Exception as e:
console.print(f"[red]Message generation failed: {e}[/red]")
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'error', '', self.mode
)
return 'error'
# Handle based on mode
if self.mode == 'interactive':
return self._handle_interactive_api(
page, candidate_slug, candidate_name, score,
reasoning, message, idx
)
elif self.mode == 'auto':
return self._handle_auto_api(
page, candidate_slug, candidate_name, score,
reasoning, message, idx
)
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
return 'error'
def _process_candidate(self, context, feed_page, candidate, idx, total):
"""
Process a single candidate.
Returns: 'sent', 'skipped', 'error', or 'quit'
"""
candidate_id = candidate['candidate_id']
candidate_url = candidate['url']
# Open profile in new tab
try:
profile_page = self.browser_manager.open_profile_tab(context, candidate_url)
except Exception as e:
console.print(f"[red]Error opening profile: {e}[/red]")
return 'error'
try:
# Parse profile
profile = self.parser.parse_profile(profile_page)
# Evaluate candidate
try:
evaluation = self.evaluator.evaluate_candidate(profile)
score = evaluation['score']
reasoning = evaluation['reasoning']
self.stats['evaluated'] += 1
except Exception as e:
console.print(f"[red]Evaluation failed: {e}[/red]")
self.logger.log_action(
candidate_id, profile['name'], 0, str(e),
'error', '', self.mode
)
return 'error'
# Check threshold
if score < self.config.evaluation_threshold:
if self.mode == 'auto':
self.auto_runner.log_evaluation(idx, total, candidate_id,
profile['name'], score, reasoning)
self.auto_runner.log_action('skipped-threshold')
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'skipped-threshold', '', self.mode
)
self.stats['skipped_threshold'] += 1
return 'skipped'
# Dry-run mode: just log evaluation
if self.mode == 'dry-run':
console.print(f"[dim]Candidate {idx}/{total}: {profile['name']}[/dim]")
console.print(f" Score: {score}/10 - {reasoning}")
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'dry-run', '', 'dry-run'
)
return 'skipped'
# Generate invitation message
try:
message = self.evaluator.generate_invitation(profile)
except Exception as e:
console.print(f"[red]Message generation failed: {e}[/red]")
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'error', '', self.mode
)
return 'error'
# Handle based on mode
if self.mode == 'interactive':
return self._handle_interactive(
profile_page, candidate_id, profile, score,
reasoning, message, idx, total, candidate_url
)
elif self.mode == 'auto':
return self._handle_auto(
profile_page, candidate_id, profile, score,
reasoning, message, idx, total
)
finally:
# Always close profile tab
self.browser_manager.close_tab(profile_page)
def _handle_interactive_api(self, page, candidate_slug, candidate_name,
score, reasoning, message, idx):
"""Handle interactive mode review for API-based candidate."""
# Display candidate
profile_url = f'https://www.startupschool.org/cofounder-matching/candidate/{candidate_slug}'
self.reviewer.display_candidate(
idx, 999, candidate_name, profile_url, score, reasoning, message
)
# Get user decision
decision = self.reviewer.get_decision()
if decision == 'y':
# Send message
success = self.api_client.send_invitation(page, candidate_slug, message)
if success:
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'sent', message, 'interactive'
)
self.stats['sent'] += 1
console.print(f"[green]✓[/green] Invitation sent to {candidate_name}\n")
return 'sent'
else:
return 'error'
elif decision == 'n':
# Skip
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'skipped-manual', '', 'interactive'
)
self.stats['skipped_manual'] += 1
console.print(f"[yellow]Skipped {candidate_name}[/yellow]\n")
return 'skipped'
elif decision == 'e':
# Edit message
custom_message = self.reviewer.get_custom_message(message)
if custom_message:
success = self.api_client.send_invitation(page, candidate_slug, custom_message)
if success:
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'sent-custom', custom_message, 'interactive'
)
self.stats['sent'] += 1
self.stats['sent_custom'] += 1
console.print(f"[green]✓[/green] Custom invitation sent to {candidate_name}\n")
return 'sent'
else:
return 'error'
else:
# User cancelled edit
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'skipped-manual', '', 'interactive'
)
self.stats['skipped_manual'] += 1
return 'skipped'
elif decision == 'q':
return 'quit'
elif decision == 'timeout':
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'skipped-timeout', '', 'interactive'
)
self.stats['skipped_timeout'] += 1
console.print(f"[yellow]Timeout - skipped {candidate_name}[/yellow]\n")
return 'skipped'
return 'skipped'
def _handle_auto_api(self, page, candidate_slug, candidate_name,
score, reasoning, message, idx):
"""Handle auto mode for API-based candidate."""
# Log evaluation
self.auto_runner.log_evaluation(idx, 999, candidate_slug,
candidate_name, score, reasoning)
self.auto_runner.log_message(message)
# Send invitation
success = self.api_client.send_invitation(page, candidate_slug, message)
if success:
self.auto_runner.log_action('sent')
self.logger.log_action(
candidate_slug, candidate_name, score, reasoning,
'sent', message, 'auto'
)
self.stats['sent'] += 1
return 'sent'
else:
self.auto_runner.log_action('error')
return 'error'
def _handle_interactive(self, profile_page, candidate_id, profile,
score, reasoning, message, idx, total, url):
"""Handle interactive mode review."""
# Display candidate
self.reviewer.display_candidate(
idx, total, profile['name'], url, score, reasoning, message
)
# Get user decision
decision = self.reviewer.get_decision()
if decision == 'y':
# Send message
self._send_invitation(profile_page, message)
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'sent', message, 'interactive'
)
self.stats['sent'] += 1
self.stats['sent_auto'] += 1
console.print(f"[green]✓[/green] Invitation sent to {profile['name']}\n")
return 'sent'
elif decision == 'n':
# Skip
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'skipped-manual', '', 'interactive'
)
self.stats['skipped_manual'] += 1
console.print(f"[yellow]Skipped {profile['name']}[/yellow]\n")
return 'skipped'
elif decision == 'e':
# Edit message
custom_message = self.reviewer.get_custom_message(message)
if custom_message:
self._send_invitation(profile_page, custom_message)
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'sent-custom', custom_message, 'interactive'
)
self.stats['sent'] += 1
self.stats['sent_custom'] += 1
console.print(f"[green]✓[/green] Custom invitation sent to {profile['name']}\n")
return 'sent'
else:
# Cancelled
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'skipped-manual', '', 'interactive'
)
self.stats['skipped_manual'] += 1
return 'skipped'
elif decision == 'q':
# Quit
return 'quit'
elif decision == 'timeout':
# Timeout
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'skipped-timeout', '', 'interactive'
)
self.stats['skipped_timeout'] += 1
return 'skipped'
return 'skipped'
def _handle_auto(self, profile_page, candidate_id, profile,
score, reasoning, message, idx, total):
"""Handle auto mode (no human review)."""
# Log evaluation
self.auto_runner.log_evaluation(
idx, total, candidate_id, profile['name'], score, reasoning
)
# Send invitation
self._send_invitation(profile_page, message)
# Log action
self.logger.log_action(
candidate_id, profile['name'], score, reasoning,
'sent', message, 'auto'
)
self.stats['sent'] += 1
self.auto_runner.log_action('sent', profile['name'])
return 'sent'
def _send_invitation(self, page, message):
"""
Send invitation message via browser automation.
This is a placeholder - actual implementation depends on page structure.
"""
try:
# Wait for page to be ready
page.wait_for_load_state('networkidle', timeout=5000)
# Find and click "invite" or "connect" button
# This selector needs to be updated based on actual page structure
invite_button = page.query_selector('button:has-text("Invite"), button:has-text("Connect")')
if invite_button:
invite_button.click()
self.browser_manager.random_delay(2, 4)
# Find message textarea
# This selector needs to be updated based on actual page structure
message_field = page.query_selector('textarea, input[type="text"]')
if message_field:
message_field.fill(message)
self.browser_manager.random_delay(1, 2)
# Find and click send button
send_button = page.query_selector('button:has-text("Send"), button[type="submit"]')
if send_button:
send_button.click()
self.browser_manager.random_delay(3, 6)
except Exception as e:
console.print(f"[yellow]Warning: Could not send message automatically: {e}[/yellow]")
console.print("[yellow]You may need to update the selectors in _send_invitation()[/yellow]")
# Don't raise - log the warning but continue
def _display_summary(self):
"""Display final summary."""
if self.mode == 'interactive':
self.reviewer.display_summary(self.stats)
elif self.mode == 'auto':
self.auto_runner.display_summary(self.stats)
else:
console.print(f"\nProcessed {self.stats['evaluated']} candidates")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description='YC Cofounder Matcher - Automated candidate discovery and outreach',
formatter_class=argparse.RawDescriptionHelpFormatter
)
# Mode selection (mutually exclusive)
mode_group = parser.add_mutually_exclusive_group()
mode_group.add_argument('--auth', action='store_true',
help='Authenticate and save session')
mode_group.add_argument('--interactive', action='store_true',
help='Interactive mode with human review (RECOMMENDED)')
mode_group.add_argument('--auto', action='store_true',
help='Fully automated mode (use with caution)')
mode_group.add_argument('--dry-run', action='store_true',
help='Evaluate only, no messages sent')
# Options
parser.add_argument('--max-invites', type=int,
help='Maximum invites per run (default: 10)')
parser.add_argument('--headless', type=str, choices=['true', 'false'],
help='Run browser in headless mode (default: true)')
parser.add_argument('--start-fresh', action='store_true',
help='Delete existing session and re-authenticate')
parser.add_argument('--evaluation-threshold', type=int,
help='Minimum score to send invitation (default: 5)')
args = parser.parse_args()
# Determine mode
if args.auth:
mode = 'auth'
elif args.interactive:
mode = 'interactive'
elif args.auto:
mode = 'auto'
elif args.dry_run:
mode = 'dry-run'
else:
# Default to interactive for safety
mode = 'interactive'
console.print("[yellow]No mode specified, defaulting to --interactive[/yellow]\n")
# Build CLI args dict for config
cli_args = {}
if args.max_invites:
cli_args['max_invites'] = args.max_invites
if args.headless:
cli_args['headless'] = args.headless
if args.evaluation_threshold:
cli_args['evaluation_threshold'] = args.evaluation_threshold
# Create config
config = Config(cli_args)
# Handle start-fresh
if args.start_fresh:
session_manager = SessionManager(config.storage_state_path)
session_manager.delete_session()
if mode != 'auth':
console.print("[yellow]Session deleted. Switching to --auth mode[/yellow]\n")
mode = 'auth'
# Run matcher
matcher = CofounderMatcher(config, mode)
sys.exit(matcher.run())
if __name__ == '__main__':
main()