Spaces:
Sleeping
Sleeping
File size: 3,245 Bytes
065189e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | 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")
@app.get("/")
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")
@app.post("/process")
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))
@app.get("/download/{filename}")
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)
|