File size: 3,079 Bytes
9a65320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43e2c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a65320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""共通ユーティリティ関数。"""

import io
import base64
import json

from PIL import Image


def sse_event(data: dict) -> str:
    """

    辞書を SSE フォーマット文字列に変換する。



    Args:

        data: JSON シリアライズ可能な辞書



    Returns:

        str: "data: {...}\\n\\n" 形式の SSE 文字列

    """
    return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"


def open_image_or_pdf(file_bytes: bytes, filename: str = "") -> Image.Image:
    """

    画像バイト列または PDF バイト列から PIL Image (RGB) を返す。

    PDF の場合は1ページ目を 2x 解像度でレンダリングして返す。



    Args:

        file_bytes: 画像または PDF のバイト列

        filename: 元ファイル名(拡張子で PDF を判別する際に使用)



    Returns:

        PIL.Image: RGB 形式の画像



    Raises:

        ImportError: PDF 処理に pymupdf が必要なのにインストールされていない場合

        ValueError: PDF にページが存在しない場合

    """
    is_pdf = (
        filename.lower().endswith(".pdf")
        or file_bytes[:4] == b"%PDF"
    )
    if is_pdf:
        return _pdf_first_page_to_image(file_bytes)
    return Image.open(io.BytesIO(file_bytes)).convert("RGB")


def _pdf_first_page_to_image(pdf_bytes: bytes) -> Image.Image:
    """

    PDF バイト列の1ページ目を PIL Image に変換する(内部用)。



    Args:

        pdf_bytes: PDF ファイルのバイト列



    Returns:

        PIL.Image: 1ページ目を 2x 解像度でレンダリングした RGB 画像



    Raises:

        ImportError: pymupdf がインストールされていない場合

        ValueError: PDF にページが存在しない場合

    """
    try:
        import fitz  # pymupdf
    except ImportError as exc:
        raise ImportError(
            "PDF の処理には pymupdf が必要です: pip install pymupdf"
        ) from exc

    doc = fitz.open(stream=pdf_bytes, filetype="pdf")
    if doc.page_count == 0:
        doc.close()
        raise ValueError("PDF にページが存在しません。")

    page = doc[0]
    mat = fitz.Matrix(2.0, 2.0)  # 2x 解像度でレンダリング
    pix = page.get_pixmap(matrix=mat)
    img_bytes = pix.tobytes("png")
    doc.close()

    return Image.open(io.BytesIO(img_bytes)).convert("RGB")


def resize_image_to_base64(image: Image.Image, max_size: int = 512) -> str:
    """

    PIL 画像をリサイズして Base64 エンコード済み JPEG 文字列を返す。



    Args:

        image: PIL.Image オブジェクト

        max_size: 長辺の最大ピクセル数



    Returns:

        str: Base64 エンコード済み文字列(JPEG 形式)

    """
    img = image.copy()
    img.thumbnail((max_size, max_size), Image.LANCZOS)
    buffer = io.BytesIO()
    img.save(buffer, format="JPEG", quality=85)
    buffer.seek(0)
    return base64.b64encode(buffer.read()).decode("utf-8")