Spaces:
Sleeping
Sleeping
Download app_fastapi.py from Skinnyeggs/auto-caption: direct link, hf CLI and curl.
- Browser
- Download file 3.25 kB
-
https://huggingface.co/spaces/Skinnyeggs/auto-caption/resolve/main/app_fastapi.py
- Command line
-
hf download hf://spaces/Skinnyeggs/auto-caption/app_fastapi.py
-
curl -L -o app_fastapi.py https://huggingface.co/spaces/Skinnyeggs/auto-caption/resolve/main/app_fastapi.py
3.25 kB
| import os | |
| import shutil | |
| import uuid | |
| import whisper | |
| from fastapi import FastAPI, UploadFile, File, HTTPException | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| from typing import List | |
| import datetime | |
| import subprocess | |
| # Try to find ffmpeg via imageio_ffmpeg if not in PATH | |
| try: | |
| import imageio_ffmpeg | |
| ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe() | |
| os.environ["PATH"] += os.pathsep + os.path.dirname(ffmpeg_path) | |
| print(f"Using ffmpeg from: {ffmpeg_path}") | |
| except ImportError: | |
| print("imageio-ffmpeg not found, relying on system PATH for ffmpeg") | |
| app = FastAPI() | |
| # Create directories if they don't exist | |
| UPLOAD_DIR = "uploads" | |
| OUTPUT_DIR = "outputs" | |
| os.makedirs(UPLOAD_DIR, exist_ok=True) | |
| os.makedirs(OUTPUT_DIR, exist_ok=True) | |
| # Load Whisper model | |
| print("Loading Whisper model (base)...") | |
| model = whisper.load_model("base") | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| async def read_index(): | |
| return FileResponse("static/index.html") | |
| def format_timestamp(seconds: float): | |
| td = datetime.timedelta(seconds=seconds) | |
| total_seconds = int(td.total_seconds()) | |
| hours = total_seconds // 3600 | |
| minutes = (total_seconds % 3600) // 60 | |
| secs = total_seconds % 60 | |
| millis = int(td.microseconds / 1000) | |
| return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}" | |
| def create_srt(segments: List[dict], output_path: str): | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| for i, segment in enumerate(segments): | |
| start = format_timestamp(segment['start']) | |
| end = format_timestamp(segment['end']) | |
| text = segment['text'].strip() | |
| f.write(f"{i + 1}\n") | |
| f.write(f"{start} --> {end}\n") | |
| f.write(f"{text}\n\n") | |
| async def process_video(file: UploadFile = File(...)): | |
| file_id = str(uuid.uuid4()) | |
| ext = os.path.splitext(file.filename)[1] | |
| video_path = os.path.join(UPLOAD_DIR, f"{file_id}{ext}") | |
| with open(video_path, "wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| try: | |
| # Transcribe | |
| result = model.transcribe(video_path) | |
| srt_filename = f"{file_id}.srt" | |
| srt_path = os.path.join(OUTPUT_DIR, srt_filename) | |
| create_srt(result['segments'], srt_path) | |
| return { | |
| "srt_filename": srt_filename, | |
| "transcript": [{"start": s['start'], "text": s['text']} for s in result['segments']] | |
| } | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| if "ffmpeg" in str(e).lower(): | |
| raise HTTPException(status_code=500, detail="FFmpeg not found. Please install FFmpeg.") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def download_file(filename: str): | |
| path = os.path.join(OUTPUT_DIR, filename) | |
| if os.path.exists(path): | |
| return FileResponse(path, filename=filename, media_type='application/x-subrip') | |
| raise HTTPException(status_code=404, detail="File not found") | |
| if __name__ == "__main__": | |
| import uvicorn | |
| print("Starting AutoCap Server at http://localhost:8000") | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |