Spaces:
Sleeping
Sleeping
Upload 7 files
Browse filesFiles changed (7)
- DockerfileAdded+53
- README.md+6-4
- app.pyAdded+237
- gitattributesAdded+35
- index.htmlAdded+491
- requirements.txtAdded+11
- startup.pyAdded+43
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# 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 \ 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
# ダウンロード用ファイル設置ディレクトリの作成RUN mkdir -p /app/download_files && chmod 777 /app/download_files
# 依存ライブラリのインストールCOPY requirements.txt .RUN pip install --no-cache-dir -U pip && \ pip install --no-cache-dir -r requirements.txt \ --timeout 120
# アプリケーションファイルのコピーCOPY . .
# セキュリティと動作のため、/app 全体に権限を付与 (Hugging Faceの慣習)RUN chmod -R 777 /app
# デフォルトのポートEXPOSE 7860
# 起動スクリプトの実行# 1. HuggingFace Datasetsからファイルを取得# 2. uvicornでアプリを起動CMD ["sh", "-c", "python startup.py && uvicorn app:app --host 0.0.0.0 --port 7860"]1234567891011---title: MediaMaster V2emoji: 🐨colorFrom: bluecolorTo: purplesdk: dockerpinned: falselicense: apache-2.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213---title: MediaMasterAsyncPreemoji: 😻colorFrom: bluecolorTo: yellowsdk: dockerapp_port: 7860startup_duration_timeout: 30mpinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""app.pyFastAPI のルーティング・起動設定のみを記述する。変換ロジックは tools/ 配下の各モジュールに委譲する。"""import osimport shutilimport uuidimport timeimport asyncioimport pathlib
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks, Bodyfrom fastapi.responses import FileResponse, HTMLResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Optional
# --- 共通モジュール ---from tools.base_tool import ( BASE_TEMP_DIR, tasks, init_db, get_colab_url, set_colab_url, get_session_paths, zip_output,)
# --- 各ツールモジュール ---from tools.image_tools import convert_heic_to_jpg, convert_jpeg_to_pdf, convert_pdf_to_pngfrom tools.audio_tools import convert_to_mp3from tools.youtube_tools import download_youtubefrom tools.file_tools import verify_password, list_files, build_zip # ←追加①
SECRET_TOKEN = os.environ.get("SECRET_TOKEN", "")
app = FastAPI()
# --- CORS ---app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
# --- DB 初期化 ---init_db()
# --- 有効な tool_id と output_format の定義 ---VALID_TOOL_IDS = {"youtube", "heic-jpg", "m4a-mp3", "mp4-mp3", "jpeg-pdf", "pdf-png"}VALID_FORMATS = {"mp3", "mp4"}
# ------------------------------------------------------------------ ## バックグラウンドタスク:各ツールへの振り分け# ------------------------------------------------------------------ #
def process_task( task_id: str, tool_id: str, url_text: str, filenames: List[str], output_format: str = "mp3"): session_path, input_path, output_path = get_session_paths(task_id)
try: # バリデーション if tool_id not in VALID_TOOL_IDS: raise ValueError(f"無効なtool_idです: {tool_id}") if output_format not in VALID_FORMATS: raise ValueError(f"無効なoutput_formatです: {output_format}")
# --- ツール振り分け --- if tool_id == "youtube": download_youtube(task_id, url_text, session_path, output_path, output_format)
elif tool_id == "heic-jpg": convert_heic_to_jpg(task_id, filenames, input_path, output_path)
elif tool_id == "jpeg-pdf": convert_jpeg_to_pdf(task_id, filenames, input_path, output_path)
elif tool_id == "pdf-png": convert_pdf_to_png(task_id, filenames, input_path, output_path)
elif tool_id in ("m4a-mp3", "mp4-mp3"): convert_to_mp3(task_id, filenames, input_path, output_path)
# --- 結果を ZIP 化 --- tasks[task_id]["last_log"] = "ファイルを圧縮中..." zip_output(session_path, output_path)
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(), })
# ------------------------------------------------------------------ ## 定期クリーンアップ(1時間ごとに完了済みタスクを削除)# ------------------------------------------------------------------ #
async def cleanup_loop(): while True: await asyncio.sleep(3600) now = time.time() to_delete = [ tid for tid, t in list(tasks.items()) if t.get("completed_at") and now - t["completed_at"] > 3600 ] for tid in to_delete: tasks.pop(tid, None) shutil.rmtree(os.path.join(BASE_TEMP_DIR, tid), ignore_errors=True)
@app.on_event("startup")async def startup_event(): try: asyncio.create_task(cleanup_loop()) except Exception as e: print(f"Cleanup loop error: {e}")
# ------------------------------------------------------------------ ## エンドポイント# ------------------------------------------------------------------ #
@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() return {"youtube_enabled": url != "", "colab_url": url}
@app.post("/api/update_colab_url")async def update_colab_url(payload: dict = Body(...)): if not SECRET_TOKEN or payload.get("token") != SECRET_TOKEN: raise HTTPException(status_code=403, detail="Forbidden") url = payload.get("url") if not url: raise HTTPException(status_code=400, detail="URLが必要です") set_colab_url(url) print(f"Colab URL Updated: {url}") return {"status": "success", "url": url}
@app.post("/api/convert")async def convert_start( background_tasks: BackgroundTasks, tool_id: str = Form(...), url: Optional[str] = Form(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: safe_name = pathlib.Path(f.filename).name file_path = os.path.join(BASE_TEMP_DIR, task_id, "input", safe_name) 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": "タスクを開始しました"} background_tasks.add_task(process_task, task_id, tool_id, url, fnames, output_format) 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") if task_id in tasks: raise HTTPException(status_code=503, detail="ファイルが一時領域から消えました。再度変換をやり直してください。") raise HTTPException(status_code=404, detail="タスクが見つかりません。")
# --- ファイルダウンロード機能 --- ←追加②
@app.post("/api/files/auth")async def files_auth(payload: dict = Body(...)): """パスワードを照合し、正しければファイル一覧を返す""" password = payload.get("password", "") if not verify_password(password): raise HTTPException(status_code=401, detail="パスワードが正しくありません") return {"files": list_files()}
@app.post("/api/files/download")async def files_download(payload: dict = Body(...)): """選択されたファイルをZIPにまとめて返す""" password = payload.get("password", "") if not verify_password(password): raise HTTPException(status_code=401, detail="パスワードが正しくありません") filenames = payload.get("filenames", []) if not filenames: raise HTTPException(status_code=400, detail="ファイルが選択されていません") try: zip_path = build_zip(filenames) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) return FileResponse(zip_path, filename="download.zip", media_type="application/zip")1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491<!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: 'video', color: 'bg-rose-600', description: '動画・音声を最高画質で保存 (Colab経由)' }, { id: 'file-download', title: 'ファイル配布', icon: 'folder-down', color: 'bg-teal-500', description: 'パスワード認証でファイルをダウンロード' }, ];
function App() { const [selectedTool, setSelectedTool] = useState(null); const [files, setFiles] = useState([]); const [youtubeUrl, setYoutubeUrl] = useState(""); const [youtubeFormat, setYoutubeFormat] = useState('mp3'); 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 [filePassword, setFilePassword] = useState(""); const [fileList, setFileList] = useState([]); const [selectedFiles, setSelectedFiles] = useState([]); const [fileError, setFileError] = useState(null); const [fileDownloading, setFileDownloading] = useState(false);
const pollInterval = useRef(null);
const handleFileChange = (e) => { 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;
setStatus('uploading'); setProgress(10); setLastLog('サーバーにリクエストを送信中...'); setDownloadUrl(null); setError(null);
const formData = new FormData(); formData.append('tool_id', selectedTool.id); if (selectedTool.id === 'youtube') { formData.append('url', youtubeUrl); formData.append('output_format', youtubeFormat); } else { files.forEach(file => formData.append('files', file)); formData.append('output_format', 'mp3'); }
try { const res = await fetch('/api/convert', { method: 'POST', body: formData }); const data = await res.json(); if (data.task_id) { startPolling(data.task_id); } else { throw new Error(data.error || "リクエストに失敗しました"); } } catch (err) { setStatus('failed'); setError(err.message || '通信エラーが発生しました'); setLastLog("処理に失敗しました"); } };
const startPolling = (tid) => { if (pollInterval.current) clearInterval(pollInterval.current); pollInterval.current = setInterval(async () => { try { const res = await fetch(`/api/status/${tid}`); const data = await res.json(); setStatus(data.status); setProgress(data.progress || 0); setLastLog(data.last_log || data.error || "");
if (data.status === 'completed') { clearInterval(pollInterval.current); setDownloadUrl(`/api/download/${tid}`); } else if (data.status === 'failed') { clearInterval(pollInterval.current); setError(data.error || '不明なエラーが発生しました'); } } catch (err) { console.error('Polling error:', err); } }, 2000); };
const reset = () => { if (pollInterval.current) clearInterval(pollInterval.current); setSelectedTool(null); setFiles([]); setYoutubeUrl(""); setYoutubeFormat('mp3'); setStatus('idle'); setProgress(0); setLastLog(""); setDownloadUrl(null); setError(null); setIsDragging(false); };
const backToInput = () => { if (pollInterval.current) clearInterval(pollInterval.current); setStatus('idle'); setProgress(0); setLastLog(""); setDownloadUrl(null); setError(null); };
const handleFileAuth = async () => { setFileError(null); try { const res = await fetch('/api/files/auth', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: filePassword }), }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || "認証に失敗しました"); setFileList(data.files); } catch (err) { setFileError(err.message); } };
const handleFilesDownload = async () => { if (selectedFiles.length === 0) return; setFileDownloading(true); setFileError(null); try { const res = await fetch('/api/files/download', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: filePassword, filenames: selectedFiles }), }); if (!res.ok) { const data = await res.json(); throw new Error(data.detail || "ダウンロードに失敗しました"); } const blob = await res.blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'download.zip'; a.click(); URL.revokeObjectURL(url); } catch (err) { setFileError(err.message); } finally { setFileDownloading(false); } };
return ( <div className="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-2 md:grid-cols-3 gap-4"> {TOOLS.map(tool => ( <button key={tool.id} onClick={() => setSelectedTool(tool)} 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={`inline-flex p-3 ${tool.color} rounded-2xl mb-4 shadow-lg`}> <Icon name={tool.icon} className="w-6 h-6 text-white" /> </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> ) : selectedTool.id === 'file-download' ? ( <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="bg-teal-500 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="folder-down" className="w-8 h-8 text-white" /> <div> <h2 className="text-xl font-black text-white">ファイル配布</h2> <p className="text-white/70 text-sm font-medium">パスワード認証でファイルをダウンロード</p> </div> </div> </div> {/* Content */} <div className="p-6 space-y-4"> {fileList.length === 0 ? ( <div className="space-y-4"> <div> <label className="block text-sm font-bold text-slate-600 mb-2">パスワード</label> <input type="password" className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl focus:border-teal-500 focus:outline-none transition-all" placeholder="パスワードを入力" value={filePassword} onChange={(e) => setFilePassword(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleFileAuth()} /> </div> {fileError && ( <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl text-rose-600 font-bold text-center text-sm"> {fileError} </div> )} <button onClick={handleFileAuth} disabled={!filePassword} className="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-teal-600 disabled:bg-slate-200 transition-all" > 認証する </button> </div> ) : ( <div className="space-y-4"> <p className="text-sm font-bold text-slate-600">ダウンロードするファイルを選択してください</p> <div className="space-y-2 max-h-64 overflow-y-auto"> {fileList.map(fname => ( <label key={fname} className="flex items-center gap-3 p-3 bg-slate-50 rounded-2xl cursor-pointer hover:bg-teal-50 transition-colors"> <input type="checkbox" className="w-4 h-4 accent-teal-500" checked={selectedFiles.includes(fname)} onChange={(e) => { if (e.target.checked) { setSelectedFiles([...selectedFiles, fname]); } else { setSelectedFiles(selectedFiles.filter(f => f !== fname)); } }} /> <Icon name="file" className="w-4 h-4 text-slate-400" /> <span className="text-sm font-medium text-slate-700">{fname}</span> </label> ))} </div> {fileError && ( <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl text-rose-600 font-bold text-center text-sm"> {fileError} </div> )} <button onClick={handleFilesDownload} disabled={selectedFiles.length === 0 || fileDownloading} className="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-teal-600 disabled:bg-slate-200 transition-all flex items-center justify-center gap-2" > <Icon name="download" className="w-5 h-5" /> {fileDownloading ? 'ダウンロード中...' : `${selectedFiles.length}件をダウンロード`} </button> </div> )} </div> </div> </div> ) : ( <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="p-6 space-y-4"> {status === 'idle' || status === 'uploading' ? ( <> {selectedTool.id === 'youtube' ? ( <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"> <input type="radio" name="format" value="mp3" checked={youtubeFormat === 'mp3'} onChange={(e) => setYoutubeFormat(e.target.value)} className="w-4 h-4 accent-indigo-600" /> <span className={`text-sm font-bold ${youtubeFormat === 'mp3' ? 'text-indigo-600' : 'text-slate-400'}`}>MP3 (音声)</span> </label> <label className="flex items-center gap-2 cursor-pointer group"> <input type="radio" name="format" value="mp4" checked={youtubeFormat === 'mp4'} onChange={(e) => setYoutubeFormat(e.target.value)} className="w-4 h-4 accent-indigo-600" /> <span className={`text-sm font-bold ${youtubeFormat === 'mp4' ? 'text-indigo-600' : 'text-slate-400'}`}>MP4 (動画)</span> </label> </div> </div> ) : ( <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 className="hidden" id="fileInput" onChange={handleFileChange} /> <label htmlFor="fileInput" className="cursor-pointer block"> <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}個のファイルを選択中` : isDragging ? 'ここにドロップ' : 'ファイルをドラッグ&ドロップ'} </p> <p className="text-slate-400 text-sm font-medium">またはクリックしてファイルを選択</p> </label> </div> )}
<button onClick={startProcessing} disabled={status !== 'idle' || (selectedTool.id === 'youtube' ? !youtubeUrl : files.length === 0)} className="w-full bg-slate-900 text-white py-4 rounded-2xl font-bold hover:bg-indigo-600 disabled:bg-slate-200 transition-all shadow-lg active:scale-[0.98]" > 処理開始 </button> </> ) : ( <div className="space-y-6 animate-in slide-in-from-bottom-2 duration-300"> <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={status === 'failed' ? 'text-rose-600' : 'text-indigo-600'}> {status === 'completed' ? '完了しました' : lastLog} </span> <span className="text-slate-400">{progress}%</span> </div> <div className="w-full bg-slate-200 rounded-full h-3 overflow-hidden"> <div className={`h-full transition-all duration-500 shadow-lg ${status === 'failed' ? 'bg-rose-500' : 'bg-indigo-600'}`} style={{ width: `${progress}%` }} ></div> </div> </div>
{error && ( <div className="p-4 bg-rose-50 border border-rose-100 rounded-2xl text-rose-600 font-bold text-center text-sm"> {error} </div> )}
<div className="flex gap-4"> <button onClick={backToInput} className="flex-1 bg-slate-100 text-slate-600 py-4 rounded-2xl font-bold hover:bg-slate-200 transition-all" > 入力に戻る </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 flex items-center justify-center gap-2" > <Icon name="download" className="w-5 h-5" /> ダウンロード </a> )} </div> </div> )} </div> </div> </div> )} </div>
{/* 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> <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>1234567891011fastapi==0.110.0uvicorn==0.27.1python-multipart==0.0.12Pillow==10.2.0pillow-heif==0.16.0pydub==0.25.1pdf2image==1.17.0yt-dlp>=2025.01.15aiofiles==23.2.1requests==2.31.0huggingface_hub==0.23.012345678910111213141516171819202122232425262728293031323334353637383940414243"""startup.pyコンテナ起動時に HuggingFace Datasets からファイルを取得する。Dockerfile の CMD で uvicorn より先に実行される。"""import osimport sysimport shutil
from huggingface_hub import snapshot_download
REPO_ID = "KeyBow/my-download-files"LOCAL_DIR = "/app/download_files"HF_TOKEN = os.environ.get("HF_TOKEN", "")
def main(): if not HF_TOKEN: print("[WARN] HF_TOKEN が設定されていません。download_files は空のまま起動します。") return
# 既存ファイルをすべて削除してから取得し直す(キャッシュ対策) if os.path.exists(LOCAL_DIR): shutil.rmtree(LOCAL_DIR) os.makedirs(LOCAL_DIR, exist_ok=True)
print(f"[INFO] Datasets からファイルを取得中: {REPO_ID}") try: snapshot_download( repo_id=REPO_ID, repo_type="dataset", local_dir=LOCAL_DIR, token=HF_TOKEN, local_dir_use_symlinks=False, # 実ファイルとして配置する ignore_patterns=[".gitattributes", "*.md"], ) files = [f for f in os.listdir(LOCAL_DIR) if os.path.isfile(os.path.join(LOCAL_DIR, f))] print(f"[INFO] 取得完了: {len(files)} 件 → {files}") except Exception as e: print(f"[ERROR] ファイル取得に失敗しました: {e}") sys.exit(1)
if __name__ == "__main__": main()DockerfileAdded+53
README.md+6-4
app.pyAdded+237
gitattributesAdded+35
index.htmlAdded+491
requirements.txtAdded+11
startup.pyAdded+43