Spaces:
Sleeping
Sleeping
Update app.py
Browse files123414 unmodified lines1920212122232425262728292223247 unmodified lines3233344335363718 unmodified lines5657586869596061626364656667686970717273747531 unmodified lines1071081091081101111121131141151161151171181191181201211221231241231251261271281271291301311321311331341351341361371381392 unmodified lines1421431441431451461471481491501491511521511531541531551561571581571591601611629 unmodified lines17217317417317517617717824 unmodified lines2032042052042052062062072082092102112122132122142152162172 unmodified lines220221222221223224223225226227from contextlib import asynccontextmanagerfrom fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Bodyfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddleware14 unmodified linesimport asyncio
SECRET_TOKEN = os.environ.get("SECRET_TOKEN", "")app = FastAPI()
# CORS設定app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
# パス設定BASE_TEMP_DIR = "/tmp/media_master"7 unmodified linesdef init_db(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() # 既存テーブルがない場合のみ作成 cursor.execute(''' CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY,18 unmodified lines tasks.pop(tid, None) shutil.rmtree(os.path.join(BASE_TEMP_DIR, tid), ignore_errors=True)
@app.on_event("startup")async def startup_event():@asynccontextmanagerasync def lifespan(app: FastAPI): asyncio.create_task(cleanup_loop()) yield
app = FastAPI(lifespan=lifespan)
# CORS設定app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
def get_colab_url() -> str: try:31 unmodified lines
if output_format not in ('mp3', 'mp4'): raise ValueError(f"無効なoutput_formatです: {output_format}")
current_colab_url = get_colab_url()
# YouTube 処理 if tool_id == 'youtube' and url_text: if not current_colab_url: raise Exception("Colabサーバーが接続されていません。")
urls = [u.strip() for u in url_text.split('\n') if u.strip()] tasks[task_id]["last_log"] = f"Colabへリクエスト送信中... ({output_format})"
try: response = requests.post( f"{current_colab_url.rstrip('/')}/batch-download", json={"urls": urls, "format": output_format}, timeout=900 timeout=900 ) if response.status_code != 200: raise Exception(f"Colabエラー: {response.text}")
colab_zip = os.path.join(session_path, "colab_result.zip") with open(colab_zip, "wb") as f: f.write(response.content)
with zipfile.ZipFile(colab_zip, 'r') as z: z.extractall(output_path)
tasks[task_id]["last_log"] = "取得完了" tasks[task_id]["progress"] = 90 except Exception as e:2 unmodified lines raise Exception("サーバーが停止しています。管理者にお問い合わせください。") raise Exception(f"Colab接続失敗: {error_msg}")
# 通常のメディア変換処理 (HEIC, M4A, etc) # 通常のメディア変換処理 else: 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)) * 60)
if tool_id == 'heic-jpg': img = Image.open(in_f) # register後はPillowが直接開ける img = Image.open(in_f) img.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg"), "JPEG")
elif tool_id in ['m4a-mp3', '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, f"{os.path.splitext(fname)[0]}.pdf"), "PDF")9 unmodified lines with zipfile.ZipFile(final_zip, '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, "last_log": "完了", "completed_at": time.time()})
except Exception as e:24 unmodified lines
@app.post("/api/convert")async def convert_start( background_tasks: BackgroundTasks, tool_id: str = Form(...), url: Optional[str] = Form(None), background_tasks: BackgroundTasks, tool_id: str = Form(...), url: Optional[str] = Form(None), files: Optional[List[UploadFile]] = File(None), output_format: str = Form("mp3")): 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:2 unmodified lines with open(file_path, "wb") as buf: shutil.copyfileobj(f.file, buf) fnames.append(safe_name)
tasks[task_id] = {"status": "processing", "progress": 10, "last_log": "タスクを開始しました"} # 引数に output_format を追加 background_tasks.add_task(process_task, task_id, tool_id, url, fnames, output_format) return {"task_id": task_id}
app.py+32-31