Spaces:
Sleeping
Sleeping
Upload 4 files
Browse filesFiles changed (4)
- Dockerfile+29-36
- main.py+3-12
- requirements.txt+4-4
- start.shAdded+28
123456789101112131415161718192021222324252627282930313233343536373839404142FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04ENV DEBIAN_FRONTEND=noninteractive \PIP_NO_CACHE_DIR=1 \PYTHONUNBUFFERED=1 \TRANSFORMERS_CACHE=/home/user/.cache/huggingface \HF_HOME=/home/user/.cache/huggingface \XDG_CACHE_HOME=/home/user/.cache \WHISPER_CACHE_DIR=/home/user/.cache/whisper \WHISPER_MODEL=large-v2 \MAX_UPLOAD_BYTES=52428800 \MAX_CONCURRENT=1RUN apt-get update && apt-get install -y --no-install-recommends \ffmpeg git python3 python3-pip && rm -rf /var/lib/apt/lists/*# Non-root runtime userRUN useradd -m -u 1000 userWORKDIR /app# ---- Python depsCOPY requirements.txt /app/requirements.txtRUN python3 -m pip install --upgrade pip && python3 -m pip install -r /app/requirements.txt# ---- Warm model cache to avoid cold startRUN mkdir -p /home/user/.cache/huggingface /home/user/.cache/whisper && \chown -R user:user /home/user/.cacheRUN python3 - <<'PY'import os, whispercache = os.environ.get("WHISPER_CACHE_DIR", "/home/user/.cache/whisper")model = os.environ.get("WHISPER_MODEL","large-v2")whisper.load_model(model, download_root=cache)print(f"Preloaded model {model} into {cache}")PY# ---- App codeCOPY main.py /app/main.pyRUN chown -R user:user /appUSER userEXPOSE 7860CMD ["uvicorn","main:app","--host","0.0.0.0","--port","7860","--timeout-keep-alive","75"]1234567891011121314151617181920212223242526272829303132333435FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04ENV DEBIAN_FRONTEND=noninteractive \PIP_NO_CACHE_DIR=1 \PYTHONUNBUFFERED=1 \TRANSFORMERS_CACHE=/home/user/.cache/huggingface \HF_HOME=/home/user/.cache/huggingface \XDG_CACHE_HOME=/home/user/.cache \WHISPER_CACHE_DIR=/home/user/.cache/whisper \WHISPER_MODEL=tiny \MAX_UPLOAD_BYTES=52428800 \MAX_CONCURRENT=1RUN apt-get update && apt-get install -y --no-install-recommends \ffmpeg git python3 python3-pip && rm -rf /var/lib/apt/lists/*# Non-root runtime userRUN useradd -m -u 1000 userWORKDIR /app# ---- Python depsCOPY requirements.txt /app/requirements.txtRUN python3 -m pip install --upgrade pip \&& python3 -m pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cu121 torch==2.3.1+cu121 \&& python3 -m pip install --no-cache-dir -r /app/requirements.txt# App codeCOPY main.py /app/main.pyCOPY start.sh /app/start.shRUN chmod +x /app/start.sh && chown -R user:user /app /home/userUSER userEXPOSE 7860# Warm model cache at runtime if missing, then launchENTRYPOINT ["/app/start.sh"]
48 unmodified lines495051525354551 unmodified line5758596061626322 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412534 unmodified lines16016116216316416516648 unmodified linesfp16 = device == "cuda"log.info(f"Loading Whisper '%s' on %s (fp16=%s)", MODEL_NAME, device, fp16)# Global model (loaded at process start, benefits from Docker preload)model = whisper.load_model(MODEL_NAME, device=device, download_root=CACHE_DIR)# ------------------------1 unmodified line# ------------------------app = FastAPI(title="Whisper API",version="1.2.0",openapi_url="/api/v1/stt/openapi.json",docs_url="/api/v1/stt/docs")22 unmodified lines@app.get("/healthz")def healthz():# cheap check: returns device and cuda mem if availableinfo = {"device": device}if device == "cuda":try:info["cuda_mem_allocated"] = torch.cuda.memory_allocated() # bytesinfo["cuda_mem_reserved"] = torch.cuda.memory_reserved()except Exception:passreturn {"ok": True, **info}# ---- helpers ----def _safe_tmp(suffix: str = ".wav") -> str:fd, path = tempfile.mkstemp(prefix="aud_", suffix=suffix, dir="/tmp")os.close(fd)return pathdef _ffmpeg_norm(src: str, dst: str):# Force mono/16k PCM WAV for maximum stabilitycmd = ["ffmpeg","-y","-i",src,"-ac","1","-ar","16000","-f","wav",dst]r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)if r.returncode != 0:raise RuntimeError(r.stderr.decode(errors="ignore")[:400])# ------------------------# Transcription endpoint# ------------------------@app.post("/transcribe")async def transcribir_audio(file: UploadFile = File(...), _: bool = Depends(verify_token)):# Read whole body (keeps code simple, you can stream if needed)raw = await file.read()if len(raw) > MAX_BYTES:raise HTTPException(413, f"Archivo excede {MAX_BYTES/1024/1024:.1f} MB")# Use safe temp names (avoid path traversal using user filename)src_suffix = os.path.splitext(file.filename or "")[1] or ".bin"src = _safe_tmp(src_suffix)with open(src, "wb") as f:34 unmodified linesexcept Exception:pass# Local run: uvicorn main:app --host 0.0.0.0 --port 7860if __name__ == "__main__":import uvicornuvicorn.run("main:app", host="0.0.0.0", port=int(os.getenv("PORT", "7860")))48 unmodified lines495051525354551 unmodified line5758596061626322 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211311411511611734 unmodified lines15215315415515615748 unmodified linesfp16 = device == "cuda"log.info(f"Loading Whisper '%s' on %s (fp16=%s)", MODEL_NAME, device, fp16)# Global model (loaded at process start; cache is prewarmed by start.sh)model = whisper.load_model(MODEL_NAME, device=device, download_root=CACHE_DIR)# ------------------------1 unmodified line# ------------------------app = FastAPI(title="Whisper API",version="1.2.1",openapi_url="/api/v1/stt/openapi.json",docs_url="/api/v1/stt/docs")22 unmodified lines@app.get("/healthz")def healthz():info = {"device": device}if device == "cuda":try:info["cuda_mem_allocated"] = torch.cuda.memory_allocated()info["cuda_mem_reserved"] = torch.cuda.memory_reserved()except Exception:passreturn {"ok": True, **info}def _safe_tmp(suffix: str = ".wav") -> str:fd, path = tempfile.mkstemp(prefix="aud_", suffix=suffix, dir="/tmp")os.close(fd)return pathdef _ffmpeg_norm(src: str, dst: str):cmd = ["ffmpeg","-y","-i",src,"-ac","1","-ar","16000","-f","wav",dst]r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)if r.returncode != 0:raise RuntimeError(r.stderr.decode(errors="ignore")[:400])@app.post("/transcribe")async def transcribir_audio(file: UploadFile = File(...), _: bool = Depends(verify_token)):raw = await file.read()if len(raw) > MAX_BYTES:raise HTTPException(413, f"Archivo excede {MAX_BYTES/1024/1024:.1f} MB")src_suffix = os.path.splitext(file.filename or "")[1] or ".bin"src = _safe_tmp(src_suffix)with open(src, "wb") as f:34 unmodified linesexcept Exception:passif __name__ == "__main__":import uvicornuvicorn.run("main:app", host="0.0.0.0", port=int(os.getenv("PORT", "7860")))
123456fastapi==0.110.0uvicorn==0.27.1python-multipart==0.0.9torch>=2.0.0openai-whisper==20231117ffmpeg-python==0.2.0123456fastapi==0.111.0uvicorn==0.30.6python-multipart==0.0.9openai-whisper==20231117# torch is installed separately for CUDA 12.1 (cu121) in Dockerfile# ffmpeg provided by OS package in Docker image
12345678910111213141516171819202122232425262728 #!/usr/bin/env bash set -euo pipefail
export HOME=/home/user export TRANSFORMERS_CACHE=${TRANSFORMERS_CACHE:-/home/user/.cache/huggingface} export HF_HOME=${HF_HOME:-/home/user/.cache/huggingface} export XDG_CACHE_HOME=${XDG_CACHE_HOME:-/home/user/.cache} export WHISPER_CACHE_DIR=${WHISPER_CACHE_DIR:-/home/user/.cache/whisper} export WHISPER_MODEL=${WHISPER_MODEL:-large-v2}
mkdir -p "$TRANSFORMERS_CACHE" "$WHISPER_CACHE_DIR"
echo "[startup] Checking Whisper model cache for $WHISPER_MODEL ..." python3 - <<'PY'import os, glob, whispercache = os.environ.get("WHISPER_CACHE_DIR", "/home/user/.cache/whisper")model = os.environ.get("WHISPER_MODEL", "large-v2")# Simple presence check (whisper stores model files under cache dir)existing = glob.glob(os.path.join(cache, "*"))if existing: print(f"[startup] Cache has {len(existing)} entries in {cache}")else: print(f"[startup] Preloading model {model} into {cache} (first run)...") whisper.load_model(model, download_root=cache) print("[startup] Preload done")PY
exec uvicorn main:app --host 0.0.0.0 --port 7860 --timeout-keep-alive 75Dockerfile+29-36
main.py+3-12
requirements.txt+4-4
start.shAdded+28