Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines89101111121314151617181920212223242526272829303132331617189 unmodified lines282930313233343536373839404142431 unmodified line45464756574849505960616263646566676869707172737475767778798081828384515286878853545556575859609091926162636465666768699470717273747576779778798081821028384858611 unmodified lines98991001201011021031 unmodified line1051061071281081091101115 unmodified lines1171181191401201211221237 unmodified linesimport uuidimport timeimport subprocessimport socketimport requestsfrom 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 lines
tasks: 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 line try: if tool_id == 'youtube': tasks[task_id].update({"last_log": "最新の回避策を適用中..."}) success, cookie_msg = setup_cookies() if not COLAB_API_URL: raise Exception("外部ダウンローダーが設定されていません。") # ネットワークエラー対策: DNSの事前解決を試みる try: socket.gethostbyname('www.youtube.com') except: pass
ydl_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, } tasks[task_id].update({"last_log": "外部サーバー(Colab)に接続中..."}) if success: ydl_opts['cookiefile'] = COOKIE_FILE_PATH tasks[task_id].update({"last_log": "Cookieを使用してダウンロード中..."}) # Colabにリクエスト response = requests.post( f"{COLAB_API_URL.rstrip('/')}/download", data={"url": url}, stream=True, timeout=600 # 10分 ) with YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) tasks[task_id].update({"last_log": f"完了: {info.get('title')}"}) 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('"') tasks[task_id].update({"progress": 90}) 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 i, fp in enumerate(files_to_process): 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 lines 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):1 unmodified line tasks[task_id].update({"status": "completed", "progress": 100})
except Exception as e: tasks[task_id].update({"status": "failed", "error": f"エラー: {str(e)[:200]}"}) 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 lines 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": "開始しました"} 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