Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines6789101112138 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001014 unmodified lines1061071081091101111125 unmodified linesimport shutilimport zipfileimport uuidimport requestsfrom pathlib import Pathfrom pydub import AudioSegmentfrom PIL import Imageimport pyheif8 unmodified linesallow_headers=["*"],)BASE_TEMP_DIR = Path("/tmp/media_master")BASE_TEMP_DIR.mkdir(parents=True, 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:passreturn 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_idoutput_path = session_path / "output"output_path.mkdir(parents=True, exist_ok=True)try:if tool_id == 'youtube' and url_text:# 実行直前に最新URLを取得current_colab_url = fetch_colab_url()if not current_colab_url:raise Exception("ColabのURLが取得できません。Colabが起動しているか確認してください。")tasks[task_id].update({"progress": 30, "last_log": "Colabへ転送中..."})response = requests.post(f"{current_colab_url}/api/youtube", data={"url": url_text}, timeout=300)if response.status_code == 200:with open(output_path / "youtube_video.mp4", "wb") as f:f.write(response.content)else:raise Exception(f"Colabエラー: {response.status_code}")# ... (他の変換ロジックは変更なし) ...# 完了処理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")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)}"})# --- 以下、APIエンドポイント群 (以前の修正案と同様) ---@app.get("/")async def read_index():return HTMLResponse(content=Path("index.html").read_text(encoding="utf-8"))@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)fnames = []if files:for f in files:if not f.filename: continuewith open(BASE_TEMP_DIR / task_id / "input" / f.filename, "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_idif (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)5 unmodified lines6789101112138 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311324 unmodified lines1371381391401411421431441451461471485 unmodified linesimport shutilimport zipfileimport uuidimport timeimport requestsfrom pydub import AudioSegmentfrom PIL import Imageimport pyheif8 unmodified linesallow_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")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: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)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")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)})@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)fnames = []if files:for f in files: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):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