Spaces:
Sleeping
Sleeping
Download api.py from Oulkra/mesure-intelligibilite: direct link, hf CLI and curl.
- Browser
- Download file 4.47 kB
-
https://huggingface.co/spaces/Oulkra/mesure-intelligibilite/resolve/main/api.py
- Command line
-
hf download hf://spaces/Oulkra/mesure-intelligibilite/api.py
-
curl -L -o api.py https://huggingface.co/spaces/Oulkra/mesure-intelligibilite/resolve/main/api.py
4.47 kB
| import asyncio | |
| import json | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import wave | |
| from fastapi import FastAPI, File, HTTPException, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| ROOT = Path(__file__).resolve().parent | |
| MAX_AUDIO_BYTES = 15 * 1024 * 1024 | |
| MIN_DURATION_SECONDS = 4 | |
| MAX_DURATION_SECONDS = 30 | |
| ANALYSIS_TIMEOUT_SECONDS = 240 | |
| analysis_lock = asyncio.Lock() | |
| app = FastAPI( | |
| title="Mesure d'intelligibilite", | |
| version="3.3.0", | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=[ | |
| "http://127.0.0.1:4173", | |
| "http://127.0.0.1:4174", | |
| "http://localhost:4173", | |
| "http://localhost:4174", | |
| "https://louiiiiiiis.github.io", | |
| "https://louis-gabernet.fr", | |
| "https://www.louis-gabernet.fr", | |
| ], | |
| allow_credentials=False, | |
| allow_methods=["GET", "POST", "OPTIONS"], | |
| allow_headers=["*"], | |
| ) | |
| def health(): | |
| return { | |
| "status": "ready", | |
| "model": "Whisper Base calibration + short ambiguity guard", | |
| "mode": "free_speech_asr_robustness", | |
| "retention": "temporary", | |
| } | |
| async def analyze(audio: UploadFile = File(...)): | |
| content = await audio.read(MAX_AUDIO_BYTES + 1) | |
| await audio.close() | |
| if not content: | |
| raise HTTPException(status_code=400, detail="L'enregistrement est vide.") | |
| if len(content) > MAX_AUDIO_BYTES: | |
| raise HTTPException(status_code=413, detail="L'enregistrement depasse 15 Mo.") | |
| if content[:4] != b"RIFF" or content[8:12] != b"WAVE": | |
| raise HTTPException(status_code=415, detail="Le moteur attend un fichier WAV PCM.") | |
| async with analysis_lock: | |
| return await asyncio.to_thread(run_analysis, content) | |
| def run_analysis(content): | |
| with tempfile.TemporaryDirectory(prefix="intelligibilite_") as temp_dir: | |
| temp_path = Path(temp_dir) | |
| wav_path = temp_path / "enregistrement.wav" | |
| output_path = temp_path / "resultat.json" | |
| wav_path.write_bytes(content) | |
| duration = validate_wav(wav_path) | |
| command = [ | |
| sys.executable, | |
| str(ROOT / "metrics.py"), | |
| "--wav_dir", | |
| str(temp_path), | |
| "--nisqa_repo", | |
| str(ROOT / "NISQA"), | |
| "--whisper_cache", | |
| str(ROOT / ".cache" / "whisper"), | |
| "--output", | |
| str(output_path), | |
| ] | |
| environment = { | |
| **os.environ, | |
| "PYTHONIOENCODING": "utf-8", | |
| } | |
| try: | |
| completed = subprocess.run( | |
| command, | |
| cwd=ROOT, | |
| env=environment, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| timeout=ANALYSIS_TIMEOUT_SECONDS, | |
| check=False, | |
| ) | |
| except subprocess.TimeoutExpired as error: | |
| raise HTTPException(status_code=504, detail="L'analyse a depasse quatre minutes.") from error | |
| if completed.returncode != 0 or not output_path.is_file(): | |
| details = (completed.stderr or completed.stdout or "Erreur inconnue").strip() | |
| raise HTTPException(status_code=500, detail=f"Echec du moteur : {details[-1200:]}") | |
| payload = json.loads(output_path.read_text(encoding="utf-8")) | |
| if not payload: | |
| raise HTTPException(status_code=500, detail="Le moteur n'a retourne aucun resultat.") | |
| result = payload[0] | |
| result["duration_seconds"] = round(duration, 2) | |
| if result.get("MetricErrors"): | |
| result["warning"] = "Certaines metriques n'ont pas pu etre calculees." | |
| return result | |
| def validate_wav(path): | |
| try: | |
| with wave.open(str(path), "rb") as wav_file: | |
| frame_rate = wav_file.getframerate() | |
| frame_count = wav_file.getnframes() | |
| duration = frame_count / frame_rate if frame_rate else 0 | |
| except (wave.Error, EOFError) as error: | |
| raise HTTPException(status_code=415, detail="Le fichier WAV est invalide.") from error | |
| if duration < MIN_DURATION_SECONDS: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="L'enregistrement doit durer au moins quatre secondes.", | |
| ) | |
| if duration > MAX_DURATION_SECONDS + 1: | |
| raise HTTPException(status_code=413, detail="L'enregistrement depasse 30 secondes.") | |
| return duration | |