Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142437 unmodified lines51525354555657581 unmodified line606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111126 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511 unmodified line15315415515615715815916016116216316416516610 unmodified lines1771781791806 unmodified linesimport zipfileimport uuidimport timeimport subprocessimport socketfrom pydub import AudioSegmentfrom PIL import Imageimport pyheiffrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDL# --- DNS解決の確認 (ネットワークの疎通確認) ---def check_network():try:# youtube.com のIPが引けるか確認socket.gethostbyname('www.youtube.com')return Trueexcept socket.gaierror:return False# --- Cookieファイルパス ---COOKIE_FILE_PATH = "/tmp/youtube_cookies.txt"def setup_cookies():yt_cookies = os.getenv("YT_COOKIES")if not yt_cookies:return False, "Secret 'YT_COOKIES' が設定されていません。"try:content = yt_cookies.strip()with open(COOKIE_FILE_PATH, "w", encoding="utf-8") as f:f.write(content)return True, "Cookieを適用しました。"except Exception as e:return False, f"Cookieエラー: {str(e)}"app = FastAPI()7 unmodified linesBASE_TEMP_DIR = "/tmp/media_master"os.makedirs(BASE_TEMP_DIR, exist_ok=True)tasks: Dict[str, dict] = {}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 複数ダウンロード対応if tool_id == 'youtube' and url_text:# 事前にネットワーク疎通を確認if not check_network():tasks[task_id]["last_log"] = "警告: ネットワーク不安定(DNS解決に失敗)。数秒後に再試行します..."time.sleep(5)urls = [u.strip() for u in url_text.split('\n') if u.strip()]total = len(urls)for i, url in enumerate(urls):tasks[task_id]["last_log"] = f"ダウンロード中 ({i+1}/{total}): {url[:30]}..."tasks[task_id]["progress"] = int(20 + (i / total) * 70)# エラー発生時の再試行ループmax_retries = 3for attempt in range(max_retries):try:ydl_opts = {'format': 'best','outtmpl': f'{output_path}/%(title)s.%(ext)s','noplaylist': True,'quiet': True,'no_warnings': True,# 接続タイムアウト設定を追加'socket_timeout': 30,}if os.path.exists(COOKIE_FILE_PATH):ydl_opts['cookiefile'] = COOKIE_FILE_PATHwith YoutubeDL(ydl_opts) as ydl:ydl.download([url])break # 成功したらループを抜けるexcept Exception as e:if attempt < max_retries - 1:tasks[task_id]["last_log"] = f"再試行中 ({attempt+1}/{max_retries}): {url[:20]}"time.sleep(3) # 3秒待機して再試行else:raise e # 最終的に失敗した場合はエラーを投げるtasks[task_id]["last_log"] = "全てのYouTube動画を取得しました"# 画像・音声変換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)) * 70)if tool_id == 'heic-jpg':heif_file = pyheif.read(in_f)6 unmodified lineselif tool_id == 'jpeg-pdf':img = Image.open(in_f).convert('RGB')img.save(os.path.join(output_path, "combined.pdf"), save_all=True, append_images=[])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"] = "ファイルを圧縮しています..."zip_path = os.path.join(session_path, "result.zip")with zipfile.ZipFile(zip_path, '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:# エラーメッセージを分かりやすく表示error_msg = str(e)if "No address associated with hostname" in error_msg:error_msg = "ネットワークエラー: サーバーが一時的にYouTubeに接続できませんでした。少し待ってから再度お試しください。"tasks[task_id].update({"status": "failed", "error": error_msg})@app.get("/")async def read_index():# Cookieをバックグラウンドでセットアップsetup_cookies()with open("index.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())1 unmodified lineasync 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:with open(os.path.join(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}10 unmodified lines@app.get("/api/config")async def get_config():return {"youtube_enabled": os.getenv("YT_COOKIES") is not None}6 unmodified lines78910111213141516177 unmodified lines252627282930313233343536371 unmodified line3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182836 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161 unmodified line11811912012112212312412512612712812913013113213310 unmodified lines1441451461471486 unmodified linesimport zipfileimport uuidimport timeimport requestsfrom pydub import AudioSegmentfrom PIL import Imageimport pyheiffrom pdf2image import convert_from_pathapp = FastAPI()7 unmodified linesBASE_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)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)6 unmodified lineselif 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())1 unmodified lineasync 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}10 unmodified lines@app.get("/api/config")async def get_config():# ColabのURLが設定されているかどうかをフロントエンドに伝えるreturn {"youtube_enabled": COLAB_URL != ""}
app.py+50-82