Spaces:
Sleeping
Sleeping
Upload 4 files
Browse filesFiles changed (4)
- DockerfileAdded+40
- app.pyAdded+148
- index.htmlAdded+231
- requirements.txtAdded+10
12345678910111213141516171819202122232425262728293031323334353637383940# Pythonの軽量版を使用FROM python:3.10-slim
# 環境変数の設定# .pycファイルを作成しないようにするENV PYTHONDONTWRITEBYTECODE=1# 標準出力をバッファリングせず、リアルタイムにログを表示ENV PYTHONUNBUFFERED=1
# システム依存関係のインストールとクリーンアップ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"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasksfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dictimport osimport shutilimport zipfileimport uuidimport timeimport requestsfrom pydub import AudioSegmentfrom PIL import Imageimport pyheiffrom pdf2image import convert_from_path
app = FastAPI()
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
BASE_TEMP_DIR = "/tmp/media_master"os.makedirs(BASE_TEMP_DIR, exist_ok=True)
# 進行状況管理tasks: Dict[str, dict] = {}
# --- Colab サーバーのURL (実行時に書き換わるか、環境変数から取得) ---# Colab側で発行された ngrok などのURLをここに入れますCOLAB_URL = os.getenv("COLAB_URL", "")
def process_task(task_id: str, tool_id: str, url_text: str, filenames: List[str]): 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)
try: # --- YouTube 処理 (Colabへ委託) --- if tool_id == 'youtube' and url_text: if not COLAB_URL: raise Exception("ColabサーバーのURLが設定されていません。Hugging FaceのSettingsからCOLAB_URLを設定してください。") urls = [u.strip() for u in url_text.split('\n') if u.strip()] tasks[task_id]["last_log"] = f"Colabサーバーへリクエスト送信中... (計{len(urls)}件)" # Colab側のAPIを叩く (一括処理用) try: response = requests.post( f"{COLAB_URL.rstrip('/')}/batch-download", json={"urls": urls}, timeout=600 # 長めのタイムアウト ) if response.status_code != 200: raise Exception(f"Colabエラー: {response.text}") # Colabから送られてきたZIPファイルを保存 colab_zip = os.path.join(session_path, "colab_result.zip") with open(colab_zip, "wb") as f: f.write(response.content) # ZIPを展開してoutputディレクトリへ移動 with zipfile.ZipFile(colab_zip, 'r') as z: z.extractall(output_path) tasks[task_id]["last_log"] = "Colabからのダウンロードが完了しました" tasks[task_id]["progress"] = 90
except Exception as e: raise Exception(f"Colab接続失敗: {str(e)}")
# --- 通常のメディア変換処理 (HFS内で実行) --- 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) img.save(os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg"), "JPEG") elif tool_id == 'm4a-mp3' or tool_id == 'mp4-mp3': 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': 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")
# --- 最終ZIP作成 --- tasks[task_id]["last_log"] = "結果をまとめています..." 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) tasks[task_id].update({"status": "completed", "progress": 100, "last_log": "完了しました"})
except Exception as e: tasks[task_id].update({"status": "failed", "error": str(e)})
@app.get("/")async def read_index(): with open("index.html", "r", encoding="utf-8") as f: return HTMLResponse(content=f.read())
@app.post("/api/convert")async def convert_start(background_tasks: BackgroundTasks, tool_id: str = Form(...), url: str = Form(None), files: List[UploadFile] = File(None)): 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: file_path = os.path.join(BASE_TEMP_DIR, task_id, "input", f.filename) with open(file_path, "wb") as buf: shutil.copyfileobj(f.file, buf) fnames.append(f.filename) tasks[task_id] = {"status": "processing", "progress": 10, "last_log": "タスクを開始しました"} background_tasks.add_task(process_task, task_id, tool_id, url, fnames) return {"task_id": task_id}
@app.get("/api/status/{task_id}")async def get_status(task_id: str): return tasks.get(task_id, {"status": "failed", "error": "Task not found"})
@app.get("/api/download/{task_id}")async def download_result(task_id: str): zip_path = os.path.join(BASE_TEMP_DIR, task_id, "result.zip") if os.path.exists(zip_path): return FileResponse(zip_path, filename="result.zip") raise HTTPException(status_code=404, detail="File not found")
@app.get("/api/config")async def get_config(): # ColabのURLが設定されているかどうかをフロントエンドに伝える return {"youtube_enabled": COLAB_URL != ""}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231<!DOCTYPE html><html lang="ja"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MediaMaster Async</title> <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script src="https://cdn.tailwindcss.com"></script> <script src="https://unpkg.com/lucide@latest"></script></head><body class="bg-slate-50 min-h-screen flex flex-col"> <div id="root" class="flex-grow"></div> <script type="text/babel"> const { useState, useEffect, useRef } = React;
// アイコンコンポーネント const Icon = ({ name, className = "" }) => { useEffect(() => { if (window.lucide) { window.lucide.createIcons(); } }, [name]); return <i data-lucide={name} className={className}></i>; };
const TOOLS = [ { id: 'heic-jpg', title: 'HEIC → JPG', icon: 'image', color: 'bg-blue-500', description: 'iPhoneの写真を一般的な形式に変換' }, { id: 'm4a-mp3', title: 'M4A → MP3', icon: 'music', color: 'bg-purple-500', description: 'Apple録音データをMP3に変換' }, { id: 'mp4-mp3', title: '動画 → MP3', icon: 'volume-2', color: 'bg-orange-500', description: '動画から音声のみを抽出' }, { id: 'jpeg-pdf', title: '画像 → PDF', icon: 'file-text', color: 'bg-red-500', description: '複数の画像を1つのPDFに結合' }, { id: 'pdf-png', title: 'PDF → PNG', icon: 'files', color: 'bg-emerald-500', description: 'PDFの各ページを画像に変換' }, { id: 'youtube', title: 'YouTube 保存', icon: 'youtube', color: 'bg-rose-600', description: '動画・音声を最高画質で保存 (Colab経由)' }, ];
function App() { const [selectedTool, setSelectedTool] = useState(null); const [files, setFiles] = useState([]); const [youtubeUrl, setYoutubeUrl] = useState(""); const [taskState, setTaskState] = useState({ status: 'idle', progress: 0, last_log: "" }); const [downloadUrl, setDownloadUrl] = useState(null); const [youtubeEnabled, setYoutubeEnabled] = useState(false);
useEffect(() => { fetch('/api/config') .then(res => res.json()) .then(data => setYoutubeEnabled(data.youtube_enabled)) .catch(() => setYoutubeEnabled(false)); }, []);
const startProcessing = async () => { if (!selectedTool) return; setTaskState({ status: 'uploading', progress: 10, last_log: "ファイルをアップロード中..." }); setDownloadUrl(null);
const formData = new FormData(); formData.append('tool_id', selectedTool.id); if (selectedTool.id === 'youtube') { formData.append('url', youtubeUrl); } else { files.forEach(file => formData.append('files', file)); }
try { const res = await fetch('/api/convert', { method: 'POST', body: formData }); const { task_id } = await res.json();
const checkStatus = setInterval(async () => { const statusRes = await fetch(`/api/status/${task_id}`); const data = await statusRes.json(); setTaskState({ status: data.status, progress: data.progress || 0, last_log: data.last_log || data.error || "" });
if (data.status === 'completed') { clearInterval(checkStatus); setDownloadUrl(`/api/download/${task_id}`); } else if (data.status === 'failed') { clearInterval(checkStatus); } }, 2000); } catch (e) { setTaskState({ status: 'failed', progress: 0, last_log: "通信エラーが発生しました" }); } };
return ( <div class="flex flex-col min-h-screen"> <div className="max-w-4xl mx-auto px-4 py-12 flex-grow w-full"> {/* Header */} <div className="text-center mb-12"> <div className="inline-block p-3 bg-indigo-600 rounded-2xl mb-4 shadow-lg shadow-indigo-200"> <Icon name="zap" className="text-white w-8 h-8" /> </div> <h1 className="text-4xl font-black text-slate-900 mb-2 tracking-tight">MediaMaster Async</h1> <p className="text-slate-500 font-medium">高速・非同期メディア変換ツール</p> </div>
{!selectedTool ? ( <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {TOOLS.map(tool => ( <button key={tool.id} onClick={() => setSelectedTool(tool)} className="group bg-white p-6 rounded-3xl border border-slate-100 shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all text-left relative overflow-hidden" > <div className={`w-12 h-12 ${tool.color} rounded-2xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}> <Icon name={tool.icon} className="text-white w-6 h-6" /> </div> <h3 className="font-bold text-slate-900 mb-1">{tool.title}</h3> <p className="text-xs text-slate-500 leading-relaxed">{tool.description}</p> {tool.id === 'youtube' && ( <div className="absolute top-2 right-2 bg-amber-100 text-amber-700 text-[10px] px-2 py-0.5 rounded-full font-bold"> 要Colab設定 </div> )} </button> ))} </div> ) : ( <div className="bg-white rounded-[2.5rem] border border-slate-100 shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-300"> <div className="p-8"> <button onClick={() => {setSelectedTool(null); setTaskState({status:'idle', progress:0}); setFiles([]); setYoutubeUrl("");}} className="flex items-center text-slate-400 hover:text-indigo-600 font-bold mb-8 transition-colors" > <Icon name="arrow-left" className="w-5 h-5 mr-2" /> ツール選択に戻る </button>
<div className="flex items-center gap-4 mb-8"> <div className={`w-14 h-14 ${selectedTool.color} rounded-2xl flex items-center justify-center shadow-lg`}> <Icon name={selectedTool.icon} className="text-white w-7 h-7" /> </div> <div> <h2 className="text-2xl font-black text-slate-900">{selectedTool.title}</h2> <p className="text-slate-500 font-medium">{selectedTool.description}</p> </div> </div>
<div className="space-y-6"> {selectedTool.id === 'youtube' ? ( <div className="space-y-2"> <label className="block text-sm font-bold text-slate-700">YouTube URL (1行に1つ)</label> <textarea placeholder="https://www.youtube.com/watch?v=..." className="w-full h-32 p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl focus:border-indigo-500 focus:outline-none transition-all font-mono text-sm" value={youtubeUrl} onChange={(e) => setYoutubeUrl(e.target.value)} /> </div> ) : ( <div className="border-2 border-dashed border-slate-200 rounded-3xl p-12 text-center hover:border-indigo-400 transition-all bg-slate-50 group"> <input type="file" multiple className="hidden" id="fileInput" onChange={(e) => setFiles(Array.from(e.target.files))} /> <label htmlFor="fileInput" className="cursor-pointer block"> <Icon name="upload-cloud" className="w-12 h-12 text-slate-300 mx-auto mb-4 group-hover:text-indigo-500 transition-colors" /> <p className="text-slate-600 font-bold mb-1"> {files.length > 0 ? `${files.length}個のファイルを選択中` : 'ファイルをドラッグ&ドロップ'} </p> <p className="text-slate-400 text-sm font-medium">またはクリックしてファイルを選択</p> </label> </div> )}
{taskState.status !== 'idle' && ( <div className="bg-slate-50 rounded-2xl p-6 border border-slate-100"> <div className="flex justify-between text-sm font-bold mb-3"> <span className="text-indigo-600">{taskState.last_log}</span> <span className="text-slate-400">{taskState.progress}%</span> </div> <div className="w-full bg-slate-200 rounded-full h-3 overflow-hidden"> <div className="h-full bg-indigo-600 transition-all duration-500 shadow-[0_0_10px_rgba(79,70,229,0.5)]" style={{ width: `${taskState.progress}%` }} ></div> </div> </div> )}
<div className="flex gap-4"> <button onClick={startProcessing} disabled={taskState.status === 'processing' || taskState.status === 'uploading' || (selectedTool.id === 'youtube' && !youtubeUrl)} className="flex-1 bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-indigo-600 disabled:bg-slate-200 transition-all shadow-lg" > 処理開始 </button> {downloadUrl && ( <a href={downloadUrl} className="flex-1 bg-emerald-500 text-white py-4 rounded-2xl font-bold text-center hover:bg-emerald-600 animate-pulse shadow-lg" > ダウンロード </a> )} </div> </div> </div> </div> )} </div>
{/* Footer / Copyright */} <footer className="py-8 text-center border-t border-slate-100"> <div className="flex items-center justify-center gap-2 text-slate-400 text-sm font-medium"> <span>© {new Date().getFullYear()}</span> <span className="text-slate-900 font-black tracking-tight">HatakeyamaTechnology</span> <span className="hidden sm:inline">|</span> <span className="hidden sm:inline">All Rights Reserved.</span> </div> </footer> </div> ); }
const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />); </script></body></html>12345678910fastapi==0.110.0uvicorn==0.27.1python-multipart==0.0.9Pillow==10.2.0pyheif==0.8.0pydub==0.25.1pdf2image==1.17.0yt-dlp>=2024.11.18aiofiles==23.2.1requests==2.31.0DockerfileAdded+40
app.pyAdded+148
index.htmlAdded+231
requirements.txtAdded+10