import os import gc import threading import time import sys import requests import gradio as gr from TTS.api import TTS import noisereduce as nr import soundfile as sf # Memory optimize gc.collect() os.environ['COQUI_TOS_AGREED'] = '1' print("⏳ Starting VoiceForge AI Backend (Developer: Rahul Terpathi)...") # Main Heavy Engine tts = TTS("tts_models/multilingual/multi-dataset/your_tts") print("✅ System Ready!") # ── Auto-restart: 47 hrs baad restart ── def auto_restart(): time.sleep(169200) print("🔄 Auto-restart: 47hrs complete — restarting now...") os.execv(sys.executable, [sys.executable] + sys.argv) threading.Thread(target=auto_restart, daemon=True).start() # ── Keep-alive ping: 25 min ── def keep_alive(): while True: time.sleep(1500) print("💓 Keep-alive ping — Space still running!") threading.Thread(target=keep_alive, daemon=True).start() def generate_api_voice(text, reference_audio): if not text: return None, "Error: Script missing!" try: if not reference_audio: raise Exception("No reference audio provided for main engine") # Audio clean karna data, rate = sf.read(reference_audio) if len(data.shape) > 1: data = data.mean(axis=1) clean_data = nr.reduce_noise(y=data, sr=rate) sf.write("clean_ref.wav", clean_data, rate) output_file = "output_voice.wav" # Main Voice Generation tts.tts_to_file( text=text, speaker_wav="clean_ref.wav", language="en", file_path=output_file ) # ✅ Process ke baad kachra saaf gc.collect() return output_file, "✅ Success: Main Engine" except Exception as e: print(f"⚠️ Main Engine Overloaded. Auto-Switching... Error: {e}") # 🔄 AUTO-SWITCH: Agar Your_TTS fail ho gaya (OOM ya error), toh halki API par switch karega try: gc.collect() # Pura RAM free karo fallback_url = "https://api-inference.huggingface.co/models/facebook/mms-tts-eng" resp = requests.post(fallback_url, json={"inputs": text}) if resp.status_code == 200: with open("fallback_voice.wav", "wb") as f: f.write(resp.content) return "fallback_voice.wav", "⚡ Auto-Switched to Backup Engine!" else: raise Exception("Backup API Busy") except Exception as backup_e: # Agar dono fail ho jayein (Extreme Memory Crash), toh khud ko restart kar lo print("💥 Fatal Crash! Rebooting System...") os.execv(sys.executable, [sys.executable] + sys.argv) return None, "🔄 Restarting Server..." # ── Clean & Simple UI ── iface = gr.Interface( fn=generate_api_voice, inputs=[ gr.Textbox(label="Script"), gr.Audio(type="filepath", label="Voice Upload") ], outputs=[ gr.Audio(label="Voice Output"), gr.Textbox(label="API Status") ], title="🎙️ VoiceForge AI" ) # show_api=False se faltu clutter nahi aayega backend mein iface.launch(show_api=False)