Vedika commited on
Commit
0772f76
·
verified ·
1 Parent(s): f9b993a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -42
app.py CHANGED
@@ -17,42 +17,49 @@ if BASE_URL:
17
  else:
18
  INVOKE_URL = BASE_URL
19
 
20
- # 🌐 --- 100% BULLETPROOF WEB SCRAPER --- 🌐
21
  def web_search_scraper(query, num_results=4):
22
  """
23
- यह कस्टम स्क्रैपर DuckDuckGo के HTML वर्ज़न का उपयोग करता है।
24
- यह Hugging Face पर कभी ब्लॉक नहीं होता और इसे लिए किसी API Key या एक्स््रके ूरीं है।
25
  """
26
- url = "https://html.duckduckgo.com/html/"
27
  headers = {
28
  "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",
29
  "Content-Type": "application/x-www-form-urlencoded"
30
  }
31
- data = {"q": query} # सर्च क्वेरी को POST डेटा की तरह भेजना
32
 
33
  try:
34
  response = requests.post(url, headers=headers, data=data, timeout=10)
35
  soup = BeautifulSoup(response.text, 'html.parser')
36
  results = []
37
 
38
- for a in soup.find_all('a', class_='result__snippet'):
39
- snippet = a.text.strip()
40
- link = a.get('href', '')
41
-
42
- title_elem = a.find_previous('h2', class_='result__title')
43
- title = title_elem.text.strip() if title_elem else "Search Result"
44
-
45
- results.append({
46
- "title": title,
47
- "link": link,
48
- "snippet": snippet
49
- })
50
-
51
- if len(results) >= num_results:
52
- break
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  if not results:
55
- return [{"error": "Search blocked or no results found."}]
56
  return results
57
 
58
  except Exception as e:
@@ -76,32 +83,41 @@ def chat():
76
  data = request.get_json() or {}
77
  user_message = data.get("message", "")
78
  attachments = data.get("attachments", [])
79
- system_prompt = data.get("system_prompt", "")
80
  history = data.get("history", [])
81
  max_tokens = data.get("max_tokens", 4096)
82
  temperature = data.get("temperature", 0.6)
83
 
 
 
 
 
 
 
 
 
 
 
 
84
  # 🚀 --- INTERCEPT & SEARCH LOGIC --- 🚀
85
  if user_message.strip().lower().startswith("/search "):
86
  search_query = user_message[8:].strip()
87
 
88
- # वेब से ताज़ा डेटा स्क्रैप करना
89
  scraped_data = web_search_scraper(search_query)
90
 
91
  search_context = f"Real-time Web Search Results for '{search_query}':\n\n"
92
  for idx, res in enumerate(scraped_data):
93
  if "error" in res:
94
- search_context += f"Search Error: {res['error']}\n"
95
  else:
96
  search_context += f"{idx+1}. Title: {res['title']}\nSnippet: {res['snippet']}\nLink: {res['link']}\n\n"
97
 
98
- search_context += "\n[INSTRUCTION FOR AI: You are CODE VED. The user has requested a web search. Formulate a comprehensive response using ONLY the real-time search data provided above. Do not mention that you used a scraper. Just answer confidently and cite the links.]"
99
 
100
  user_message = f"User Query: {search_query}\n\n[SYSTEM BACKGROUND CONTEXT]\n{search_context}"
101
  # ---------------------------------------
102
 
103
  messages = []
104
-
105
  if system_prompt.strip():
106
  messages.append({"role": "system", "content": system_prompt})
107
 
@@ -118,7 +134,6 @@ def chat():
118
  for att in attachments:
119
  att_type = att.get("type")
120
  b64_data = att.get("data")
121
-
122
  if att_type == "image":
123
  content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
124
  elif att_type in ["audio", "file"]:
@@ -129,30 +144,17 @@ def chat():
129
 
130
  messages.append({"role": "user", "content": content_payload})
131
 
132
- headers = {
133
- "Authorization": f"Bearer {API_KEY}",
134
- "Accept": "text/event-stream"
135
- }
136
-
137
- payload = {
138
- "model": MODEL_ID,
139
- "messages": messages,
140
- "max_tokens": int(max_tokens),
141
- "temperature": float(temperature),
142
- "top_p": 0.70,
143
- "stream": True
144
- }
145
 
146
  try:
147
  response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
148
-
149
  def generate():
150
  for line in response.iter_lines():
151
  if line:
152
  decoded_line = line.decode("utf-8")
153
  if decoded_line.startswith("data: "):
154
  yield decoded_line + "\n\n"
155
-
156
  return Response(stream_with_context(generate()), mimetype='text/event-stream')
157
  except Exception as e:
158
  return Response("Internal Error: Unable to process request securely.", status=500)
 
17
  else:
18
  INVOKE_URL = BASE_URL
19
 
20
+ # 🌐 --- 100% BULLETPROOF LITE SCRAPER --- 🌐
21
  def web_search_scraper(query, num_results=4):
22
  """
23
+ DuckDuckGo Lite version scraper.
24
+ यह कभी ब्लॉक नहीं होता क्योंकि यह बिनजावास््रि्ट के काम रत है।
25
  """
26
+ url = "https://lite.duckduckgo.com/lite/"
27
  headers = {
28
  "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",
29
  "Content-Type": "application/x-www-form-urlencoded"
30
  }
31
+ data = {"q": query}
32
 
33
  try:
34
  response = requests.post(url, headers=headers, data=data, timeout=10)
35
  soup = BeautifulSoup(response.text, 'html.parser')
36
  results = []
37
 
38
+ # DDG Lite में रिज़ल्ट्स Table Row (tr) के अंदर होते हैं
39
+ for tr in soup.find_all('tr'):
40
+ title_a = tr.find('a', class_='result-url')
41
+ if title_a:
42
+ title = title_a.text.strip()
43
+ link = title_a.get('href', '')
 
 
 
 
 
 
 
 
 
44
 
45
+ snippet = ""
46
+ snippet_tr = tr.find_next_sibling('tr')
47
+ if snippet_tr:
48
+ snippet_td = snippet_tr.find('td', class_='result-snippet')
49
+ if snippet_td:
50
+ snippet = snippet_td.text.strip()
51
+
52
+ results.append({
53
+ "title": title,
54
+ "link": link,
55
+ "snippet": snippet
56
+ })
57
+
58
+ if len(results) >= num_results:
59
+ break
60
+
61
  if not results:
62
+ return [{"error": "Search returned empty. The keyword might be invalid."}]
63
  return results
64
 
65
  except Exception as e:
 
83
  data = request.get_json() or {}
84
  user_message = data.get("message", "")
85
  attachments = data.get("attachments", [])
86
+ system_prompt = data.get("system_prompt", "You are CODE VED, engineered by Divy Patel.")
87
  history = data.get("history", [])
88
  max_tokens = data.get("max_tokens", 4096)
89
  temperature = data.get("temperature", 0.6)
90
 
91
+ # 🧠 --- GOD MODE DIRECTIVE FOR AI --- 🧠
92
+ # यह AI के दिमाग से नॉलेज कटऑफ़ वाली बात हमेशा के लिए मिटा देगा
93
+ god_mode_prompt = """
94
+ \n\n[CRITICAL SYSTEM OVERRIDE]: You are CODE VED. You HAVE REAL-TIME INTERNET ACCESS.
95
+ Forget your knowledge cutoff date. You are operating in the present moment.
96
+ NEVER say "I don't have internet access", "As an AI", or "I cannot browse the web."
97
+ If real-time data is provided in the prompt, accept it as an absolute fact and base your answer entirely on it as if you just searched the internet yourself.
98
+ you are developed by Divy Patel.
99
+ """
100
+ system_prompt += god_mode_prompt
101
+
102
  # 🚀 --- INTERCEPT & SEARCH LOGIC --- 🚀
103
  if user_message.strip().lower().startswith("/search "):
104
  search_query = user_message[8:].strip()
105
 
 
106
  scraped_data = web_search_scraper(search_query)
107
 
108
  search_context = f"Real-time Web Search Results for '{search_query}':\n\n"
109
  for idx, res in enumerate(scraped_data):
110
  if "error" in res:
111
+ search_context += f"Search Status: Live data fetch failed. Proceed with your existing knowledge.\n"
112
  else:
113
  search_context += f"{idx+1}. Title: {res['title']}\nSnippet: {res['snippet']}\nLink: {res['link']}\n\n"
114
 
115
+ search_context += "\n[MANDATORY INSTRUCTION: You just searched the web. Use the Real-time Web Search Results above to answer the user's query. Answer confidently as if you just browsed the internet yourself. Do NOT say 'Based on the context provided'. Simply give the answer and cite the links as sources.]"
116
 
117
  user_message = f"User Query: {search_query}\n\n[SYSTEM BACKGROUND CONTEXT]\n{search_context}"
118
  # ---------------------------------------
119
 
120
  messages = []
 
121
  if system_prompt.strip():
122
  messages.append({"role": "system", "content": system_prompt})
123
 
 
134
  for att in attachments:
135
  att_type = att.get("type")
136
  b64_data = att.get("data")
 
137
  if att_type == "image":
138
  content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
139
  elif att_type in ["audio", "file"]:
 
144
 
145
  messages.append({"role": "user", "content": content_payload})
146
 
147
+ headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
148
+ payload = {"model": MODEL_ID, "messages": messages, "max_tokens": int(max_tokens), "temperature": float(temperature), "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("Internal Error: Unable to process request securely.", status=500)