Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines15161718192021222324252627282930313233343536373839404142434445469 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified line12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221314 unmodified linesfrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDL# --- 環境変数からCookieを復元する処理 ---COOKIE_FILE_PATH = "/tmp/youtube_cookies.txt"def setup_cookies():yt_cookies = os.getenv("YT_COOKIES")if not yt_cookies:return False, "Hugging FaceのSecret 'YT_COOKIES' が設定されていません。"try:# 文字列の前後にある余計な空白を削除して書き込みcontent = yt_cookies.strip()if not content.startswith("# Netscape"):return False, "Cookieの形式が正しくありません(# Netscape で始まる必要があります)。"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)}"def resolve_youtube_dns():try:socket.gethostbyname('www.youtube.com')socket.gethostbyname('youtube.com')except:passapp = FastAPI()9 unmodified linestasks: Dict[str, dict] = {}ALLOWED_EXTENSIONS = {'heic-jpg': ['.heic', '.HEIC'],'m4a-mp3': ['.m4a'],'mp4-mp3': ['.mp4'],'jpeg-pdf': ['.jpg', '.jpeg', '.JPG', '.JPEG'],'pdf-png': ['.pdf']}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):shutil.rmtree(path)if 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")output_path = os.path.join(session_path, "output")os.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()success, msg = setup_cookies()tasks[task_id].update({"last_log": msg})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,'nocheckcertificate': True,'socket_timeout': 60,'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/',}if success:ydl_opts['cookiefile'] = COOKIE_FILE_PATHtasks[task_id].update({"last_log": "認証情報を適用しました。ダウンロードを開始します..."})else:tasks[task_id].update({"last_log": "警告: Cookieなしで接続を試みます..."})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]if tool_id == 'heic-jpg':1 unmodified lineheif_file = pyheif.read(fp)image = Image.frombytes(heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride)image.save(os.path.join(output_path, os.path.basename(fp).rsplit('.', 1)[0] + ".jpg"), "JPEG")tasks[task_id].update({"progress": 30 + int(50 * (i+1)/len(files_to_process))})elif tool_id == 'm4a-mp3':for i, fp in enumerate(files_to_process):audio = AudioSegment.from_file(fp, format="m4a")audio.export(os.path.join(output_path, os.path.basename(fp).rsplit('.', 1)[0] + ".mp3"), format="mp3")tasks[task_id].update({"progress": 30 + int(50 * (i+1)/len(files_to_process))})elif tool_id == 'mp4-mp3':for i, fp in enumerate(files_to_process):out_fp = os.path.join(output_path, os.path.basename(fp).rsplit('.', 1)[0] + ".mp3")subprocess.run(['ffmpeg', '-i', fp, '-vn', '-ab', '192k', '-y', out_fp], check=True)tasks[task_id].update({"progress": 30 + int(50 * (i+1)/len(files_to_process))})elif tool_id == 'jpeg-pdf':image_list = []for fp in sorted(files_to_process):image_list.append(Image.open(fp).convert('RGB'))if image_list:image_list[0].save(os.path.join(output_path, "merged.pdf"), save_all=True, append_images=image_list[1:])tasks[task_id].update({"progress": 85})elif tool_id == 'pdf-png':for fp in files_to_process:images = convert_from_path(fp)base = os.path.splitext(os.path.basename(fp))[0]for j, img in enumerate(images):img.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):for f in files_in_dir:z.write(os.path.join(root, f), f)tasks[task_id].update({"status": "completed", "progress": 100, "last_log": "全ての処理が完了しました"})except Exception as e:error_msg = str(e)if "403" in error_msg:error_msg = "YouTubeから拒否されました(403)。Secretに設定したCookieが古いか、取得したアカウントが制限されています。"elif any(x in error_msg.lower() for x in ["timeout", "resolve", "errno -5", "connection"]):error_msg = f"ネットワークエラー(Timeout/DNS)。サーバーのIPが遮断されている可能性があります。SpaceをSettingsからRestartしてください。詳細: {error_msg[:100]}"tasks[task_id].update({"status": "failed", "error": error_msg})@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())session_path = os.path.join(BASE_TEMP_DIR, task_id)input_path = os.path.join(session_path, "input")os.makedirs(input_path, exist_ok=True)saved_filenames = []if files:for file in files:file_path = os.path.join(input_path, file.filename)with open(file_path, "wb") as buffer:shutil.copyfileobj(file.file, buffer)saved_filenames.append(file.filename)tasks[task_id] = {"status": "accepted", "progress": 10, "last_log": "リクエストを受理しました"}background_tasks.add_task(process_task, task_id, tool_id, url, saved_filenames)background_tasks.add_task(cleanup_task, task_id)return {"task_id": task_id}@app.get("/api/status/{task_id}")async def get_status(task_id: str):return tasks.get(task_id, {"status": "failed", "error": "Task not found"})@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=f"result.zip")raise HTTPException(status_code=404)@app.get("/", response_class=HTMLResponse)async def serve_index():try:with open("index.html", "r", encoding="utf-8") as f:return f.read()except FileNotFoundError:return "<h1>Error: index.html not found</h1>"14 unmodified lines151617181920212223242526272829303132333435369 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011 unmodified line10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115214 unmodified linesfrom pdf2image import convert_from_pathfrom yt_dlp import YoutubeDL# --- Cookieファイルパス ---COOKIE_FILE_PATH = "/tmp/youtube_cookies.txt"def setup_cookies():yt_cookies = os.getenv("YT_COOKIES")if not yt_cookies:return False, "Hugging FaceのSecret 'YT_COOKIES' が設定されていません。"try:content = yt_cookies.strip()if not content.startswith("# Netscape"):return False, "Cookieの形式が不正です。(# Netscapeで始まる必要があります)"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()9 unmodified linestasks: Dict[str, dict] = {}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)output_path = os.path.join(session_path, "output")os.makedirs(output_path, exist_ok=True)try:if tool_id == 'youtube':tasks[task_id].update({"last_log": "最新の回避策を適用中..."})success, cookie_msg = setup_cookies()# ネットワークエラー対策: DNSの事前解決を試みるtry:socket.gethostbyname('www.youtube.com')except:passydl_opts = {'format': 'best','outtmpl': f'{output_path}/%(title)s.%(ext)s','quiet': True,'no_warnings': True,# --- 最新の規制回避設定 ---'extractor_args': {'youtube': {'player_client': ['android', 'web'],'skip': ['dash', 'hls'],}},'http_headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language': 'ja,en-US;q=0.7,en;q=0.3',},'retries': 10,'socket_timeout': 30,}if success:ydl_opts['cookiefile'] = COOKIE_FILE_PATHtasks[task_id].update({"last_log": "Cookieを使用してダウンロード中..."})with YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=True)tasks[task_id].update({"last_log": f"完了: {info.get('title')}"})tasks[task_id].update({"progress": 90})else:# 他のツールの処理(省略せずに元のロジックを維持)input_path = os.path.join(session_path, "input")files_to_process = [os.path.join(input_path, f) for f in filenames]if tool_id == 'heic-jpg':1 unmodified lineheif_file = pyheif.read(fp)image = Image.frombytes(heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride)image.save(os.path.join(output_path, os.path.basename(fp).rsplit('.', 1)[0] + ".jpg"), "JPEG")elif tool_id == 'm4a-mp3':for fp in files_to_process:AudioSegment.from_file(fp, format="m4a").export(os.path.join(output_path, os.path.basename(fp).rsplit('.', 1)[0] + ".mp3"), format="mp3")elif tool_id == 'mp4-mp3':for fp in files_to_process:subprocess.run(['ffmpeg', '-i', fp, '-vn', '-ab', '192k', '-y', os.path.join(output_path, os.path.basename(fp).rsplit('.', 1)[0] + ".mp3")])elif tool_id == 'jpeg-pdf':imgs = [Image.open(fp).convert('RGB') for fp in sorted(files_to_process)]if imgs: imgs[0].save(os.path.join(output_path, "merged.pdf"), save_all=True, append_images=imgs[1:])elif tool_id == 'pdf-png':for fp in files_to_process:for j, img in enumerate(convert_from_path(fp)):img.save(os.path.join(output_path, f"{os.path.splitext(os.path.basename(fp))[0]}_{j}.png"), "PNG")# ZIP圧縮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})except Exception as e:tasks[task_id].update({"status": "failed", "error": f"エラー: {str(e)[:200]}"})@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: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}@app.get("/api/status/{task_id}")async def get_status(task_id: str): return tasks.get(task_id, {"status": "failed"})@app.get("/api/download/{task_id}")async def download(task_id: str): return FileResponse(os.path.join(BASE_TEMP_DIR, task_id, "result.zip"))@app.get("/", response_class=HTMLResponse)async def serve_index():with open("index.html", "r", encoding="utf-8") as f: return f.read()
app.py+57-118