PrathameshRaut commited on
Commit
14ca8d2
·
verified ·
1 Parent(s): fb99df6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -5
app.py CHANGED
@@ -246,10 +246,8 @@ def clean_raw_text(text: str) -> str:
246
  """
247
  Remove base64-encoded image data that Sarvam Document Intelligence
248
  carries over from PDFs/images into the markdown output.
249
-
250
  These blobs are never useful for field extraction and can easily push
251
  the prompt far beyond sarvam-m's 7 192-token context window.
252
-
253
  Two patterns are handled:
254
  1. Markdown image syntax: ![alt](data:image/png;base64,<data>)
255
  2. Bare data URIs that leaked outside markdown syntax
@@ -324,6 +322,19 @@ def extract_text_with_sdk(file_bytes: bytes, filename: str) -> str:
324
  # Step 2: Extract structured JSON via Sarvam Chat (sarvam-m)
325
  # ---------------------------------------------------------------------------
326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  async def extract_json_via_chat(doc_type: str, raw_text: str, parameters: list[str]) -> dict:
328
  description = SUPPORTED_TYPES[doc_type]
329
  param_list = "\n".join(f" - {p}" for p in parameters)
@@ -340,7 +351,6 @@ Rules:
340
  3. If a field is not found or not legible, set its value to null.
341
  4. Do not invent or infer values not explicitly present in the document.
342
  5. Resond everything in english language only. Also convert date into proper DD/MM/YYYY Foramt.
343
-
344
  Respond with the JSON object only."""
345
 
346
  async with httpx.AsyncClient(timeout=60) as http:
@@ -360,15 +370,19 @@ Respond with the JSON object only."""
360
 
361
  raw = resp.json()["choices"][0]["message"]["content"].strip()
362
 
363
- raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL).strip()
 
364
 
 
365
  if raw.startswith("```"):
366
  raw = raw.split("\n", 1)[-1]
367
  if raw.endswith("```"):
368
  raw = raw[: raw.rfind("```")]
369
 
 
 
370
  try:
371
- return json.loads(raw.strip())
372
  except json.JSONDecodeError:
373
  return {"raw_response": raw, "parse_error": "Model did not return valid JSON"}
374
 
 
246
  """
247
  Remove base64-encoded image data that Sarvam Document Intelligence
248
  carries over from PDFs/images into the markdown output.
 
249
  These blobs are never useful for field extraction and can easily push
250
  the prompt far beyond sarvam-m's 7 192-token context window.
 
251
  Two patterns are handled:
252
  1. Markdown image syntax: ![alt](data:image/png;base64,<data>)
253
  2. Bare data URIs that leaked outside markdown syntax
 
322
  # Step 2: Extract structured JSON via Sarvam Chat (sarvam-m)
323
  # ---------------------------------------------------------------------------
324
 
325
+ def strip_think_tags(text: str) -> str:
326
+ """
327
+ Remove <think>…</think> reasoning blocks from sarvam-m output.
328
+ Handles both complete tags and truncated blocks where the closing
329
+ tag was cut off due to max_tokens being reached mid-response.
330
+ """
331
+ # Pass 1: remove complete <think>…</think> blocks
332
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
333
+ # Pass 2: remove any unclosed/truncated <think> block that runs to end-of-string
334
+ text = re.sub(r"<think>.*$", "", text, flags=re.DOTALL)
335
+ return text.strip()
336
+
337
+
338
  async def extract_json_via_chat(doc_type: str, raw_text: str, parameters: list[str]) -> dict:
339
  description = SUPPORTED_TYPES[doc_type]
340
  param_list = "\n".join(f" - {p}" for p in parameters)
 
351
  3. If a field is not found or not legible, set its value to null.
352
  4. Do not invent or infer values not explicitly present in the document.
353
  5. Resond everything in english language only. Also convert date into proper DD/MM/YYYY Foramt.
 
354
  Respond with the JSON object only."""
355
 
356
  async with httpx.AsyncClient(timeout=60) as http:
 
370
 
371
  raw = resp.json()["choices"][0]["message"]["content"].strip()
372
 
373
+ # Remove <think> blocks handles both complete and truncated closing tags
374
+ raw = strip_think_tags(raw)
375
 
376
+ # Strip markdown code fences if present
377
  if raw.startswith("```"):
378
  raw = raw.split("\n", 1)[-1]
379
  if raw.endswith("```"):
380
  raw = raw[: raw.rfind("```")]
381
 
382
+ raw = raw.strip()
383
+
384
  try:
385
+ return json.loads(raw)
386
  except json.JSONDecodeError:
387
  return {"raw_response": raw, "parse_error": "Model did not return valid JSON"}
388