Spaces:
Sleeping
Sleeping
Download app.py from KeyBow/MediaMasterAsyncPre: direct link, hf CLI and curl.
- Browser
- Download file 7.88 kB
-
https://huggingface.co/spaces/KeyBow/MediaMasterAsyncPre/resolve/main/app.py
- Command line
-
hf download hf://spaces/KeyBow/MediaMasterAsyncPre/app.py
-
curl -L -o app.py https://huggingface.co/spaces/KeyBow/MediaMasterAsyncPre/resolve/main/app.py
7.88 kB
| """ | |
| 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, | |
| init_db, | |
| get_colab_url, | |
| set_colab_url, | |
| 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.youtube_tools import download_youtube | |
| from tools.file_tools import verify_password, list_files, build_zip # ←追加① | |
| SECRET_TOKEN = os.environ.get("SECRET_TOKEN", "") | |
| app = FastAPI() | |
| # --- CORS --- | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --- DB 初期化 --- | |
| init_db() | |
| # --- 有効な tool_id と output_format の定義 --- | |
| VALID_TOOL_IDS = {"youtube", "heic-jpg", "m4a-mp3", "mp4-mp3", "jpeg-pdf", "pdf-png"} | |
| VALID_FORMATS = {"mp3", "mp4"} | |
| # ------------------------------------------------------------------ # | |
| # バックグラウンドタスク:各ツールへの振り分け | |
| # ------------------------------------------------------------------ # | |
| def process_task( | |
| task_id: str, | |
| tool_id: str, | |
| url_text: str, | |
| filenames: List[str], | |
| output_format: str = "mp3" | |
| ): | |
| session_path, input_path, output_path = get_session_paths(task_id) | |
| try: | |
| # バリデーション | |
| if tool_id not in VALID_TOOL_IDS: | |
| raise ValueError(f"無効なtool_idです: {tool_id}") | |
| if output_format not in VALID_FORMATS: | |
| raise ValueError(f"無効なoutput_formatです: {output_format}") | |
| # --- ツール振り分け --- | |
| if tool_id == "youtube": | |
| download_youtube(task_id, url_text, session_path, output_path, output_format) | |
| elif 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(), | |
| }) | |
| # ------------------------------------------------------------------ # | |
| # 定期クリーンアップ(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) | |
| async def startup_event(): | |
| try: | |
| asyncio.create_task(cleanup_loop()) | |
| except Exception as e: | |
| print(f"Cleanup loop error: {e}") | |
| # ------------------------------------------------------------------ # | |
| # エンドポイント | |
| # ------------------------------------------------------------------ # | |
| async def read_index(): | |
| with open("index.html", "r", encoding="utf-8") as f: | |
| return HTMLResponse(content=f.read()) | |
| async def health_check(): | |
| return {"status": "ok"} | |
| async def get_config(): | |
| url = get_colab_url() | |
| return {"youtube_enabled": url != "", "colab_url": url} | |
| async def update_colab_url(payload: dict = Body(...)): | |
| if not SECRET_TOKEN or payload.get("token") != SECRET_TOKEN: | |
| raise HTTPException(status_code=403, detail="Forbidden") | |
| url = payload.get("url") | |
| if not url: | |
| raise HTTPException(status_code=400, detail="URLが必要です") | |
| set_colab_url(url) | |
| print(f"Colab URL Updated: {url}") | |
| return {"status": "success", "url": url} | |
| async def convert_start( | |
| background_tasks: BackgroundTasks, | |
| tool_id: str = Form(...), | |
| url: Optional[str] = Form(None), | |
| files: List[UploadFile] = File(default=[]), | |
| output_format: str = Form("mp3"), | |
| ): | |
| 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 | |
| fnames = [] | |
| if files: | |
| for f in files: | |
| 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: | |
| shutil.copyfileobj(f.file, buf) | |
| fnames.append(safe_name) | |
| tasks[task_id] = {"status": "processing", "progress": 10, "last_log": "タスクを開始しました"} | |
| background_tasks.add_task(process_task, task_id, tool_id, url, fnames, output_format) | |
| return {"task_id": task_id} | |
| async def get_status(task_id: str): | |
| return tasks.get(task_id, {"status": "failed", "error": "Task not found"}) | |
| 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="タスクが見つかりません。") | |
| # --- ファイルダウンロード機能 --- ←追加② | |
| 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()} | |
| 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") |