Vedika commited on
Commit
d6b39c3
·
verified ·
1 Parent(s): 00701d3

Delete app.py

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