Dipti Dhawade commited on
Commit
33ad1a2
·
1 Parent(s): 661e1b8

Fix flashcard parsing

Browse files
Files changed (1) hide show
  1. backend/llm_pipeline.py +13 -1
backend/llm_pipeline.py CHANGED
@@ -390,11 +390,23 @@ def sarvam_rag_answer_stream(question: str, context: str, language: str = "Engli
390
  raise LLMError(str(e)) from e
391
 
392
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  def _parse_json_loose(raw: str) -> Any:
394
  raw = raw.strip()
395
  raw = re.sub(r"^```(?:json)?\s*", "", raw)
396
  raw = re.sub(r"\s*```\s*$", "", raw)
397
- return json.loads(raw)
398
 
399
 
400
  def _tokens(text: str) -> list[str]:
 
390
  raise LLMError(str(e)) from e
391
 
392
 
393
+ # Models often write LaTeX inside JSON strings with single backslashes: "\cdot" is an invalid JSON
394
+ # escape (the whole reply fails to parse), and "\frac" / "\theta" / "\neq" parse silently as a form
395
+ # feed / tab / newline. A backslash followed by two or more lowercase letters is a LaTeX command (a
396
+ # real line break is "\n" before a capital, digit or space), so it is escaped before parsing.
397
+ _LATEX_COMMAND = re.compile(r"(?<!\\)\\(?=[a-z]{2,})")
398
+ _BAD_JSON_ESCAPE = re.compile(r'(?<!\\)\\(?![\\"/bfnrtu])')
399
+
400
+
401
+ def _repair_latex_escapes(raw: str) -> str:
402
+ return _BAD_JSON_ESCAPE.sub(r"\\\\", _LATEX_COMMAND.sub(r"\\\\", raw))
403
+
404
+
405
  def _parse_json_loose(raw: str) -> Any:
406
  raw = raw.strip()
407
  raw = re.sub(r"^```(?:json)?\s*", "", raw)
408
  raw = re.sub(r"\s*```\s*$", "", raw)
409
+ return json.loads(_repair_latex_escapes(raw))
410
 
411
 
412
  def _tokens(text: str) -> list[str]: