Vedika commited on
Commit
bd1d223
Β·
verified Β·
1 Parent(s): 40a703c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -45
app.py CHANGED
@@ -8,40 +8,64 @@ from flask import Flask, request, Response, stream_with_context, render_template
8
  app = Flask(__name__)
9
 
10
  # πŸ” --- SECURE ENVIRONMENT VARIABLES ---
11
- # ΰ€―ΰ€Ή ΰ€†ΰ€ͺΰ€•ΰ₯‡ Hugging Face Secrets ΰ€Έΰ₯‡ ΰ€…ΰ€ͺΰ€¨ΰ₯‡ ΰ€†ΰ€ͺ ΰ€²ΰ₯‹ΰ€‘ ΰ€Ήΰ₯‹ ΰ€œΰ€Ύΰ€ΰ€—ΰ€Ύ
12
- API_KEY = os.environ.get("NVIDIA_API_KEY") or os.environ.get("YOUR_VEDIKA_API_KEY")
13
- MODEL_ID = os.environ.get("MODEL_ID")
14
 
15
- # NVIDIA ΰ€•ΰ€Ύ ΰ€‘ΰ€Ύΰ€―ΰ€°ΰ₯‡ΰ€•ΰ₯ΰ€Ÿ URL (BASE_URL ΰ€•ΰ€Ύ ΰ€²ΰ₯‰ΰ€œΰ€Ώΰ€• ΰ€ͺΰ₯‚ΰ€°ΰ₯€ ΰ€€ΰ€°ΰ€Ή ΰ€Ήΰ€Ÿΰ€Ύ ΰ€¦ΰ€Ώΰ€―ΰ€Ύ ΰ€—ΰ€―ΰ€Ύ ΰ€Ήΰ₯ˆ)
16
  INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
17
 
18
- # 🌐 --- BULLETPROOF SCRAPER (News + Wiki) ---
19
  def web_search_scraper(query, num_results=4):
 
 
 
20
  results = []
21
- headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
 
 
 
22
 
23
- # 1. Google News RSS (Never blocks, gives real latest news)
24
  try:
25
- rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
26
- res = requests.get(rss_url, headers=headers, timeout=5)
27
- soup = BeautifulSoup(res.content, 'xml') # Use XML parser
28
- items = soup.find_all('item')
29
 
30
- for item in items[:num_results]:
31
- title = item.title.text if item.title else ""
32
- link = item.link.text if item.link else ""
33
- pub_date = item.pubDate.text if item.pubDate else ""
34
- if title:
35
- results.append({
36
- "title": title,
37
- "link": link,
38
- "snippet": f"Published: {pub_date}"
39
- })
 
 
 
40
  except Exception as e:
41
- pass
42
 
43
- # 2. Wikipedia API Fallback (Never blocks)
44
- if len(results) < 2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  try:
46
  wiki_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(query)}&utf8=&format=json"
47
  res = requests.get(wiki_url, headers=headers, timeout=5).json()
@@ -78,41 +102,37 @@ def chat():
78
  is_search = data.get("is_search", False)
79
  history = data.get("history", [])
80
  max_tokens = data.get("max_tokens", 4096)
81
- temperature = data.get("temperature", 1.00) # Updated to NVIDIA default if not passed
82
 
83
  # πŸ•’ --- REAL-TIME IST INJECTION ---
84
  ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
85
  current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
86
 
87
- # 🧠 --- STRICT SYSTEM PROMPT (ANTI-HALLUCINATION) ---
88
  system_prompt = f"""
89
  You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
90
- Current Date: {current_date}.
91
 
92
  STRICT DIRECTIVES:
93
  1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
94
- 2. If you are provided with live search data, base your answer PURELY on that data.
95
- 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."
96
  """
97
 
98
- # πŸš€ --- AUTO-SEARCH LOGIC WITH FAILSAFE ---
99
  if is_search:
100
  scraped_data = web_search_scraper(user_message)
101
 
 
102
  if scraped_data:
103
- search_context = "\n\n--- [LIVE VERIFIED WEB DATA] ---\n"
104
  for idx, res in enumerate(scraped_data):
105
  search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
106
 
107
- search_context += "[SYSTEM: Use the above verified data to answer. Cite sources.]"
108
  else:
109
- search_context = """
110
- \n\n[CRITICAL SYSTEM ALERT: LIVE SEARCH FAILED OR BLOCKED.
111
- YOU HAVE NO NEW DATA FOR THIS QUERY.
112
- MANDATORY RULE: DO NOT INVENT ANY NEWS OR DATES. TELL THE USER HONESTLY THAT YOU COULD NOT FETCH THE LATEST LIVE DATA.]
113
- """
114
 
115
- user_message = f"{search_context}\n\nUSER QUERY: {user_message}"
116
 
117
  messages = [{"role": "system", "content": system_prompt}]
118
 
@@ -130,7 +150,6 @@ def chat():
130
  att_type = att.get("type")
131
  b64_data = att.get("data")
132
  if att_type == "image":
133
- # Image formatting compatible with standard APIs
134
  content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
135
  elif att_type in ["audio", "file"]:
136
  content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
@@ -144,16 +163,16 @@ def chat():
144
  "Authorization": f"Bearer {API_KEY}",
145
  "Accept": "text/event-stream"
146
  }
147
-
148
- # 🌟 --- NEW NVIDIA FORMAT PAYLOAD INTEGRATED HERE --- 🌟
149
  payload = {
150
- "model": MODEL_ID, # Dynamically fetching from your secrets
151
  "messages": messages,
152
  "max_tokens": int(max_tokens),
153
  "temperature": float(temperature),
154
- "top_p": 0.95, # As per your format
155
- "stream": True, # Stream is kept True for fast UI response
156
- "chat_template_kwargs": {"enable_thinking": True} # πŸ‘ˆ New NVIDIA feature added
157
  }
158
 
159
  try:
 
8
  app = Flask(__name__)
9
 
10
  # πŸ” --- SECURE ENVIRONMENT VARIABLES ---
11
+ API_KEY = os.environ.get("YOUR_VEDIKA_API_KEY")
12
+ MODEL_ID = os.environ.get("MODEL_ID") # Default fallback
 
13
 
14
+ # NVIDIA's official invoke URL
15
  INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
16
 
17
+ # 🌐 --- SUPER-HYBRID UNBLOCKABLE SCRAPER --- 🌐
18
  def web_search_scraper(query, num_results=4):
19
+ """
20
+ Yahoo Search + Google News + Wikipedia (Never blocks on Hugging Face)
21
+ """
22
  results = []
23
+ headers = {
24
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
25
+ "Accept-Language": "en-US,en;q=0.9"
26
+ }
27
 
28
+ # 1. YAHOO SEARCH (Highly reliable for Datacenter IPs like Hugging Face)
29
  try:
30
+ url = f"https://search.yahoo.com/search?p={urllib.parse.quote(query)}"
31
+ res = requests.get(url, headers=headers, timeout=8)
32
+ soup = BeautifulSoup(res.text, 'html.parser')
 
33
 
34
+ for div in soup.find_all('div', class_='algo'):
35
+ title_tag = div.find('h3', class_='title')
36
+ desc_tag = div.find('div', class_='compText')
37
+
38
+ if title_tag and desc_tag:
39
+ title = title_tag.text.strip()
40
+ link = title_tag.find('a').get('href', '') if title_tag.find('a') else ""
41
+ snippet = desc_tag.text.strip()
42
+
43
+ results.append({"title": title, "link": link, "snippet": snippet})
44
+
45
+ if len(results) >= num_results:
46
+ break
47
  except Exception as e:
48
+ print(f"Yahoo Scraper Error: {e}")
49
 
50
+ # 2. GOOGLE NEWS RSS FALLBACK (If Yahoo fails or for latest news)
51
+ if not results:
52
+ try:
53
+ rss_url = f"https://news.google.com/rss/search?q={urllib.parse.quote(query)}&hl=en-IN&gl=IN&ceid=IN:en"
54
+ res = requests.get(rss_url, headers=headers, timeout=5)
55
+ soup = BeautifulSoup(res.content, 'xml')
56
+ items = soup.find_all('item')
57
+
58
+ for item in items[:num_results]:
59
+ title = item.title.text if item.title else ""
60
+ link = item.link.text if item.link else ""
61
+ pub_date = item.pubDate.text if item.pubDate else ""
62
+ if title:
63
+ results.append({"title": title, "link": link, "snippet": f"News Published on: {pub_date}"})
64
+ except Exception as e:
65
+ print(f"News Scraper Error: {e}")
66
+
67
+ # 3. WIKIPEDIA 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()
 
102
  is_search = data.get("is_search", False)
103
  history = data.get("history", [])
104
  max_tokens = data.get("max_tokens", 4096)
105
+ temperature = data.get("temperature", 1.0) # NVIDIA Recommended
106
 
107
  # πŸ•’ --- REAL-TIME IST INJECTION ---
108
  ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)
109
  current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")
110
 
111
+ # 🧠 --- GOD MODE SYSTEM PROMPT ---
112
  system_prompt = f"""
113
  You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.
114
+ Current Live Date and Time: {current_date}.
115
 
116
  STRICT DIRECTIVES:
117
  1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.
118
+ 2. If you receive "LIVE WEB SEARCH RESULTS", you MUST base your answer ENTIRELY on that data.
119
+ 3. Do NOT say "Based on the provided search results". Just answer naturally and confidently, citing the sources/links if needed.
120
  """
121
 
122
+ # πŸš€ --- AUTO-SEARCH INJECTION ---
123
  if is_search:
124
  scraped_data = web_search_scraper(user_message)
125
 
126
+ search_context = "\n\n--- [LIVE VERIFIED WEB DATA] ---\n"
127
  if scraped_data:
 
128
  for idx, res in enumerate(scraped_data):
129
  search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"
130
 
131
+ search_context += "[SYSTEM COMMAND: Use the above live data to answer the user accurately.]"
132
  else:
133
+ search_context += "[SYSTEM ALERT: Live search blocked. Rely on your existing knowledge, but DO NOT hallucinate recent news.]"
 
 
 
 
134
 
135
+ user_message = f"USER QUERY: {user_message}\n\n{search_context}"
136
 
137
  messages = [{"role": "system", "content": system_prompt}]
138
 
 
150
  att_type = att.get("type")
151
  b64_data = att.get("data")
152
  if att_type == "image":
 
153
  content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})
154
  elif att_type in ["audio", "file"]:
155
  content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})
 
163
  "Authorization": f"Bearer {API_KEY}",
164
  "Accept": "text/event-stream"
165
  }
166
+
167
+ # 🌟 --- NVIDIA FORMAT INTEGRATED ---
168
  payload = {
169
+ "model": MODEL_ID,
170
  "messages": messages,
171
  "max_tokens": int(max_tokens),
172
  "temperature": float(temperature),
173
+ "top_p": 0.95,
174
+ "stream": True,
175
+ "chat_template_kwargs": {"enable_thinking": True} # Thinking logic enabled
176
  }
177
 
178
  try: