""" ccpu_parser.pdf_loader ---------------------- Responsabilité : - Normaliser n'importe quel fichier d'entrée (PDF ou image) en un JPEG unique. - Pour un PDF : rendre la 1ère page en image via PyMuPDF. - Pour une image (JPG/PNG/WEBP) : la charger avec Pillow et la re-sauver en JPEG. Fonctions fournies : - file_bytes_to_jpeg(file_bytes: bytes) -> bytes Détecte si PDF ou image, renvoie les octets d'un JPEG RGB. """ from __future__ import annotations import io from typing import Optional from PIL import Image import fitz # PyMuPDF from .utils import logger def _is_pdf(data: bytes) -> bool: """ Détection très simple : un PDF commence par '%PDF'. """ return data.startswith(b"%PDF") def _pdf_first_page_to_jpeg(pdf_bytes: bytes, dpi: int = 200) -> bytes: """ Rend la première page d'un PDF en JPEG. - Utilise PyMuPDF pour ouvrir le PDF depuis des bytes. - Rendu en pixmap, puis conversion en Image PIL et sauvegarde en JPEG. """ logger.info("pdf_loader: rendu de la première page PDF en image (dpi=%d)", dpi) try: doc = fitz.open(stream=pdf_bytes, filetype="pdf") except Exception as exc: # pragma: no cover logger.error("pdf_loader: impossible d'ouvrir le PDF via PyMuPDF : %s", exc) raise if doc.page_count == 0: doc.close() raise ValueError("pdf_loader: PDF sans page exploitable") page = doc.load_page(0) # matrix pour régler la résolution de rendu zoom = dpi / 72.0 mat = fitz.Matrix(zoom, zoom) pix = page.get_pixmap(matrix=mat, alpha=False) doc.close() img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) buf = io.BytesIO() img.save(buf, format="JPEG", quality=90) jpeg_bytes = buf.getvalue() logger.info( "pdf_loader: PDF -> JPEG (w=%d h=%d, taille=%d octets)", pix.width, pix.height, len(jpeg_bytes), ) return jpeg_bytes def _image_to_jpeg(image_bytes: bytes) -> bytes: """ Convertit une image quelconque (JPG/PNG/WEBP/...) en JPEG RGB. - Charge avec Pillow. - Force en RGB. - Sauvegarde en JPEG de qualité correcte. """ try: img = Image.open(io.BytesIO(image_bytes)) except Exception as exc: # pragma: no cover logger.error("pdf_loader: impossible d'ouvrir l'image avec Pillow : %s", exc) raise original_mode = img.mode if img.mode != "RGB": img = img.convert("RGB") buf = io.BytesIO() img.save(buf, format="JPEG", quality=90) jpeg_bytes = buf.getvalue() logger.info( "pdf_loader: image (%s) -> JPEG (w=%d h=%d, taille=%d octets)", original_mode, img.width, img.height, len(jpeg_bytes), ) return jpeg_bytes def file_bytes_to_jpeg(file_bytes: bytes) -> bytes: """ Point d'entrée unique : bytes (PDF ou image) -> JPEG bytes. - Si le header commence par %PDF : on traite comme un PDF (1ère page). - Sinon : on essaie de traiter comme une image via Pillow. """ if not file_bytes: raise ValueError("pdf_loader: fichier vide reçu") logger.info( "pdf_loader: normalisation d'un fichier binaire (taille=%d octets)", len(file_bytes), ) if _is_pdf(file_bytes): logger.info("pdf_loader: header PDF détecté -> rendu 1ère page en JPEG") return _pdf_first_page_to_jpeg(file_bytes) else: logger.info("pdf_loader: header non-PDF -> tentative ouverture image directe") return _image_to_jpeg(file_bytes)