Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -18,13 +18,12 @@ from threading import Thread, Lock
|
|
| 18 |
from huggingface_hub import snapshot_download
|
| 19 |
|
| 20 |
# π‘οΈ 1. SILENCE VERBOSE LOGGING
|
| 21 |
-
# Minimize "steps" in logs as requested by user
|
| 22 |
logging.getLogger("transformers").setLevel(logging.ERROR)
|
| 23 |
logging.getLogger("TTS").setLevel(logging.ERROR)
|
| 24 |
os.environ["CT2_VERBOSE"] = "0"
|
| 25 |
os.environ["KMP_WARNINGS"] = "0"
|
| 26 |
|
| 27 |
-
# π οΈ 2.
|
| 28 |
if "torchaudio.backend" not in sys.modules:
|
| 29 |
backend = types.ModuleType("torchaudio.backend")
|
| 30 |
common = types.ModuleType("torchaudio.backend.common")
|
|
@@ -78,8 +77,8 @@ except ImportError:
|
|
| 78 |
if f is None: return lambda x: x
|
| 79 |
return f
|
| 80 |
|
| 81 |
-
# FORCE BUILD TRIGGER: 11:
|
| 82 |
-
#
|
| 83 |
|
| 84 |
os.environ["COQUI_TOS_AGREED"] = "1"
|
| 85 |
MODELS = {"stt": None, "translate": None, "tts": None, "denoiser": None}
|
|
@@ -88,47 +87,34 @@ WARMUP_STATUS = {"complete": False, "in_progress": False, "error": None}
|
|
| 88 |
WARMUP_LOCK = Lock()
|
| 89 |
|
| 90 |
def activate_gpu_models(action):
|
| 91 |
-
"""
|
| 92 |
global MODELS, WARMUP_STATUS
|
| 93 |
-
|
| 94 |
-
# Force local-only if warmup is done
|
| 95 |
local_only = WARMUP_STATUS["complete"]
|
| 96 |
|
| 97 |
-
# 1. Faster-Whisper
|
| 98 |
if action in ["stt", "s2st"]:
|
| 99 |
stt_ready = False
|
| 100 |
try: stt_ready = MODELS["stt"] is not None and MODELS["stt"].model.device == "cuda"
|
| 101 |
except: pass
|
| 102 |
-
|
| 103 |
if not stt_ready:
|
| 104 |
-
print(f"ποΈ [
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
gc.collect(); torch.cuda.empty_cache()
|
| 108 |
-
|
| 109 |
-
MODELS["stt"] = WhisperModel(
|
| 110 |
-
"large-v3",
|
| 111 |
-
device="cuda",
|
| 112 |
-
compute_type="float16",
|
| 113 |
-
local_files_only=local_only
|
| 114 |
-
)
|
| 115 |
|
| 116 |
-
# 2. XTTS-v2
|
| 117 |
if action in ["tts", "s2st"]:
|
| 118 |
-
|
| 119 |
try:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
except: pass
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
print(f"π [v93] Activating XTTS-v2 (Local Mode={local_only})...")
|
| 126 |
if MODELS["tts"] is None:
|
| 127 |
MODELS["tts"] = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2", gpu=True)
|
| 128 |
-
else:
|
| 129 |
-
MODELS["tts"].to("cuda")
|
| 130 |
|
| 131 |
-
# 3. Helpers
|
| 132 |
if MODELS["denoiser"] is None:
|
| 133 |
try: MODELS["denoiser"] = init_df()
|
| 134 |
except: pass
|
|
@@ -136,38 +122,26 @@ def activate_gpu_models(action):
|
|
| 136 |
chatterbox_utils.load_chatterbox(device="cuda" if torch.cuda.is_available() else "cpu")
|
| 137 |
|
| 138 |
def warmup_task():
|
| 139 |
-
"""Silent Background Warmup (
|
| 140 |
global WARMUP_STATUS
|
| 141 |
with WARMUP_LOCK:
|
| 142 |
if WARMUP_STATUS["complete"] or WARMUP_STATUS["in_progress"]: return
|
| 143 |
WARMUP_STATUS["in_progress"] = True
|
| 144 |
|
| 145 |
-
|
| 146 |
-
print("\nπ₯ --- SILENT WARMUP STARTED (v93) ---")
|
| 147 |
start = time.time()
|
| 148 |
try:
|
| 149 |
-
# 1. Faster-Whisper
|
| 150 |
-
print("π₯ Pre-loading Whisper to System RAM...")
|
| 151 |
MODELS["stt"] = WhisperModel("large-v3", device="cpu", compute_type="int8")
|
| 152 |
-
|
| 153 |
-
# 2. XTTS-v2
|
| 154 |
-
print("π₯ Pre-loading XTTS-v2 to System RAM...")
|
| 155 |
MODELS["tts"] = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)
|
| 156 |
-
|
| 157 |
-
# 3. Chatterbox
|
| 158 |
chatterbox_utils.warmup_chatterbox()
|
| 159 |
-
|
| 160 |
WARMUP_STATUS["complete"] = True
|
| 161 |
-
print(f"β
--- SYSTEM
|
| 162 |
except Exception as e:
|
| 163 |
print(f"β Warmup fail: {e}")
|
| 164 |
WARMUP_STATUS["error"] = str(e)
|
| 165 |
finally:
|
| 166 |
WARMUP_STATUS["in_progress"] = False
|
| 167 |
|
| 168 |
-
def start_background_warmup():
|
| 169 |
-
Thread(target=warmup_task, daemon=True).start()
|
| 170 |
-
|
| 171 |
def _stt_logic(request_dict):
|
| 172 |
audio_bytes = base64.b64decode(request_dict.get("file"))
|
| 173 |
lang = request_dict.get("lang")
|
|
@@ -187,7 +161,6 @@ def _tts_logic(text, lang, speaker_wav_b64):
|
|
| 187 |
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"}
|
| 188 |
clean_lang = lang.strip().lower().split('-')[0]
|
| 189 |
mapped_lang = XTTS_MAP.get(clean_lang) or ("zh-cn" if clean_lang == "zh" else None)
|
| 190 |
-
|
| 191 |
if mapped_lang:
|
| 192 |
speaker_wav_path = None
|
| 193 |
if speaker_wav_b64:
|
|
@@ -203,7 +176,6 @@ def _tts_logic(text, lang, speaker_wav_b64):
|
|
| 203 |
finally:
|
| 204 |
if speaker_wav_path and "default_speaker" not in speaker_wav_path and os.path.exists(speaker_wav_path): os.unlink(speaker_wav_path)
|
| 205 |
if 'output_path' in locals() and os.path.exists(output_path): os.unlink(output_path)
|
| 206 |
-
|
| 207 |
try:
|
| 208 |
temp_ref = None
|
| 209 |
if speaker_wav_b64:
|
|
@@ -218,9 +190,8 @@ def _tts_logic(text, lang, speaker_wav_b64):
|
|
| 218 |
@spaces.GPU(duration=150)
|
| 219 |
def core_process(request_dict):
|
| 220 |
action = request_dict.get("action")
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
print(f"--- [v93] π GPU SESSION START: {action} ---")
|
| 224 |
activate_gpu_models(action)
|
| 225 |
try:
|
| 226 |
if action == "stt": res = _stt_logic(request_dict)
|
|
@@ -234,12 +205,19 @@ def core_process(request_dict):
|
|
| 234 |
elif action == "health": res = {"status": "awake"}
|
| 235 |
else: res = {"error": f"Unknown action: {action}"}
|
| 236 |
finally:
|
| 237 |
-
print(f"--- [
|
| 238 |
gc.collect()
|
| 239 |
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 240 |
return res
|
| 241 |
|
| 242 |
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
@app.post("/api/v1/process")
|
| 244 |
async def api_process(request: Request):
|
| 245 |
try: return core_process(await request.json())
|
|
@@ -247,12 +225,7 @@ async def api_process(request: Request):
|
|
| 247 |
|
| 248 |
@app.get("/health")
|
| 249 |
def health():
|
| 250 |
-
return {
|
| 251 |
-
"status": "ok",
|
| 252 |
-
"optimized": WARMUP_STATUS["complete"],
|
| 253 |
-
"gpu_available": torch.cuda.is_available(),
|
| 254 |
-
"time": time.ctime()
|
| 255 |
-
}
|
| 256 |
|
| 257 |
@app.post("/api/v1/clear_cache")
|
| 258 |
async def clear_cache():
|
|
@@ -273,6 +246,7 @@ def gradio_fn(req_json):
|
|
| 273 |
demo = gr.Interface(fn=gradio_fn, inputs="text", outputs="text", title="π AI Engine")
|
| 274 |
app = gr.mount_gradio_app(app, demo, path="/")
|
| 275 |
|
|
|
|
| 276 |
if __name__ == "__main__":
|
| 277 |
-
|
| 278 |
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="error")
|
|
|
|
| 18 |
from huggingface_hub import snapshot_download
|
| 19 |
|
| 20 |
# π‘οΈ 1. SILENCE VERBOSE LOGGING
|
|
|
|
| 21 |
logging.getLogger("transformers").setLevel(logging.ERROR)
|
| 22 |
logging.getLogger("TTS").setLevel(logging.ERROR)
|
| 23 |
os.environ["CT2_VERBOSE"] = "0"
|
| 24 |
os.environ["KMP_WARNINGS"] = "0"
|
| 25 |
|
| 26 |
+
# π οΈ 2. COMPATIBILITY PATCHES
|
| 27 |
if "torchaudio.backend" not in sys.modules:
|
| 28 |
backend = types.ModuleType("torchaudio.backend")
|
| 29 |
common = types.ModuleType("torchaudio.backend.common")
|
|
|
|
| 77 |
if f is None: return lambda x: x
|
| 78 |
return f
|
| 79 |
|
| 80 |
+
# FORCE BUILD TRIGGER: 11:55:00 Jan 21 2026
|
| 81 |
+
# v94: Startup Event Warmup + Fix Port Conflict. Final Stabilization.
|
| 82 |
|
| 83 |
os.environ["COQUI_TOS_AGREED"] = "1"
|
| 84 |
MODELS = {"stt": None, "translate": None, "tts": None, "denoiser": None}
|
|
|
|
| 87 |
WARMUP_LOCK = Lock()
|
| 88 |
|
| 89 |
def activate_gpu_models(action):
|
| 90 |
+
"""v94: Direct GPU Activation"""
|
| 91 |
global MODELS, WARMUP_STATUS
|
|
|
|
|
|
|
| 92 |
local_only = WARMUP_STATUS["complete"]
|
| 93 |
|
| 94 |
+
# 1. Faster-Whisper
|
| 95 |
if action in ["stt", "s2st"]:
|
| 96 |
stt_ready = False
|
| 97 |
try: stt_ready = MODELS["stt"] is not None and MODELS["stt"].model.device == "cuda"
|
| 98 |
except: pass
|
|
|
|
| 99 |
if not stt_ready:
|
| 100 |
+
print(f"ποΈ [v94] Activating Whisper (Local={local_only})...")
|
| 101 |
+
if MODELS["stt"]: del MODELS["stt"]; gc.collect(); torch.cuda.empty_cache()
|
| 102 |
+
MODELS["stt"] = WhisperModel("large-v3", device="cuda", compute_type="float16", local_files_only=local_only)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
# 2. XTTS-v2
|
| 105 |
if action in ["tts", "s2st"]:
|
| 106 |
+
tts_ready = False
|
| 107 |
try:
|
| 108 |
+
curr = str(next(MODELS["tts"].synthesizer.tts_model.parameters()).device)
|
| 109 |
+
tts_ready = "cuda" in curr
|
| 110 |
except: pass
|
| 111 |
+
if MODELS["tts"] is None or not tts_ready:
|
| 112 |
+
print(f"π [v94] Activating XTTS-v2 (Local={local_only})...")
|
|
|
|
| 113 |
if MODELS["tts"] is None:
|
| 114 |
MODELS["tts"] = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2", gpu=True)
|
| 115 |
+
else: MODELS["tts"].to("cuda")
|
|
|
|
| 116 |
|
| 117 |
+
# 3. Helpers
|
| 118 |
if MODELS["denoiser"] is None:
|
| 119 |
try: MODELS["denoiser"] = init_df()
|
| 120 |
except: pass
|
|
|
|
| 122 |
chatterbox_utils.load_chatterbox(device="cuda" if torch.cuda.is_available() else "cpu")
|
| 123 |
|
| 124 |
def warmup_task():
|
| 125 |
+
"""Silent Background Warmup (Threaded)"""
|
| 126 |
global WARMUP_STATUS
|
| 127 |
with WARMUP_LOCK:
|
| 128 |
if WARMUP_STATUS["complete"] or WARMUP_STATUS["in_progress"]: return
|
| 129 |
WARMUP_STATUS["in_progress"] = True
|
| 130 |
|
| 131 |
+
print("\nπ₯ --- SILENT WARMUP STARTED (v94) ---")
|
|
|
|
| 132 |
start = time.time()
|
| 133 |
try:
|
|
|
|
|
|
|
| 134 |
MODELS["stt"] = WhisperModel("large-v3", device="cpu", compute_type="int8")
|
|
|
|
|
|
|
|
|
|
| 135 |
MODELS["tts"] = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)
|
|
|
|
|
|
|
| 136 |
chatterbox_utils.warmup_chatterbox()
|
|
|
|
| 137 |
WARMUP_STATUS["complete"] = True
|
| 138 |
+
print(f"β
--- SYSTEM READY ({time.time()-start:.2f}s) --- \n")
|
| 139 |
except Exception as e:
|
| 140 |
print(f"β Warmup fail: {e}")
|
| 141 |
WARMUP_STATUS["error"] = str(e)
|
| 142 |
finally:
|
| 143 |
WARMUP_STATUS["in_progress"] = False
|
| 144 |
|
|
|
|
|
|
|
|
|
|
| 145 |
def _stt_logic(request_dict):
|
| 146 |
audio_bytes = base64.b64decode(request_dict.get("file"))
|
| 147 |
lang = request_dict.get("lang")
|
|
|
|
| 161 |
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"}
|
| 162 |
clean_lang = lang.strip().lower().split('-')[0]
|
| 163 |
mapped_lang = XTTS_MAP.get(clean_lang) or ("zh-cn" if clean_lang == "zh" else None)
|
|
|
|
| 164 |
if mapped_lang:
|
| 165 |
speaker_wav_path = None
|
| 166 |
if speaker_wav_b64:
|
|
|
|
| 176 |
finally:
|
| 177 |
if speaker_wav_path and "default_speaker" not in speaker_wav_path and os.path.exists(speaker_wav_path): os.unlink(speaker_wav_path)
|
| 178 |
if 'output_path' in locals() and os.path.exists(output_path): os.unlink(output_path)
|
|
|
|
| 179 |
try:
|
| 180 |
temp_ref = None
|
| 181 |
if speaker_wav_b64:
|
|
|
|
| 190 |
@spaces.GPU(duration=150)
|
| 191 |
def core_process(request_dict):
|
| 192 |
action = request_dict.get("action")
|
| 193 |
+
t1 = time.time()
|
| 194 |
+
print(f"--- [v94] π GPU SESSION START: {action} ---")
|
|
|
|
| 195 |
activate_gpu_models(action)
|
| 196 |
try:
|
| 197 |
if action == "stt": res = _stt_logic(request_dict)
|
|
|
|
| 205 |
elif action == "health": res = {"status": "awake"}
|
| 206 |
else: res = {"error": f"Unknown action: {action}"}
|
| 207 |
finally:
|
| 208 |
+
print(f"--- [v94] β¨ END: {action} ({time.time()-t1:.2f}s) ---")
|
| 209 |
gc.collect()
|
| 210 |
if torch.cuda.is_available(): torch.cuda.empty_cache()
|
| 211 |
return res
|
| 212 |
|
| 213 |
app = FastAPI()
|
| 214 |
+
|
| 215 |
+
@app.on_event("startup")
|
| 216 |
+
async def startup_event():
|
| 217 |
+
"""Ensure warmup starts regardless of entry point (v94)"""
|
| 218 |
+
print("π App Startup Event: Launching Background Warmup")
|
| 219 |
+
Thread(target=warmup_task, daemon=True).start()
|
| 220 |
+
|
| 221 |
@app.post("/api/v1/process")
|
| 222 |
async def api_process(request: Request):
|
| 223 |
try: return core_process(await request.json())
|
|
|
|
| 225 |
|
| 226 |
@app.get("/health")
|
| 227 |
def health():
|
| 228 |
+
return {"status": "ok", "optimized": WARMUP_STATUS["complete"], "time": time.ctime()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
@app.post("/api/v1/clear_cache")
|
| 231 |
async def clear_cache():
|
|
|
|
| 246 |
demo = gr.Interface(fn=gradio_fn, inputs="text", outputs="text", title="π AI Engine")
|
| 247 |
app = gr.mount_gradio_app(app, demo, path="/")
|
| 248 |
|
| 249 |
+
# Note: if __name__ == "__main__" is skipped if launched via 'uvicorn app:app'
|
| 250 |
if __name__ == "__main__":
|
| 251 |
+
print("π οΈ Manual Start detected")
|
| 252 |
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="error")
|