Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines678910101112138 unmodified lines2223242526252627282930303132333435363738394041424344313233343547484936373839404142435354555657444546596047484962635051525354555657585960616263656664656667686970717273746875767778798081828384858687888990919293947071727374757695969798991001011021031041051061071081098111011183112113861141151161171181199112012112212312495961251261271281291301311324 unmodified lines1371381391091101111121401411421431441451461471485 unmodified linesimport shutilimport zipfileimport uuidimport timeimport requestsfrom pathlib import Pathfrom pydub import AudioSegmentfrom PIL import Imageimport pyheif8 unmodified lines allow_headers=["*"],)
BASE_TEMP_DIR = Path("/tmp/media_master")BASE_TEMP_DIR.mkdir(parents=True, exist_ok=True)BASE_TEMP_DIR = "/tmp/media_master"os.makedirs(BASE_TEMP_DIR, exist_ok=True)
# 進行状況管理tasks: Dict[str, dict] = {}
# --- FirestoreからURLを取得する関数 ---def fetch_colab_url(): try: # Colab側で設定したのと同じプロジェクトIDを使用 project_id = "YOUR_PROJECT_ID" res = requests.get( f"https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents/configs/colab_config", timeout=5 ) if res.status_code == 200: data = res.json() return data['fields']['url']['stringValue'] except Exception: pass return os.getenv("COLAB_URL", "")# --- 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 = BASE_TEMP_DIR / task_id output_path = session_path / "output" output_path.mkdir(parents=True, exist_ok=True) session_path = os.path.join(BASE_TEMP_DIR, task_id) input_path = os.path.join(session_path, "input") output_path = os.path.join(session_path, "output") os.makedirs(output_path, exist_ok=True)
try: # --- YouTube 処理 (Colabへ委託) --- if tool_id == 'youtube' and url_text: # 実行直前に最新URLを取得 current_colab_url = fetch_colab_url() if not current_colab_url: raise Exception("ColabのURLが取得できません。Colabが起動しているか確認してください。") if not COLAB_URL: raise Exception("ColabサーバーのURLが設定されていません。Hugging FaceのSettingsからCOLAB_URLを設定してください。") tasks[task_id].update({"progress": 30, "last_log": "Colabへ転送中..."}) response = requests.post(f"{current_colab_url}/api/youtube", data={"url": url_text}, timeout=300) urls = [u.strip() for u in url_text.split('\n') if u.strip()] tasks[task_id]["last_log"] = f"Colabサーバーへリクエスト送信中... (計{len(urls)}件)" if response.status_code == 200: with open(output_path / "youtube_video.mp4", "wb") as f: # 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) else: raise Exception(f"Colabエラー: {response.status_code}") # ZIPを展開してoutputディレクトリへ移動 with zipfile.ZipFile(colab_zip, 'r') as z: z.extractall(output_path) tasks[task_id]["last_log"] = "Colabからのダウンロードが完了しました" tasks[task_id]["progress"] = 90
except 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) tasks[task_id]["last_log"] = f"処理中: {fname}" tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60) if tool_id == 'heic-jpg': heif_file = pyheif.read(in_f) 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': audio = AudioSegment.from_file(in_f) audio.export(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.mp3"), format="mp3") elif tool_id == 'jpeg-pdf': img = Image.open(in_f).convert('RGB') img.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.pdf"), "PDF")
# 完了処理 out_files = list(output_path.glob("*")) if len(out_files) > 1: with zipfile.ZipFile(session_path / "result.zip", 'w') as z: for f in out_files: z.write(f, f.name) elif len(out_files) == 1: shutil.copy(out_files[0], session_path / "result.bin") elif tool_id == 'pdf-png': 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")
# --- 最終ZIP作成 --- tasks[task_id]["last_log"] = "結果をまとめています..." final_zip = os.path.join(session_path, "result.zip") with zipfile.ZipFile(final_zip, 'w') as z: for f in os.listdir(output_path): z.write(os.path.join(output_path, f), f) tasks[task_id].update({"status": "completed", "progress": 100, "last_log": "完了しました"})
except Exception as e: tasks[task_id].update({"status": "failed", "error": str(e), "last_log": f"エラー: {str(e)}"}) tasks[task_id].update({"status": "failed", "error": str(e)})
# --- 以下、APIエンドポイント群 (以前の修正案と同様) ---@app.get("/")async def read_index(): return HTMLResponse(content=Path("index.html").read_text(encoding="utf-8")) 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()) (BASE_TEMP_DIR / task_id / "input").mkdir(parents=True, exist_ok=True) os.makedirs(os.path.join(BASE_TEMP_DIR, task_id, "input"), exist_ok=True) fnames = [] if files: for f in files: if not f.filename: continue with open(BASE_TEMP_DIR / task_id / "input" / f.filename, "wb") as buf: file_path = os.path.join(BASE_TEMP_DIR, task_id, "input", f.filename) with open(file_path, "wb") as buf: shutil.copyfileobj(f.file, buf) fnames.append(f.filename) tasks[task_id] = {"status": "processing", "progress": 10, "last_log": "タスクを開始しました"} background_tasks.add_task(process_task, task_id, tool_id, url, fnames) return {"task_id": task_id}4 unmodified lines
@app.get("/api/download/{task_id}")async def download_result(task_id: str): s_path = BASE_TEMP_DIR / task_id if (s_path / "result.zip").exists(): return FileResponse(s_path / "result.zip", filename="result.zip") if (s_path / "result.bin").exists(): return FileResponse(s_path / "result.bin", filename="result.bin") raise HTTPException(status_code=404) 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") raise HTTPException(status_code=404, detail="File not found")
@app.get("/api/config")async def get_config(): # ColabのURLが設定されているかどうかをフロントエンドに伝える return {"youtube_enabled": COLAB_URL != ""}app.py+86-50