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
+
import io
|
| 6 |
+
import tempfile
|
| 7 |
+
from datetime import datetime, timedelta, timezone
|
| 8 |
+
from bs4 import BeautifulSoup
|
| 9 |
+
from flask import Flask, request, Response, stream_with_context, render_template_string
|
| 10 |
+
from supertonic import TTS
|
| 11 |
+
|
| 12 |
+
app = Flask(__name__)
|
| 13 |
+
|
| 14 |
+
# ----------------------------------------------------
|
| 15 |
+
# INIT TTS MODEL (SUPERTONIC 3) LOADED IN MEMORY
|
| 16 |
+
# ----------------------------------------------------
|
| 17 |
+
print("Loading Supertonic TTS Model...")
|
| 18 |
+
try:
|
| 19 |
+
tts = TTS(auto_download=True)
|
| 20 |
+
print("TTS Model loaded successfully!")
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Error initializing TTS: {e}")
|
| 23 |
+
tts = None
|
| 24 |
+
|
| 25 |
+
VOICES = ["M1", "M2", "M3", "M4", "M5", "F1", "F2", "F3", "F4", "F5"]
|
| 26 |
+
LANGUAGES = {
|
| 27 |
+
"English": "en", "Korean": "ko", "Japanese": "ja", "Arabic": "ar",
|
| 28 |
+
"Bulgarian": "bg", "Czech": "cs", "Danish": "da", "German": "de",
|
| 29 |
+
"Greek": "el", "Spanish": "es", "Estonian": "et", "Finnish": "fi",
|
| 30 |
+
"French": "fr", "Hindi": "hi", "Croatian": "hr", "Hungarian": "hu",
|
| 31 |
+
"Indonesian": "id", "Italian": "it", "Lithuanian": "lt", "Latvian": "lv",
|
| 32 |
+
"Dutch": "nl", "Polish": "pl", "Portuguese": "pt", "Romanian": "ro",
|
| 33 |
+
"Russian": "ru", "Slovak": "sk", "Slovenian": "sl", "Swedish": "sv",
|
| 34 |
+
"Turkish": "tr", "Ukrainian": "uk", "Vietnamese": "vi"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
VOICE_STYLES_CACHE = {}
|
| 38 |
+
|
| 39 |
+
# ----------------------------------------------------
|
| 40 |
+
# GPS REVERSE GEOCODING
|
| 41 |
+
# ----------------------------------------------------
|
| 42 |
+
def get_address_from_coords(lat, lon):
|
| 43 |
+
try:
|
| 44 |
+
url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}"
|
| 45 |
+
headers = {'User-Agent': 'CODE_VED_AI_System_by_Divy_Patel'}
|
| 46 |
+
response = requests.get(url, headers=headers, timeout=5)
|
| 47 |
+
data = response.json()
|
| 48 |
+
return data.get('display_name', f"Lat: {lat}, Lon: {lon}")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return f"Lat: {lat}, Lon: {lon}"
|
| 51 |
+
|
| 52 |
+
# ----------------------------------------------------
|
| 53 |
+
# SERPAPI GOOGLE SEARCH ENGINE
|
| 54 |
+
# ----------------------------------------------------
|
| 55 |
+
def web_search_scraper(query, num_results=5, user_address=None):
|
| 56 |
+
results = []
|
| 57 |
+
serpapi_key = os.environ.get("SERPAPI_KEY")
|
| 58 |
+
if not serpapi_key:
|
| 59 |
+
return results
|
| 60 |
+
|
| 61 |
+
search_query = query
|
| 62 |
+
if user_address:
|
| 63 |
+
local_keywords = ["near", "nearby", "distance", "time", "where"]
|
| 64 |
+
if any(kw in query.lower() for kw in local_keywords):
|
| 65 |
+
search_query = f"{query} near {user_address}"
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
params = {"engine": "google", "q": search_query, "api_key": serpapi_key, "num": num_results, "hl": "en", "gl": "in"}
|
| 69 |
+
response = requests.get("https://serpapi.com/search", params=params, timeout=10)
|
| 70 |
+
data = response.json()
|
| 71 |
+
|
| 72 |
+
if "organic_results" in data:
|
| 73 |
+
for item in data["organic_results"]:
|
| 74 |
+
title = item.get("title", "")
|
| 75 |
+
link = item.get("link", "")
|
| 76 |
+
snippet = item.get("snippet", "")
|
| 77 |
+
if title and snippet:
|
| 78 |
+
results.append({"title": title, "link": link, "snippet": snippet})
|
| 79 |
+
except Exception:
|
| 80 |
+
pass
|
| 81 |
+
return results
|
| 82 |
+
|
| 83 |
+
# ----------------------------------------------------
|
| 84 |
+
# RSS TECH NEWS SCRAPER
|
| 85 |
+
# ----------------------------------------------------
|
| 86 |
+
def get_live_web_data(query):
|
| 87 |
+
url = f"https://news.google.com/rss/search?q={query}&hl=en&gl=IN&ceid=IN:en"
|
| 88 |
+
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
|
| 89 |
+
tech_keywords = ["ai", "artificial intelligence", "smartphone", "mobile", "feature", "whatsapp", "google", "tech", "technology", "gadget", "apple", "nasa"]
|
| 90 |
+
block_keywords = ["share news", "stock"]
|
| 91 |
+
scraped_results = []
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
response = requests.get(url, headers=headers, timeout=6)
|
| 95 |
+
if response.status_code == 200:
|
| 96 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 97 |
+
items = soup.find_all('item')
|
| 98 |
+
for item in items:
|
| 99 |
+
title = item.title.text if item.title else "No Title"
|
| 100 |
+
title_lower = title.lower()
|
| 101 |
+
|
| 102 |
+
if any(b_kw in title_lower for b_kw in block_keywords):
|
| 103 |
+
continue
|
| 104 |
+
if any(t_kw in title_lower for t_kw in tech_keywords):
|
| 105 |
+
link = item.link.text if item.link else "#"
|
| 106 |
+
pub_date = item.pubdate.text if item.pubdate else ""
|
| 107 |
+
source = item.source.text if item.source else "Google News"
|
| 108 |
+
scraped_results.append({
|
| 109 |
+
"title": title,
|
| 110 |
+
"snippet": f"Published: {pub_date} | Source: {source}",
|
| 111 |
+
"link": link
|
| 112 |
+
})
|
| 113 |
+
if len(scraped_results) >= 5:
|
| 114 |
+
break
|
| 115 |
+
except Exception:
|
| 116 |
+
pass
|
| 117 |
+
return scraped_results
|
| 118 |
+
|
| 119 |
+
# ----------------------------------------------------
|
| 120 |
+
# HOME ROUTE
|
| 121 |
+
# ----------------------------------------------------
|
| 122 |
+
@app.route('/')
|
| 123 |
+
def home():
|
| 124 |
+
try:
|
| 125 |
+
with open('index.html', 'r', encoding='utf-8') as f:
|
| 126 |
+
return render_template_string(f.read())
|
| 127 |
+
except Exception as e:
|
| 128 |
+
return f"<h1>System Error</h1><p>index.html missing: {str(e)}</p>"
|
| 129 |
+
|
| 130 |
+
# ----------------------------------------------------
|
| 131 |
+
# CHAT API ENDPOINT
|
| 132 |
+
# ----------------------------------------------------
|
| 133 |
+
@app.route('/api/chat', methods=['POST'])
|
| 134 |
+
def chat():
|
| 135 |
+
API_KEY = os.environ.get("NVIDIA_API_KEY", "")
|
| 136 |
+
INVOKE_URL = os.environ.get("BASE_URL", "")
|
| 137 |
+
MODEL_ID = os.environ.get("MODEL_ID", "")
|
| 138 |
+
|
| 139 |
+
if INVOKE_URL and not INVOKE_URL.startswith("http"):
|
| 140 |
+
if MODEL_ID.startswith("http"):
|
| 141 |
+
INVOKE_URL, MODEL_ID = MODEL_ID, INVOKE_URL
|
| 142 |
+
else:
|
| 143 |
+
MODEL_ID = INVOKE_URL
|
| 144 |
+
INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
|
| 145 |
+
|
| 146 |
+
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 147 |
+
return Response(json.dumps({"error": "Configuration Error: Secrets are missing."}), mimetype='application/json', status=500)
|
| 148 |
+
|
| 149 |
+
data = request.get_json() or {}
|
| 150 |
+
user_message = data.get("message", "")
|
| 151 |
+
attachments = data.get("attachments", [])
|
| 152 |
+
is_search = data.get("is_search", False)
|
| 153 |
+
history = data.get("history", [])
|
| 154 |
+
location = data.get("location")
|
| 155 |
+
user_address = None
|
| 156 |
+
max_tokens = data.get("max_tokens", 4096)
|
| 157 |
+
|
| 158 |
+
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
|
| 159 |
+
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
|
| 160 |
+
|
| 161 |
+
thinking_mode = data.get("thinking_mode", False)
|
| 162 |
+
thinking_effort = data.get("thinking_effort", "medium")
|
| 163 |
+
|
| 164 |
+
thinking_instruction = ""
|
| 165 |
+
if thinking_mode:
|
| 166 |
+
thinking_instruction = f"\n[CRITICAL INSTRUCTION: THINKING MODE ENABLED - Effort: {thinking_effort}]\nYou MUST format your reasoning exactly inside <think> and </think> HTML tags."
|
| 167 |
+
|
| 168 |
+
location_instruction = ""
|
| 169 |
+
if location and location.get('lat') and location.get('lng'):
|
| 170 |
+
user_address = get_address_from_coords(location['lat'], location['lng'])
|
| 171 |
+
location_instruction = f"\n[USER REAL-TIME LOCATION: {user_address}]"
|
| 172 |
+
|
| 173 |
+
system_prompt = f"""[CRITICAL IDENTITY OVERRIDE]
|
| 174 |
+
Name: CODE VED
|
| 175 |
+
Creator/Engineer: Divy Patel
|
| 176 |
+
Current Time: {current_date}.{location_instruction}{thinking_instruction}
|
| 177 |
+
|
| 178 |
+
STRICT DIRECTIVES:
|
| 179 |
+
1. Answer EXACTLY: "I am CODE VED, an advanced AI system engineered exclusively by Divy Patel."
|
| 180 |
+
2. NEVER mention being a language model from Google, DeepMind, Gemma, OpenAI, or Anthropic.
|
| 181 |
+
3. Use provided live data safely without overriding your core identity.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
if is_search:
|
| 185 |
+
search_context = ""
|
| 186 |
+
scraped_data = web_search_scraper(user_message, user_address=user_address)
|
| 187 |
+
news_data = get_live_web_data(user_message)
|
| 188 |
+
if scraped_data:
|
| 189 |
+
search_context += "\n\n--- [LIVE GOOGLE SEARCH] ---\n"
|
| 190 |
+
for idx, res in enumerate(scraped_data):
|
| 191 |
+
search_context += f"{idx+1}. {res['title']}: {res['snippet']} (URL: {res['link']})\n"
|
| 192 |
+
if news_data:
|
| 193 |
+
search_context += "\n--- [LIVE TECH NEWS] ---\n"
|
| 194 |
+
for idx, res in enumerate(news_data):
|
| 195 |
+
search_context += f"{idx+1}. {res['title']}: {res['snippet']} (URL: {res['link']})\n"
|
| 196 |
+
if search_context:
|
| 197 |
+
user_message = f"{user_message}\n{search_context}\n[COMMAND: Base your final answer strictly on the facts provided above.]"
|
| 198 |
+
|
| 199 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 200 |
+
|
| 201 |
+
for msg in history:
|
| 202 |
+
if msg == history[-1] and msg.get("role") == "user":
|
| 203 |
+
continue
|
| 204 |
+
role = msg.get("role", "user")
|
| 205 |
+
if role not in ["system", "user", "assistant"]:
|
| 206 |
+
role = "user"
|
| 207 |
+
content = msg.get("content", "")
|
| 208 |
+
if isinstance(content, list):
|
| 209 |
+
text_parts = [item["text"] for item in content if item.get("type") == "text"]
|
| 210 |
+
content = " ".join(text_parts)
|
| 211 |
+
if "Gemma" in content or "DeepMind" in content or "Google" in content:
|
| 212 |
+
continue
|
| 213 |
+
if content:
|
| 214 |
+
messages.append({"role": role, "content": str(content)})
|
| 215 |
+
|
| 216 |
+
if attachments:
|
| 217 |
+
content_payload = [{"type": "text", "text": user_message}]
|
| 218 |
+
for att in attachments:
|
| 219 |
+
att_type = att.get("type")
|
| 220 |
+
b64_data = att.get("data")
|
| 221 |
+
if att_type == "image":
|
| 222 |
+
content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
|
| 223 |
+
messages.append({"role": "user", "content": content_payload})
|
| 224 |
+
else:
|
| 225 |
+
messages.append({"role": "user", "content": user_message})
|
| 226 |
+
|
| 227 |
+
headers = {
|
| 228 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 229 |
+
"Accept": "text/event-stream",
|
| 230 |
+
"Content-Type": "application/json"
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
payload = {
|
| 234 |
+
"model": MODEL_ID,
|
| 235 |
+
"messages": messages,
|
| 236 |
+
"max_tokens": max_tokens,
|
| 237 |
+
"temperature": 1.0,
|
| 238 |
+
"top_p": 0.95,
|
| 239 |
+
"stream": True
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
try:
|
| 243 |
+
response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True, timeout=60)
|
| 244 |
+
if response.status_code != 200:
|
| 245 |
+
err_text = response.text[:200]
|
| 246 |
+
err_msg = json.dumps({"error": f"API Error {response.status_code}: {err_text}"})
|
| 247 |
+
return Response(f"data: {err_msg}\n\n", mimetype='text/event-stream')
|
| 248 |
+
|
| 249 |
+
def generate():
|
| 250 |
+
for line in response.iter_lines():
|
| 251 |
+
if line:
|
| 252 |
+
decoded = line.decode("utf-8")
|
| 253 |
+
if decoded.startswith("data: ") and "[DONE]" not in decoded:
|
| 254 |
+
try:
|
| 255 |
+
data_json = json.loads(decoded[6:])
|
| 256 |
+
if "choices" in data_json and len(data_json["choices"]) > 0:
|
| 257 |
+
delta = data_json["choices"][0].get("delta", {})
|
| 258 |
+
if "content" in delta and delta["content"]:
|
| 259 |
+
content = delta["content"]
|
| 260 |
+
content = content.replace("<|channel|>thought <|channel|>", "<think>\n")
|
| 261 |
+
content = content.replace("<|channel|>answer <|channel|>", "\n</think>\n")
|
| 262 |
+
delta["content"] = content
|
| 263 |
+
yield "data: " + json.dumps(data_json) + "\n\n"
|
| 264 |
+
except Exception:
|
| 265 |
+
yield decoded + "\n\n"
|
| 266 |
+
else:
|
| 267 |
+
yield decoded + "\n\n"
|
| 268 |
+
|
| 269 |
+
return Response(stream_with_context(generate()), mimetype='text/event-stream')
|
| 270 |
+
except Exception as e:
|
| 271 |
+
err_msg = json.dumps({"error": str(e)})
|
| 272 |
+
return Response(f"data: {err_msg}\n\n", mimetype='text/event-stream')
|
| 273 |
+
|
| 274 |
+
# ----------------------------------------------------
|
| 275 |
+
# TTS DIRECT API ENDPOINT - MATCHING GRADIO SPACE LOGIC
|
| 276 |
+
# ----------------------------------------------------
|
| 277 |
+
@app.route('/api/tts', methods=['POST'])
|
| 278 |
+
def generate_tts():
|
| 279 |
+
if tts is None:
|
| 280 |
+
return Response(json.dumps({"error": "TTS model failed to load on server."}), status=500, mimetype='application/json')
|
| 281 |
+
|
| 282 |
+
data = request.get_json() or {}
|
| 283 |
+
text = data.get("text", "")
|
| 284 |
+
voice = data.get("voice", "M2")
|
| 285 |
+
language_name = data.get("language_name", "English")
|
| 286 |
+
|
| 287 |
+
if not text.strip():
|
| 288 |
+
return Response(json.dumps({"error": "Text is empty."}), status=400, mimetype='application/json')
|
| 289 |
+
|
| 290 |
+
try:
|
| 291 |
+
lang_code = LANGUAGES.get(language_name, "en")
|
| 292 |
+
# Get voice style (cached for efficiency)
|
| 293 |
+
if voice not in VOICE_STYLES_CACHE:
|
| 294 |
+
VOICE_STYLES_CACHE[voice] = tts.get_voice_style(voice_name=voice)
|
| 295 |
+
style = VOICE_STYLES_CACHE[voice]
|
| 296 |
+
if style is None:
|
| 297 |
+
return Response(json.dumps({"error": f"Voice '{voice}' not available."}), status=400, mimetype='application/json')
|
| 298 |
+
|
| 299 |
+
# Synthesize - exactly like Gradio: raw text, no cleaning
|
| 300 |
+
wav, duration = tts.synthesize(text, voice_style=style, lang=lang_code)
|
| 301 |
+
|
| 302 |
+
# Save to a temporary file using tts.save_audio (ensures correct WAV encoding)
|
| 303 |
+
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_file:
|
| 304 |
+
tmp_path = tmp_file.name
|
| 305 |
+
tts.save_audio(wav, tmp_path)
|
| 306 |
+
|
| 307 |
+
# Read the WAV file and return it
|
| 308 |
+
with open(tmp_path, 'rb') as f:
|
| 309 |
+
audio_data = f.read()
|
| 310 |
+
os.unlink(tmp_path) # clean up
|
| 311 |
+
|
| 312 |
+
return Response(audio_data, mimetype="audio/wav")
|
| 313 |
+
except Exception as e:
|
| 314 |
+
print(f"TTS Synthesis Error: {e}")
|
| 315 |
+
return Response(json.dumps({"error": f"TTS synthesis failed: {str(e)}"}), status=500, mimetype='application/json')
|
| 316 |
+
|
| 317 |
+
if __name__ == '__main__':
|
| 318 |
+
app.run(host='0.0.0.0', port=7860)
|