Spaces:
Running
Running
Push Bot
commited on
Commit
·
6c7c5ff
1
Parent(s):
e5b2e62
Fix debug NameError: add preview_image_from_pdf and first-page rasterizer helpers
Browse files
app.py
CHANGED
|
@@ -558,6 +558,53 @@ def _pdf_to_iframe_file(pdf_path: Path, width="100%", height="900px") -> str:
|
|
| 558 |
except Exception:
|
| 559 |
return ""
|
| 560 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
def _compile_tex_to_pdf(tex_path: Path, logs):
|
| 562 |
"""Generic TeX compile helper for a .tex file. Returns Path to PDF or None."""
|
| 563 |
try:
|
|
|
|
| 558 |
except Exception:
|
| 559 |
return ""
|
| 560 |
|
| 561 |
+
def _pdf_to_image_first_page(pdf_path: Path, out_dir: Path, logs) -> Path | None:
|
| 562 |
+
try:
|
| 563 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 564 |
+
out_path = out_dir / "poster_preview.png"
|
| 565 |
+
# Try PyMuPDF
|
| 566 |
+
try:
|
| 567 |
+
import fitz # PyMuPDF
|
| 568 |
+
doc = fitz.open(str(pdf_path))
|
| 569 |
+
if doc.page_count == 0:
|
| 570 |
+
return None
|
| 571 |
+
page = doc.load_page(0)
|
| 572 |
+
mat = fitz.Matrix(2, 2)
|
| 573 |
+
pix = page.get_pixmap(matrix=mat, alpha=False)
|
| 574 |
+
pix.save(str(out_path))
|
| 575 |
+
return out_path if out_path.exists() else None
|
| 576 |
+
except Exception as e:
|
| 577 |
+
logs.append(f"⚠️ PyMuPDF render failed: {e}")
|
| 578 |
+
# Fallback: pypdfium2
|
| 579 |
+
try:
|
| 580 |
+
import pypdfium2 as pdfium
|
| 581 |
+
pdf = pdfium.PdfDocument(str(pdf_path))
|
| 582 |
+
if len(pdf) == 0:
|
| 583 |
+
return None
|
| 584 |
+
page = pdf[0]
|
| 585 |
+
bitmap = page.render(scale=2).to_pil()
|
| 586 |
+
bitmap.save(out_path)
|
| 587 |
+
return out_path if out_path.exists() else None
|
| 588 |
+
except Exception as e:
|
| 589 |
+
logs.append(f"⚠️ pypdfium2 render failed: {e}")
|
| 590 |
+
except Exception as e:
|
| 591 |
+
logs.append(f"⚠️ image preview failed: {e}")
|
| 592 |
+
return None
|
| 593 |
+
|
| 594 |
+
def preview_image_from_pdf(pdf_file):
|
| 595 |
+
try:
|
| 596 |
+
path = pdf_file
|
| 597 |
+
if hasattr(pdf_file, 'name'):
|
| 598 |
+
path = pdf_file.name
|
| 599 |
+
if not path:
|
| 600 |
+
return None
|
| 601 |
+
p = Path(path)
|
| 602 |
+
logs = []
|
| 603 |
+
img = _pdf_to_image_first_page(p, p.parent, logs)
|
| 604 |
+
return str(img) if img and img.exists() else None
|
| 605 |
+
except Exception:
|
| 606 |
+
return None
|
| 607 |
+
|
| 608 |
def _compile_tex_to_pdf(tex_path: Path, logs):
|
| 609 |
"""Generic TeX compile helper for a .tex file. Returns Path to PDF or None."""
|
| 610 |
try:
|