Spaces:
Sleeping
Sleeping
fix: recover partial JSON + skip failed batches instead of crashing
Browse files- app.py +5 -1
- core/agent.py +32 -9
app.py
CHANGED
|
@@ -48,7 +48,11 @@ def _run_job(job_id: str, pdf_path: str, page_from: int, page_to: int,
|
|
| 48 |
out = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
|
| 49 |
out.close()
|
| 50 |
to_csv(articles, out.name, margin_pct)
|
| 51 |
-
_jobs[job_id] = {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
except Exception as exc:
|
| 54 |
_jobs[job_id] = {
|
|
|
|
| 48 |
out = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
|
| 49 |
out.close()
|
| 50 |
to_csv(articles, out.name, margin_pct)
|
| 51 |
+
_jobs[job_id] = {
|
| 52 |
+
"status": "done",
|
| 53 |
+
"result": out.name,
|
| 54 |
+
"count": len(articles),
|
| 55 |
+
}
|
| 56 |
|
| 57 |
except Exception as exc:
|
| 58 |
_jobs[job_id] = {
|
core/agent.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import json
|
|
|
|
| 2 |
import anthropic
|
| 3 |
|
| 4 |
_SYSTEM = """\
|
|
@@ -15,6 +16,26 @@ Ne retourne aucun texte, commentaire ou balise avant ou après le tableau JSON.\
|
|
| 15 |
_BATCH_SIZE = 5 # pages par appel Claude
|
| 16 |
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
def _call_claude(client: anthropic.Anthropic, batch: list[str], default_unit: str) -> list[dict]:
|
| 19 |
combined = "\n\n--- PAGE ---\n\n".join(batch)
|
| 20 |
user_msg = f"Unité par défaut : {default_unit}\n\nTexte du catalogue :\n{combined}"
|
|
@@ -24,10 +45,8 @@ def _call_claude(client: anthropic.Anthropic, batch: list[str], default_unit: st
|
|
| 24 |
system=_SYSTEM,
|
| 25 |
messages=[{"role": "user", "content": user_msg}],
|
| 26 |
)
|
| 27 |
-
raw = message.content[0].text
|
| 28 |
-
|
| 29 |
-
raw = raw.split("\n", 1)[1].rsplit("```", 1)[0]
|
| 30 |
-
return json.loads(raw)
|
| 31 |
|
| 32 |
|
| 33 |
def extract_articles(
|
|
@@ -35,13 +54,17 @@ def extract_articles(
|
|
| 35 |
margin_pct: float,
|
| 36 |
default_unit: str,
|
| 37 |
) -> list[dict]:
|
| 38 |
-
"""Process pages in batches
|
| 39 |
client = anthropic.Anthropic(timeout=180.0)
|
| 40 |
all_articles: list[dict] = []
|
| 41 |
-
|
| 42 |
batches = [pages_text[i:i + _BATCH_SIZE] for i in range(0, len(pages_text), _BATCH_SIZE)]
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
return all_articles
|
|
|
|
| 1 |
import json
|
| 2 |
+
import re
|
| 3 |
import anthropic
|
| 4 |
|
| 5 |
_SYSTEM = """\
|
|
|
|
| 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:
|
| 35 |
+
continue
|
| 36 |
+
return results
|
| 37 |
+
|
| 38 |
+
|
| 39 |
def _call_claude(client: anthropic.Anthropic, batch: list[str], default_unit: str) -> list[dict]:
|
| 40 |
combined = "\n\n--- PAGE ---\n\n".join(batch)
|
| 41 |
user_msg = f"Unité par défaut : {default_unit}\n\nTexte du catalogue :\n{combined}"
|
|
|
|
| 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(
|
|
|
|
| 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 Exception:
|
| 67 |
+
# Batch raté → on continue avec les suivants
|
| 68 |
+
continue
|
| 69 |
|
| 70 |
return all_articles
|