Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, Form
|
| 2 |
+
from faster_whisper import WhisperModel
|
| 3 |
+
import uvicorn
|
| 4 |
+
import tempfile
|
| 5 |
+
import shutil
|
| 6 |
+
import torch
|
| 7 |
+
import os
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
+
compute_type = "float16" if device == "cuda" else "int8"
|
| 11 |
+
origins = [
|
| 12 |
+
"cabane-data.fr", # ton WordPress
|
| 13 |
+
]
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
|
| 16 |
+
app.add_middleware(
|
| 17 |
+
CORSMiddleware,
|
| 18 |
+
allow_origins=origins,
|
| 19 |
+
allow_credentials=True,
|
| 20 |
+
allow_methods=["*"],
|
| 21 |
+
allow_headers=["*"],
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# === Dictionnaire des modèles dispo ===
|
| 27 |
+
AVAILABLE_MODELS = ["tiny", "base", "small", "medium", "large-v2"]
|
| 28 |
+
|
| 29 |
+
def load_model(model_name: str):
|
| 30 |
+
"""Charger un modèle Whisper avec CPU (modifiable si GPU dispo)"""
|
| 31 |
+
return WhisperModel(model_name, device=device, compute_type="int8")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# === Endpoint API REST ===
|
| 35 |
+
@app.post("/transcribe")
|
| 36 |
+
async def transcribe(
|
| 37 |
+
file: UploadFile = File(...),
|
| 38 |
+
model_name: str = Form("base") # par défaut "base"
|
| 39 |
+
):
|
| 40 |
+
if model_name not in AVAILABLE_MODELS:
|
| 41 |
+
return {"error": f"Modèle non reconnu. Choisissez parmi {AVAILABLE_MODELS}"}
|
| 42 |
+
|
| 43 |
+
model = load_model(model_name)
|
| 44 |
+
|
| 45 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp:
|
| 46 |
+
shutil.copyfileobj(file.file, tmp)
|
| 47 |
+
tmp_path = tmp.name
|
| 48 |
+
|
| 49 |
+
segments, info = model.transcribe(tmp_path, beam_size=5)
|
| 50 |
+
text_result = " ".join([segment.text for segment in segments])
|
| 51 |
+
|
| 52 |
+
os.remove(tmp_path)
|
| 53 |
+
|
| 54 |
+
return {
|
| 55 |
+
"model_used": model_name,
|
| 56 |
+
"language": info.language,
|
| 57 |
+
"probability": info.language_probability,
|
| 58 |
+
"transcription": text_result,
|
| 59 |
+
}
|
| 60 |
+
|