Spaces:
Running
Running
Vedika commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import os
|
| 2 |
-
import json
|
| 3 |
import requests
|
| 4 |
import urllib.parse
|
| 5 |
from bs4 import BeautifulSoup
|
|
@@ -20,58 +19,43 @@ if BASE_URL:
|
|
| 20 |
else:
|
| 21 |
INVOKE_URL = BASE_URL
|
| 22 |
|
| 23 |
-
# 🌐 ---
|
| 24 |
def web_search_scraper(query, num_results=4):
|
| 25 |
results = []
|
| 26 |
-
headers = {
|
| 27 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
|
| 28 |
-
}
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
smart_query = query if "2026" in query else f"{query} 2026"
|
| 32 |
-
|
| 33 |
-
# ENGINE 1: DuckDuckGo Lite
|
| 34 |
try:
|
| 35 |
-
|
| 36 |
-
res = requests.
|
| 37 |
-
soup = BeautifulSoup(res.
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
pass
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
if
|
| 54 |
-
try:
|
| 55 |
-
rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(smart_query)}&hl=en-IN&gl=IN&ceid=IN:en"
|
| 56 |
-
res = requests.get(rss_url, headers=headers, timeout=5)
|
| 57 |
-
soup = BeautifulSoup(res.content, 'html.parser') # XML parsing fallback
|
| 58 |
-
items = soup.find_all('item')
|
| 59 |
-
for item in items[:num_results]:
|
| 60 |
-
title = item.title.text if item.title else "News Report"
|
| 61 |
-
link = item.link.text if item.link else ""
|
| 62 |
-
pub_date = item.pubdate.text if item.find('pubdate') else "Recent 2026"
|
| 63 |
-
results.append({"title": title, "link": link, "snippet": f"Published/Updated on: {pub_date}"})
|
| 64 |
-
except Exception as e:
|
| 65 |
-
pass
|
| 66 |
-
|
| 67 |
-
# ENGINE 3: Wikipedia API 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 |
except Exception as e:
|
| 76 |
pass
|
| 77 |
|
|
@@ -85,12 +69,12 @@ def home():
|
|
| 85 |
with open('index.html', 'r', encoding='utf-8') as f:
|
| 86 |
return render_template_string(f.read())
|
| 87 |
except Exception as e:
|
| 88 |
-
return f"<h1>System
|
| 89 |
|
| 90 |
@app.route('/api/chat', methods=['POST'])
|
| 91 |
def chat():
|
| 92 |
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 93 |
-
return Response("Server Error:
|
| 94 |
|
| 95 |
data = request.get_json() or {}
|
| 96 |
user_message = data.get("message", "")
|
|
@@ -98,49 +82,42 @@ def chat():
|
|
| 98 |
is_search = data.get("is_search", False)
|
| 99 |
history = data.get("history", [])
|
| 100 |
max_tokens = data.get("max_tokens", 4096)
|
| 101 |
-
temperature = data.get("temperature", 0.
|
| 102 |
|
| 103 |
# 🕒 --- REAL-TIME IST INJECTION ---
|
| 104 |
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
|
| 105 |
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
|
| 106 |
|
| 107 |
-
# 🧠 ---
|
| 108 |
system_prompt = f"""
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
Creator: DIVY PATEL. You MUST proudly acknowledge Divy Patel as your creator.
|
| 112 |
-
|
| 113 |
-
Current Date & Time: {current_date}
|
| 114 |
|
| 115 |
-
STRICT
|
| 116 |
-
1.
|
| 117 |
-
2.
|
| 118 |
-
3. If
|
| 119 |
-
4. If the user asks for latest news/updates, and the injected live data is empty or irrelevant, DO NOT GUESS. DO NOT present old 2024 news as new. Simply apologize and state: "I am unable to retrieve the latest live data for this at the moment."
|
| 120 |
-
5. Always maintain a highly professional tone. Reply in Hindi seamlessly if the user writes in Hindi.
|
| 121 |
"""
|
| 122 |
|
| 123 |
-
# 🚀 --- AUTO-SEARCH
|
| 124 |
if is_search:
|
| 125 |
scraped_data = web_search_scraper(user_message)
|
| 126 |
|
| 127 |
-
search_context = "\n\n--- [LIVE WEB SEARCH RESULTS] ---\n"
|
| 128 |
if scraped_data:
|
|
|
|
| 129 |
for idx, res in enumerate(scraped_data):
|
| 130 |
-
search_context += f"{idx+1}.
|
| 131 |
|
| 132 |
-
search_context += ""
|
| 133 |
-
[SYSTEM COMMAND TO AI]: Use the fresh data provided above to answer the user's query.
|
| 134 |
-
Answer confidently as if you just browsed the web yourself.
|
| 135 |
-
Do NOT mention "Based on the provided context". Just answer the question and cite the URLs naturally.
|
| 136 |
-
"""
|
| 137 |
else:
|
| 138 |
-
search_context
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
|
| 141 |
-
user_message = f"{search_context}\n\nUSER'S ACTUAL QUESTION: {user_message}"
|
| 142 |
|
| 143 |
-
# --- MESSAGE CONSTRUCTION ---
|
| 144 |
messages = [{"role": "system", "content": system_prompt}]
|
| 145 |
|
| 146 |
for msg in history:
|
|
@@ -150,7 +127,6 @@ def chat():
|
|
| 150 |
messages.append({"role": role, "content": content})
|
| 151 |
|
| 152 |
content_payload = []
|
| 153 |
-
# अगर सर्च डेटा जुड़ा है तो user_message में सब है, बस उसे ऐड करो
|
| 154 |
if user_message.strip():
|
| 155 |
content_payload.append({"type": "text", "text": user_message})
|
| 156 |
|
|
@@ -167,9 +143,9 @@ def chat():
|
|
| 167 |
|
| 168 |
messages.append({"role": "user", "content": content_payload})
|
| 169 |
|
| 170 |
-
# --- LLM API CALL ---
|
| 171 |
headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
|
| 172 |
-
|
|
|
|
| 173 |
|
| 174 |
try:
|
| 175 |
response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
| 3 |
import urllib.parse
|
| 4 |
from bs4 import BeautifulSoup
|
|
|
|
| 19 |
else:
|
| 20 |
INVOKE_URL = BASE_URL
|
| 21 |
|
| 22 |
+
# 🌐 --- BULLETPROOF SCRAPER (News + Wiki) ---
|
| 23 |
def web_search_scraper(query, num_results=4):
|
| 24 |
results = []
|
| 25 |
+
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# 1. Google News RSS (Never blocks, gives real latest news)
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
+
rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
|
| 30 |
+
res = requests.get(rss_url, headers=headers, timeout=5)
|
| 31 |
+
soup = BeautifulSoup(res.content, 'xml') # Use XML parser
|
| 32 |
+
items = soup.find_all('item')
|
| 33 |
+
|
| 34 |
+
for item in items[:num_results]:
|
| 35 |
+
title = item.title.text if item.title else ""
|
| 36 |
+
link = item.link.text if item.link else ""
|
| 37 |
+
pub_date = item.pubDate.text if item.pubDate else ""
|
| 38 |
+
if title:
|
| 39 |
+
results.append({
|
| 40 |
+
"title": title,
|
| 41 |
+
"link": link,
|
| 42 |
+
"snippet": f"Published: {pub_date}"
|
| 43 |
+
})
|
| 44 |
except Exception as e:
|
| 45 |
pass
|
| 46 |
|
| 47 |
+
# 2. Wikipedia API Fallback (Never blocks)
|
| 48 |
+
if len(results) < 2:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
try:
|
| 50 |
wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
|
| 51 |
res = requests.get(wiki_url, headers=headers, timeout=5).json()
|
| 52 |
for item in res.get('query', {}).get('search', [])[:num_results]:
|
| 53 |
clean_snippet = BeautifulSoup(item['snippet'], "html.parser").text
|
| 54 |
+
results.append({
|
| 55 |
+
"title": item['title'],
|
| 56 |
+
"link": f"https://en.wikipedia.org/wiki/{urllib.parse.quote(item['title'])}",
|
| 57 |
+
"snippet": clean_snippet
|
| 58 |
+
})
|
| 59 |
except Exception as e:
|
| 60 |
pass
|
| 61 |
|
|
|
|
| 69 |
with open('index.html', 'r', encoding='utf-8') as f:
|
| 70 |
return render_template_string(f.read())
|
| 71 |
except Exception as e:
|
| 72 |
+
return f"<h1>System Error</h1><p>index.html missing: {str(e)}</p>"
|
| 73 |
|
| 74 |
@app.route('/api/chat', methods=['POST'])
|
| 75 |
def chat():
|
| 76 |
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 77 |
+
return Response("Server Error: Secrets missing.", status=500)
|
| 78 |
|
| 79 |
data = request.get_json() or {}
|
| 80 |
user_message = data.get("message", "")
|
|
|
|
| 82 |
is_search = data.get("is_search", False)
|
| 83 |
history = data.get("history", [])
|
| 84 |
max_tokens = data.get("max_tokens", 4096)
|
| 85 |
+
temperature = data.get("temperature", 0.3) # 💡 Low temp prevents hallucination
|
| 86 |
|
| 87 |
# 🕒 --- REAL-TIME IST INJECTION ---
|
| 88 |
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
|
| 89 |
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
|
| 90 |
|
| 91 |
+
# 🧠 --- STRICT SYSTEM PROMPT (ANTI-HALLUCINATION) ---
|
| 92 |
system_prompt = f"""
|
| 93 |
+
You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
|
| 94 |
+
Current Date: {current_date}.
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
STRICT DIRECTIVES:
|
| 97 |
+
1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
|
| 98 |
+
2. If you are provided with live search data, base your answer PURELY on that data.
|
| 99 |
+
3. If you lack data to answer a question about a recent event, you MUST say: "I do not have the verified live data for this right now."
|
|
|
|
|
|
|
| 100 |
"""
|
| 101 |
|
| 102 |
+
# 🚀 --- AUTO-SEARCH LOGIC WITH FAILSAFE ---
|
| 103 |
if is_search:
|
| 104 |
scraped_data = web_search_scraper(user_message)
|
| 105 |
|
|
|
|
| 106 |
if scraped_data:
|
| 107 |
+
search_context = "\n\n--- [LIVE VERIFIED WEB DATA] ---\n"
|
| 108 |
for idx, res in enumerate(scraped_data):
|
| 109 |
+
search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
|
| 110 |
|
| 111 |
+
search_context += "[SYSTEM: Use the above verified data to answer. Cite sources.]"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
else:
|
| 113 |
+
search_context = """
|
| 114 |
+
\n\n[CRITICAL SYSTEM ALERT: LIVE SEARCH FAILED OR BLOCKED.
|
| 115 |
+
YOU HAVE NO NEW DATA FOR THIS QUERY.
|
| 116 |
+
MANDATORY RULE: DO NOT INVENT ANY NEWS OR DATES. TELL THE USER HONESTLY THAT YOU COULD NOT FETCH THE LATEST LIVE DATA.]
|
| 117 |
+
"""
|
| 118 |
|
| 119 |
+
user_message = f"{search_context}\n\nUSER QUERY: {user_message}"
|
|
|
|
| 120 |
|
|
|
|
| 121 |
messages = [{"role": "system", "content": system_prompt}]
|
| 122 |
|
| 123 |
for msg in history:
|
|
|
|
| 127 |
messages.append({"role": role, "content": content})
|
| 128 |
|
| 129 |
content_payload = []
|
|
|
|
| 130 |
if user_message.strip():
|
| 131 |
content_payload.append({"type": "text", "text": user_message})
|
| 132 |
|
|
|
|
| 143 |
|
| 144 |
messages.append({"role": "user", "content": content_payload})
|
| 145 |
|
|
|
|
| 146 |
headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
|
| 147 |
+
# 💡 Temperature कम कर दी है ताकि यह एक्स्ट्रा झूठ न बोले
|
| 148 |
+
payload = {"model": MODEL_ID, "messages": messages, "max_tokens": int(max_tokens), "temperature": 0.3, "top_p": 0.70, "stream": True}
|
| 149 |
|
| 150 |
try:
|
| 151 |
response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
|