Spaces:
Sleeping

File size: 2,535 Bytes
4f3fd1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
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 "<!DOCTYPE html>" in text or "ngrok" in text.lower()