CodeVed / app.py
Vedika
Update app.py
40a703c verified
Raw
History Blame
7.19 kB
import os
import requests
import urllib.parse
from bs4 import BeautifulSoup
from datetime import datetime, timedelta, timezone
from flask import Flask, request, Response, stream_with_context, render_template_string
app = Flask(__name__)
# πŸ” --- SECURE ENVIRONMENT VARIABLES ---
# ΰ€―ΰ€Ή ΰ€†ΰ€ͺΰ€•ΰ₯‡ Hugging Face Secrets ΰ€Έΰ₯‡ ΰ€…ΰ€ͺΰ€¨ΰ₯‡ ΰ€†ΰ€ͺ ΰ€²ΰ₯‹ΰ€‘ ΰ€Ήΰ₯‹ ΰ€œΰ€Ύΰ€ΰ€—ΰ€Ύ
API_KEY = os.environ.get("NVIDIA_API_KEY") or os.environ.get("YOUR_VEDIKA_API_KEY")
MODEL_ID = os.environ.get("MODEL_ID")
# NVIDIA ΰ€•ΰ€Ύ ΰ€‘ΰ€Ύΰ€―ΰ€°ΰ₯‡ΰ€•ΰ₯ΰ€Ÿ URL (BASE_URL ΰ€•ΰ€Ύ ΰ€²ΰ₯‰ΰ€œΰ€Ώΰ€• ΰ€ͺΰ₯‚ΰ€°ΰ₯€ ΰ€€ΰ€°ΰ€Ή ΰ€Ήΰ€Ÿΰ€Ύ ΰ€¦ΰ€Ώΰ€―ΰ€Ύ ΰ€—ΰ€―ΰ€Ύ ΰ€Ήΰ₯ˆ)
INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
# 🌐 --- BULLETPROOF SCRAPER (News + Wiki) ---
def web_search_scraper(query, num_results=4):
results = []
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
# 1. Google News RSS (Never blocks, gives real latest news)
try:
rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
res = requests.get(rss_url, headers=headers, timeout=5)
soup = BeautifulSoup(res.content, 'xml') # Use XML parser
items = soup.find_all('item')
for item in items[:num_results]:
title = item.title.text if item.title else ""
link = item.link.text if item.link else ""
pub_date = item.pubDate.text if item.pubDate else ""
if title:
results.append({
"title": title,
"link": link,
"snippet": f"Published: {pub_date}"
})
except Exception as e:
pass
# 2. Wikipedia API Fallback (Never blocks)
if len(results) < 2:
try:
wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
res = requests.get(wiki_url, headers=headers, timeout=5).json()
for item in res.get('query', {}).get('search', [])[:num_results]:
clean_snippet = BeautifulSoup(item['snippet'], "html.parser").text
results.append({
"title": item['title'],
"link": f"https://en.wikipedia.org/wiki/{urllib.parse.quote(item['title'])}",
"snippet": clean_snippet
})
except Exception as e:
pass
return results
# ----------------------------------------------------
@app.route('/')
def home():
try:
with open('index.html', 'r', encoding='utf-8') as f:
return render_template_string(f.read())
except Exception as e:
return f"<h1>System Error</h1><p>index.html missing: {str(e)}</p>"
@app.route('/api/chat', methods=['POST'])
def chat():
if not API_KEY or not INVOKE_URL or not MODEL_ID:
return Response("Server Error: Secrets missing.", status=500)
data = request.get_json() or {}
user_message = data.get("message", "")
attachments = data.get("attachments", [])
is_search = data.get("is_search", False)
history = data.get("history", [])
max_tokens = data.get("max_tokens", 4096)
temperature = data.get("temperature", 1.00) # Updated to NVIDIA default if not passed
# πŸ•’ --- REAL-TIME IST INJECTION ---
ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
# 🧠 --- STRICT SYSTEM PROMPT (ANTI-HALLUCINATION) ---
system_prompt = f"""
You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
Current Date: {current_date}.
STRICT DIRECTIVES:
1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
2. If you are provided with live search data, base your answer PURELY on that data.
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."
"""
# πŸš€ --- AUTO-SEARCH LOGIC WITH FAILSAFE ---
if is_search:
scraped_data = web_search_scraper(user_message)
if scraped_data:
search_context = "\n\n--- [LIVE VERIFIED WEB DATA] ---\n"
for idx, res in enumerate(scraped_data):
search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
search_context += "[SYSTEM: Use the above verified data to answer. Cite sources.]"
else:
search_context = """
\n\n[CRITICAL SYSTEM ALERT: LIVE SEARCH FAILED OR BLOCKED.
YOU HAVE NO NEW DATA FOR THIS QUERY.
MANDATORY RULE: DO NOT INVENT ANY NEWS OR DATES. TELL THE USER HONESTLY THAT YOU COULD NOT FETCH THE LATEST LIVE DATA.]
"""
user_message = f"{search_context}\n\nUSER QUERY: {user_message}"
messages = [{"role": "system", "content": system_prompt}]
for msg in history:
role = msg.get("role", "user")
content = msg.get("content", "")
if content:
messages.append({"role": role, "content": content})
content_payload = []
if user_message.strip():
content_payload.append({"type": "text", "text": user_message})
for att in attachments:
att_type = att.get("type")
b64_data = att.get("data")
if att_type == "image":
# Image formatting compatible with standard APIs
content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
elif att_type in ["audio", "file"]:
content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
if not content_payload:
content_payload.append({"type": "text", "text": "Hello"})
messages.append({"role": "user", "content": content_payload})
headers = {
"Authorization": f"Bearer {API_KEY}",
"Accept": "text/event-stream"
}
# 🌟 --- NEW NVIDIA FORMAT PAYLOAD INTEGRATED HERE --- 🌟
payload = {
"model": MODEL_ID, # Dynamically fetching from your secrets
"messages": messages,
"max_tokens": int(max_tokens),
"temperature": float(temperature),
"top_p": 0.95, # As per your format
"stream": True, # Stream is kept True for fast UI response
"chat_template_kwargs": {"enable_thinking": True} # πŸ‘ˆ New NVIDIA feature added
}
try:
response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
def generate():
for line in response.iter_lines():
if line:
decoded_line = line.decode("utf-8")
if decoded_line.startswith("data: "):
yield decoded_line + "\n\n"
return Response(stream_with_context(generate()), mimetype='text/event-stream')
except Exception as e:
return Response(f"Internal Error: {str(e)}", status=500)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)