Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines891011121314151617181920212223242526272829303132333435369 unmodified lines4647484950511 unmodified line535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410511 unmodified lines1171181191201211221231 unmodified line1251261271281291301315 unmodified lines1371381391401411421437 unmodified linesimport uuidimport timeimport subprocessimport socketfrom pydub import AudioSegmentfrom PIL import Imageimport pyheiffrom 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")1 unmodified linetry: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':for i, fp in enumerate(files_to_process):heif_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")11 unmodified linesfor 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):1 unmodified linetasks[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)):5 unmodified lineswith 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}7 unmodified lines891011121314151617189 unmodified lines282930313233343536373839404142431 unmodified line45464748495051525354555657585960616263646566676869707172737475767778798081828384858611 unmodified lines98991001011021031 unmodified line1051061071081091101115 unmodified lines1171181191201211221237 unmodified linesimport uuidimport timeimport subprocessimport requestsfrom pydub import AudioSegmentfrom PIL import Imageimport pyheiffrom pdf2image import convert_from_pathapp = FastAPI()9 unmodified linestasks: Dict[str, dict] = {}# --- Colab APIのURLを設定 ---COLAB_API_URL = os.getenv("COLAB_URL")@app.get("/api/config")async def get_config():"""フロントエンドに外部ダウンローダーの状態を伝える"""return {"youtube_enabled": bool(COLAB_API_URL and COLAB_API_URL.startswith("http"))}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")1 unmodified linetry:if tool_id == 'youtube':if not COLAB_API_URL:raise Exception("外部ダウンローダーが設定されていません。")tasks[task_id].update({"last_log": "外部サーバー(Colab)に接続中..."})# Colabにリクエストresponse = requests.post(f"{COLAB_API_URL.rstrip('/')}/download",data={"url": url},stream=True,timeout=600 # 10分)if response.status_code != 200:raise Exception(f"外部サーバーエラー: {response.status_code}")# ファイル名の取得と保存content_disposition = response.headers.get('Content-Disposition', '')filename = "video.mp4"if 'filename=' in content_disposition:filename = content_disposition.split('filename=')[-1].strip('"')save_path = os.path.join(output_path, filename)with open(save_path, "wb") as f:for chunk in response.iter_content(chunk_size=8192):f.write(chunk)tasks[task_id].update({"last_log": f"取得成功: {filename}", "progress": 80})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':for fp in files_to_process:heif_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")11 unmodified linesfor 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_path = os.path.join(session_path, "result.zip")with zipfile.ZipFile(zip_path, 'w') as z:for f in os.listdir(output_path):1 unmodified linetasks[task_id].update({"status": "completed", "progress": 100})except Exception as e:tasks[task_id].update({"status": "failed", "error": str(e)})@app.post("/api/convert")async def convert_start(background_tasks: BackgroundTasks, tool_id: str = Form(...), url: str = Form(None), files: List[UploadFile] = File(None)):5 unmodified lineswith 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.py+39-59