Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines1516171819202122232425262728293031321 unmodified line34353637383940414243445 unmodified lines505152535455568 unmodified lines656667686970717273747576777879808182838485868788899091929394959635 unmodified lines1321331341351361371384 unmodified lines14314414514614714814915014 unmodified linesfrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDL# --- DNS解決の強化 (Hugging Face環境対策) ---# システムのDNSが不安定な場合、IPを直接解決する試みdef resolve_youtube_dns():try:# youtube.com のIPを事前に引いておく(キャッシュ効果)socket.gethostbyname('www.youtube.com')except:passapp = FastAPI()# CORS設定app.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)# 一時フォルダの設定BASE_TEMP_DIR = "/tmp/media_master"os.makedirs(BASE_TEMP_DIR, exist_ok=True)# タスク管理tasks: Dict[str, dict] = {}ALLOWED_EXTENSIONS = {5 unmodified lines}def cleanup_task(task_id: str, delay: int = 3600):"""1時間後にファイルを削除"""time.sleep(delay)path = os.path.join(BASE_TEMP_DIR, task_id)if os.path.exists(path):8 unmodified linesos.makedirs(output_path, exist_ok=True)try:tasks[task_id].update({"status": "processing", "progress": 30, "last_log": "エンジンの初期化中..."})if tool_id == 'youtube':tasks[task_id].update({"last_log": "YouTubeに接続中 (DNS再試行)..."})resolve_youtube_dns()# yt-dlp のオプションを極限まで強化ydl_opts = {'format': 'best','outtmpl': f'{output_path}/%(title)s.%(ext)s','quiet': True,'no_warnings': True,'source_address': '0.0.0.0', # IPv4を強制'retries': 20, # リトライ回数を大幅増'fragment_retries': 20,'skip_download': False,'nocheckcertificate': True, # SSL証明書エラーを無視'socket_timeout': 30, # タイムアウトを長めに設定}# ダウンロード実行with YoutubeDL(ydl_opts) as ydl:# extract_info を呼ぶ際に download=True にする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})35 unmodified linesimg.save(os.path.join(output_path, f"{base}_{j}.png"), "PNG")tasks[task_id].update({"progress": 85})# ZIP圧縮zip_path = os.path.join(session_path, "result.zip")with zipfile.ZipFile(zip_path, 'w') as z:for root, _, files_in_dir in os.walk(output_path):4 unmodified linesexcept Exception as e:error_msg = str(e)if "Failed to resolve" in error_msg or "Errno -5" in error_msg:error_msg = "YouTubeへの接続がタイムアウトしました。Hugging Faceのサーバー混雑が原因の可能性があります。しばらく時間を置いてから再度お試しください。"tasks[task_id].update({"status": "failed", "error": error_msg})@app.post("/api/convert")14 unmodified lines151617181920212223242526272829301 unmodified line3233343536373839405 unmodified lines4647484950518 unmodified lines60616263646566676869707172737475767778798081828384858687888990919235 unmodified lines1281291301311321334 unmodified lines13813914014114214314414514 unmodified linesfrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDL# --- DNS解決の強化 ---def resolve_youtube_dns():try:socket.gethostbyname('www.youtube.com')socket.gethostbyname('youtube.com')except:passapp = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)BASE_TEMP_DIR = "/tmp/media_master"os.makedirs(BASE_TEMP_DIR, exist_ok=True)tasks: Dict[str, dict] = {}ALLOWED_EXTENSIONS = {5 unmodified lines}def cleanup_task(task_id: str, delay: int = 3600):time.sleep(delay)path = os.path.join(BASE_TEMP_DIR, task_id)if os.path.exists(path):8 unmodified linesos.makedirs(output_path, exist_ok=True)try:tasks[task_id].update({"status": "processing", "progress": 30, "last_log": "準備中..."})if tool_id == 'youtube':tasks[task_id].update({"last_log": "YouTubeに接続を試行しています..."})resolve_youtube_dns()# yt-dlp のオプションをさらに強化(ブラウザ偽装を追加)ydl_opts = {'format': 'best','outtmpl': f'{output_path}/%(title)s.%(ext)s','quiet': True,'no_warnings': True,'source_address': '0.0.0.0','retries': 15,'fragment_retries': 15,'nocheckcertificate': True,'socket_timeout': 60,# --- ブラウザを装うためのヘッダー設定 ---'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36','referer': 'https://www.google.com/','sleep_interval': 1, # リトライ間に少し待機}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})35 unmodified linesimg.save(os.path.join(output_path, f"{base}_{j}.png"), "PNG")tasks[task_id].update({"progress": 85})zip_path = os.path.join(session_path, "result.zip")with zipfile.ZipFile(zip_path, 'w') as z:for root, _, files_in_dir in os.walk(output_path):4 unmodified linesexcept Exception as e:error_msg = str(e)if "Failed to resolve" in error_msg or "Errno -5" in error_msg or "timed out" in error_msg.lower():error_msg = "YouTubeへの接続が現在制限されているか、タイムアウトしました。Hugging Faceの無料サーバー特有の制限によるものです。設定を変更して再ビルドしましたので、再度お試しいただくか、少し時間を置いてください。"tasks[task_id].update({"status": "failed", "error": error_msg})@app.post("/api/convert")
app.py+17-22