File size: 3,594 Bytes
c1b1c1f
 
 
 
a1398e5
 
 
 
 
 
 
 
c1b1c1f
 
 
 
6b2dd6c
a1398e5
298d4dd
6b2dd6c
a1398e5
298d4dd
a1398e5
298d4dd
 
a1398e5
6b2dd6c
a1398e5
922c3e0
a1398e5
6b2dd6c
8fb428c
a1398e5
922c3e0
a1398e5
d0ae0b7
a1398e5
 
8fb428c
a1398e5
922c3e0
a1398e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1b1c1f
a1398e5
 
 
 
 
922c3e0
a1398e5
298d4dd
c1b1c1f
a1398e5
c1b1c1f
a1398e5
298d4dd
a1398e5
 
 
c1b1c1f
764d758
 
a1398e5
 
 
298d4dd
a1398e5
 
 
764d758
a1398e5
 
 
764d758
 
a1398e5
 
 
 
 
764d758
a1398e5
298d4dd
764d758
a1398e5
764d758
a1398e5
d0ae0b7
a1398e5
 
764d758
a1398e5
 
922c3e0
a1398e5
 
 
 
764d758
a1398e5
 
 
764d758
a1398e5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
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)