Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines78910111011121314161718192021222324252627282930313233343536373839401516177 unmodified lines252627282930313233343536371 unmodified line39404163424365666768694445464771727374757677787980818283848586878889909192939495969798991004849505152535455565758596061626364656667681026970717273741047576777879109808182836 unmodified lines909192122939495969798991291301311321001011021031041051061361071081091391401411421431101111121131471481141151161 unmodified line11811912012112212312415912512612712812916313013113213310 unmodified lines1441451461801471486 unmodified linesimport zipfileimport uuidimport timeimport subprocessimport socketimport requestsfrom 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 True except 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] = {}
# --- 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 line os.makedirs(output_path, exist_ok=True)
try: # YouTube 複数ダウンロード対応 # --- YouTube 処理 (Colabへ委託) --- if tool_id == 'youtube' and url_text: # 事前にネットワーク疎通を確認 if not check_network(): tasks[task_id]["last_log"] = "警告: ネットワーク不安定(DNS解決に失敗)。数秒後に再試行します..." time.sleep(5)
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()] 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 = 3 for 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_PATH with 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"] = 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"] = "全てのYouTube動画を取得しました" 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)) * 70) tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60) if tool_id == 'heic-jpg': heif_file = pyheif.read(in_f)6 unmodified lines elif 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=[]) 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"] = "ファイルを圧縮しています..." zip_path = os.path.join(session_path, "result.zip") with zipfile.ZipFile(zip_path, 'w') as z: # --- 最終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": "完了"}) 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}) tasks[task_id].update({"status": "failed", "error": str(e)})
@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: 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": "リクエストを受付しました"} 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} # ColabのURLが設定されているかどうかをフロントエンドに伝える return {"youtube_enabled": COLAB_URL != ""}app.py+50-82