Spaces:
Running
Running
Vedika commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,40 +8,64 @@ from flask import Flask, request, Response, stream_with_context, render_template
|
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
# π --- SECURE ENVIRONMENT VARIABLES ---
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
MODEL_ID = os.environ.get("MODEL_ID")
|
| 14 |
|
| 15 |
-
# NVIDIA
|
| 16 |
INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
|
| 17 |
|
| 18 |
-
# π ---
|
| 19 |
def web_search_scraper(query, num_results=4):
|
|
|
|
|
|
|
|
|
|
| 20 |
results = []
|
| 21 |
-
headers = {
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
# 1.
|
| 24 |
try:
|
| 25 |
-
|
| 26 |
-
res = requests.get(
|
| 27 |
-
soup = BeautifulSoup(res.
|
| 28 |
-
items = soup.find_all('item')
|
| 29 |
|
| 30 |
-
for
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
if
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
})
|
|
|
|
|
|
|
|
|
|
| 40 |
except Exception as e:
|
| 41 |
-
|
| 42 |
|
| 43 |
-
# 2.
|
| 44 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
try:
|
| 46 |
wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
|
| 47 |
res = requests.get(wiki_url, headers=headers, timeout=5).json()
|
|
@@ -78,41 +102,37 @@ def chat():
|
|
| 78 |
is_search = data.get("is_search", False)
|
| 79 |
history = data.get("history", [])
|
| 80 |
max_tokens = data.get("max_tokens", 4096)
|
| 81 |
-
temperature = data.get("temperature", 1.
|
| 82 |
|
| 83 |
# π --- REAL-TIME IST INJECTION ---
|
| 84 |
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
|
| 85 |
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
|
| 86 |
|
| 87 |
-
# π§ ---
|
| 88 |
system_prompt = f"""
|
| 89 |
You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
|
| 90 |
-
Current Date: {current_date}.
|
| 91 |
|
| 92 |
STRICT DIRECTIVES:
|
| 93 |
1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
|
| 94 |
-
2. If you
|
| 95 |
-
3.
|
| 96 |
"""
|
| 97 |
|
| 98 |
-
# π --- AUTO-SEARCH
|
| 99 |
if is_search:
|
| 100 |
scraped_data = web_search_scraper(user_message)
|
| 101 |
|
|
|
|
| 102 |
if scraped_data:
|
| 103 |
-
search_context = "\n\n--- [LIVE VERIFIED WEB DATA] ---\n"
|
| 104 |
for idx, res in enumerate(scraped_data):
|
| 105 |
search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
|
| 106 |
|
| 107 |
-
search_context += "[SYSTEM: Use the above
|
| 108 |
else:
|
| 109 |
-
search_context = ""
|
| 110 |
-
\n\n[CRITICAL SYSTEM ALERT: LIVE SEARCH FAILED OR BLOCKED.
|
| 111 |
-
YOU HAVE NO NEW DATA FOR THIS QUERY.
|
| 112 |
-
MANDATORY RULE: DO NOT INVENT ANY NEWS OR DATES. TELL THE USER HONESTLY THAT YOU COULD NOT FETCH THE LATEST LIVE DATA.]
|
| 113 |
-
"""
|
| 114 |
|
| 115 |
-
user_message = f"
|
| 116 |
|
| 117 |
messages = [{"role": "system", "content": system_prompt}]
|
| 118 |
|
|
@@ -130,7 +150,6 @@ def chat():
|
|
| 130 |
att_type = att.get("type")
|
| 131 |
b64_data = att.get("data")
|
| 132 |
if att_type == "image":
|
| 133 |
-
# Image formatting compatible with standard APIs
|
| 134 |
content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
|
| 135 |
elif att_type in ["audio", "file"]:
|
| 136 |
content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
|
|
@@ -144,16 +163,16 @@ def chat():
|
|
| 144 |
"Authorization": f"Bearer {API_KEY}",
|
| 145 |
"Accept": "text/event-stream"
|
| 146 |
}
|
| 147 |
-
|
| 148 |
-
# π ---
|
| 149 |
payload = {
|
| 150 |
-
"model": MODEL_ID,
|
| 151 |
"messages": messages,
|
| 152 |
"max_tokens": int(max_tokens),
|
| 153 |
"temperature": float(temperature),
|
| 154 |
-
"top_p": 0.95,
|
| 155 |
-
"stream": True,
|
| 156 |
-
"chat_template_kwargs": {"enable_thinking": True} #
|
| 157 |
}
|
| 158 |
|
| 159 |
try:
|
|
|
|
| 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 |
+
# π --- SUPER-HYBRID UNBLOCKABLE SCRAPER --- π
|
| 18 |
def web_search_scraper(query, num_results=4):
|
| 19 |
+
"""
|
| 20 |
+
Yahoo Search + Google News + Wikipedia (Never blocks on Hugging Face)
|
| 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 |
+
url = f"https://search.yahoo.com/search?p={urllib.parse.quote(query)}"
|
| 31 |
+
res = requests.get(url, headers=headers, timeout=8)
|
| 32 |
+
soup = BeautifulSoup(res.text, 'html.parser')
|
|
|
|
| 33 |
|
| 34 |
+
for div in soup.find_all('div', class_='algo'):
|
| 35 |
+
title_tag = div.find('h3', class_='title')
|
| 36 |
+
desc_tag = div.find('div', class_='compText')
|
| 37 |
+
|
| 38 |
+
if title_tag and desc_tag:
|
| 39 |
+
title = title_tag.text.strip()
|
| 40 |
+
link = title_tag.find('a').get('href', '') if title_tag.find('a') else ""
|
| 41 |
+
snippet = desc_tag.text.strip()
|
| 42 |
+
|
| 43 |
+
results.append({"title": title, "link": link, "snippet": snippet})
|
| 44 |
+
|
| 45 |
+
if len(results) >= num_results:
|
| 46 |
+
break
|
| 47 |
except Exception as e:
|
| 48 |
+
print(f"Yahoo Scraper Error: {e}")
|
| 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()
|
|
|
|
| 102 |
is_search = data.get("is_search", False)
|
| 103 |
history = data.get("history", [])
|
| 104 |
max_tokens = data.get("max_tokens", 4096)
|
| 105 |
+
temperature = data.get("temperature", 1.0) # NVIDIA Recommended
|
| 106 |
|
| 107 |
# π --- REAL-TIME IST INJECTION ---
|
| 108 |
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
|
| 109 |
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
|
| 110 |
|
| 111 |
+
# π§ --- GOD MODE SYSTEM PROMPT ---
|
| 112 |
system_prompt = f"""
|
| 113 |
You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
|
| 114 |
+
Current Live Date and Time: {current_date}.
|
| 115 |
|
| 116 |
STRICT DIRECTIVES:
|
| 117 |
1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
|
| 118 |
+
2. If you receive "LIVE WEB SEARCH RESULTS", you MUST base your answer ENTIRELY on that data.
|
| 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 WEB DATA] ---\n"
|
| 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 blocked. Rely on your existing knowledge, but DO NOT hallucinate recent news.]"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
user_message = f"USER QUERY: {user_message}\n\n{search_context}"
|
| 136 |
|
| 137 |
messages = [{"role": "system", "content": system_prompt}]
|
| 138 |
|
|
|
|
| 150 |
att_type = att.get("type")
|
| 151 |
b64_data = att.get("data")
|
| 152 |
if att_type == "image":
|
|
|
|
| 153 |
content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
|
| 154 |
elif att_type in ["audio", "file"]:
|
| 155 |
content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
|
|
|
|
| 163 |
"Authorization": f"Bearer {API_KEY}",
|
| 164 |
"Accept": "text/event-stream"
|
| 165 |
}
|
| 166 |
+
|
| 167 |
+
# π --- NVIDIA FORMAT INTEGRATED ---
|
| 168 |
payload = {
|
| 169 |
+
"model": MODEL_ID,
|
| 170 |
"messages": messages,
|
| 171 |
"max_tokens": int(max_tokens),
|
| 172 |
"temperature": float(temperature),
|
| 173 |
+
"top_p": 0.95,
|
| 174 |
+
"stream": True,
|
| 175 |
+
"chat_template_kwargs": {"enable_thinking": True} # Thinking logic enabled
|
| 176 |
}
|
| 177 |
|
| 178 |
try:
|