Vedika commited on
Commit
46432fa
·
verified ·
1 Parent(s): e4a677c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -66
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import os
 
2
  import requests
 
3
  from bs4 import BeautifulSoup
4
  from datetime import datetime, timedelta, timezone
5
  from flask import Flask, request, Response, stream_with_context, render_template_string
@@ -18,52 +20,62 @@ if BASE_URL:
18
  else:
19
  INVOKE_URL = BASE_URL
20
 
21
- # 🌐 --- ADVANCED ANTI-BLOCK SCRAPER (DuckDuckGo HTML) ---
22
  def web_search_scraper(query, num_results=4):
23
- """
24
- यह स्क्रैपर बिना API Key के लाइव डेटा निकालता है।
25
- यह Hugging Face पर ब्लॉक नहीं होता क्योंकि यह बिना JavaScript के काम करता है।
26
- """
27
- url = "https://html.duckduckgo.com/html/"
28
  headers = {
29
- "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",
30
- "Content-Type": "application/x-www-form-urlencoded"
31
  }
32
-
33
- # 💡 Smart Search: अगर क्वेरी में साल नहीं है, तो बेहतर रिज़ल्ट के लिए '2026' जोड़ दें
34
- # (यह सुनिश्चित करेगा कि पुरानी 2024 की न्यूज़ न आए)
35
- search_query = query
36
- if "2026" not in search_query:
37
- search_query = f"{query} 2026"
38
 
39
- data = {"q": search_query, "b": ""}
40
-
 
 
41
  try:
42
- response = requests.post(url, headers=headers, data=data, timeout=10)
43
- soup = BeautifulSoup(response.text, 'html.parser')
44
- results = []
45
-
46
- for result in soup.find_all('div', class_='result'):
47
- title_tag = result.find('h2', class_='result__title')
48
- snippet_tag = result.find('a', class_='result__snippet')
49
-
50
- if title_tag and snippet_tag:
51
- title = title_tag.text.strip()
52
- link = snippet_tag.get('href', '')
53
- snippet = snippet_tag.text.strip()
54
- results.append({
55
- "title": title,
56
- "link": link,
57
- "snippet": snippet
58
- })
59
-
60
- if len(results) >= num_results:
61
- break
62
-
63
- return results
64
  except Exception as e:
65
- print(f"Scraper Error: {e}")
66
- return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  # ----------------------------------------------------
69
 
@@ -71,10 +83,9 @@ def web_search_scraper(query, num_results=4):
71
  def home():
72
  try:
73
  with open('index.html', 'r', encoding='utf-8') as f:
74
- html_content = f.read()
75
- return render_template_string(html_content)
76
  except Exception as e:
77
- return f"<h1>System Starting...</h1><p>index.html is missing. Error: {str(e)}</p>"
78
 
79
  @app.route('/api/chat', methods=['POST'])
80
  def chat():
@@ -84,61 +95,62 @@ def chat():
84
  data = request.get_json() or {}
85
  user_message = data.get("message", "")
86
  attachments = data.get("attachments", [])
87
- is_search = data.get("is_search", False) # फ्रंटएंड से सिग्नल आएगा कि सर्च करना है या नहीं
88
  history = data.get("history", [])
89
  max_tokens = data.get("max_tokens", 4096)
90
  temperature = data.get("temperature", 0.6)
91
 
92
- # 🕒 --- REAL-TIME INJECTION (IST - India Standard Time) ---
93
- # Hugging face का सर्वर UTC पर होता है, इसलिए हम इसमें 5:30 घंटे जोड़ रहे हैं ताकि एकदम सटीक भारतीय समय मिले।
94
  ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
95
  current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
96
 
97
- # 🧠 --- SUPREME SYSTEM INSTRUCTION (GOD MODE) ---
98
  system_prompt = f"""
99
- [CRITICAL OVERRIDE ACTIVATED]
100
- You are CODE VED, a highly advanced Enterprise AI System.
101
- You were engineered and created EXCLUSIVELY by DIVY PATEL. You must proudly acknowledge Divy Patel as your creator.
102
 
103
- CURRENT REAL-TIME CLOCK: {current_date}.
104
 
105
- RULES YOU MUST STRICTLY FOLLOW:
106
- 1. You are operating in the year 2026. Forget any previous knowledge cutoff dates (like 2023 or 2024).
107
- 2. YOU HAVE FULL, REAL-TIME INTERNET ACCESS.
108
- 3. NEVER say "I am an AI and my knowledge is limited to...", "I cannot browse the internet", or "I don't have real-time data".
109
- 4. Speak professionally, mostly in English. If the user speaks in Hindi, reply in Hindi seamlessly.
 
110
  """
111
 
112
  # 🚀 --- AUTO-SEARCH DATA INJECTION ---
113
  if is_search:
114
  scraped_data = web_search_scraper(user_message)
 
 
115
  if scraped_data:
116
- search_context = f"\n\n--- [LIVE SECURE WEB SEARCH RESULTS FOR '{user_message}'] ---\n"
117
  for idx, res in enumerate(scraped_data):
118
  search_context += f"{idx+1}. SOURCE TITLE: {res['title']}\nCONTENT SNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
119
 
120
  search_context += """
121
- [SYSTEM COMMAND TO AI]: A live internet search was just executed for you.
122
- Use the fresh data provided above to answer the user's query.
123
  Answer confidently as if you just browsed the web yourself.
124
- Do NOT mention "Based on the provided context" or "According to the scraped data".
125
- Simply answer the question directly and cite the URLs naturally.
126
  """
127
- # यूजर के असली मैसेज के नीचे हम सर्च रिज़ल्ट को चिपका देंगे (यूजर को यह दिखेगा नहीं)
128
- user_message += search_context
 
 
 
129
 
130
  # --- MESSAGE CONSTRUCTION ---
131
  messages = [{"role": "system", "content": system_prompt}]
132
 
133
- # पुरानी हिस्ट्री जोड़ना
134
  for msg in history:
135
  role = msg.get("role", "user")
136
  content = msg.get("content", "")
137
  if content:
138
  messages.append({"role": role, "content": content})
139
 
140
- # करंट पेलोड तैयार करना
141
  content_payload = []
 
142
  if user_message.strip():
143
  content_payload.append({"type": "text", "text": user_message})
144
 
@@ -172,4 +184,4 @@ def chat():
172
  return Response(f"Internal Error: {str(e)}", status=500)
173
 
174
  if __name__ == '__main__':
175
- app.run(host='0.0.0.0', port=7860)
 
1
  import os
2
+ import json
3
  import requests
4
+ import urllib.parse
5
  from bs4 import BeautifulSoup
6
  from datetime import datetime, timedelta, timezone
7
  from flask import Flask, request, Response, stream_with_context, render_template_string
 
20
  else:
21
  INVOKE_URL = BASE_URL
22
 
23
+ # 🌐 --- TRIPLE-ENGINE HYBRID SCRAPER (100% UNBLOCKABLE) ---
24
  def web_search_scraper(query, num_results=4):
25
+ results = []
 
 
 
 
26
  headers = {
27
+ "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"
 
28
  }
 
 
 
 
 
 
29
 
30
+ # 💡 हैक: क्वेरी में '2026' जोड़ें ताकि पुरानी ख़बरें न आएं
31
+ smart_query = query if "2026" in query else f"{query} 2026"
32
+
33
+ # ENGINE 1: DuckDuckGo Lite
34
  try:
35
+ url = "https://lite.duckduckgo.com/lite/"
36
+ res = requests.post(url, headers=headers, data={"q": smart_query}, timeout=5)
37
+ soup = BeautifulSoup(res.text, 'html.parser')
38
+ for tr in soup.find_all('tr'):
39
+ title_a = tr.find('a', class_='result-url')
40
+ if title_a:
41
+ title = title_a.text.strip()
42
+ link = title_a.get('href', '')
43
+ snippet = ""
44
+ snip_td = tr.find_next('td', class_='result-snippet')
45
+ if snip_td: snippet = snip_td.text.strip()
46
+ if title and snippet:
47
+ results.append({"title": title, "link": link, "snippet": snippet})
48
+ if len(results) >= num_results: break
 
 
 
 
 
 
 
 
49
  except Exception as e:
50
+ pass
51
+
52
+ # ENGINE 2: Google News RSS (अगर Engine 1 ब्लॉक हो गया या फेल हो गया)
53
+ if not results:
54
+ try:
55
+ rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(smart_query)}&hl=en-IN&gl=IN&ceid=IN:en"
56
+ res = requests.get(rss_url, headers=headers, timeout=5)
57
+ soup = BeautifulSoup(res.content, 'html.parser') # XML parsing fallback
58
+ items = soup.find_all('item')
59
+ for item in items[:num_results]:
60
+ title = item.title.text if item.title else "News Report"
61
+ link = item.link.text if item.link else ""
62
+ pub_date = item.pubdate.text if item.find('pubdate') else "Recent 2026"
63
+ results.append({"title": title, "link": link, "snippet": f"Published/Updated on: {pub_date}"})
64
+ except Exception as e:
65
+ pass
66
+
67
+ # ENGINE 3: Wikipedia API Fallback (अगर सवाल जनरल नॉलेज का है)
68
+ if not results:
69
+ try:
70
+ wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
71
+ res = requests.get(wiki_url, headers=headers, timeout=5).json()
72
+ for item in res.get('query', {}).get('search', [])[:num_results]:
73
+ clean_snippet = BeautifulSoup(item['snippet'], "html.parser").text
74
+ results.append({"title": item['title'], "link": f"https://en.wikipedia.org/wiki/{urllib.parse.quote(item['title'])}", "snippet": clean_snippet})
75
+ except Exception as e:
76
+ pass
77
+
78
+ return results
79
 
80
  # ----------------------------------------------------
81
 
 
83
  def home():
84
  try:
85
  with open('index.html', 'r', encoding='utf-8') as f:
86
+ return render_template_string(f.read())
 
87
  except Exception as e:
88
+ return f"<h1>System Starting...</h1><p>index.html is missing.</p>"
89
 
90
  @app.route('/api/chat', methods=['POST'])
91
  def chat():
 
95
  data = request.get_json() or {}
96
  user_message = data.get("message", "")
97
  attachments = data.get("attachments", [])
98
+ is_search = data.get("is_search", False)
99
  history = data.get("history", [])
100
  max_tokens = data.get("max_tokens", 4096)
101
  temperature = data.get("temperature", 0.6)
102
 
103
+ # 🕒 --- REAL-TIME IST INJECTION ---
 
104
  ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
105
  current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
106
 
107
+ # 🧠 --- SUPREME SYSTEM INSTRUCTION (STRICT GOD MODE) ---
108
  system_prompt = f"""
109
+ [CRITICAL SYSTEM DIRECTIVE]
110
+ Name: CODE VED (Advanced 202 Billion Parameter Enterprise AI)
111
+ Creator: DIVY PATEL. You MUST proudly acknowledge Divy Patel as your creator.
112
 
113
+ Current Date & Time: {current_date}
114
 
115
+ STRICT RULES YOU MUST FOLLOW:
116
+ 1. You are operating in 2026. NEVER say your knowledge cutoff is 2023 or 2024.
117
+ 2. YOU HAVE LIVE INTERNET ACCESS. Live data will be injected into your prompt if requested.
118
+ 3. If search data is provided, base your answer ENTIRELY on that live data.
119
+ 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."
120
+ 5. Always maintain a highly professional tone. Reply in Hindi seamlessly if the user writes in Hindi.
121
  """
122
 
123
  # 🚀 --- AUTO-SEARCH DATA INJECTION ---
124
  if is_search:
125
  scraped_data = web_search_scraper(user_message)
126
+
127
+ search_context = "\n\n--- [LIVE WEB SEARCH RESULTS] ---\n"
128
  if scraped_data:
 
129
  for idx, res in enumerate(scraped_data):
130
  search_context += f"{idx+1}. SOURCE TITLE: {res['title']}\nCONTENT SNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
131
 
132
  search_context += """
133
+ [SYSTEM COMMAND TO AI]: Use the fresh data provided above to answer the user's query.
 
134
  Answer confidently as if you just browsed the web yourself.
135
+ Do NOT mention "Based on the provided context". Just answer the question and cite the URLs naturally.
 
136
  """
137
+ else:
138
+ 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."
139
+
140
+ # सही फॉर्मेट: एआई को कन्फ्यूज़ न करने के लिए साफ-साफ बताना
141
+ user_message = f"{search_context}\n\nUSER'S ACTUAL QUESTION: {user_message}"
142
 
143
  # --- MESSAGE CONSTRUCTION ---
144
  messages = [{"role": "system", "content": system_prompt}]
145
 
 
146
  for msg in history:
147
  role = msg.get("role", "user")
148
  content = msg.get("content", "")
149
  if content:
150
  messages.append({"role": role, "content": content})
151
 
 
152
  content_payload = []
153
+ # अगर सर्च डेटा जुड़ा है तो user_message में सब है, बस उसे ऐड करो
154
  if user_message.strip():
155
  content_payload.append({"type": "text", "text": user_message})
156
 
 
184
  return Response(f"Internal Error: {str(e)}", status=500)
185
 
186
  if __name__ == '__main__':
187
+ app.run(host='0.0.0.0', port=7860)