Spaces:
Sleeping
Sleeping
Update app.py
Browse files1123445678910111213141 unmodified line161718192021221 unmodified line2425262728293031283233343132333435363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line74757642777879804445818283844885865087885389905591929394956096979899651001011026910310410510673107108751091101111125 unmodified lines118119120871211221231246 unmodified lines1311321331001341351361375 unmodified lines14314414514614714814915015115215315415515615715815916016116216316416511816616716816917017117217317422 unmodified lines197198199147148200201from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasksfrom fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Bodyfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dictfrom typing import List, Dict, Optionalimport osimport shutilimport zipfileimport uuidimport timeimport requestsimport sqlite3from pydub import AudioSegmentfrom PIL import Imageimport pyheif1 unmodified line
app = FastAPI()
# CORS設定app.add_middleware( CORSMiddleware, allow_origins=["*"],1 unmodified line allow_headers=["*"],)
# パス設定BASE_TEMP_DIR = "/tmp/media_master"DB_PATH = "colab_config.db"os.makedirs(BASE_TEMP_DIR, exist_ok=True)
# 進行状況管理# 進行状況管理(メモリ上)tasks: Dict[str, dict] = {}
# --- Colab サーバーのURL (実行時に書き換わるか、環境変数から取得) ---# Colab側で発行された ngrok などのURLをここに入れますCOLAB_URL = os.getenv("COLAB_URL", "")
# --- データベース初期化 ---def init_db(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY, value TEXT, updated_at REAL ) ''') conn.commit() conn.close()
init_db()
def get_colab_url() -> str: conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute('SELECT value FROM config WHERE key = "colab_url"') row = cursor.fetchone() conn.close() return row[0] if row else ""
def set_colab_url(url: str): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' INSERT OR REPLACE INTO config (key, value, updated_at) VALUES (?, ?, ?) ''', ("colab_url", url.strip(), time.time())) conn.commit() conn.close()
# --- 非同期処理ロジック ---def process_task(task_id: str, tool_id: str, url_text: str, filenames: List[str]): session_path = os.path.join(BASE_TEMP_DIR, task_id) input_path = os.path.join(session_path, "input")1 unmodified line os.makedirs(output_path, exist_ok=True)
try: # --- YouTube 処理 (Colabへ委託) --- current_colab_url = get_colab_url()
# YouTube 処理 (Colabへ委託) if tool_id == 'youtube' and url_text: if not COLAB_URL: raise Exception("ColabサーバーのURLが設定されていません。Hugging FaceのSettingsからCOLAB_URLを設定してください。") if not current_colab_url: raise Exception("ColabサーバーのURLが設定されていません。Colab側でセルを実行してください。") urls = [u.strip() for u in url_text.split('\n') if u.strip()] tasks[task_id]["last_log"] = f"Colabサーバーへリクエスト送信中... (計{len(urls)}件)" tasks[task_id]["last_log"] = f"Colabへリクエスト送信中... (計{len(urls)}件)" # Colab側のAPIを叩く (一括処理用) try: response = requests.post( f"{COLAB_URL.rstrip('/')}/batch-download", f"{current_colab_url.rstrip('/')}/batch-download", json={"urls": urls}, timeout=600 # 長めのタイムアウト timeout=900 ) if response.status_code != 200: raise Exception(f"Colabエラー: {response.text}") # Colabから送られてきたZIPファイルを保存 colab_zip = os.path.join(session_path, "colab_result.zip") with open(colab_zip, "wb") as f: f.write(response.content) # ZIPを展開してoutputディレクトリへ移動 with zipfile.ZipFile(colab_zip, 'r') as z: z.extractall(output_path) tasks[task_id]["last_log"] = "Colabからのダウンロードが完了しました" tasks[task_id]["last_log"] = "Colabからの処理が完了しました" tasks[task_id]["progress"] = 90
except Exception as e: raise Exception(f"Colab接続失敗: {str(e)}") raise Exception(f"Colab接続失敗 (URLが古い可能性があります): {str(e)}")
# --- 通常のメディア変換処理 (HFS内で実行) --- # 通常のメディア変換処理 else: for i, fname in enumerate(filenames): in_f = os.path.join(input_path, fname)5 unmodified lines img = Image.frombytes(heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride) img.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg"), "JPEG") elif tool_id == 'm4a-mp3' or tool_id == 'mp4-mp3': elif tool_id in ['m4a-mp3', 'mp4-mp3']: audio = AudioSegment.from_file(in_f) audio.export(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.mp3"), format="mp3") 6 unmodified lines for j, image in enumerate(images): image.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}_{j}.png"), "PNG")
# --- 最終ZIP作成 --- # 最終ZIP作成 tasks[task_id]["last_log"] = "結果をまとめています..." final_zip = os.path.join(session_path, "result.zip") with zipfile.ZipFile(final_zip, 'w') as z:5 unmodified lines except Exception as e: tasks[task_id].update({"status": "failed", "error": str(e)})
# --- ルート・APIエンドポイント ---
@app.get("/")async def read_index(): if not os.path.exists("index.html"): return {"error": "index.html not found"} with open("index.html", "r", encoding="utf-8") as f: return HTMLResponse(content=f.read())
@app.post("/api/update_colab_url")async def update_colab_url(payload: dict = Body(...)): """Colab側からURLを受け取って更新する""" url = payload.get("url") if not url: raise HTTPException(status_code=400, detail="URL is required") set_colab_url(url) print(f"Colab URL updated to: {url}") return {"status": "success", "updated_url": url}
@app.post("/api/convert")async def convert_start(background_tasks: BackgroundTasks, tool_id: str = Form(...), url: str = Form(None), files: List[UploadFile] = File(None)):async def convert_start( background_tasks: BackgroundTasks, tool_id: str = Form(...), url: Optional[str] = Form(None), files: Optional[List[UploadFile]] = File(None)): task_id = str(uuid.uuid4()) os.makedirs(os.path.join(BASE_TEMP_DIR, task_id, "input"), exist_ok=True) 22 unmodified lines
@app.get("/api/config")async def get_config(): # ColabのURLが設定されているかどうかをフロントエンドに伝える return {"youtube_enabled": COLAB_URL != ""} url = get_colab_url() return {"youtube_enabled": url != "", "colab_url": url}app.py+77-24