Spaces:
Sleeping

File size: 3,122 Bytes
4f3fd1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
image_tools.py
画像関連の変換処理
  - heic-jpg : HEIC → JPEG
  - jpeg-pdf : JPEG/PNG 複数枚 → 1つの PDF
  - pdf-png  : PDF の各ページ → PNG
"""
import os
import subprocess
from typing import List

from PIL import Image
try:
    from pillow_heif import register_heif_opener
    register_heif_opener()
    PILLOW_HEIF_AVAILABLE = True
except Exception:
    PILLOW_HEIF_AVAILABLE = False

from pdf2image import convert_from_path

from tools.base_tool import tasks


# ---------- HEIC → JPG ----------

def convert_heic_to_jpg(task_id: str, filenames: List[str], input_path: str, output_path: str):
    """HEIC ファイルを JPEG に変換する(ImageMagick → pillow-heif の順でフォールバック)"""
    for i, fname in enumerate(filenames):
        in_f  = os.path.join(input_path, fname)
        out_f = os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg")

        tasks[task_id]["last_log"] = f"処理中: {fname}"
        tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60)

        converted = False

        # まず ImageMagick で試みる(最も確実)
        try:
            result = subprocess.run(
                ["convert", in_f, "-quality", "95", out_f],
                capture_output=True, timeout=60
            )
            if result.returncode == 0 and os.path.exists(out_f):
                converted = True
        except Exception:
            pass

        # フォールバック: pillow-heif
        if not converted and PILLOW_HEIF_AVAILABLE:
            img = Image.open(in_f)
            img.convert("RGB").save(out_f, "JPEG", quality=95)
            converted = True

        if not converted:
            raise Exception(
                f"HEIC変換に失敗しました: {fname}。"
                "ImageMagickおよびpillow-heifが利用できません。"
            )


# ---------- JPEG/PNG → PDF ----------

def convert_jpeg_to_pdf(task_id: str, filenames: List[str], input_path: str, output_path: str):
    """複数の画像ファイルを1つの PDF に結合する"""
    imgs = []
    for fname in filenames:
        in_f = os.path.join(input_path, fname)
        imgs.append(Image.open(in_f).convert("RGB"))

    if not imgs:
        raise Exception("変換対象の画像がありません")

    out_pdf = os.path.join(output_path, "output.pdf")
    imgs[0].save(out_pdf, "PDF", save_all=True, append_images=imgs[1:])
    tasks[task_id]["progress"] = 80


# ---------- PDF → PNG ----------

def convert_pdf_to_png(task_id: str, filenames: List[str], input_path: str, output_path: str):
    """PDF の各ページを PNG 画像に変換する"""
    for i, fname in enumerate(filenames):
        in_f = os.path.join(input_path, fname)

        tasks[task_id]["last_log"] = f"処理中: {fname}"
        tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60)

        images = convert_from_path(in_f)
        for j, image in enumerate(images):
            image.save(
                os.path.join(output_path, f"{os.path.splitext(fname)[0]}_{j}.png"),
                "PNG"
            )