Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines15161718192031 unmodified lines5253545556576 unmodified lines6465666768697071727374757677787980818283848586878889909192939444 unmodified lines13914014114214314414514 unmodified linesfrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDLdef resolve_youtube_dns():try:socket.gethostbyname('www.youtube.com')31 unmodified linesif task_id in tasks:del tasks[task_id]def process_task(task_id: str, tool_id: str, url: str = None, filenames: List[str] = None):session_path = os.path.join(BASE_TEMP_DIR, task_id)input_path = os.path.join(session_path, "input")6 unmodified linesif tool_id == 'youtube':tasks[task_id].update({"last_log": "YouTubeに接続を試行しています..."})resolve_youtube_dns()# YouTubeの制限を回避するためのさらに慎重な設定ydl_opts = {'format': 'best','outtmpl': f'{output_path}/%(title)s.%(ext)s','quiet': True,'no_warnings': True,'source_address': '0.0.0.0','retries': 30, # リトライを大幅に増やす'fragment_retries': 30,'nocheckcertificate': True,'socket_timeout': 120, # タイムアウトを倍増'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36','referer': 'https://www.google.com/','sleep_interval': 3, # リトライ間隔を長めにして警戒を解く'max_sleep_interval': 10,# 'cookiefile': 'youtube.com_cookies.txt', # 方法2を使う場合はここを有効化}with YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=True)title = info.get('title', 'video')tasks[task_id].update({"last_log": f"取得完了: {title}"})tasks[task_id].update({"progress": 85})else:files_to_process = [os.path.join(input_path, f) for f in filenames]44 unmodified linesexcept Exception as e:error_msg = str(e)if any(x in error_msg for x in ["Failed to resolve", "Errno -5", "timed out", "IncompleteRead"]):error_msg = "YouTubeへの接続がタイムアウトしました。Hugging Faceの無料サーバーのIPが一時的に制限されているようです。少し時間をおいて再送するか、SettingsからSpaceをRestart(再起動)してみてください。"tasks[task_id].update({"status": "failed", "error": error_msg})@app.post("/api/convert")14 unmodified lines1516171819202122232425262728293031 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261276 unmodified lines13413513613713813914014114214314414514614744 unmodified lines19219319419519619719819920020120214 unmodified linesfrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDL# yt-dlpを起動時に自動で最新版へアップグレード(方法2)try:subprocess.run(["pip", "install", "--upgrade", "yt-dlp"],capture_output=True,timeout=60)except Exception:passdef resolve_youtube_dns():try:socket.gethostbyname('www.youtube.com')31 unmodified linesif task_id in tasks:del tasks[task_id]def try_youtube_download(url: str, output_path: str, task_id: str) -> dict:"""方法4: 複数のplayer_clientを順番に試すフォールバック付きダウンロード。成功した場合はydl.extract_info()の結果を返す。全て失敗した場合は最後の例外をraiseする。"""# 試行するクライアントの優先順位clients = ['mweb', 'web', 'android', 'ios']last_exception = Nonefor client in clients:try:tasks[task_id].update({"last_log": f"YouTubeへ接続試行中 (client={client})..."})ydl_opts = {'format': 'best','outtmpl': f'{output_path}/%(title)s.%(ext)s','quiet': True,'no_warnings': True,'source_address': '0.0.0.0','retries': 5,'fragment_retries': 5,'nocheckcertificate': True,'socket_timeout': 60,'sleep_interval': 2,'max_sleep_interval': 6,'extractor_args': {'youtube': {'player_client': [client],}},'http_headers': {'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) ''AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/124.0.0.0 Safari/537.36'),},}with YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=True)return info # 成功したら即返すexcept Exception as e:last_exception = etasks[task_id].update({"last_log": f"client={client} 失敗、次を試します..."})# 次のクライアントを試す前に少し待機time.sleep(2)# 全クライアントが失敗raise last_exceptiondef process_task(task_id: str, tool_id: str, url: str = None, filenames: List[str] = None):session_path = os.path.join(BASE_TEMP_DIR, task_id)input_path = os.path.join(session_path, "input")6 unmodified linesif tool_id == 'youtube':tasks[task_id].update({"last_log": "YouTubeに接続を試行しています..."})resolve_youtube_dns()# フォールバック付きダウンロード(方法4)を呼び出すinfo = try_youtube_download(url, output_path, task_id)title = info.get('title', 'video')tasks[task_id].update({"progress": 85,"last_log": f"取得完了: {title}"})else:files_to_process = [os.path.join(input_path, f) for f in filenames]44 unmodified linesexcept Exception as e:error_msg = str(e)if any(x in error_msg for x in ["Failed to resolve", "Errno -5", "timed out", "IncompleteRead"]):error_msg = ("全ての接続方法を試みましたが、YouTubeへの接続に失敗しました。""Hugging Faceの無料サーバーのIPが現在制限されているようです。""しばらく時間をおいて再試行するか、SettingsからSpaceをRestart(再起動)してみてください。")tasks[task_id].update({"status": "failed", "error": error_msg})@app.post("/api/convert")
app.py+83-26