Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines8910111112131415161718192021222324252627282930313233349 unmodified lines444546313233343536373839404147484950514552534748495051545556575859606162636465666768697071727374535455565758596061626364656667686970717273747575767778787980818283848586878889909192939495969798997980818283848586878889909192939495969798991001011021031041051061071081051091101111121131141151161171181191201214 unmodified lines1261271281291201301311321331341251351361371381281391401411421431441301311321451461471487 unmodified linesimport uuidimport timeimport subprocessimport requestsimport 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, "Secret 'YT_COOKIES' が設定されていません。" try: content = yt_cookies.strip() 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):def process_task(task_id: str, tool_id: str, url_text: str, filenames: List[str]): 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: if tool_id == 'youtube': if not COLAB_API_URL: raise Exception("外部ダウンローダーが設定されていません。") tasks[task_id].update({"last_log": "外部サーバー(Colab)に接続中..."}) # YouTube 複数ダウンロード対応 if tool_id == 'youtube' and url_text: urls = [u.strip() for u in url_text.split('\n') if u.strip()] total = len(urls) for i, url in enumerate(urls): tasks[task_id]["last_log"] = f"ダウンロード中 ({i+1}/{total}): {url[:30]}..." tasks[task_id]["progress"] = int(20 + (i / total) * 70) ydl_opts = { 'format': 'best', 'outtmpl': f'{output_path}/%(title)s.%(ext)s', 'noplaylist': True, 'quiet': True, 'no_warnings': True, } if os.path.exists(COOKIE_FILE_PATH): ydl_opts['cookiefile'] = COOKIE_FILE_PATH with YoutubeDL(ydl_opts) as ydl: ydl.download([url]) # 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}) tasks[task_id]["last_log"] = "全てのYouTube動画を取得しました"
# 画像・音声変換 (既存ロジック) 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") 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") for i, fname in enumerate(filenames): in_f = os.path.join(input_path, fname) tasks[task_id]["last_log"] = f"処理中: {fname}" tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 70) if tool_id == 'heic-jpg': heif_file = pyheif.read(in_f) img = Image.frombytes(heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride) img.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg"), "JPEG") elif tool_id == 'm4a-mp3' or tool_id == 'mp4-mp3': audio = AudioSegment.from_file(in_f) audio.export(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.mp3"), format="mp3") elif tool_id == 'jpeg-pdf': img = Image.open(in_f).convert('RGB') img.save(os.path.join(output_path, "combined.pdf"), save_all=True, append_images=[]) # 簡易版
elif tool_id == 'pdf-png': images = convert_from_path(in_f) for j, image in enumerate(images): image.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}_{j}.png"), "PNG")
# ZIP作成 tasks[task_id]["last_log"] = "ファイルを圧縮しています..." 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}) tasks[task_id].update({"status": "completed", "progress": 100, "last_log": "完了"})
except Exception as e: tasks[task_id].update({"status": "failed", "error": str(e)})
@app.get("/")async def read_index(): with open("index.html", "r", encoding="utf-8") as f: return HTMLResponse(content=f.read())
@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())4 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.get("/api/status/{task_id}")async def get_status(task_id: str): return tasks.get(task_id, {"status": "failed"})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(task_id: str): return FileResponse(os.path.join(BASE_TEMP_DIR, task_id, "result.zip"))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="result.zip") raise HTTPException(status_code=404, detail="File not found")
@app.get("/", response_class=HTMLResponse)async def serve_index(): with open("index.html", "r", encoding="utf-8") as f: return f.read()@app.get("/api/config")async def get_config(): # シンプルにサーバー側でYT_COOKIESが設定されているかを返す return {"youtube_enabled": os.getenv("YT_COOKIES") is not None}app.py+86-70