Spaces:
Sleeping
Sleeping
Upload 4 files
Browse filesFiles changed (4)
- tools/audio_tools.pyAdded+29
- tools/base_tool.pyAdded+83
- tools/image_tools.pyAdded+94
- tools/youtube_tools.pyAdded+61
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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""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" )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""youtube_tools.pyYouTube ダウンロード処理(Colab / ngrok 経由) - youtube : URL リストを Colab サーバーに送信してファイルを取得する"""import osimport zipfileimport requestsfrom typing import List
from tools.base_tool import tasks, get_colab_url, is_ngrok_error
# ---------- YouTube → MP3 / MP4 ----------
def download_youtube( task_id: str, url_text: str, session_path: str, output_path: str, output_format: str = "mp3"): """ Colab サーバーに YouTube URL リストを送信し、 返ってきた ZIP を output_path に展開する。 """ current_colab_url = get_colab_url() if not current_colab_url: 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 )
if response.status_code != 200: error_body = response.text if is_ngrok_error(error_body): raise Exception("サーバーが停止しています。管理者にお問い合わせください。") 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接続失敗: {error_msg}")tools/audio_tools.pyAdded+29
tools/base_tool.pyAdded+83
tools/image_tools.pyAdded+94
tools/youtube_tools.pyAdded+61