PatientChartCreation / pdf_renderer.py
sujataprakashdatycs's picture
Update pdf_renderer.py
4fe2ceb verified
import os, subprocess, re, shutil
def render_pdf(latex_code, output_path):
# 1. Improved Extraction: Look for the document structure specifically
match = re.search(r"(\\documentclass.*\\end\{document\})", latex_code, re.DOTALL)
if match:
clean_code = match.group(1).strip()
else:
# Fallback to backtick stripping
match_block = re.search(r"```(?:latex)?\n?(.*?)\n?```", latex_code, re.DOTALL)
clean_code = match_block.group(1).strip() if match_block else latex_code.strip()
# 2. Basic Sanity Check: If the AI missed \end{document}, add it
if "\\end{document}" not in clean_code:
clean_code += "\n\\end{document}"
tex_filename = "final_output.tex"
with open(tex_filename, "w") as f:
f.write(clean_code)
try:
# 3. Use -interaction=nonstopmode to prevent hanging on errors
# We run it once. If it fails, it fails.
result = subprocess.run(
["pdflatex", "-interaction=nonstopmode", tex_filename],
check=False, # Don't raise exception yet so we can check the file
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if os.path.exists("final_output.pdf"):
shutil.move("final_output.pdf", output_path)
return True
else:
# Log the error for debugging in HF Logs
print(f"LaTeX StdOut: {result.stdout.decode()[:500]}")
return False
except Exception as e:
print(f"❌ System Error: {str(e)}")
return False