Spaces:
Sleeping

File size: 8,206 Bytes
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0ff42
 
 
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
fa0ff42
 
0ad51a0
4ab4456
 
 
 
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0ff42
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ab4456
 
 
 
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0ff42
 
 
 
 
 
4ab4456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0ff42
0ad51a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0ff42
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
"""
app.py
FastAPI のルーティング・起動設定のみを記述する。
変換ロジックは tools/ 配下の各モジュールに委譲する。
"""
import os
import shutil
import uuid
import time
import asyncio
import pathlib

from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Body
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Optional

# --- 共通モジュール ---
from tools.base_tool import (
    BASE_TEMP_DIR,
    tasks,
    get_session_paths,
    zip_output,
)

# --- 各ツールモジュール ---
from tools.image_tools import convert_heic_to_jpg, convert_jpeg_to_pdf, convert_pdf_to_png
from tools.audio_tools import convert_to_mp3
from tools.file_tools  import verify_password, list_files, build_zip

app = FastAPI()

# --- CORS ---
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- 有効な tool_id と output_format の定義 ---
VALID_TOOL_IDS = {"heic-jpg", "m4a-mp3", "mp4-mp3", "jpeg-pdf", "pdf-png"}
VALID_FORMATS  = {"mp3"}

# --- 同時処理数の制限 ---
MAX_CONCURRENT    = 3
convert_semaphore = asyncio.Semaphore(MAX_CONCURRENT)


# ------------------------------------------------------------------ #
#  バックグラウンドタスク:各ツールへの振り分け
# ------------------------------------------------------------------ #

def process_task(
    task_id: str,
    tool_id: str,
    filenames: List[str],
    output_format: str = "mp3"
):
    session_path, input_path, output_path = get_session_paths(task_id)

    try:
        # --- ツール振り分け ---
        if tool_id == "heic-jpg":
            convert_heic_to_jpg(task_id, filenames, input_path, output_path)

        elif tool_id == "jpeg-pdf":
            convert_jpeg_to_pdf(task_id, filenames, input_path, output_path)

        elif tool_id == "pdf-png":
            convert_pdf_to_png(task_id, filenames, input_path, output_path)

        elif tool_id in ("m4a-mp3", "mp4-mp3"):
            convert_to_mp3(task_id, filenames, input_path, output_path)

        # --- 結果を ZIP 化 ---
        tasks[task_id]["last_log"] = "ファイルを圧縮中..."
        zip_output(session_path, output_path)

        tasks[task_id].update({
            "status": "completed",
            "progress": 100,
            "last_log": "完了",
            "completed_at": time.time(),
        })

    except Exception as e:
        print(f"[ERROR] task_id={task_id}, error={str(e)}")
        tasks[task_id].update({
            "status": "failed",
            "error": str(e),
            "completed_at": time.time(),
        })

    finally:
        # 処理が終わったら必ずセマフォを解放する
        convert_semaphore.release()


# ------------------------------------------------------------------ #
#  定期クリーンアップ(1時間ごとに完了済みタスクを削除)
# ------------------------------------------------------------------ #

async def cleanup_loop():
    while True:
        await asyncio.sleep(3600)
        now = time.time()
        to_delete = [
            tid for tid, t in list(tasks.items())
            if t.get("completed_at") and now - t["completed_at"] > 3600
        ]
        for tid in to_delete:
            tasks.pop(tid, None)
            shutil.rmtree(os.path.join(BASE_TEMP_DIR, tid), ignore_errors=True)


@app.on_event("startup")
async def startup_event():
    try:
        asyncio.create_task(cleanup_loop())
    except Exception as e:
        print(f"Cleanup loop error: {e}")


# ------------------------------------------------------------------ #
#  エンドポイント
# ------------------------------------------------------------------ #

@app.get("/")
async def read_index():
    with open("index.html", "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())


@app.get("/health")
async def health_check():
    return {"status": "ok"}


@app.post("/api/convert")
async def convert_start(
    background_tasks: BackgroundTasks,
    tool_id: str = Form(...),
    files: List[UploadFile] = File(default=[]),
    output_format: str = Form("mp3"),
):
    # エンドポイント層でバリデーション
    if tool_id not in VALID_TOOL_IDS:
        raise HTTPException(status_code=400, detail=f"無効なtool_idです: {tool_id}")
    if output_format not in VALID_FORMATS:
        raise HTTPException(status_code=400, detail=f"無効なoutput_formatです: {output_format}")

    # 同時処理数の上限チェック(待機させずに即座に拒否)
    if convert_semaphore._value <= 0:
        raise HTTPException(
            status_code=429,
            detail=f"現在サーバーが混み合っています(同時処理上限: {MAX_CONCURRENT}件)。しばらくしてから再試行してください。"
        )
    await convert_semaphore.acquire()

    try:
        task_id = str(uuid.uuid4())
        os.makedirs(os.path.join(BASE_TEMP_DIR, task_id, "input"), exist_ok=True)

        # 空リストは None として扱う
        if files is not None and len(files) == 0:
            files = None

        # ファイルサイズ上限チェック(100MB)
        MAX_FILE_SIZE = 100 * 1024 * 1024
        fnames = []
        if files:
            for f in files:
                contents = await f.read()
                if len(contents) > MAX_FILE_SIZE:
                    raise HTTPException(
                        status_code=400,
                        detail=f"{f.filename} はサイズ上限(100MB)を超えています"
                    )
                safe_name = pathlib.Path(f.filename).name
                file_path = os.path.join(BASE_TEMP_DIR, task_id, "input", safe_name)
                with open(file_path, "wb") as buf:
                    buf.write(contents)
                fnames.append(safe_name)

        tasks[task_id] = {"status": "processing", "progress": 10, "last_log": "タスクを開始しました"}
        background_tasks.add_task(process_task, task_id, tool_id, fnames, output_format)
        return {"task_id": task_id}

    except HTTPException:
        # バリデーションエラー時はセマフォを即解放(process_taskには渡らないため)
        convert_semaphore.release()
        raise


@app.get("/api/status/{task_id}")
async def get_status(task_id: str):
    return tasks.get(task_id, {"status": "failed", "error": "Task not found"})


@app.get("/api/download/{task_id}")
async def download_result(task_id: str):
    zip_path = os.path.join(BASE_TEMP_DIR, task_id, "result.zip")
    if os.path.exists(zip_path):
        return FileResponse(zip_path, filename="result.zip")
    if task_id in tasks:
        raise HTTPException(status_code=503, detail="ファイルが一時領域から消えました。再度変換をやり直してください。")
    raise HTTPException(status_code=404, detail="タスクが見つかりません。")


# --- ファイルダウンロード機能 ---

@app.post("/api/files/auth")
async def files_auth(payload: dict = Body(...)):
    """パスワードを照合し、正しければファイル一覧を返す"""
    password = payload.get("password", "")
    if not verify_password(password):
        raise HTTPException(status_code=401, detail="パスワードが正しくありません")
    return {"files": list_files()}


@app.post("/api/files/download")
async def files_download(payload: dict = Body(...)):
    """選択されたファイルをZIPにまとめて返す"""
    password = payload.get("password", "")
    if not verify_password(password):
        raise HTTPException(status_code=401, detail="パスワードが正しくありません")
    filenames = payload.get("filenames", [])
    if not filenames:
        raise HTTPException(status_code=400, detail="ファイルが選択されていません")
    try:
        zip_path = build_zip(filenames)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    return FileResponse(zip_path, filename="download.zip", media_type="application/zip")