Spaces:
Sleeping
Sleeping
Upload 5 files
Browse filesFiles changed (3)
- Dockerfile+1-12
- app.py+48-39
- requirements.txt+1-1
1234547561078910141112131415162122171825192021223023243325263627283929# Pythonの軽量版を使用FROM python:3.10-slim
# 環境変数の設定# .pycファイルを作成しないようにするENV PYTHONDONTWRITEBYTECODE=1# 標準出力をバッファリングせず、リアルタイムにログを表示ENV PYTHONUNBUFFERED=1
# システム依存関係のインストールとクリーンアップ# libheif-devは pillow-heif のビルド済みホイールが使われるため不要RUN apt-get update && apt-get install -y --no-install-recommends \ ffmpeg \ poppler-utils \ libheif-dev \ libffi-dev \ gcc \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# 一時ディレクトリの作成と権限設定# Hugging Face SpacesはユーザーID 1000で実行されるため、そのユーザーが書き込めるようにするRUN mkdir -p /tmp/media_master && chmod 777 /tmp/media_master
# 依存ライブラリのインストールCOPY requirements.txt .RUN pip install --no-cache-dir -U pip && \ pip install --no-cache-dir -r requirements.txt
# アプリケーションファイルのコピーCOPY . .
# セキュリティと動作のため、/app 全体に権限を付与 (Hugging Faceの慣習)RUN chmod -R 777 /app
# デフォルトのポートEXPOSE 7860
# アプリケーションの起動CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]12345 unmodified lines101112121314151415161720212223242526272818192032212223243 unmodified lines282930423132338 unmodified lines42434457454647483 unmodified lines5253546768555657585960616263646566676869707131 unmodified lines1031041051071061071081091101111121141131141151171161171181191201221211221231241261251261271281301291301311331321331341351361371381371391401391411421431441451461451471481471481491501511521501531541551561571541581591601611621631641651661674 unmodified lines1721731741701751761771781 unmodified line18018118218318418518618718818919017 unmodified lines2082092102012022032112122132142052152162172182092192202212222 unmodified lines225226227218228229220230231232from contextlib import asynccontextmanagerfrom fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Bodyfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddleware5 unmodified linesimport timeimport requestsimport sqlite3from pydub import AudioSegmentfrom PIL import Imageimport pyheiffrom pdf2image import convert_from_pathimport pathlibimport asyncio
SECRET_TOKEN = os.environ.get("SECRET_TOKEN", "")app = FastAPI()
# CORS設定app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
# パス設定BASE_TEMP_DIR = "/tmp/media_master"DB_PATH = "colab_config.db"DB_PATH = "/tmp/media_master/colab_config.db"os.makedirs(BASE_TEMP_DIR, exist_ok=True)
# 進行状況管理(メモリ上)3 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())3 unmodified lines tasks.pop(tid, None) shutil.rmtree(os.path.join(BASE_TEMP_DIR, tid), ignore_errors=True)
@app.on_event("startup")async def startup_event():@asynccontextmanagerasync def lifespan(app: FastAPI): asyncio.create_task(cleanup_loop()) yield
app = FastAPI(lifespan=lifespan)
# CORS設定app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
def get_colab_url() -> str: try:31 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サーバーが接続されていません。")
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: raise Exception(f"Colabエラー: {response.text}")
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 "ERR_NGROK" in error_msg or "<!DOCTYPE html>" in error_msg or "ngrok" in error_msg.lower(): raise Exception("サーバーが停止しています。管理者にお問い合わせください。") raise Exception(f"Colab接続失敗: {str(e)}") raise Exception(f"Colab接続失敗: {error_msg}")
# 通常のメディア変換処理 (HEIC, M4A, etc) # 通常のメディア変換処理(遅延インポートで起動時メモリを節約) else: 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)
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) from pillow_heif import register_heif_opener register_heif_opener() img = Image.open(in_f) img.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg"), "JPEG")
elif tool_id in ['m4a-mp3', 'mp4-mp3']: from pydub import AudioSegment 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")
elif tool_id == 'pdf-png': from pdf2image import convert_from_path 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")4 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:1 unmodified line
# --- APIエンドポイント ---
@app.get("/favicon.ico")async def favicon(): # faviconがないと404になりヘルスチェックが失敗するため204を返す raise HTTPException(status_code=204)
@app.get("/")async def read_index(): with open("index.html", "r", encoding="utf-8") as f:17 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}
1 unmodified line234556781 unmodified lineuvicorn==0.27.1python-multipart==0.0.9Pillow==10.2.0pyheif==0.8.0pillow-heif>=0.13.0pydub==0.25.1pdf2image==1.17.0yt-dlp>=2025.01.15Dockerfile+1-12
app.py+48-39
requirements.txt+1-1