GopiBNA commited on
Commit
e2f13dc
·
verified ·
1 Parent(s): 89fcaa4

Add retry-with-jitter + team session lookup

Browse files
Files changed (1) hide show
  1. engine/batch_runner.py +57 -9
engine/batch_runner.py CHANGED
@@ -31,6 +31,7 @@ import re
31
  import shutil
32
  import sys
33
  import tempfile
 
34
  import zipfile
35
  from datetime import datetime
36
  from typing import Callable, Dict, List, Optional
@@ -43,6 +44,7 @@ from tie_loader import TIE
43
  from scraper import BNAScraper
44
  from comparator import read_ai_file, build_comparison_rows, write_outputs
45
  import insights
 
46
 
47
 
48
  BASE_URL_PREFIX = "https://app.bnamericas.com/project/section/all/content/"
@@ -383,23 +385,69 @@ def run_batch(
383
  company_chips=chip_list,
384
  bna_lang=lang,
385
  ) as sc:
386
- # If the researcher handed us a session-cookie string from their
387
- # already-signed-in browser, try that first. Falls through to
388
- # credential login if the cookie is missing or has expired.
 
 
 
389
  login_ok = False
390
- if bna_cookies:
391
- log("INFO", "Trying existing BNA session (cookies)...")
 
 
 
 
 
 
 
 
 
 
392
  login_ok = sc.inject_cookies(bna_cookies)
393
  if login_ok:
394
- log("INFO", "Connected via existing session.")
395
  else:
396
  log("WARNING",
397
- "Existing session not accepted -- falling back to "
398
  "email + password.")
399
  if not login_ok:
400
- log("INFO", "Logging in to BNAmericas...")
401
- login_ok = sc.login(email, password)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  if not login_ok and not manual_login:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  log("WARNING",
404
  "Auto-login was blocked by BNAmericas (Cloudflare / MFA / "
405
  "captcha). Re-launching browser in MANUAL login mode — "
 
31
  import shutil
32
  import sys
33
  import tempfile
34
+ import time
35
  import zipfile
36
  from datetime import datetime
37
  from typing import Callable, Dict, List, Optional
 
44
  from scraper import BNAScraper
45
  from comparator import read_ai_file, build_comparison_rows, write_outputs
46
  import insights
47
+ import team_session
48
 
49
 
50
  BASE_URL_PREFIX = "https://app.bnamericas.com/project/section/all/content/"
 
385
  company_chips=chip_list,
386
  bna_lang=lang,
387
  ) as sc:
388
+ # Three-stage login resolution, in order of preference:
389
+ # 1. Team-lead daily session cookie (set via Admin tab).
390
+ # Bypasses Cloudflare's bot challenge because it arrives at
391
+ # BNA as an already-authenticated session, not a fresh login.
392
+ # 2. Researcher-supplied cookies argument (legacy / advanced).
393
+ # 3. Researcher's email + password with retry-with-jitter.
394
  login_ok = False
395
+ team_cookie = team_session.get_cookie_if_fresh()
396
+ if team_cookie:
397
+ log("INFO", "Trying team session cookie (set by team lead)...")
398
+ login_ok = sc.inject_cookies(team_cookie)
399
+ if login_ok:
400
+ log("INFO", "Connected via team session cookie.")
401
+ else:
402
+ log("WARNING",
403
+ "Team session cookie was rejected (likely expired). "
404
+ "Falling back to researcher credentials.")
405
+ if not login_ok and bna_cookies:
406
+ log("INFO", "Trying researcher-supplied BNA session cookie...")
407
  login_ok = sc.inject_cookies(bna_cookies)
408
  if login_ok:
409
+ log("INFO", "Connected via researcher session cookie.")
410
  else:
411
  log("WARNING",
412
+ "Researcher cookie not accepted -- falling back to "
413
  "email + password.")
414
  if not login_ok:
415
+ # Retry-with-jitter. BNA sits behind Cloudflare which sometimes
416
+ # throws a transient bot-challenge on first attempt and lets
417
+ # the second one through. We try up to 3 times with a small
418
+ # random pause between tries so retries don't look automated
419
+ # either. Cookies are wiped between tries to avoid carrying
420
+ # over a failed challenge token.
421
+ import random
422
+ backoffs = [0, 6, 18] # seconds before attempts 1, 2, 3
423
+ for attempt_idx, base_wait in enumerate(backoffs, start=1):
424
+ if base_wait > 0:
425
+ delay = base_wait + random.uniform(0.5, 4.5)
426
+ log("INFO",
427
+ f"Login retry {attempt_idx}/3 in "
428
+ f"{delay:.1f}s (Cloudflare cooldown)...")
429
+ time.sleep(delay)
430
+ try: sc._context.clear_cookies()
431
+ except Exception: pass
432
+ log("INFO", f"Logging in to BNAmericas (attempt {attempt_idx}/3)...")
433
+ if sc.login(email, password):
434
+ login_ok = True
435
+ break
436
  if not login_ok and not manual_login:
437
+ # The headed manual-login fallback only makes sense on a
438
+ # desktop with a display. The web app runs on Hugging Face
439
+ # Spaces, which is a headless Linux container with no X
440
+ # server -- launching a visible Chromium there crashes with
441
+ # "Missing X server or $DISPLAY". Detect that case and raise
442
+ # a clean login error instead of a Playwright traceback.
443
+ has_display = bool(os.environ.get("DISPLAY")) or sys.platform.startswith(("win", "darwin"))
444
+ if not has_display:
445
+ raise RuntimeError(
446
+ "BNA login failed. Double-check your BNAmericas email "
447
+ "and password, then try again. If the password is "
448
+ "definitely correct, BNAmericas may have temporarily "
449
+ "flagged the sign-in -- wait ~10 minutes and retry."
450
+ )
451
  log("WARNING",
452
  "Auto-login was blocked by BNAmericas (Cloudflare / MFA / "
453
  "captcha). Re-launching browser in MANUAL login mode — "