""" base_tool.py 共通ロジック:タスク状態管理・ZIP化・パス管理・DBアクセス """ import os import time import zipfile import sqlite3 from typing import Dict # --- パス設定 --- BASE_TEMP_DIR = "/tmp/media_master" DB_PATH = "/tmp/media_master/colab_config.db" os.makedirs(BASE_TEMP_DIR, exist_ok=True) # --- タスク状態管理(メモリ上) --- # app.py からインポートして使うことで、全モジュールで同一インスタンスを共有する tasks: Dict[str, dict] = {} # --- パスヘルパー --- def get_session_paths(task_id: str) -> tuple[str, str, str]: """(session_path, input_path, output_path) を返す""" 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) return session_path, input_path, output_path # --- ZIP化 --- def zip_output(session_path: str, output_path: str) -> str: """output_path 内のファイルをまとめて result.zip を作成し、そのパスを返す""" final_zip = os.path.join(session_path, "result.zip") with zipfile.ZipFile(final_zip, "w") as z: for f in os.listdir(output_path): z.write(os.path.join(output_path, f), f) return final_zip # --- DB:Colab URL 管理 --- def init_db(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY, value TEXT, updated_at REAL ) ''') conn.commit() conn.close() def get_colab_url() -> str: try: conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute('SELECT value FROM config WHERE key = "colab_url"') row = cursor.fetchone() conn.close() return row[0] if row else "" except Exception as e: print(f"DB Read Error: {e}") return "" def set_colab_url(url: str): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' INSERT OR REPLACE INTO config (key, value, updated_at) VALUES (?, ?, ?) ''', ("colab_url", url.strip(), time.time())) conn.commit() conn.close() # --- ngrok エラー判定 --- def is_ngrok_error(text: str) -> bool: """ngrok のオフラインページかどうかを判定する""" return "ERR_NGROK" in text or "" in text or "ngrok" in text.lower()