CodeVed / app.py
Vedika
Update app.py
ce04afa verified
Raw
History Blame
7.47 kB
import os
import requests
import urllib.parse
from bs4 import BeautifulSoup
from flask import Flask, request, Response, stream_with_context, render_template_string
app = Flask(__name__)
# 🔐 100% सुरक्षित: सब कुछ केवल 'Secrets' से कॉल होगा, कोई हार्डकोडेड डेटा नहीं।
API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
BASE_URL = os.environ.get("BASE_URL")
MODEL_ID = os.environ.get("MODEL_ID")
# URL को सुरक्षित रूप से बनाना ताकि कोई डिफ़ॉल्ट लिंक न दिखे
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
# 🌐 --- GOOGLE SEARCH SCRAPER ENGINE --- 🌐
def google_search_scraper(query, num_results=4):
"""
यह फंक्शन Google सर्च से डेटा निकालता है और उसे AI के समझने लायक बनाता है।
"""
# Google को धोखा देने के लिए असली ब्राउज़र का User-Agent
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
url = f"https://www.google.com/search?q={urllib.parse.quote(query)}&hl=en"
try:
response = requests.get(url, headers=headers, timeout=10)
soup = BeautifulSoup(response.text, 'html.parser')
results = []
# Google के सर्च रिजल्ट्स 'div.g' के अंदर होते हैं
for g in soup.find_all('div', class_='g'):
title_elem = g.find('h3')
link_elem = g.find('a')
if title_elem and link_elem:
title = title_elem.text
link = link_elem.get('href', '')
# Snippet (डिस्क्रिप्शन) निकालना
snippet = ""
snippet_box = g.find('div', class_='VwiC3b')
if snippet_box:
snippet = snippet_box.text
results.append({
"title": title,
"link": link,
"snippet": snippet
})
if len(results) >= num_results:
break
return results
except Exception as e:
return [{"error": str(e)}]
# ---------------------------------------------
@app.route('/')
def home():
try:
with open('index.html', 'r', encoding='utf-8') as f:
html_content = f.read()
return render_template_string(html_content)
except Exception as e:
return f"index.html file missing! Error: {str(e)}"
@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", [])
system_prompt = data.get("system_prompt", "")
history = data.get("history", [])
max_tokens = data.get("max_tokens", 4096)
temperature = data.get("temperature", 0.6)
# 🚀 --- INTERCEPT & SEARCH LOGIC --- 🚀
# अगर यूजर के मैसेज में /search या /google है, तो स्क्रैपर चालू करें
if user_message.strip().lower().startswith("/search "):
search_query = user_message[8:].strip()
scraped_data = google_search_scraper(search_query)
search_context = f"Real-time Google Search Results for '{search_query}':\n\n"
for idx, res in enumerate(scraped_data):
if "error" in res:
search_context += f"Search Error: {res['error']}\n"
else:
search_context += f"{idx+1}. Title: {res['title']}\nSnippet: {res['snippet']}\nLink: {res['link']}\n\n"
search_context += "\n[INSTRUCTION FOR AI: Formulate a comprehensive, professional response to the user's query using ONLY the real-time search data provided above. Cite sources if applicable.]"
# एआई के लिए प्रॉम्प्ट को मॉडिफाई करना (यूजर को यह बैकग्राउंड डेटा नहीं दिखेगा)
user_message = f"User Query: {search_query}\n\n[SYSTEM BACKGROUND CONTEXT]\n{search_context}"
# ---------------------------------------
messages = []
# 1. सिस्टम प्रॉम्प्ट
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
# 2. पुरानी हिस्ट्री को मॉडल के पेलोड में जोड़ना
for msg in history:
role = msg.get("role", "user")
content = msg.get("content", "")
if content:
messages.append({"role": role, "content": content})
# 3. मल्टीमोडल इनपुट (करेंट मैसेज)
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":
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"
}
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("Internal Error: Unable to process request securely.", status=500)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)