Stephan86 Claude Sonnet 4.6 commited on
Commit
ddef99f
·
1 Parent(s): 72065ef

fix: 90s timeout per batch + real progress + partial CSV on hang

Browse files
Files changed (3) hide show
  1. app.py +6 -1
  2. core/agent.py +36 -28
  3. static/index.html +5 -0
app.py CHANGED
@@ -40,7 +40,10 @@ def _run_job(job_id: str, pdf_path: str, page_from: int, page_to: int,
40
  _jobs[job_id] = {"status": "error", "error": "Aucune page extraite dans la plage indiquée."}
41
  return
42
 
43
- articles = extract_articles(pages, margin_pct, default_unit)
 
 
 
44
  if not articles:
45
  _jobs[job_id] = {"status": "error", "error": "Aucun article détecté dans ces pages."}
46
  return
@@ -132,6 +135,8 @@ async def status(job_id: str):
132
  return JSONResponse({"status": "error", "error": job["error"]})
133
  if job["status"] == "done":
134
  return JSONResponse({"status": "done", "count": job["count"]})
 
 
135
  return JSONResponse({"status": "processing"})
136
 
137
 
 
40
  _jobs[job_id] = {"status": "error", "error": "Aucune page extraite dans la plage indiquée."}
41
  return
42
 
43
+ def _progress(done, total):
44
+ _jobs[job_id]["progress"] = f"{done}/{total}"
45
+
46
+ articles = extract_articles(pages, margin_pct, default_unit, progress_cb=_progress)
47
  if not articles:
48
  _jobs[job_id] = {"status": "error", "error": "Aucun article détecté dans ces pages."}
49
  return
 
135
  return JSONResponse({"status": "error", "error": job["error"]})
136
  if job["status"] == "done":
137
  return JSONResponse({"status": "done", "count": job["count"]})
138
+ if job.get("progress"):
139
+ return JSONResponse({"status": "processing", "progress": job["progress"]})
140
  return JSONResponse({"status": "processing"})
141
 
142
 
core/agent.py CHANGED
@@ -1,5 +1,7 @@
1
  import json
2
  import re
 
 
3
  import anthropic
4
 
5
  _SYSTEM = """\
@@ -13,22 +15,20 @@ Chaque objet doit avoir exactement ces quatre champs :
13
  Ne retourne aucun texte, commentaire ou balise avant ou après le tableau JSON.\
14
  """
15
 
16
- _BATCH_SIZE = 5 # pages par appel Claude
 
17
 
18
 
19
  def _parse_json_safe(raw: str) -> list[dict]:
20
- """Try to parse JSON, recovering truncated arrays if possible."""
21
  raw = raw.strip()
22
- # Retire les fences markdown
23
  if raw.startswith("```"):
24
  raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
25
  try:
26
  return json.loads(raw)
27
  except json.JSONDecodeError:
28
- # Tente de récupérer les objets complets si le JSON est tronqué
29
- objects = re.findall(r'\{[^{}]*\}', raw)
30
  results = []
31
- for obj in objects:
32
  try:
33
  results.append(json.loads(obj))
34
  except json.JSONDecodeError:
@@ -45,37 +45,45 @@ def _call_claude(client: anthropic.Anthropic, batch: list[str], default_unit: st
45
  system=_SYSTEM,
46
  messages=[{"role": "user", "content": user_msg}],
47
  )
48
- raw = message.content[0].text
49
- return _parse_json_safe(raw)
50
 
51
 
52
  def extract_articles(
53
  pages_text: list[str],
54
  margin_pct: float,
55
  default_unit: str,
 
56
  ) -> list[dict]:
57
- """Process pages in batches — skips failed batches, returns all collected articles."""
58
- client = anthropic.Anthropic(timeout=180.0)
 
 
 
 
59
  all_articles: list[dict] = []
60
  batches = [pages_text[i:i + _BATCH_SIZE] for i in range(0, len(pages_text), _BATCH_SIZE)]
61
 
62
- for i, batch in enumerate(batches):
63
- try:
64
- articles = _call_claude(client, batch, default_unit)
65
- all_articles.extend(articles)
66
- except anthropic.APIConnectionError as exc:
67
- # Erreur réseau vers l'API → fatale, on arrête tout
68
- raise RuntimeError(
69
- "Impossible de joindre l'API Anthropic. "
70
- "Vérifie que ANTHROPIC_API_KEY est bien configurée dans les secrets HF Spaces."
71
- ) from exc
72
- except anthropic.AuthenticationError as exc:
73
- raise RuntimeError(
74
- "Clé API Anthropic invalide ou expirée. "
75
- "Vérifie la valeur de ANTHROPIC_API_KEY dans les secrets HF Spaces."
76
- ) from exc
77
- except Exception:
78
- # Autre erreur (JSON tronqué, timeout isolé) → on passe au batch suivant
79
- continue
 
 
 
 
80
 
81
  return all_articles
 
1
  import json
2
  import re
3
+ from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
4
+
5
  import anthropic
6
 
7
  _SYSTEM = """\
 
15
  Ne retourne aucun texte, commentaire ou balise avant ou après le tableau JSON.\
16
  """
17
 
18
+ _BATCH_SIZE = 5 # pages par appel Claude
19
+ _BATCH_TIMEOUT = 90 # secondes max par batch
20
 
21
 
22
  def _parse_json_safe(raw: str) -> list[dict]:
 
23
  raw = raw.strip()
 
24
  if raw.startswith("```"):
25
  raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
26
  try:
27
  return json.loads(raw)
28
  except json.JSONDecodeError:
29
+ # Récupère les objets complets si le JSON est tronqué
 
30
  results = []
31
+ for obj in re.findall(r'\{[^{}]*\}', raw):
32
  try:
33
  results.append(json.loads(obj))
34
  except json.JSONDecodeError:
 
45
  system=_SYSTEM,
46
  messages=[{"role": "user", "content": user_msg}],
47
  )
48
+ return _parse_json_safe(message.content[0].text)
 
49
 
50
 
51
  def extract_articles(
52
  pages_text: list[str],
53
  margin_pct: float,
54
  default_unit: str,
55
+ progress_cb=None,
56
  ) -> list[dict]:
57
+ """
58
+ Process pages in batches with a per-batch timeout.
59
+ progress_cb(batch_index, total_batches) called after each batch.
60
+ Failed/timed-out batches are skipped.
61
+ """
62
+ client = anthropic.Anthropic(timeout=_BATCH_TIMEOUT + 10)
63
  all_articles: list[dict] = []
64
  batches = [pages_text[i:i + _BATCH_SIZE] for i in range(0, len(pages_text), _BATCH_SIZE)]
65
 
66
+ with ThreadPoolExecutor(max_workers=1) as pool:
67
+ for i, batch in enumerate(batches):
68
+ future = pool.submit(_call_claude, client, batch, default_unit)
69
+ try:
70
+ articles = future.result(timeout=_BATCH_TIMEOUT)
71
+ all_articles.extend(articles)
72
+ except FutureTimeout:
73
+ future.cancel()
74
+ except anthropic.APIConnectionError as exc:
75
+ raise RuntimeError(
76
+ "Impossible de joindre l'API Anthropic. "
77
+ "Vérifie ANTHROPIC_API_KEY dans les secrets HF Spaces."
78
+ ) from exc
79
+ except anthropic.AuthenticationError as exc:
80
+ raise RuntimeError(
81
+ "Clé API Anthropic invalide ou expirée."
82
+ ) from exc
83
+ except Exception:
84
+ pass # JSON tronqué ou autre → batch ignoré
85
+
86
+ if progress_cb:
87
+ progress_cb(i + 1, len(batches))
88
 
89
  return all_articles
static/index.html CHANGED
@@ -390,6 +390,11 @@
390
  } else if (data.status === 'error') {
391
  clearInterval(poll); clearInterval(ticker);
392
  reject(new Error(data.error));
 
 
 
 
 
393
  }
394
  } catch (e) { /* réseau temporaire, on réessaie */ }
395
  }, 3000);
 
390
  } else if (data.status === 'error') {
391
  clearInterval(poll); clearInterval(ticker);
392
  reject(new Error(data.error));
393
+ } else if (data.progress) {
394
+ const [done, total] = data.progress.split('/').map(Number);
395
+ const pct = 20 + Math.round((done / total) * 75);
396
+ progressBar.style.width = pct + '%';
397
+ progressLbl.textContent = `Batch ${done}/${total} traité…`;
398
  }
399
  } catch (e) { /* réseau temporaire, on réessaie */ }
400
  }, 3000);