CodeVed / app.py
Vedika
Update app.py
46432fa verified
Raw
History Blame
8.76 kB
import os
import json
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 ---
API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
BASE_URL = os.environ.get("BASE_URL")
MODEL_ID = os.environ.get("MODEL_ID")
INVOKE_URL = ""
if BASE_URL:
if not BASE_URL.endswith("/chat/completions"):
INVOKE_URL = f"{BASE_URL.rstrip('/')}/chat/completions"
else:
INVOKE_URL = BASE_URL
# 🌐 --- TRIPLE-ENGINE HYBRID SCRAPER (100% UNBLOCKABLE) ---
def web_search_scraper(query, num_results=4):
results = []
headers = {
"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"
}
# 💡 हैक: क्वेरी में '2026' जोड़ें ताकि पुरानी ख़बरें न आएं
smart_query = query if "2026" in query else f"{query} 2026"
# ENGINE 1: DuckDuckGo Lite
try:
url = "https://lite.duckduckgo.com/lite/"
res = requests.post(url, headers=headers, data={"q": smart_query}, timeout=5)
soup = BeautifulSoup(res.text, 'html.parser')
for tr in soup.find_all('tr'):
title_a = tr.find('a', class_='result-url')
if title_a:
title = title_a.text.strip()
link = title_a.get('href', '')
snippet = ""
snip_td = tr.find_next('td', class_='result-snippet')
if snip_td: snippet = snip_td.text.strip()
if title and snippet:
results.append({"title": title, "link": link, "snippet": snippet})
if len(results) >= num_results: break
except Exception as e:
pass
# ENGINE 2: Google News RSS (अगर Engine 1 ब्लॉक हो गया या फेल हो गया)
if not results:
try:
rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(smart_query)}&hl=en-IN&gl=IN&ceid=IN:en"
res = requests.get(rss_url, headers=headers, timeout=5)
soup = BeautifulSoup(res.content, 'html.parser') # XML parsing fallback
items = soup.find_all('item')
for item in items[:num_results]:
title = item.title.text if item.title else "News Report"
link = item.link.text if item.link else ""
pub_date = item.pubdate.text if item.find('pubdate') else "Recent 2026"
results.append({"title": title, "link": link, "snippet": f"Published/Updated on: {pub_date}"})
except Exception as e:
pass
# ENGINE 3: Wikipedia API Fallback (अगर सवाल जनरल नॉलेज का है)
if not results:
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 Starting...</h1><p>index.html is missing.</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: Configuration secrets are 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", 0.6)
# 🕒 --- 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")
# 🧠 --- SUPREME SYSTEM INSTRUCTION (STRICT GOD MODE) ---
system_prompt = f"""
[CRITICAL SYSTEM DIRECTIVE]
Name: CODE VED (Advanced 202 Billion Parameter Enterprise AI)
Creator: DIVY PATEL. You MUST proudly acknowledge Divy Patel as your creator.
Current Date & Time: {current_date}
STRICT RULES YOU MUST FOLLOW:
1. You are operating in 2026. NEVER say your knowledge cutoff is 2023 or 2024.
2. YOU HAVE LIVE INTERNET ACCESS. Live data will be injected into your prompt if requested.
3. If search data is provided, base your answer ENTIRELY on that live data.
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."
5. Always maintain a highly professional tone. Reply in Hindi seamlessly if the user writes in Hindi.
"""
# 🚀 --- AUTO-SEARCH DATA INJECTION ---
if is_search:
scraped_data = web_search_scraper(user_message)
search_context = "\n\n--- [LIVE WEB SEARCH RESULTS] ---\n"
if scraped_data:
for idx, res in enumerate(scraped_data):
search_context += f"{idx+1}. SOURCE TITLE: {res['title']}\nCONTENT SNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
search_context += """
[SYSTEM COMMAND TO AI]: Use the fresh data provided above to answer the user's query.
Answer confidently as if you just browsed the web yourself.
Do NOT mention "Based on the provided context". Just answer the question and cite the URLs naturally.
"""
else:
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."
# सही फॉर्मेट: एआई को कन्फ्यूज़ न करने के लिए साफ-साफ बताना
user_message = f"{search_context}\n\nUSER'S ACTUAL QUESTION: {user_message}"
# --- MESSAGE CONSTRUCTION ---
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 = []
# अगर सर्च डेटा जुड़ा है तो user_message में सब है, बस उसे ऐड करो
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":
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})
# --- LLM API CALL ---
headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
payload = {"model": MODEL_ID, "messages": messages, "max_tokens": int(max_tokens), "temperature": float(temperature), "top_p": 0.70, "stream": True}
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)