Spaces:
Sleeping
Sleeping
Update app.py
Browse files38 unmodified lines394041424243448 unmodified lines535455575657585929 unmodified lines899091929394959697988 unmodified lines1071081091071101111121131141151131141161171181191171201211221231241221251261271281291301311251261321331341351361301371381391331401411421431441451461371471481491501 unmodified line1521531541451551561571581591501601611621631541641651661679 unmodified lines17717817917018018118218324 unmodified lines2082092102012022032112122132142052152162172182092192202212222 unmodified lines22522622721822822922023023123238 unmodified linesdef init_db(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() # 既存テーブルがない場合のみ作成 cursor.execute(''' CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY,8 unmodified lines
async def cleanup_loop(): while True: await asyncio.sleep(3600) # 1時間ごとに実行 await asyncio.sleep(3600) now = time.time() to_delete = [ tid for tid, t in list(tasks.items())29 unmodified lines conn.commit() conn.close()
def is_ngrok_error(text: str) -> bool: """ngrok のオフラインページかどうかを判定する""" return "ERR_NGROK" in text or "<!DOCTYPE html>" in text or "ngrok" in text.lower()
# --- 非同期処理ロジック ---def process_task(task_id: str, tool_id: str, url_text: str, filenames: List[str], output_format: str = "mp3"): session_path = os.path.join(BASE_TEMP_DIR, task_id)8 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サーバーが接続されていません。") raise Exception("サーバーが停止しています。管理者にお問い合わせください。")
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: error_body = response.text if is_ngrok_error(error_body): raise Exception("サーバーが停止しています。管理者にお問い合わせください。") raise Exception(f"Colabエラー: {response.text}") raise Exception(f"Colabエラー: {error_body}")
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: error_msg = str(e) if is_ngrok_error(error_msg) or "サーバーが停止しています" in error_msg: raise Exception("サーバーが停止しています。管理者にお問い合わせください。") raise Exception(f"Colab接続失敗: {str(e)}") raise Exception(f"Colab接続失敗: {error_msg}")
# 通常のメディア変換処理 (HEIC, M4A, etc) else:1 unmodified line 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': 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 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") # 追加 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-23