"""Session-local, incremental previews of actual Pandoc PowerPoint slides. Pandoc still builds the complete presentation so slide boundaries, references and metadata have exactly the same semantics as the regular converter. Only changed slides go through LibreOffice PDF export and Poppler rasterization. """ import hashlib import json import shutil import subprocess import tempfile import threading import time from pathlib import Path from pptx import Presentation from services.converter import ( MAX_PREVIEW_PAGES, _embed_external_images, pptx_to_pdf, render_pdf_preview, ) DEBOUNCE_SECONDS = 0.8 class LiveSession: """One browser session; fast edits can supersede an in-flight conversion.""" def __init__(self): self.lock = threading.RLock() self.revision = 0 self.rendered_revision = -1 self.edited_at = 0.0 self.markdown = "" self.template = None self.root = None self.cache = {} self.build_key = None self.pptx_path = None self.closed = False def __deepcopy__(self, memo): # Gradio copies initial state; locks and temporary files must not be shared. return LiveSession() def stage(self, markdown, template): with self.lock: self.markdown = markdown or "" self.template = template self.revision += 1 self.edited_at = time.monotonic() return self.revision def snapshot(self): with self.lock: return self.revision, self.markdown, self.template def directory(self): with self.lock: if self.closed: raise RuntimeError("編輯工作階段已結束,請重新整理頁面。") if self.root is None: self.root = Path(tempfile.mkdtemp(prefix="md2ppt-live-")) return self.root def close(self): with self.lock: self.closed = True if self.root is not None: shutil.rmtree(self.root, ignore_errors=True) self.cache.clear() def _digest(value): return hashlib.sha256(value).hexdigest() def slide_fingerprints(pptx_path, template_digest=""): """Hash each slide and its rendering dependencies, including embedded media. Do not follow links to other slides or notes. A master links to all its layouts; those sibling layouts do not affect the current slide. Tracking visited parts also handles the layout/master relationship cycle. """ presentation = Presentation(pptx_path) fingerprints = [] for index, slide in enumerate(presentation.slides): visited = set() digest = hashlib.sha256() digest.update(f"{index}:{presentation.slide_width}:{presentation.slide_height}:{template_digest}".encode()) def visit(part): name = str(part.partname) if name in visited: return visited.add(name) digest.update(name.encode()) digest.update(part.blob) for rel in sorted(part.rels.values(), key=lambda item: item.rId): kind = rel.reltype.rsplit("/", 1)[-1] if kind in {"slide", "notesSlide", "notesMaster"}: continue if kind == "slideLayout" and "/slideMasters/" in name: continue digest.update(f"{rel.rId}:{rel.reltype}:{rel.target_ref}".encode()) if not rel.is_external: visit(rel.target_part) visit(slide.part) fingerprints.append(digest.hexdigest()) return fingerprints def build_presentation(session, markdown, template): """Reuse the current PPTX when exporting an already-previewed revision.""" template_bytes = Path(template).read_bytes() if template else b"" template_digest = _digest(template_bytes) key = _digest(markdown.encode() + b"\0" + template_digest.encode()) if session.build_key == key and session.pptx_path and session.pptx_path.is_file(): return session.pptx_path, template_digest root = session.directory() with tempfile.TemporaryDirectory(prefix="build-", dir=root) as workdir: workdir = Path(workdir) source = workdir / "source.md" source.write_text(markdown, encoding="utf-8") parsed = subprocess.run( ["pandoc", "--sandbox", str(source), "--to=json"], check=True, capture_output=True, text=True, timeout=30, ) document = _embed_external_images(json.loads(parsed.stdout)) output = workdir / "presentation.pptx" command = ["pandoc", "--from=json", "--output", str(output)] if template: reference = workdir / "reference.pptx" reference.write_bytes(template_bytes) command.append(f"--reference-doc={reference}") subprocess.run( command, input=json.dumps(document, ensure_ascii=False), check=True, capture_output=True, text=True, timeout=60, ) destination = root / "presentation.pptx" output.replace(destination) session.build_key = key session.pptx_path = destination return destination, template_digest def update_preview(session, revision, markdown, template): """Return a complete ordered gallery, reusing all unchanged image files. None means this result was superseded and must never replace the gallery. Cache changes are committed only after every requested page was rendered. """ pptx_path, template_digest = build_presentation(session, markdown, template) fingerprints = slide_fingerprints(pptx_path, template_digest) visible = fingerprints[:MAX_PREVIEW_PAGES] changed = [ index for index, fingerprint in enumerate(visible) if fingerprint not in session.cache or not Path(session.cache[fingerprint]).is_file() ] if session.snapshot()[0] != revision: return None cache = dict(session.cache) created = [] if changed: with tempfile.TemporaryDirectory(prefix="render-", dir=session.directory()) as workdir: pdf = pptx_to_pdf( str(pptx_path), page_numbers=[index + 1 for index in changed], output_dir=workdir, ) pages, truncated = render_pdf_preview(pdf) if truncated or len(pages) != len(changed): raise RuntimeError("預覽頁數與投影片不一致,請重新更新預覽。") if session.snapshot()[0] != revision: return None for index, (image_path, _) in zip(changed, pages): destination = session.directory() / f"{visible[index]}.jpg" shutil.copyfile(image_path, destination) created.append(destination) cache[visible[index]] = str(destination) with session.lock: if session.revision != revision or session.closed: for path in created: path.unlink(missing_ok=True) return None current_cache = {fingerprint: cache[fingerprint] for fingerprint in visible} # Bound disk use to the current preview, even after many editing rounds. for fingerprint, path in cache.items(): if fingerprint not in current_cache: Path(path).unlink(missing_ok=True) session.cache = current_cache session.rendered_revision = revision gallery = [(current_cache[fingerprint], f"第 {index + 1} 頁") for index, fingerprint in enumerate(visible)] status = f"已更新 · {len(fingerprints)} 頁投影片 · 重新渲染 {len(changed)} 頁 · 沿用 {len(visible) - len(changed)} 頁" if len(fingerprints) > MAX_PREVIEW_PAGES: status += f"\n預覽顯示前 {MAX_PREVIEW_PAGES} 頁;下載包含全部投影片。" return gallery, status def export_presentation(session, markdown, template): """Generate full downloads in a separate directory from partial preview PDFs.""" pptx_path, _ = build_presentation(session, markdown, template) # Gradio copies returned files to its own cache before the next export. export_dir = session.directory() / "export" export_dir.mkdir(exist_ok=True) destination = export_dir / "presentation.pptx" shutil.copyfile(pptx_path, destination) pdf_path = destination.with_suffix(".pdf") pdf_path.unlink(missing_ok=True) pdf = pptx_to_pdf(str(destination)) return str(destination), pdf