Spaces:
Sleeping

saidchrf commited on
Commit
4a2cc5a
·
verified ·
1 Parent(s): 6a7937b

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +56 -0
main.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Response
2
+ from kokoro_onnx import Kokoro
3
+ from huggingface_hub import hf_hub_download
4
+ import soundfile as sf
5
+ import io
6
+ import os
7
+
8
+ app = FastAPI()
9
+
10
+ # --- Configuration ---
11
+ # On télécharge les fichiers modèles au démarrage s'ils ne sont pas là
12
+ print("⏳ Chargement ou téléchargement du modèle Kokoro...")
13
+
14
+ if not os.path.exists("kokoro-v0_19.onnx"):
15
+ hf_hub_download(repo_id="hexgrad/Kokoro-82M", filename="kokoro-v0_19.onnx", local_dir=".")
16
+
17
+ if not os.path.exists("voices.json"):
18
+ hf_hub_download(repo_id="hexgrad/Kokoro-82M", filename="voices.json", local_dir=".")
19
+
20
+ # Initialisation de Kokoro (Une seule fois pour ne pas saturer la RAM)
21
+ kokoro = Kokoro("kokoro-v0_19.onnx", "voices.json")
22
+ print("✅ Kokoro est prêt !")
23
+
24
+ @app.get("/")
25
+ def home():
26
+ return {"status": "Kokoro API is running", "dev": "Ton Nom Freelance"}
27
+
28
+ @app.post("/generate")
29
+ def generate_audio(text: str, voice: str = "af_bella", speed: float = 1.0, lang: str = "en-us"):
30
+ """
31
+ Génère de l'audio et renvoie le fichier WAV directement.
32
+ """
33
+ # Langues supportées par Kokoro: 'a' (US), 'b' (UK), 'f' (FR), 'j' (JP), etc.
34
+ # Petit mapping pour faciliter la vie
35
+ lang_map = {"fr": "f", "en": "a", "us": "a", "uk": "b"}
36
+ lang_code = lang_map.get(lang.lower(), lang) # Par défaut garde la lettre si pas dans la map
37
+
38
+ try:
39
+ # Génération
40
+ audio, sample_rate = kokoro.create(
41
+ text,
42
+ voice=voice,
43
+ speed=speed,
44
+ lang=lang_code
45
+ )
46
+
47
+ # Conversion en fichier binaire (WAV) en mémoire
48
+ buffer = io.BytesIO()
49
+ sf.write(buffer, audio, sample_rate, format='WAV')
50
+ buffer.seek(0)
51
+
52
+ # Renvoie le fichier audio
53
+ return Response(content=buffer.read(), media_type="audio/wav")
54
+
55
+ except Exception as e:
56
+ return {"error": str(e)}