Spaces:
Sleeping
Sleeping
Upload 5 files
Browse filesFiles changed (5)
- Dockerfile+22-3
- README.md+6-4
- app.py+94-50
- index.html+72-43
- requirements.txt+3-3
12345678971011121314151617181920212223242526272829303132333421353637383940414243444546472948# 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 \ libheif1 \ libffi-dev \ gcc \ imagemagick \ libmagickwand-dev \ && rm -rf /var/lib/apt/lists/*
# ImageMagickのHEIC読み取り制限を解除RUN sed -i 's/<policy domain="coder" rights="none" pattern="HEIC" \/>/<!-- HEIC allowed -->/' /etc/ImageMagick-6/policy.xml 2>/dev/null || true && \ sed -i 's/<policy domain="coder" rights="none" pattern="HEIF" \/>/<!-- HEIF allowed -->/' /etc/ImageMagick-6/policy.xml 2>/dev/null || true
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 pip install --no-cache-dir -r requirements.txt \ --timeout 120
# アプリケーションファイルのコピーCOPY . .
# セキュリティと動作のため、/app 全体に権限を付与 (Hugging Faceの慣習)RUN chmod -R 777 /app
# デフォルトのポートEXPOSE 7860
# アプリケーションの起動CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]12345234567891011---title: Media Master Asyncemoji: 🔥colorFrom: redcolorTo: redtitle: MediaMasterAsyncPreemoji: 😻colorFrom: bluecolorTo: yellowsdk: dockerapp_port: 7860startup_duration_timeout: 30mpinned: falselicense: mit---11235 unmodified lines91011121314151617181920212223242526272829303132333435363731 unmodified lines697071555657585960616263646566676872737475767778798017 unmodified lines989910010110210310410510610714 unmodified lines1221231241121251261271284 unmodified lines1331341351361371381391401241411421431446 unmodified lines1511521531371541551561571411581591431441451461471481491501511521531541551561571581591601611621631641651611621631641651661671661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092105 unmodified lines21621721821922022122222318318418518618722422522622722822923023123223323423515 unmodified lines25125225321425425525625725825926026126226326426526618 unmodified lines285286287244288from 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 sqlite3import subprocessfrom pydub import AudioSegmentfrom PIL import Imagetry: from pillow_heif import register_heif_opener register_heif_opener() PILLOW_HEIF_AVAILABLE = Trueexcept Exception: PILLOW_HEIF_AVAILABLE = Falsefrom 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"31 unmodified lines tasks.pop(tid, None) shutil.rmtree(os.path.join(BASE_TEMP_DIR, tid), ignore_errors=True)
@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=["*"],)@app.on_event("startup")async def startup_event(): try: asyncio.create_task(cleanup_loop()) except Exception as e: print(f"Cleanup loop error: {e}")
def get_colab_url() -> str: try:17 unmodified lines conn.commit() conn.close()
def is_ngrok_error(text: str) -> bool: """ngrok のオフラインページかどうかを判定する""" return "ERR_NGROK" in text or "<!DOCTYPE html>" in text or "ngrok" in text.lower()
# --- 非同期処理ロジック ---def process_task(task_id: str, tool_id: str, url_text: str, filenames: List[str], output_format: str = "mp3"): session_path = os.path.join(BASE_TEMP_DIR, task_id)14 unmodified lines # YouTube 処理 if tool_id == 'youtube' and url_text: if not current_colab_url: raise Exception("Colabサーバーが接続されていません。") raise Exception("サーバーが停止しています。管理者にお問い合わせください。")
urls = [u.strip() for u in url_text.split('\n') if u.strip()] tasks[task_id]["last_log"] = f"Colabへリクエスト送信中... ({output_format})"4 unmodified lines 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エラー: {response.text}") raise Exception(f"Colabエラー: {error_body}")
colab_zip = os.path.join(session_path, "colab_result.zip") with open(colab_zip, "wb") as f:6 unmodified lines 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(): if is_ngrok_error(error_msg) or "サーバーが停止しています" in error_msg: raise Exception("サーバーが停止しています。管理者にお問い合わせください。") raise Exception(f"Colab接続失敗: {error_msg}")
# 通常のメディア変換処理(遅延インポートで起動時メモリを節約) # 通常のメディア変換処理 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': 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': # jpeg-pdf は全ファイルをまとめて1つのPDFに結合 if tool_id == 'jpeg-pdf': imgs = [] for fname in filenames: in_f = os.path.join(input_path, fname) 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") imgs.append(img) 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
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': out_f = os.path.join(output_path, f"{os.path.splitext(fname)[0]}.jpg") 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が利用できません。")
elif tool_id in ['m4a-mp3', '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 == '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"] = "ファイルを圧縮中..."5 unmodified lines tasks[task_id].update({"status": "completed", "progress": 100, "last_log": "完了", "completed_at": time.time()})
except Exception as e: print(f"[ERROR] task_id={task_id}, error={str(e)}") tasks[task_id].update({"status": "failed", "error": str(e), "completed_at": time.time()})
# --- 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: return HTMLResponse(content=f.read())
@app.get("/health")async def health_check(): return {"status": "ok"}
@app.get("/api/config")async def get_config(): url = get_colab_url()15 unmodified lines background_tasks: BackgroundTasks, tool_id: str = Form(...), url: Optional[str] = Form(None), files: Optional[List[UploadFile]] = File(None), files: List[UploadFile] = File(default=[]), output_format: str = Form("mp3")): task_id = str(uuid.uuid4()) os.makedirs(os.path.join(BASE_TEMP_DIR, task_id, "input"), exist_ok=True)
# 空リストはNoneとして扱う if files is not None and len(files) == 0: files = None
fnames = [] if files: for f in files:18 unmodified lines return FileResponse(zip_path, filename="result.zip") if task_id in tasks: raise HTTPException(status_code=503, detail="ファイルが一時領域から消えました。再度変換をやり直してください。") raise HTTPException(status_code=404, detail="タスクが見つかりません。") raise HTTPException(status_code=404, detail="タスクが見つかりません。")38 unmodified lines394041424243444546474849501 unmodified line525354555657585960616263646566676869707172737475767778798012 unmodified lines9394959697989936 unmodified lines1361371381141391401415 unmodified lines14714814915015115212815315415516 unmodified lines17217317415117517617717817915618018115815918218318416116216316416516616718518618718818919017217317417517617717817918018118218318418518618718819119219319419519619719819920020120220320420520620720819219320921021121219619719819921321421521621721821922022122220622322422521 unmodified lines2472482492342502512522532542552562572582592602612622 unmodified lines26526626724326826924527027127227327427527627756 unmodified lines33433533630833733833934010 unmodified lines35135235332535438 unmodified lines const [files, setFiles] = useState([]); const [youtubeUrl, setYoutubeUrl] = useState(""); const [youtubeFormat, setYoutubeFormat] = useState('mp3'); const [status, setStatus] = useState('idle'); // idle, uploading, processing, completed, failed const [status, setStatus] = useState('idle'); const [progress, setProgress] = useState(0); const [lastLog, setLastLog] = useState(""); const [downloadUrl, setDownloadUrl] = useState(null); const [error, setError] = useState(null); const [isDragging, setIsDragging] = useState(false);
const pollInterval = useRef(null);
1 unmodified line setFiles(Array.from(e.target.files)); };
// ドラッグ&ドロップハンドラ const handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); };
const handleDragLeave = (e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); };
const handleDrop = (e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); const dropped = Array.from(e.dataTransfer.files); if (dropped.length > 0) { setFiles(dropped); } };
const startProcessing = async () => { if (selectedTool.id === 'youtube' && !youtubeUrl) return; if (selectedTool.id !== 'youtube' && files.length === 0) return;12 unmodified lines formData.append('output_format', youtubeFormat); } else { files.forEach(file => formData.append('files', file)); formData.append('output_format', 'mp3'); }
try {36 unmodified lines }, 2000); };
// ツール選択画面に完全に戻る(データを消去) const reset = () => { if (pollInterval.current) clearInterval(pollInterval.current); setSelectedTool(null);5 unmodified lines setLastLog(""); setDownloadUrl(null); setError(null); setIsDragging(false); };
// 入力画面に戻る(URLや選択ファイルを保持) const backToInput = () => { if (pollInterval.current) clearInterval(pollInterval.current); setStatus('idle');16 unmodified lines </div>
{!selectedTool ? ( <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> <div className="grid grid-cols-2 md: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" className="group p-6 bg-white rounded-3xl shadow-sm hover:shadow-xl transition-all duration-300 text-left border border-slate-100 hover:border-indigo-200 hover:-translate-y-1" > <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 className={`inline-flex p-3 ${tool.color} rounded-2xl mb-4 shadow-lg`}> <Icon name={tool.icon} className="w-6 h-6 text-white" /> </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> )} <p className="font-black text-slate-900 mb-1">{tool.title}</p> <p className="text-xs text-slate-400 font-medium leading-relaxed">{tool.description}</p> </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={reset} 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 className="max-w-lg mx-auto"> <div className="bg-white rounded-3xl shadow-sm border border-slate-100 overflow-hidden"> {/* Tool Header */} <div className={`${selectedTool.color} p-6`}> <button onClick={reset} className="flex items-center gap-2 text-white/80 hover:text-white mb-4 text-sm font-bold transition-colors"> <Icon name="arrow-left" className="w-4 h-4" /> ツール選択に戻る </button> <div className="flex items-center gap-3"> <Icon name={selectedTool.icon} className="w-8 h-8 text-white" /> <div> <h2 className="text-xl font-black text-white">{selectedTool.title}</h2> <p className="text-white/70 text-sm font-medium">{selectedTool.description}</p> </div> </div> </div>
{/* Content */} <div className="space-y-6"> {status === 'idle' ? ( <div className="p-6 space-y-4"> {status === 'idle' || status === 'uploading' ? ( <> {selectedTool.id === 'youtube' ? ( <div className="space-y-4 animate-in fade-in duration-300"> <div className="space-y-2"> <label className="block text-sm font-bold text-slate-700">YouTube URL (1行に1つ)</label> <textarea <div className="space-y-4"> <div> <label className="block text-sm font-bold text-slate-600 mb-2">YouTube URL(複数行入力可)</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="flex gap-4 p-4 bg-slate-50 rounded-2xl border border-slate-100"> <span className="text-sm font-bold text-slate-500 flex items-center">保存形式:</span> <label className="flex items-center gap-2 cursor-pointer group">21 unmodified lines </div> </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"> <div className={`border-2 border-dashed rounded-3xl p-12 text-center transition-all ${ isDragging ? 'border-indigo-500 bg-indigo-50' : 'border-slate-200 bg-slate-50 hover:border-indigo-400' }`} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop} > <input type="file" multiple 2 unmodified lines onChange={handleFileChange} /> <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" /> <Icon name="upload-cloud" className={`w-12 h-12 mx-auto mb-4 transition-colors ${isDragging ? 'text-indigo-500' : 'text-slate-300'}`} /> <p className="text-slate-600 font-bold mb-1"> {files.length > 0 ? `${files.length}個のファイルを選択中` : 'ファイルをドラッグ&ドロップ'} {files.length > 0 ? `${files.length}個のファイルを選択中` : isDragging ? 'ここにドロップ' : 'ファイルをドラッグ&ドロップ'} </p> <p className="text-slate-400 text-sm font-medium">またはクリックしてファイルを選択</p> </label>56 unmodified lines )} </div>
{/* Footer / Copyright */} {/* Footer */} <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>10 unmodified lines root.render(<App />); </script></body></html></html>123345567891010fastapi==0.110.0uvicorn==0.27.1python-multipart==0.0.9python-multipart==0.0.12Pillow==10.2.0pillow-heif>=0.13.0pillow-heif==0.16.0pydub==0.25.1pdf2image==1.17.0yt-dlp>=2025.01.15aiofiles==23.2.1requests==2.31.0requests==2.31.0Dockerfile+22-3
README.md+6-4
app.py+94-50
index.html+72-43
requirements.txt+3-3