Spaces:
Running
Running
Vedika commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,83 +1,56 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
-
import urllib.parse
|
| 4 |
-
from bs4 import BeautifulSoup
|
| 5 |
from datetime import datetime, timedelta, timezone
|
| 6 |
from flask import Flask, request, Response, stream_with_context, render_template_string
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
# 🔐 --- SECURE ENVIRONMENT VARIABLES ---
|
| 11 |
-
API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
|
| 12 |
-
MODEL_ID = os.environ.get("MODEL_ID") # Default fallback
|
| 13 |
|
| 14 |
# NVIDIA's official invoke URL
|
| 15 |
INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
"""
|
| 20 |
-
|
|
|
|
| 21 |
"""
|
| 22 |
results = []
|
| 23 |
-
headers = {
|
| 24 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
| 25 |
-
"Accept-Language": "en-US,en;q=0.9"
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
# 1. YAHOO SEARCH (Highly reliable for Datacenter IPs like Hugging Face)
|
| 29 |
try:
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
-
print(f"
|
| 49 |
-
|
| 50 |
-
# 2. GOOGLE NEWS RSS FALLBACK (If Yahoo fails or for latest news)
|
| 51 |
-
if not results:
|
| 52 |
-
try:
|
| 53 |
-
rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
|
| 54 |
-
res = requests.get(rss_url, headers=headers, timeout=5)
|
| 55 |
-
soup = BeautifulSoup(res.content, 'xml')
|
| 56 |
-
items = soup.find_all('item')
|
| 57 |
-
|
| 58 |
-
for item in items[:num_results]:
|
| 59 |
-
title = item.title.text if item.title else ""
|
| 60 |
-
link = item.link.text if item.link else ""
|
| 61 |
-
pub_date = item.pubDate.text if item.pubDate else ""
|
| 62 |
-
if title:
|
| 63 |
-
results.append({"title": title, "link": link, "snippet": f"News Published on: {pub_date}"})
|
| 64 |
-
except Exception as e:
|
| 65 |
-
print(f"News Scraper Error: {e}")
|
| 66 |
-
|
| 67 |
-
# 3. WIKIPEDIA FALLBACK
|
| 68 |
-
if not results:
|
| 69 |
-
try:
|
| 70 |
-
wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
|
| 71 |
-
res = requests.get(wiki_url, headers=headers, timeout=5).json()
|
| 72 |
-
for item in res.get('query', {}).get('search', [])[:num_results]:
|
| 73 |
-
clean_snippet = BeautifulSoup(item['snippet'], "html.parser").text
|
| 74 |
-
results.append({
|
| 75 |
-
"title": item['title'],
|
| 76 |
-
"link": f"https://en.wikipedia.org/wiki/{urllib.parse.quote(item['title'])}",
|
| 77 |
-
"snippet": clean_snippet
|
| 78 |
-
})
|
| 79 |
-
except Exception as e:
|
| 80 |
-
pass
|
| 81 |
|
| 82 |
return results
|
| 83 |
|
|
@@ -94,7 +67,7 @@ def home():
|
|
| 94 |
@app.route('/api/chat', methods=['POST'])
|
| 95 |
def chat():
|
| 96 |
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 97 |
-
return Response("Server Error: Secrets missing.", status=500)
|
| 98 |
|
| 99 |
data = request.get_json() or {}
|
| 100 |
user_message = data.get("message", "")
|
|
@@ -119,18 +92,18 @@ def chat():
|
|
| 119 |
3. Do NOT say "Based on the provided search results". Just answer naturally and confidently, citing the sources/links if needed.
|
| 120 |
"""
|
| 121 |
|
| 122 |
-
# 🚀 --- AUTO-SEARCH INJECTION ---
|
| 123 |
if is_search:
|
| 124 |
scraped_data = web_search_scraper(user_message)
|
| 125 |
|
| 126 |
-
search_context = "\n\n--- [LIVE VERIFIED
|
| 127 |
if scraped_data:
|
| 128 |
for idx, res in enumerate(scraped_data):
|
| 129 |
search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
|
| 130 |
|
| 131 |
-
search_context += "[SYSTEM COMMAND: Use the above live data to answer the user accurately.]"
|
| 132 |
else:
|
| 133 |
-
search_context += "[SYSTEM ALERT: Live search
|
| 134 |
|
| 135 |
user_message = f"USER QUERY: {user_message}\n\n{search_context}"
|
| 136 |
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
|
|
|
|
|
|
| 3 |
from datetime import datetime, timedelta, timezone
|
| 4 |
from flask import Flask, request, Response, stream_with_context, render_template_string
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
| 7 |
|
| 8 |
# 🔐 --- SECURE ENVIRONMENT VARIABLES ---
|
| 9 |
+
API_KEY = os.environ.get("NVIDIA_API_KEY") or os.environ.get("YOUR_VEDIKA_API_KEY")
|
| 10 |
+
MODEL_ID = os.environ.get("MODEL_ID", "google/diffusiongemma-26b-a4b-it") # Default fallback
|
| 11 |
|
| 12 |
# NVIDIA's official invoke URL
|
| 13 |
INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
|
| 14 |
|
| 15 |
+
# 🔑 --- SERPAPI KEY (Provided by Divy Patel) ---
|
| 16 |
+
SERPAPI_KEY = "df7dc67448cc9fe63ee6bbc7c20c50662ac18bc1f4682cd480da97bde1970381"
|
| 17 |
+
|
| 18 |
+
# 🌐 --- SERPAPI GOOGLE SEARCH ENGINE (100% BULLETPROOF) --- 🌐
|
| 19 |
+
def web_search_scraper(query, num_results=5):
|
| 20 |
"""
|
| 21 |
+
यह SerpApi का उपयोग करके सीधे Google Search से एकदम सटीक और ताज़ा (JSON) डेटा लाता है।
|
| 22 |
+
इसे Hugging Face या Google कभी ब्लॉक नहीं कर सकता।
|
| 23 |
"""
|
| 24 |
results = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
try:
|
| 26 |
+
params = {
|
| 27 |
+
"engine": "google",
|
| 28 |
+
"q": query,
|
| 29 |
+
"api_key": SERPAPI_KEY,
|
| 30 |
+
"num": num_results,
|
| 31 |
+
"hl": "en",
|
| 32 |
+
"gl": "in" # India Region for local context
|
| 33 |
+
}
|
| 34 |
|
| 35 |
+
response = requests.get("https://serpapi.com/search", params=params, timeout=10)
|
| 36 |
+
data = response.json()
|
| 37 |
+
|
| 38 |
+
# 'organic_results' से असली Google सर्च का डेटा निकालना
|
| 39 |
+
if "organic_results" in data:
|
| 40 |
+
for item in data["organic_results"]:
|
| 41 |
+
title = item.get("title", "")
|
| 42 |
+
link = item.get("link", "")
|
| 43 |
+
snippet = item.get("snippet", "")
|
| 44 |
|
| 45 |
+
if title and snippet:
|
| 46 |
+
results.append({
|
| 47 |
+
"title": title,
|
| 48 |
+
"link": link,
|
| 49 |
+
"snippet": snippet
|
| 50 |
+
})
|
| 51 |
+
|
| 52 |
except Exception as e:
|
| 53 |
+
print(f"SerpApi Error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
return results
|
| 56 |
|
|
|
|
| 67 |
@app.route('/api/chat', methods=['POST'])
|
| 68 |
def chat():
|
| 69 |
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 70 |
+
return Response("Server Error: Secrets missing. Check NVIDIA API Key.", status=500)
|
| 71 |
|
| 72 |
data = request.get_json() or {}
|
| 73 |
user_message = data.get("message", "")
|
|
|
|
| 92 |
3. Do NOT say "Based on the provided search results". Just answer naturally and confidently, citing the sources/links if needed.
|
| 93 |
"""
|
| 94 |
|
| 95 |
+
# 🚀 --- AUTO-SEARCH INJECTION (USING SERPAPI) ---
|
| 96 |
if is_search:
|
| 97 |
scraped_data = web_search_scraper(user_message)
|
| 98 |
|
| 99 |
+
search_context = "\n\n--- [LIVE VERIFIED GOOGLE SEARCH DATA] ---\n"
|
| 100 |
if scraped_data:
|
| 101 |
for idx, res in enumerate(scraped_data):
|
| 102 |
search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
|
| 103 |
|
| 104 |
+
search_context += "[SYSTEM COMMAND: Use the above live Google data to answer the user accurately. Synthesize the info naturally without claiming you read it from a prompt.]"
|
| 105 |
else:
|
| 106 |
+
search_context += "[SYSTEM ALERT: Live search did not return results. Rely on your existing knowledge, but DO NOT hallucinate recent news.]"
|
| 107 |
|
| 108 |
user_message = f"USER QUERY: {user_message}\n\n{search_context}"
|
| 109 |
|