"""Thumbnail generation service.""" import pymupdf from pathlib import Path from app.config import settings def generate_thumbnail(file_id: str) -> None: """Generate a PNG thumbnail for the first page of a PDF.""" pdf_path = settings.PDF_STORAGE_PATH / f"{file_id}.pdf" thumb_path = settings.THUMBNAILS_PATH / f"{file_id}.png" if not pdf_path.exists(): return try: doc = pymupdf.open(pdf_path) if len(doc) > 0: page = doc[0] # Zoom to approximately 600px width rect = page.rect zoom = 600.0 / rect.width if rect.width > 0 else 1.0 mat = pymupdf.Matrix(zoom, zoom) # Render pixmap pix = page.get_pixmap(matrix=mat, alpha=False) # Save as PNG pix.save(thumb_path, output="png") doc.close() except Exception as e: print(f"Failed to generate thumbnail for {file_id}: {e}") def delete_thumbnail(file_id: str) -> None: """Delete a thumbnail file.""" thumb_path = settings.THUMBNAILS_PATH / f"{file_id}.png" if thumb_path.exists(): thumb_path.unlink()