Spaces:
Running
Running
Vedika commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,163 +1,31 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 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 |
-
|
| 62 |
-
return results
|
| 63 |
-
|
| 64 |
-
# ----------------------------------------------------
|
| 65 |
-
|
| 66 |
-
@app.route('/')
|
| 67 |
-
def home():
|
| 68 |
-
try:
|
| 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", "")
|
| 81 |
-
attachments = data.get("attachments", [])
|
| 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:
|
| 124 |
-
role = msg.get("role", "user")
|
| 125 |
-
content = msg.get("content", "")
|
| 126 |
-
if content:
|
| 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 |
-
|
| 133 |
-
for att in attachments:
|
| 134 |
-
att_type = att.get("type")
|
| 135 |
-
b64_data = att.get("data")
|
| 136 |
-
if att_type == "image":
|
| 137 |
-
content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
|
| 138 |
-
elif att_type in ["audio", "file"]:
|
| 139 |
-
content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
|
| 140 |
-
|
| 141 |
-
if not content_payload:
|
| 142 |
-
content_payload.append({"type": "text", "text": "Hello"})
|
| 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)
|
| 152 |
-
def generate():
|
| 153 |
-
for line in response.iter_lines():
|
| 154 |
-
if line:
|
| 155 |
-
decoded_line = line.decode("utf-8")
|
| 156 |
-
if decoded_line.startswith("data: "):
|
| 157 |
-
yield decoded_line + "\n\n"
|
| 158 |
-
return Response(stream_with_context(generate()), mimetype='text/event-stream')
|
| 159 |
-
except Exception as e:
|
| 160 |
-
return Response(f"Internal Error: {str(e)}", status=500)
|
| 161 |
-
|
| 162 |
-
if __name__ == '__main__':
|
| 163 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
+
import requests, base64
|
| 2 |
+
|
| 3 |
+
invoke_url = "https://integrate.api.nvidia.com/v1/chat/completions"
|
| 4 |
+
stream = False
|
| 5 |
+
|
| 6 |
+
def read_b64(path):
|
| 7 |
+
with open(path, "rb") as f:
|
| 8 |
+
return base64.b64encode(f.read()).decode()
|
| 9 |
+
|
| 10 |
+
headers = {
|
| 11 |
+
"Authorization": "Bearer $NVIDIA_API_KEY",
|
| 12 |
+
"Accept": "text/event-stream" if stream else "application/json"
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
payload = {
|
| 16 |
+
"model": "google/diffusiongemma-26b-a4b-it",
|
| 17 |
+
"messages": [{"role":"user","content":""}],
|
| 18 |
+
"max_tokens": 4096,
|
| 19 |
+
"temperature": 1.00,
|
| 20 |
+
"top_p": 0.95,
|
| 21 |
+
"stream": stream,
|
| 22 |
+
"chat_template_kwargs": {"enable_thinking":True},
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
response = requests.post(invoke_url, headers=headers, json=payload, stream=stream)
|
| 26 |
+
if stream:
|
| 27 |
+
for line in response.iter_lines():
|
| 28 |
+
if line:
|
| 29 |
+
print(line.decode("utf-8"))
|
| 30 |
+
else:
|
| 31 |
+
print(response.json())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|