Spaces:
Running
Running
Vedika commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,15 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
-
import urllib.parse
|
| 4 |
-
from bs4 import BeautifulSoup
|
| 5 |
from flask import Flask, request, Response, stream_with_context, render_template_string
|
|
|
|
| 6 |
|
| 7 |
app = Flask(__name__)
|
| 8 |
|
| 9 |
-
# 🔐 100% सुरक्षित: स
|
| 10 |
API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
|
| 11 |
BASE_URL = os.environ.get("BASE_URL")
|
| 12 |
MODEL_ID = os.environ.get("MODEL_ID")
|
| 13 |
|
| 14 |
-
# URL को सुरक्षित रूप से बनाना ताकि कोई डिफ़ॉल्ट लिंक न दिखे
|
| 15 |
INVOKE_URL = ""
|
| 16 |
if BASE_URL:
|
| 17 |
if not BASE_URL.endswith("/chat/completions"):
|
|
@@ -19,52 +17,26 @@ if BASE_URL:
|
|
| 19 |
else:
|
| 20 |
INVOKE_URL = BASE_URL
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
def google_search_scraper(query, num_results=4):
|
| 25 |
"""
|
| 26 |
-
|
|
|
|
| 27 |
"""
|
| 28 |
-
# Google को धोखा देने के लिए असली ब्राउज़र का User-Agent
|
| 29 |
-
headers = {
|
| 30 |
-
"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"
|
| 31 |
-
}
|
| 32 |
-
url = f"https://www.google.com/search?q={urllib.parse.quote(query)}&hl=en"
|
| 33 |
-
|
| 34 |
try:
|
| 35 |
-
response = requests.get(url, headers=headers, timeout=10)
|
| 36 |
-
soup = BeautifulSoup(response.text, 'html.parser')
|
| 37 |
results = []
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
title_elem = g.find('h3')
|
| 42 |
-
link_elem = g.find('a')
|
| 43 |
-
|
| 44 |
-
if title_elem and link_elem:
|
| 45 |
-
title = title_elem.text
|
| 46 |
-
link = link_elem.get('href', '')
|
| 47 |
-
|
| 48 |
-
# Snippet (डिस्क्रिप्शन) निकालना
|
| 49 |
-
snippet = ""
|
| 50 |
-
snippet_box = g.find('div', class_='VwiC3b')
|
| 51 |
-
if snippet_box:
|
| 52 |
-
snippet = snippet_box.text
|
| 53 |
-
|
| 54 |
results.append({
|
| 55 |
-
"title": title,
|
| 56 |
-
"link":
|
| 57 |
-
"snippet":
|
| 58 |
})
|
| 59 |
-
|
| 60 |
-
if len(results) >= num_results:
|
| 61 |
-
break
|
| 62 |
-
|
| 63 |
return results
|
| 64 |
except Exception as e:
|
| 65 |
return [{"error": str(e)}]
|
| 66 |
-
# ---------------------------------------------
|
| 67 |
-
|
| 68 |
|
| 69 |
@app.route('/')
|
| 70 |
def home():
|
|
@@ -77,7 +49,6 @@ def home():
|
|
| 77 |
|
| 78 |
@app.route('/api/chat', methods=['POST'])
|
| 79 |
def chat():
|
| 80 |
-
# सुरक्षा जांच: अगर सीक्रेट्स सेट नहीं हैं, तो रिक्वेस्ट आगे नहीं जाएगी
|
| 81 |
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 82 |
return Response("Server Error: Configuration secrets are missing.", status=500)
|
| 83 |
|
|
@@ -90,38 +61,36 @@ def chat():
|
|
| 90 |
temperature = data.get("temperature", 0.6)
|
| 91 |
|
| 92 |
# 🚀 --- INTERCEPT & SEARCH LOGIC --- 🚀
|
| 93 |
-
# अगर यूजर के मैसेज में /search या /google है, तो स्क्रैपर चालू करें
|
| 94 |
if user_message.strip().lower().startswith("/search "):
|
| 95 |
search_query = user_message[8:].strip()
|
| 96 |
-
scraped_data = google_search_scraper(search_query)
|
| 97 |
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
for idx, res in enumerate(scraped_data):
|
| 100 |
if "error" in res:
|
| 101 |
search_context += f"Search Error: {res['error']}\n"
|
| 102 |
else:
|
| 103 |
search_context += f"{idx+1}. Title: {res['title']}\nSnippet: {res['snippet']}\nLink: {res['link']}\n\n"
|
| 104 |
|
| 105 |
-
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.]"
|
| 106 |
|
| 107 |
-
#
|
| 108 |
user_message = f"User Query: {search_query}\n\n[SYSTEM BACKGROUND CONTEXT]\n{search_context}"
|
| 109 |
# ---------------------------------------
|
| 110 |
|
| 111 |
messages = []
|
| 112 |
|
| 113 |
-
# 1. सिस्टम प्रॉम्प्ट
|
| 114 |
if system_prompt.strip():
|
| 115 |
messages.append({"role": "system", "content": system_prompt})
|
| 116 |
|
| 117 |
-
# 2. पुरानी हिस्ट्री को मॉडल के पेलोड में जोड़ना
|
| 118 |
for msg in history:
|
| 119 |
role = msg.get("role", "user")
|
| 120 |
content = msg.get("content", "")
|
| 121 |
if content:
|
| 122 |
messages.append({"role": role, "content": content})
|
| 123 |
|
| 124 |
-
# 3. मल्टीमोडल इनपुट (करेंट मैसेज)
|
| 125 |
content_payload = []
|
| 126 |
if user_message.strip():
|
| 127 |
content_payload.append({"type": "text", "text": user_message})
|
|
@@ -138,7 +107,6 @@ def chat():
|
|
| 138 |
if not content_payload:
|
| 139 |
content_payload.append({"type": "text", "text": "Hello"})
|
| 140 |
|
| 141 |
-
# नया मैसेज सबसे आखिरी में जोड़ना
|
| 142 |
messages.append({"role": "user", "content": content_payload})
|
| 143 |
|
| 144 |
headers = {
|
|
@@ -156,7 +124,6 @@ def chat():
|
|
| 156 |
}
|
| 157 |
|
| 158 |
try:
|
| 159 |
-
# सुरक्षित स्ट्रीमिंग रिक्वेस्ट
|
| 160 |
response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
|
| 161 |
|
| 162 |
def generate():
|
|
@@ -171,4 +138,4 @@ def chat():
|
|
| 171 |
return Response("Internal Error: Unable to process request securely.", status=500)
|
| 172 |
|
| 173 |
if __name__ == '__main__':
|
| 174 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
|
|
|
|
|
|
| 3 |
from flask import Flask, request, Response, stream_with_context, render_template_string
|
| 4 |
+
from duckduckgo_search import DDGS # नया, पावरफुल और एंटी-ब्लॉक स्क्रैपर
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
| 7 |
|
| 8 |
+
# 🔐 100% सुरक्षित: सीक्रेट्स से डेटा लोड
|
| 9 |
API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
|
| 10 |
BASE_URL = os.environ.get("BASE_URL")
|
| 11 |
MODEL_ID = os.environ.get("MODEL_ID")
|
| 12 |
|
|
|
|
| 13 |
INVOKE_URL = ""
|
| 14 |
if BASE_URL:
|
| 15 |
if not BASE_URL.endswith("/chat/completions"):
|
|
|
|
| 17 |
else:
|
| 18 |
INVOKE_URL = BASE_URL
|
| 19 |
|
| 20 |
+
# 🌐 --- ADVANCED WEB SEARCH ENGINE (Anti-Block) --- 🌐
|
| 21 |
+
def web_search_scraper(query, num_results=4):
|
|
|
|
| 22 |
"""
|
| 23 |
+
बिना किसी API Key के लाइव वेब सर्च करने के लिए DDGS का इस्तेमाल।
|
| 24 |
+
यह Hugging Face Spaces पर कभी ब्लॉक नहीं होता।
|
| 25 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
try:
|
|
|
|
|
|
|
| 27 |
results = []
|
| 28 |
+
with DDGS() as ddgs:
|
| 29 |
+
# max_results को सेट करके टॉप रिज़ल्ट्स निकालना
|
| 30 |
+
for r in ddgs.text(query, max_results=num_results):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
results.append({
|
| 32 |
+
"title": r.get("title", ""),
|
| 33 |
+
"link": r.get("href", ""),
|
| 34 |
+
"snippet": r.get("body", "")
|
| 35 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
return results
|
| 37 |
except Exception as e:
|
| 38 |
return [{"error": str(e)}]
|
| 39 |
+
# ----------------------------------------------------
|
|
|
|
| 40 |
|
| 41 |
@app.route('/')
|
| 42 |
def home():
|
|
|
|
| 49 |
|
| 50 |
@app.route('/api/chat', methods=['POST'])
|
| 51 |
def chat():
|
|
|
|
| 52 |
if not API_KEY or not INVOKE_URL or not MODEL_ID:
|
| 53 |
return Response("Server Error: Configuration secrets are missing.", status=500)
|
| 54 |
|
|
|
|
| 61 |
temperature = data.get("temperature", 0.6)
|
| 62 |
|
| 63 |
# 🚀 --- INTERCEPT & SEARCH LOGIC --- 🚀
|
|
|
|
| 64 |
if user_message.strip().lower().startswith("/search "):
|
| 65 |
search_query = user_message[8:].strip()
|
|
|
|
| 66 |
|
| 67 |
+
# वेब से ताज़ा डेटा स्क्रैप करना
|
| 68 |
+
scraped_data = web_search_scraper(search_query)
|
| 69 |
+
|
| 70 |
+
search_context = f"Real-time Web Search Results for '{search_query}':\n\n"
|
| 71 |
for idx, res in enumerate(scraped_data):
|
| 72 |
if "error" in res:
|
| 73 |
search_context += f"Search Error: {res['error']}\n"
|
| 74 |
else:
|
| 75 |
search_context += f"{idx+1}. Title: {res['title']}\nSnippet: {res['snippet']}\nLink: {res['link']}\n\n"
|
| 76 |
|
| 77 |
+
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 the provided links as sources if applicable. Respond in the user's language.]"
|
| 78 |
|
| 79 |
+
# AI के लिए बैकग्राउंड प्रॉम्प्ट तैयार
|
| 80 |
user_message = f"User Query: {search_query}\n\n[SYSTEM BACKGROUND CONTEXT]\n{search_context}"
|
| 81 |
# ---------------------------------------
|
| 82 |
|
| 83 |
messages = []
|
| 84 |
|
|
|
|
| 85 |
if system_prompt.strip():
|
| 86 |
messages.append({"role": "system", "content": system_prompt})
|
| 87 |
|
|
|
|
| 88 |
for msg in history:
|
| 89 |
role = msg.get("role", "user")
|
| 90 |
content = msg.get("content", "")
|
| 91 |
if content:
|
| 92 |
messages.append({"role": role, "content": content})
|
| 93 |
|
|
|
|
| 94 |
content_payload = []
|
| 95 |
if user_message.strip():
|
| 96 |
content_payload.append({"type": "text", "text": user_message})
|
|
|
|
| 107 |
if not content_payload:
|
| 108 |
content_payload.append({"type": "text", "text": "Hello"})
|
| 109 |
|
|
|
|
| 110 |
messages.append({"role": "user", "content": content_payload})
|
| 111 |
|
| 112 |
headers = {
|
|
|
|
| 124 |
}
|
| 125 |
|
| 126 |
try:
|
|
|
|
| 127 |
response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
|
| 128 |
|
| 129 |
def generate():
|
|
|
|
| 138 |
return Response("Internal Error: Unable to process request securely.", status=500)
|
| 139 |
|
| 140 |
if __name__ == '__main__':
|
| 141 |
+
app.run(host='0.0.0.0', port=7860)
|