TGPro1 commited on
Commit
f7660ed
Β·
verified Β·
1 Parent(s): 36f4ae1

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +55 -65
app.py CHANGED
@@ -5,75 +5,77 @@ import base64
5
  import torch
6
  import tempfile
7
  import traceback
8
- import gc
9
  from fastapi import FastAPI, Request
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from fastapi.responses import HTMLResponse
12
  import uvicorn
13
 
14
- # --- [v143] πŸš€ SEAMLESS HYBRID ENGINE (CPU STT + GPU TTS / FIX NESTING) ---
15
- print(f"--- [v143] πŸ“‘ BOOTING SEAMLESS HYBRID ---")
16
 
17
  from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
18
  from TTS.api import TTS
19
  from deep_translator import GoogleTranslator
20
 
21
- try:
22
- import chatterbox_utils
23
- HAS_CHATTERBOX = True
24
- except ImportError:
25
- HAS_CHATTERBOX = False
26
-
27
- try:
28
- import spaces
29
- HAS_SPACES = True
30
- except ImportError:
31
- HAS_SPACES = False
32
- class spaces:
33
- @staticmethod
34
- def GPU(duration=60, f=None):
35
- if f is None: return lambda x: x
36
- return f
37
-
38
  os.environ["COQUI_TOS_AGREED"] = "1"
39
  os.environ["PYTHONWARNINGS"] = "ignore"
40
 
41
  app = FastAPI()
42
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
43
 
 
 
 
44
  MODELS = {"stt": None, "tts": None}
45
 
46
- def load_cpu_stt():
47
- """Loads Whisper on CPU."""
48
  global MODELS
 
49
  if MODELS.get("stt") is None:
50
- print("--- [v143] πŸ“₯ LOADING WHISPER ON CPU ---")
51
  model_id = "openai/whisper-large-v3-turbo"
52
- model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch.float32, low_cpu_mem_usage=True)
 
 
 
53
  processor = AutoProcessor.from_pretrained(model_id)
54
- MODELS["stt"] = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor, device="cpu")
55
- print("--- [v143] βœ… WHISPER LOADED (CPU) ---")
 
 
 
 
 
 
 
56
 
57
- def load_gpu_tts_internal():
58
- """Loads XTTS on GPU (called within @spaces.GPU). No decorator here to avoid nesting."""
59
- global MODELS
60
  if MODELS.get("tts") is None:
61
- print("--- [v143] πŸ“₯ LOADING XTTS ON GPU ---")
62
- MODELS["tts"] = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to("cuda")
63
- print("--- [v143] βœ… XTTS LOADED (GPU) ---")
64
-
65
- @spaces.GPU(duration=120)
66
- def tts_process_gpu(text, target_lang, speaker_wav_b64=None):
67
- """The ONLY @spaces.GPU entry point for TTS."""
68
- load_gpu_tts_internal()
 
 
 
 
 
 
 
 
 
 
 
 
69
  XTTS_MAP = {"en": "en", "de": "de", "fr": "fr", "es": "es", "it": "it", "pl": "pl", "pt": "pt", "tr": "tr", "ru": "ru", "nl": "nl", "cs": "cs", "ar": "ar", "hu": "hu", "ko": "ko", "hi": "hi", "zh": "zh-cn"}
70
  clean_lang = target_lang.split('-')[0].lower()
71
  mapped_lang = XTTS_MAP.get(clean_lang) or ("zh-cn" if clean_lang == "zh" else None)
72
 
73
- if not mapped_lang:
74
- if HAS_CHATTERBOX:
75
- audio_bytes = chatterbox_utils.run_chatterbox_inference(text, clean_lang)
76
- return base64.b64encode(audio_bytes).decode()
77
  return {"error": f"Language {clean_lang} not supported."}
78
 
79
  speaker_wav_path = "default_speaker.wav"
@@ -85,42 +87,31 @@ def tts_process_gpu(text, target_lang, speaker_wav_b64=None):
85
  speaker_wav_path = None
86
 
87
  try:
88
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as out_f: out_p = out_f.name
 
89
  MODELS["tts"].tts_to_file(text=text, language=mapped_lang, file_path=out_p, speaker_wav=speaker_wav_path)
90
- with open(out_p, "rb") as f: audio_b64 = base64.b64encode(f.read()).decode()
 
91
  return audio_b64
92
  finally:
93
  if speaker_wav_b64 and os.path.exists(speaker_wav_path): os.unlink(speaker_wav_path)
94
  if 'out_p' in locals() and os.path.exists(out_p): os.unlink(out_p)
95
 
96
- def stt_process_cpu(audio_b64, lang):
97
- load_cpu_stt()
98
- audio_bytes = base64.b64decode(audio_b64)
99
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
100
- f.write(audio_bytes); temp_path = f.name
101
- try:
102
- result = MODELS["stt"](temp_path, generate_kwargs={"language": lang if lang and len(lang) <= 3 else None})
103
- return result["text"].strip()
104
- finally:
105
- if os.path.exists(temp_path): os.unlink(temp_path)
106
-
107
  @app.post("/process")
108
  async def api_process(request: Request):
109
  try:
110
  data = await request.json()
111
  action = data.get("action")
112
- if action == "health": return {"status": "awake", "v": "143"}
113
 
114
- print(f"--- [v143] πŸ› οΈ HYBRID ACTION: {action} ---")
115
  t1 = time.time()
116
 
117
- # πŸŽ™οΈ STT Segment (CPU)
118
  stt_text = None
119
  if action in ["stt", "s2st"]:
120
- stt_text = stt_process_cpu(data.get("file"), data.get("lang"))
121
  if action == "stt": return {"text": stt_text}
122
 
123
- # πŸ”Š TTS Segment (GPU)
124
  if action in ["tts", "s2st"]:
125
  text = (data.get("text") if action == "tts" else stt_text).strip()
126
  trans_text = text
@@ -131,24 +122,23 @@ async def api_process(request: Request):
131
 
132
  if len(text) < 2: return {"audio": ""} if action == "tts" else {"text": stt_text, "translated": "", "audio": ""}
133
 
134
- # This is the single @spaces.GPU gated call
135
- audio_res = tts_process_gpu(text, (data.get("lang") if action == "tts" else target), data.get("speaker_wav"))
136
 
137
  if isinstance(audio_res, dict) and "error" in audio_res: return audio_res
138
  if action == "tts": return {"audio": audio_res}
139
  return {"text": stt_text, "translated": trans_text, "audio": audio_res}
140
 
141
  except Exception as e:
142
- print(f"❌ [v143] ERROR: {traceback.format_exc()}")
143
  return {"error": str(e)}
144
  finally:
145
- print(f"--- [v143] ✨ DONE ({time.time()-t1:.1f}s) ---")
146
 
147
  @app.get("/health")
148
- def health(): return {"status": "ok", "v": "143", "mode": "HYBRID"}
149
 
150
  @app.get("/", response_class=HTMLResponse)
151
- def root(): return "<html><body><h1>πŸš€ AI Engine v143 (SEAMLESS HYBRID)</h1></body></html>"
152
 
153
  if __name__ == "__main__":
154
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
5
  import torch
6
  import tempfile
7
  import traceback
 
8
  from fastapi import FastAPI, Request
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.responses import HTMLResponse
11
  import uvicorn
12
 
13
+ # --- [v145] πŸš€ PERSISTENT GPU ENGINE (NO SERVERLESS) ---
14
+ print(f"--- [v145] πŸ“‘ BOOTING PERSISTENT GPU ENGINE ---")
15
 
16
  from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
17
  from TTS.api import TTS
18
  from deep_translator import GoogleTranslator
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  os.environ["COQUI_TOS_AGREED"] = "1"
21
  os.environ["PYTHONWARNINGS"] = "ignore"
22
 
23
  app = FastAPI()
24
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
25
 
26
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
27
+ print(f"--- [v145] πŸ–₯️ DEVICE: {DEVICE} ---")
28
+
29
  MODELS = {"stt": None, "tts": None}
30
 
31
+ def load_models():
32
+ """Load models once at startup, keep in VRAM."""
33
  global MODELS
34
+
35
  if MODELS.get("stt") is None:
36
+ print("--- [v145] πŸ“₯ LOADING WHISPER ---")
37
  model_id = "openai/whisper-large-v3-turbo"
38
+ dtype = torch.float16 if DEVICE == "cuda" else torch.float32
39
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
40
+ model_id, torch_dtype=dtype, low_cpu_mem_usage=True, use_safetensors=True
41
+ ).to(DEVICE)
42
  processor = AutoProcessor.from_pretrained(model_id)
43
+ MODELS["stt"] = pipeline(
44
+ "automatic-speech-recognition",
45
+ model=model,
46
+ tokenizer=processor.tokenizer,
47
+ feature_extractor=processor.feature_extractor,
48
+ torch_dtype=dtype,
49
+ device=DEVICE
50
+ )
51
+ print("--- [v145] βœ… WHISPER LOADED ---")
52
 
 
 
 
53
  if MODELS.get("tts") is None:
54
+ print("--- [v145] πŸ“₯ LOADING XTTS ---")
55
+ MODELS["tts"] = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(DEVICE)
56
+ print("--- [v145] βœ… XTTS LOADED ---")
57
+
58
+ # Load models at startup
59
+ print("--- [v145] πŸ”„ LOADING MODELS AT STARTUP ---")
60
+ load_models()
61
+ print("--- [v145] βœ… ALL MODELS READY ---")
62
+
63
+ def stt_process(audio_b64, lang):
64
+ audio_bytes = base64.b64decode(audio_b64)
65
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
66
+ f.write(audio_bytes); temp_path = f.name
67
+ try:
68
+ result = MODELS["stt"](temp_path, generate_kwargs={"language": lang if lang and len(lang) <= 3 else None})
69
+ return result["text"].strip()
70
+ finally:
71
+ if os.path.exists(temp_path): os.unlink(temp_path)
72
+
73
+ def tts_process(text, target_lang, speaker_wav_b64=None):
74
  XTTS_MAP = {"en": "en", "de": "de", "fr": "fr", "es": "es", "it": "it", "pl": "pl", "pt": "pt", "tr": "tr", "ru": "ru", "nl": "nl", "cs": "cs", "ar": "ar", "hu": "hu", "ko": "ko", "hi": "hi", "zh": "zh-cn"}
75
  clean_lang = target_lang.split('-')[0].lower()
76
  mapped_lang = XTTS_MAP.get(clean_lang) or ("zh-cn" if clean_lang == "zh" else None)
77
 
78
+ if not mapped_lang:
 
 
 
79
  return {"error": f"Language {clean_lang} not supported."}
80
 
81
  speaker_wav_path = "default_speaker.wav"
 
87
  speaker_wav_path = None
88
 
89
  try:
90
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as out_f:
91
+ out_p = out_f.name
92
  MODELS["tts"].tts_to_file(text=text, language=mapped_lang, file_path=out_p, speaker_wav=speaker_wav_path)
93
+ with open(out_p, "rb") as f:
94
+ audio_b64 = base64.b64encode(f.read()).decode()
95
  return audio_b64
96
  finally:
97
  if speaker_wav_b64 and os.path.exists(speaker_wav_path): os.unlink(speaker_wav_path)
98
  if 'out_p' in locals() and os.path.exists(out_p): os.unlink(out_p)
99
 
 
 
 
 
 
 
 
 
 
 
 
100
  @app.post("/process")
101
  async def api_process(request: Request):
102
  try:
103
  data = await request.json()
104
  action = data.get("action")
105
+ if action == "health": return {"status": "awake", "v": "145", "mode": "PERSISTENT_GPU", "device": DEVICE}
106
 
107
+ print(f"--- [v145] πŸ› οΈ PROCESSING: {action} ---")
108
  t1 = time.time()
109
 
 
110
  stt_text = None
111
  if action in ["stt", "s2st"]:
112
+ stt_text = stt_process(data.get("file"), data.get("lang"))
113
  if action == "stt": return {"text": stt_text}
114
 
 
115
  if action in ["tts", "s2st"]:
116
  text = (data.get("text") if action == "tts" else stt_text).strip()
117
  trans_text = text
 
122
 
123
  if len(text) < 2: return {"audio": ""} if action == "tts" else {"text": stt_text, "translated": "", "audio": ""}
124
 
125
+ audio_res = tts_process(text, data.get("lang") if action == "tts" else target, data.get("speaker_wav"))
 
126
 
127
  if isinstance(audio_res, dict) and "error" in audio_res: return audio_res
128
  if action == "tts": return {"audio": audio_res}
129
  return {"text": stt_text, "translated": trans_text, "audio": audio_res}
130
 
131
  except Exception as e:
132
+ print(f"❌ [v145] ERROR: {traceback.format_exc()}")
133
  return {"error": str(e)}
134
  finally:
135
+ print(f"--- [v145] ✨ DONE ({time.time()-t1:.1f}s) ---")
136
 
137
  @app.get("/health")
138
+ def health(): return {"status": "ok", "v": "145", "mode": "PERSISTENT_GPU", "device": DEVICE}
139
 
140
  @app.get("/", response_class=HTMLResponse)
141
+ def root(): return f"<html><body><h1>πŸš€ AI Engine v145 (PERSISTENT GPU)</h1><p>Device: {DEVICE}</p></body></html>"
142
 
143
  if __name__ == "__main__":
144
  uvicorn.run(app, host="0.0.0.0", port=7860)