Spaces:
Sleeping
Sleeping
Upload 5 files
Browse filesFiles changed (5)
- tools/__init__.pyAdded
- tools/audio_tools.pyAdded+29
- tools/base_tool.pyAdded+83
- tools/file_tools.pyAdded+62
- tools/image_tools.pyAdded+94
1234567891011121314151617181920212223242526272829"""audio_tools.py音声関連の変換処理 - m4a-mp3 : M4A → MP3 - mp4-mp3 : MP4(動画)→ MP3(音声抽出)"""import osfrom typing import List
from pydub import AudioSegment
from tools.base_tool import tasks
# ---------- M4A / MP4 → MP3 ----------
def convert_to_mp3(task_id: str, filenames: List[str], input_path: str, output_path: str): """M4A または MP4 ファイルを MP3 に変換する""" 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)
audio = AudioSegment.from_file(in_f) audio.export( os.path.join(output_path, f"{os.path.splitext(fname)[0]}.mp3"), format="mp3" )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""base_tool.py共通ロジック:タスク状態管理・ZIP化・パス管理・DBアクセス"""import osimport timeimport zipfileimport sqlite3from 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""file_tools.pyファイルダウンロード機能 - パスワード照合 - ファイル一覧取得 - 選択ファイルのZIP生成"""import osimport zipfileimport tempfilefrom typing import List
DOWNLOAD_FILES_DIR = "/app/download_files"DOWNLOAD_PASSWORD = os.environ.get("DOWNLOAD_PASSWORD", "")
# --- パスワード照合 ---
def verify_password(password: str) -> bool: """入力されたパスワードが正しいか照合する""" if not DOWNLOAD_PASSWORD: return False return password == DOWNLOAD_PASSWORD
# --- ファイル一覧取得 ---
def list_files() -> List[str]: """download_files ディレクトリ内のファイル一覧を返す""" if not os.path.exists(DOWNLOAD_FILES_DIR): return [] return sorted([ f for f in os.listdir(DOWNLOAD_FILES_DIR) if os.path.isfile(os.path.join(DOWNLOAD_FILES_DIR, f)) ])
# --- ZIP生成 ---
def build_zip(filenames: List[str]) -> str: """ 指定されたファイルをZIPにまとめ、一時ファイルのパスを返す。 呼び出し元でファイルを返却後に削除すること。 """ if not filenames: raise ValueError("ファイルが選択されていません")
tmp = tempfile.NamedTemporaryFile( delete=False, suffix=".zip", dir="/tmp/media_master" ) tmp.close()
with zipfile.ZipFile(tmp.name, "w", zipfile.ZIP_DEFLATED) as zf: for fname in filenames: # パストラバーサル対策:ファイル名のみ取り出す safe_name = os.path.basename(fname) full_path = os.path.join(DOWNLOAD_FILES_DIR, safe_name) if not os.path.isfile(full_path): raise ValueError(f"ファイルが見つかりません: {safe_name}") zf.write(full_path, safe_name)
return tmp.name12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""image_tools.py画像関連の変換処理 - heic-jpg : HEIC → JPEG - jpeg-pdf : JPEG/PNG 複数枚 → 1つの PDF - pdf-png : PDF の各ページ → PNG"""import osimport subprocessfrom typing import List
from PIL import Imagetry: from pillow_heif import register_heif_opener register_heif_opener() PILLOW_HEIF_AVAILABLE = Trueexcept Exception: PILLOW_HEIF_AVAILABLE = False
from pdf2image import convert_from_path
from tools.base_tool import tasks
# ---------- HEIC → JPG ----------
def convert_heic_to_jpg(task_id: str, filenames: List[str], input_path: str, output_path: str): """HEIC ファイルを JPEG に変換する(ImageMagick → pillow-heif の順でフォールバック)""" for i, fname in enumerate(filenames): in_f = os.path.join(input_path, fname) out_f = os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg")
tasks[task_id]["last_log"] = f"処理中: {fname}" tasks[task_id]["progress"] = int(20 + (i / len(filenames)) * 60)
converted = False
# まず ImageMagick で試みる(最も確実) try: result = subprocess.run( ["convert", in_f, "-quality", "95", out_f], capture_output=True, timeout=60 ) if result.returncode == 0 and os.path.exists(out_f): converted = True except Exception: pass
# フォールバック: pillow-heif if not converted and PILLOW_HEIF_AVAILABLE: img = Image.open(in_f) img.convert("RGB").save(out_f, "JPEG", quality=95) converted = True
if not converted: raise Exception( f"HEIC変換に失敗しました: {fname}。" "ImageMagickおよびpillow-heifが利用できません。" )
# ---------- JPEG/PNG → PDF ----------
def convert_jpeg_to_pdf(task_id: str, filenames: List[str], input_path: str, output_path: str): """複数の画像ファイルを1つの PDF に結合する""" imgs = [] for fname in filenames: in_f = os.path.join(input_path, fname) imgs.append(Image.open(in_f).convert("RGB"))
if not imgs: raise Exception("変換対象の画像がありません")
out_pdf = os.path.join(output_path, "output.pdf") imgs[0].save(out_pdf, "PDF", save_all=True, append_images=imgs[1:]) tasks[task_id]["progress"] = 80
# ---------- PDF → PNG ----------
def convert_pdf_to_png(task_id: str, filenames: List[str], input_path: str, output_path: str): """PDF の各ページを 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)) * 60)
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" )tools/__init__.pyAdded
tools/audio_tools.pyAdded+29
tools/base_tool.pyAdded+83
tools/file_tools.pyAdded+62
tools/image_tools.pyAdded+94