File size: 1,327 Bytes
3859913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, UploadFile, File, HTTPException
from pydantic import BaseModel
from pathlib import Path
import tempfile
import asyncio

from .utils import download_video, extract_audio, trim_silence
from .accent_classifier import get_classifier

api = FastAPI()

class URLBody(BaseModel):
    url: str

@api.post("/analyze/url")
async def analyze_url(body: URLBody):
    with tempfile.TemporaryDirectory() as td:
        tdir = Path(td)
        video = await download_video(body.url, tdir)
        wav = tdir / "aud.wav"
        await extract_audio(video, wav)
        wav = trim_silence(wav)
        return get_classifier().classify(str(wav))

@api.post("/analyze/upload")
async def analyze_upload(file: UploadFile = File(...)):
    if not file.content_type.startswith(("audio", "video")):
        raise HTTPException(400, "Unsupported file type")
    with tempfile.NamedTemporaryFile(delete=False, suffix=file.filename) as tmp:
        tmp.write(await file.read())
        tmp.flush()
        path = Path(tmp.name)
    if file.content_type.startswith("video"):
        wav = path.with_suffix(".wav")
        await extract_audio(path, wav)
    else:
        wav = path
    wav = trim_silence(wav)
    return get_classifier().classify(str(wav))

@api.get("/healthz")
async def health():
    return {"status": "ok"}