Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131 unmodified line1516171819201 unmodified line222324252627282930313233343536371 unmodified line394041424344454647484950515253545556575859606162636465666768697071727374757677785 unmodified lines848586878889906 unmodified lines9798991001011021035 unmodified lines10911011111211311411511611711811912012122 unmodified lines144145146147148from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasksfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dictimport osimport shutilimport zipfileimport uuidimport timeimport requestsfrom pydub import AudioSegmentfrom PIL import Imageimport pyheif1 unmodified lineapp = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)BASE_TEMP_DIR = "/tmp/media_master"os.makedirs(BASE_TEMP_DIR, exist_ok=True)# 進行状況管理tasks: Dict[str, dict] = {}# --- Colab サーバーのURL (実行時に書き換わるか、環境変数から取得) ---# Colab側で発行された ngrok などのURLをここに入れますCOLAB_URL = os.getenv("COLAB_URL", "")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 lineos.makedirs(output_path, exist_ok=True)try:# --- YouTube 処理 (Colabへ委託) ---if tool_id == 'youtube' and url_text:if not COLAB_URL:raise Exception("ColabサーバーのURLが設定されていません。Hugging FaceのSettingsからCOLAB_URLを設定してください。")urls = [u.strip() for u in url_text.split('\n') if u.strip()]tasks[task_id]["last_log"] = f"Colabサーバーへリクエスト送信中... (計{len(urls)}件)"# Colab側のAPIを叩く (一括処理用)try:response = requests.post(f"{COLAB_URL.rstrip('/')}/batch-download",json={"urls": urls},timeout=600 # 長めのタイムアウト)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]["progress"] = 90except Exception as e:raise Exception(f"Colab接続失敗: {str(e)}")# --- 通常のメディア変換処理 (HFS内で実行) ---else:for i, fname in enumerate(filenames):in_f = os.path.join(input_path, fname)5 unmodified linesimg = 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':audio = AudioSegment.from_file(in_f)audio.export(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.mp3"), format="mp3")6 unmodified linesfor j, image in enumerate(images):image.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}_{j}.png"), "PNG")# --- 最終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 linesexcept Exception as e:tasks[task_id].update({"status": "failed", "error": str(e)})@app.get("/")async def read_index():with open("index.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())@app.post("/api/convert")async def convert_start(background_tasks: BackgroundTasks, tool_id: str = Form(...), url: str = Form(None), files: 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 != ""}12345678910111213141 unmodified line161718192021221 unmodified line242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111125 unmodified lines1181191201211221231246 unmodified lines1311321331341351361375 unmodified lines14314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317422 unmodified lines197198199200201from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Bodyfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dict, Optionalimport osimport shutilimport zipfileimport uuidimport timeimport requestsimport sqlite3from pydub import AudioSegmentfrom PIL import Imageimport pyheif1 unmodified lineapp = FastAPI()# CORS設定app.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)# パス設定BASE_TEMP_DIR = "/tmp/media_master"DB_PATH = "colab_config.db"os.makedirs(BASE_TEMP_DIR, exist_ok=True)# 進行状況管理(メモリ上)tasks: Dict[str, dict] = {}# --- データベース初期化 ---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 lineos.makedirs(output_path, exist_ok=True)try:current_colab_url = get_colab_url()# YouTube 処理 (Colabへ委託)if tool_id == 'youtube' and url_text: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)}件)"try:response = requests.post(f"{current_colab_url.rstrip('/')}/batch-download",json={"urls": urls},timeout=900)if response.status_code != 200:raise Exception(f"Colabエラー: {response.text}")colab_zip = os.path.join(session_path, "colab_result.zip")with open(colab_zip, "wb") as f:f.write(response.content)with zipfile.ZipFile(colab_zip, 'r') as z:z.extractall(output_path)tasks[task_id]["last_log"] = "Colabからの処理が完了しました"tasks[task_id]["progress"] = 90except Exception as e:raise Exception(f"Colab接続失敗 (URLが古い可能性があります): {str(e)}")# 通常のメディア変換処理else:for i, fname in enumerate(filenames):in_f = os.path.join(input_path, fname)5 unmodified linesimg = 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 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 linesfor j, image in enumerate(images):image.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}_{j}.png"), "PNG")# 最終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 linesexcept 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: 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():url = get_colab_url()return {"youtube_enabled": url != "", "colab_url": url}
app.py+77-24