| """共通ユーティリティ関数。"""
|
|
|
| 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
|
| 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)
|
| 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")
|
|
|