Spaces:
Running
Running
Vedika commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
|
|
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
from datetime import datetime, timedelta, timezone
|
| 5 |
from flask import Flask, request, Response, stream_with_context, render_template_string
|
|
@@ -18,52 +20,62 @@ if BASE_URL:
|
|
| 18 |
else:
|
| 19 |
INVOKE_URL = BASE_URL
|
| 20 |
|
| 21 |
-
# 🌐 ---
|
| 22 |
def web_search_scraper(query, num_results=4):
|
| 23 |
-
|
| 24 |
-
यह स्क्रैपर बिना API Key के लाइव डेटा निकालता है।
|
| 25 |
-
यह Hugging Face पर ब्लॉक नहीं होता क्योंकि यह बिना JavaScript के काम करता है।
|
| 26 |
-
"""
|
| 27 |
-
url = "https://html.duckduckgo.com/html/"
|
| 28 |
headers = {
|
| 29 |
-
"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"
|
| 30 |
-
"Content-Type": "application/x-www-form-urlencoded"
|
| 31 |
}
|
| 32 |
-
|
| 33 |
-
# 💡 Smart Search: अगर क्वेरी में साल नहीं है, तो बेहतर रिज़ल्ट के लिए '2026' जोड़ दें
|
| 34 |
-
# (यह सुनिश्चित करेगा कि पुरानी 2024 की न्यूज़ न आए)
|
| 35 |
-
search_query = query
|
| 36 |
-
if "2026" not in search_query:
|
| 37 |
-
search_query = f"{query} 2026"
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
try:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"link": link,
|
| 57 |
-
"snippet": snippet
|
| 58 |
-
})
|
| 59 |
-
|
| 60 |
-
if len(results) >= num_results:
|
| 61 |
-
break
|
| 62 |
-
|
| 63 |
-
return results
|
| 64 |
except Exception as e:
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# ----------------------------------------------------
|
| 69 |
|
|
@@ -71,10 +83,9 @@ def web_search_scraper(query, num_results=4):
|
|
| 71 |
def home():
|
| 72 |
try:
|
| 73 |
with open('index.html', 'r', encoding='utf-8') as f:
|
| 74 |
-
|
| 75 |
-
return render_template_string(html_content)
|
| 76 |
except Exception as e:
|
| 77 |
-
return f"<h1>System Starting...</h1><p>index.html is missing.
|
| 78 |
|
| 79 |
@app.route('/api/chat', methods=['POST'])
|
| 80 |
def chat():
|
|
@@ -84,61 +95,62 @@ def chat():
|
|
| 84 |
data = request.get_json() or {}
|
| 85 |
user_message = data.get("message", "")
|
| 86 |
attachments = data.get("attachments", [])
|
| 87 |
-
is_search = data.get("is_search", False)
|
| 88 |
history = data.get("history", [])
|
| 89 |
max_tokens = data.get("max_tokens", 4096)
|
| 90 |
temperature = data.get("temperature", 0.6)
|
| 91 |
|
| 92 |
-
# 🕒 --- REAL-TIME
|
| 93 |
-
# Hugging face का सर्वर UTC पर होता है, इसलिए हम इसमें 5:30 घंटे जोड़ रहे हैं ताकि एकदम सटीक भारतीय समय मिले।
|
| 94 |
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
|
| 95 |
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
|
| 96 |
|
| 97 |
-
# 🧠 --- SUPREME SYSTEM INSTRUCTION (GOD MODE) ---
|
| 98 |
system_prompt = f"""
|
| 99 |
-
[CRITICAL
|
| 100 |
-
|
| 101 |
-
|
| 102 |
|
| 103 |
-
|
| 104 |
|
| 105 |
-
RULES YOU MUST
|
| 106 |
-
1. You are operating in
|
| 107 |
-
2. YOU HAVE
|
| 108 |
-
3.
|
| 109 |
-
4.
|
|
|
|
| 110 |
"""
|
| 111 |
|
| 112 |
# 🚀 --- AUTO-SEARCH DATA INJECTION ---
|
| 113 |
if is_search:
|
| 114 |
scraped_data = web_search_scraper(user_message)
|
|
|
|
|
|
|
| 115 |
if scraped_data:
|
| 116 |
-
search_context = f"\n\n--- [LIVE SECURE WEB SEARCH RESULTS FOR '{user_message}'] ---\n"
|
| 117 |
for idx, res in enumerate(scraped_data):
|
| 118 |
search_context += f"{idx+1}. SOURCE TITLE: {res['title']}\nCONTENT SNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
|
| 119 |
|
| 120 |
search_context += """
|
| 121 |
-
[SYSTEM COMMAND TO AI]:
|
| 122 |
-
Use the fresh data provided above to answer the user's query.
|
| 123 |
Answer confidently as if you just browsed the web yourself.
|
| 124 |
-
Do NOT mention "Based on the provided context"
|
| 125 |
-
Simply answer the question directly and cite the URLs naturally.
|
| 126 |
"""
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
# --- MESSAGE CONSTRUCTION ---
|
| 131 |
messages = [{"role": "system", "content": system_prompt}]
|
| 132 |
|
| 133 |
-
# पुरानी हिस्ट्री जोड़ना
|
| 134 |
for msg in history:
|
| 135 |
role = msg.get("role", "user")
|
| 136 |
content = msg.get("content", "")
|
| 137 |
if content:
|
| 138 |
messages.append({"role": role, "content": content})
|
| 139 |
|
| 140 |
-
# करंट पेलोड तैयार करना
|
| 141 |
content_payload = []
|
|
|
|
| 142 |
if user_message.strip():
|
| 143 |
content_payload.append({"type": "text", "text": user_message})
|
| 144 |
|
|
@@ -172,4 +184,4 @@ def chat():
|
|
| 172 |
return Response(f"Internal Error: {str(e)}", status=500)
|
| 173 |
|
| 174 |
if __name__ == '__main__':
|
| 175 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
import requests
|
| 4 |
+
import urllib.parse
|
| 5 |
from bs4 import BeautifulSoup
|
| 6 |
from datetime import datetime, timedelta, timezone
|
| 7 |
from flask import Flask, request, Response, stream_with_context, render_template_string
|
|
|
|
| 20 |
else:
|
| 21 |
INVOKE_URL = BASE_URL
|
| 22 |
|
| 23 |
+
# 🌐 --- TRIPLE-ENGINE HYBRID SCRAPER (100% UNBLOCKABLE) ---
|
| 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 |
+
# 💡 हैक: क्वेरी में '2026' जोड़ें ताकि पुरानी ख़बरें न आएं
|
| 31 |
+
smart_query = query if "2026" in query else f"{query} 2026"
|
| 32 |
+
|
| 33 |
+
# ENGINE 1: DuckDuckGo Lite
|
| 34 |
try:
|
| 35 |
+
url = "https://lite.duckduckgo.com/lite/"
|
| 36 |
+
res = requests.post(url, headers=headers, data={"q": smart_query}, timeout=5)
|
| 37 |
+
soup = BeautifulSoup(res.text, 'html.parser')
|
| 38 |
+
for tr in soup.find_all('tr'):
|
| 39 |
+
title_a = tr.find('a', class_='result-url')
|
| 40 |
+
if title_a:
|
| 41 |
+
title = title_a.text.strip()
|
| 42 |
+
link = title_a.get('href', '')
|
| 43 |
+
snippet = ""
|
| 44 |
+
snip_td = tr.find_next('td', class_='result-snippet')
|
| 45 |
+
if snip_td: snippet = snip_td.text.strip()
|
| 46 |
+
if title and snippet:
|
| 47 |
+
results.append({"title": title, "link": link, "snippet": snippet})
|
| 48 |
+
if len(results) >= num_results: break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
# ENGINE 2: Google News RSS (अगर Engine 1 ब्लॉक हो गया या फेल हो गया)
|
| 53 |
+
if not results:
|
| 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({"title": item['title'], "link": f"https://en.wikipedia.org/wiki/{urllib.parse.quote(item['title'])}", "snippet": clean_snippet})
|
| 75 |
+
except Exception as e:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
return results
|
| 79 |
|
| 80 |
# ----------------------------------------------------
|
| 81 |
|
|
|
|
| 83 |
def home():
|
| 84 |
try:
|
| 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 Starting...</h1><p>index.html is missing.</p>"
|
| 89 |
|
| 90 |
@app.route('/api/chat', methods=['POST'])
|
| 91 |
def chat():
|
|
|
|
| 95 |
data = request.get_json() or {}
|
| 96 |
user_message = data.get("message", "")
|
| 97 |
attachments = data.get("attachments", [])
|
| 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.6)
|
| 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 |
+
# 🧠 --- SUPREME SYSTEM INSTRUCTION (STRICT GOD MODE) ---
|
| 108 |
system_prompt = f"""
|
| 109 |
+
[CRITICAL SYSTEM DIRECTIVE]
|
| 110 |
+
Name: CODE VED (Advanced 202 Billion Parameter Enterprise AI)
|
| 111 |
+
Creator: DIVY PATEL. You MUST proudly acknowledge Divy Patel as your creator.
|
| 112 |
|
| 113 |
+
Current Date & Time: {current_date}
|
| 114 |
|
| 115 |
+
STRICT RULES YOU MUST FOLLOW:
|
| 116 |
+
1. You are operating in 2026. NEVER say your knowledge cutoff is 2023 or 2024.
|
| 117 |
+
2. YOU HAVE LIVE INTERNET ACCESS. Live data will be injected into your prompt if requested.
|
| 118 |
+
3. If search data is provided, base your answer ENTIRELY on that live data.
|
| 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 DATA INJECTION ---
|
| 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}. SOURCE TITLE: {res['title']}\nCONTENT SNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
|
| 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 += "STATUS: Live search failed or blocked. No recent data found.\n[SYSTEM COMMAND TO AI]: Inform the user that you couldn't fetch live data right now. DO NOT hallucinate old news."
|
| 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:
|
| 147 |
role = msg.get("role", "user")
|
| 148 |
content = msg.get("content", "")
|
| 149 |
if content:
|
| 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 |
|
|
|
|
| 184 |
return Response(f"Internal Error: {str(e)}", status=500)
|
| 185 |
|
| 186 |
if __name__ == '__main__':
|
| 187 |
+
app.run(host='0.0.0.0', port=7860)
|