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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -71
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import json
3
  import requests
4
  import urllib.parse
5
  from bs4 import BeautifulSoup
@@ -20,58 +19,43 @@ if BASE_URL:
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
 
@@ -85,12 +69,12 @@ def home():
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():
92
  if not API_KEY or not INVOKE_URL or not MODEL_ID:
93
- return Response("Server Error: Configuration secrets are missing.", status=500)
94
 
95
  data = request.get_json() or {}
96
  user_message = data.get("message", "")
@@ -98,49 +82,42 @@ def chat():
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:
@@ -150,7 +127,6 @@ def chat():
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
 
@@ -167,9 +143,9 @@ def chat():
167
 
168
  messages.append({"role": "user", "content": content_payload})
169
 
170
- # --- LLM API CALL ---
171
  headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
172
- payload = {"model": MODEL_ID, "messages": messages, "max_tokens": int(max_tokens), "temperature": float(temperature), "top_p": 0.70, "stream": True}
 
173
 
174
  try:
175
  response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)
 
1
  import os
 
2
  import requests
3
  import urllib.parse
4
  from bs4 import BeautifulSoup
 
19
  else:
20
  INVOKE_URL = BASE_URL
21
 
22
+ # 🌐 --- BULLETPROOF SCRAPER (News + Wiki) ---
23
  def web_search_scraper(query, num_results=4):
24
  results = []
25
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
 
 
26
 
27
+ # 1. Google News RSS (Never blocks, gives real latest news)
 
 
 
28
  try:
29
+ rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
30
+ res = requests.get(rss_url, headers=headers, timeout=5)
31
+ soup = BeautifulSoup(res.content, 'xml') # Use XML parser
32
+ items = soup.find_all('item')
33
+
34
+ for item in items[:num_results]:
35
+ title = item.title.text if item.title else ""
36
+ link = item.link.text if item.link else ""
37
+ pub_date = item.pubDate.text if item.pubDate else ""
38
+ if title:
39
+ results.append({
40
+ "title": title,
41
+ "link": link,
42
+ "snippet": f"Published: {pub_date}"
43
+ })
44
  except Exception as e:
45
  pass
46
 
47
+ # 2. Wikipedia API Fallback (Never blocks)
48
+ if len(results) < 2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  try:
50
  wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
51
  res = requests.get(wiki_url, headers=headers, timeout=5).json()
52
  for item in res.get('query', {}).get('search', [])[:num_results]:
53
  clean_snippet = BeautifulSoup(item['snippet'], "html.parser").text
54
+ results.append({
55
+ "title": item['title'],
56
+ "link": f"https://en.wikipedia.org/wiki/{urllib.parse.quote(item['title'])}",
57
+ "snippet": clean_snippet
58
+ })
59
  except Exception as e:
60
  pass
61
 
 
69
  with open('index.html', 'r', encoding='utf-8') as f:
70
  return render_template_string(f.read())
71
  except Exception as e:
72
+ return f"<h1>System Error</h1><p>index.html missing: {str(e)}</p>"
73
 
74
  @app.route('/api/chat', methods=['POST'])
75
  def chat():
76
  if not API_KEY or not INVOKE_URL or not MODEL_ID:
77
+ return Response("Server Error: Secrets missing.", status=500)
78
 
79
  data = request.get_json() or {}
80
  user_message = data.get("message", "")
 
82
  is_search = data.get("is_search", False)
83
  history = data.get("history", [])
84
  max_tokens = data.get("max_tokens", 4096)
85
+ temperature = data.get("temperature", 0.3) # 💡 Low temp prevents hallucination
86
 
87
  # 🕒 --- REAL-TIME IST INJECTION ---
88
  ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
89
  current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
90
 
91
+ # 🧠 --- STRICT SYSTEM PROMPT (ANTI-HALLUCINATION) ---
92
  system_prompt = f"""
93
+ You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
94
+ Current Date: {current_date}.
 
 
 
95
 
96
+ STRICT DIRECTIVES:
97
+ 1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
98
+ 2. If you are provided with live search data, base your answer PURELY on that data.
99
+ 3. If you lack data to answer a question about a recent event, you MUST say: "I do not have the verified live data for this right now."
 
 
100
  """
101
 
102
+ # 🚀 --- AUTO-SEARCH LOGIC WITH FAILSAFE ---
103
  if is_search:
104
  scraped_data = web_search_scraper(user_message)
105
 
 
106
  if scraped_data:
107
+ search_context = "\n\n--- [LIVE VERIFIED WEB DATA] ---\n"
108
  for idx, res in enumerate(scraped_data):
109
+ search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
110
 
111
+ search_context += "[SYSTEM: Use the above verified data to answer. Cite sources.]"
 
 
 
 
112
  else:
113
+ search_context = """
114
+ \n\n[CRITICAL SYSTEM ALERT: LIVE SEARCH FAILED OR BLOCKED.
115
+ YOU HAVE NO NEW DATA FOR THIS QUERY.
116
+ MANDATORY RULE: DO NOT INVENT ANY NEWS OR DATES. TELL THE USER HONESTLY THAT YOU COULD NOT FETCH THE LATEST LIVE DATA.]
117
+ """
118
 
119
+ user_message = f"{search_context}\n\nUSER QUERY: {user_message}"
 
120
 
 
121
  messages = [{"role": "system", "content": system_prompt}]
122
 
123
  for msg in history:
 
127
  messages.append({"role": role, "content": content})
128
 
129
  content_payload = []
 
130
  if user_message.strip():
131
  content_payload.append({"type": "text", "text": user_message})
132
 
 
143
 
144
  messages.append({"role": "user", "content": content_payload})
145
 
 
146
  headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "text/event-stream"}
147
+ # 💡 Temperature कम कर दी है ताकि यह एक्स्ट्रा झूठ बोले
148
+ payload = {"model": MODEL_ID, "messages": messages, "max_tokens": int(max_tokens), "temperature": 0.3, "top_p": 0.70, "stream": True}
149
 
150
  try:
151
  response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)