Vedika commited on
Commit
5c52905
·
verified ·
1 Parent(s): b6d1d41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -31
app.py CHANGED
@@ -48,22 +48,20 @@ def get_address_from_coords(lat, lon):
48
  data = response.json()
49
  return data.get('display_name', f"Lat: {lat}, Lon: {lon}")
50
  except Exception as e:
51
- print(f"Geocoding Error: {e}")
52
  return f"Lat: {lat}, Lon: {lon}"
53
 
54
  # ----------------------------------------------------
55
- # 🌐 SERPAPI GOOGLE SEARCH ENGINE (Location Aware)
56
  # ----------------------------------------------------
57
  def web_search_scraper(query, num_results=5, user_address=None):
58
  results = []
59
  serpapi_key = os.environ.get("SERPAPI_KEY")
60
  if not serpapi_key:
61
- print("ALERT: SERPAPI_KEY missing in secrets.")
62
  return results
63
 
64
  search_query = query
65
  if user_address:
66
- local_keywords = ["near", "nearby", "आसपास", "रेस्टोरेंट", "दुकान", "distance", "time", "where"]
67
  if any(kw in query.lower() for kw in local_keywords):
68
  search_query = f"{query} near {user_address}"
69
 
@@ -79,25 +77,22 @@ def web_search_scraper(query, num_results=5, user_address=None):
79
  snippet = item.get("snippet", "")
80
  if title and snippet:
81
  results.append({"title": title, "link": link, "snippet": snippet})
82
- except Exception as e:
83
- print(f"SerpApi Error: {e}")
84
-
85
  return results
86
 
87
  # ----------------------------------------------------
88
- # 📰 RSS TECH NEWS SCRAPER (Pure Tech Filter)
89
  # ----------------------------------------------------
90
  def get_live_web_data(query):
91
- print(f"[Live Feed] Fetching news for topic: '{query}'...")
92
- url = f"https://news.google.com/rss/search?q={query}&hl=hi&gl=IN&ceid=IN:hi"
93
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
94
 
95
  tech_keywords = [
96
- "ai", "artificial intelligence", "एआई", "इंटेलिजेंस", "स्मार्टफोन",
97
- "smartphone", "mobile", "मोबाइल", "फीचर", "feature", "whatsapp",
98
- "google", "tech", "तकनीक", "टेक्नोलॉजी", "गैजेट", "gadget", "apple", "nasa"
99
  ]
100
- block_keywords = ["share news", "stock", "शेयर", "म्यूचुअल फंड"]
101
  scraped_results = []
102
 
103
  try:
@@ -117,14 +112,13 @@ def get_live_web_data(query):
117
  source = item.source.text if item.source else "Google News"
118
  scraped_results.append({
119
  "title": title,
120
- "snippet": f"प्रकाशित तिथि: {pub_date} | स्रोत: {source}",
121
  "link": link
122
  })
123
  if len(scraped_results) >= 5:
124
  break
125
- except Exception as e:
126
- print(f"[Live Feed Error] Failed to fetch: {e}")
127
-
128
  return scraped_results
129
 
130
  # ----------------------------------------------------
@@ -143,13 +137,11 @@ def home():
143
  # ----------------------------------------------------
144
  @app.route('/api/chat', methods=['POST'])
145
  def chat():
146
- # SECRETS MAPPED EXACTLY TO USER'S HUGGINGFACE SPACE ENVIRONMENT
147
  API_KEY = os.environ.get("NVIDIA_API_KEY")
148
  INVOKE_URL = os.environ.get("BASE_URL")
149
  MODEL_ID = os.environ.get("MODEL_ID")
150
 
151
  if not API_KEY or not INVOKE_URL or not MODEL_ID:
152
- print("Missing Environment Variables. API_KEY:", bool(API_KEY), "INVOKE_URL:", bool(INVOKE_URL), "MODEL_ID:", bool(MODEL_ID))
153
  return Response("Server Error: Critical configuration secrets missing.", status=500)
154
 
155
  data = request.get_json() or {}
@@ -184,7 +176,7 @@ def chat():
184
  [CRITICAL INSTRUCTION: THINKING MODE ENABLED]
185
  Effort Level: {thinking_effort.upper()} - {effort_text}
186
  You MUST format your reasoning exactly inside <think> and </think> HTML tags.
187
- Do NOT use special system tokens like <|channel|>thought or <|im_start|>. Use standard <think> tags.
188
  """
189
 
190
  location_instruction = ""
@@ -232,18 +224,25 @@ STRICT DIRECTIVES:
232
 
233
  messages = [{"role": "system", "content": system_prompt}]
234
 
235
- clean_history = []
236
  for msg in history:
237
  if msg == history[-1] and msg.get("role") == "user":
238
  continue
 
239
  role = msg.get("role", "user")
 
 
 
240
  content = msg.get("content", "")
 
 
 
 
 
241
  if "Gemma" in content or "DeepMind" in content or "Google" in content or "Alibaba" in content or "Tongyi" in content:
242
  continue
243
- if content:
244
- clean_history.append({"role": role, "content": content})
245
 
246
- messages.extend(clean_history)
 
247
 
248
  if attachments:
249
  content_payload = [{"type": "text", "text": user_message}]
@@ -278,8 +277,8 @@ STRICT DIRECTIVES:
278
  response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True, timeout=60)
279
 
280
  if response.status_code != 200:
281
- print(f"API Error: {response.status_code} - {response.text}")
282
- return Response(f"Upstream API Error: {response.status_code}", status=500)
283
 
284
  def generate():
285
  for line in response.iter_lines():
@@ -303,12 +302,12 @@ STRICT DIRECTIVES:
303
 
304
  return Response(stream_with_context(generate()), mimetype='text/event-stream')
305
  except Exception as e:
306
- print(f"Request Exception: {str(e)}")
307
- return Response(f"Internal Error: {str(e)}", status=500)
308
 
309
 
310
  # ----------------------------------------------------
311
- # 🎙️ TTS DIRECT API ENDPOINT (OPTIMIZED)
312
  # ----------------------------------------------------
313
  @app.route('/api/tts', methods=['POST'])
314
  def generate_tts():
@@ -361,7 +360,6 @@ def generate_tts():
361
  return Response(mp3_buffer.read(), mimetype="audio/mpeg")
362
 
363
  except Exception as e:
364
- print(f"TTS Error: {str(e)}")
365
  return Response(json.dumps({"error": str(e)}), status=500, mimetype='application/json')
366
 
367
 
 
48
  data = response.json()
49
  return data.get('display_name', f"Lat: {lat}, Lon: {lon}")
50
  except Exception as e:
 
51
  return f"Lat: {lat}, Lon: {lon}"
52
 
53
  # ----------------------------------------------------
54
+ # 🌐 SERPAPI GOOGLE SEARCH ENGINE
55
  # ----------------------------------------------------
56
  def web_search_scraper(query, num_results=5, user_address=None):
57
  results = []
58
  serpapi_key = os.environ.get("SERPAPI_KEY")
59
  if not serpapi_key:
 
60
  return results
61
 
62
  search_query = query
63
  if user_address:
64
+ local_keywords = ["near", "nearby", "distance", "time", "where"]
65
  if any(kw in query.lower() for kw in local_keywords):
66
  search_query = f"{query} near {user_address}"
67
 
 
77
  snippet = item.get("snippet", "")
78
  if title and snippet:
79
  results.append({"title": title, "link": link, "snippet": snippet})
80
+ except Exception:
81
+ pass
 
82
  return results
83
 
84
  # ----------------------------------------------------
85
+ # 📰 RSS TECH NEWS SCRAPER
86
  # ----------------------------------------------------
87
  def get_live_web_data(query):
88
+ url = f"https://news.google.com/rss/search?q={query}&hl=en&gl=IN&ceid=IN:en"
 
89
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
90
 
91
  tech_keywords = [
92
+ "ai", "artificial intelligence", "smartphone", "mobile",
93
+ "feature", "whatsapp", "google", "tech", "technology", "gadget", "apple", "nasa"
 
94
  ]
95
+ block_keywords = ["share news", "stock"]
96
  scraped_results = []
97
 
98
  try:
 
112
  source = item.source.text if item.source else "Google News"
113
  scraped_results.append({
114
  "title": title,
115
+ "snippet": f"Published: {pub_date} | Source: {source}",
116
  "link": link
117
  })
118
  if len(scraped_results) >= 5:
119
  break
120
+ except Exception:
121
+ pass
 
122
  return scraped_results
123
 
124
  # ----------------------------------------------------
 
137
  # ----------------------------------------------------
138
  @app.route('/api/chat', methods=['POST'])
139
  def chat():
 
140
  API_KEY = os.environ.get("NVIDIA_API_KEY")
141
  INVOKE_URL = os.environ.get("BASE_URL")
142
  MODEL_ID = os.environ.get("MODEL_ID")
143
 
144
  if not API_KEY or not INVOKE_URL or not MODEL_ID:
 
145
  return Response("Server Error: Critical configuration secrets missing.", status=500)
146
 
147
  data = request.get_json() or {}
 
176
  [CRITICAL INSTRUCTION: THINKING MODE ENABLED]
177
  Effort Level: {thinking_effort.upper()} - {effort_text}
178
  You MUST format your reasoning exactly inside <think> and </think> HTML tags.
179
+ Do NOT use special system tokens.
180
  """
181
 
182
  location_instruction = ""
 
224
 
225
  messages = [{"role": "system", "content": system_prompt}]
226
 
 
227
  for msg in history:
228
  if msg == history[-1] and msg.get("role") == "user":
229
  continue
230
+
231
  role = msg.get("role", "user")
232
+ if role not in ["system", "user", "assistant"]:
233
+ role = "user"
234
+
235
  content = msg.get("content", "")
236
+
237
+ if isinstance(content, list):
238
+ text_parts = [item["text"] for item in content if item.get("type") == "text"]
239
+ content = " ".join(text_parts)
240
+
241
  if "Gemma" in content or "DeepMind" in content or "Google" in content or "Alibaba" in content or "Tongyi" in content:
242
  continue
 
 
243
 
244
+ if content:
245
+ messages.append({"role": role, "content": str(content)})
246
 
247
  if attachments:
248
  content_payload = [{"type": "text", "text": user_message}]
 
277
  response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True, timeout=60)
278
 
279
  if response.status_code != 200:
280
+ err_msg = json.dumps({"error": f"NVIDIA API Error {response.status_code}: {response.text[:200]}"})
281
+ return Response(f"data: {err_msg}\n\n", mimetype='text/event-stream')
282
 
283
  def generate():
284
  for line in response.iter_lines():
 
302
 
303
  return Response(stream_with_context(generate()), mimetype='text/event-stream')
304
  except Exception as e:
305
+ err_msg = json.dumps({"error": str(e)})
306
+ return Response(f"data: {err_msg}\n\n", mimetype='text/event-stream')
307
 
308
 
309
  # ----------------------------------------------------
310
+ # 🎙️ TTS DIRECT API ENDPOINT
311
  # ----------------------------------------------------
312
  @app.route('/api/tts', methods=['POST'])
313
  def generate_tts():
 
360
  return Response(mp3_buffer.read(), mimetype="audio/mpeg")
361
 
362
  except Exception as e:
 
363
  return Response(json.dumps({"error": str(e)}), status=500, mimetype='application/json')
364
 
365