krrishkh12 commited on
Commit
e356aa5
·
verified ·
1 Parent(s): 0edb171

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -128
app.py CHANGED
@@ -41,12 +41,15 @@ def get_current_time_in_timezone(timezone: str) -> str:
41
  return f"The current local time in {timezone} is: {local_time}"
42
  except Exception as e:
43
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
44
-
 
 
45
  @tool
46
  def get_horoscope(sign: str, date: str = None, language: str = "EN") -> str:
47
- """Fetches the horoscope for a given zodiac sign and date.
 
48
  Uses the ExaWeb API. Defaults to today if no date is provided.
49
-
50
  Args:
51
  sign: Zodiac sign (e.g., Aries, Taurus, Gemini)
52
  date: Date in any format (optional)
@@ -54,123 +57,139 @@ def get_horoscope(sign: str, date: str = None, language: str = "EN") -> str:
54
  """
55
  try:
56
  if date:
57
- date_obj = parse_date(date)
58
  else:
59
  date_obj = datetime.datetime.now()
60
-
61
  formatted_date = date_obj.strftime("%d-%m-%Y")
62
-
63
  params = {
64
  "rashi": sign.upper(),
65
  "language": language,
66
- "day": formatted_date # Always include the formatted day
67
  }
68
-
69
  url = "https://api.exaweb.in:3004/api/rashi"
 
70
  response = requests.get(url, params=params)
71
- response.raise_for_status()
 
72
  data = response.json()
73
-
74
- sign_upper = sign.upper()
75
- sign_data = data.get(sign_upper)
76
 
77
  if sign_data:
78
- return sign_data
79
-
80
- return f"No horoscope found for sign: {sign}"
81
 
 
 
 
 
82
  except Exception as e:
83
- return f"Error fetching horoscope: {str(e)}"
 
84
 
85
 
 
 
 
 
86
  @tool
87
  def get_date_panchang(date: str = None, data_language: str = "EN") -> str:
88
- """Fetches the Panchang data for a given date.
 
89
  If the user does not provide a date, use today's real date.
 
90
  Args:
91
- date: Date in any format (optional)
92
  data_language: Language of the Panchang data (e.g., 'EN' for English, 'HI' for Hindi).
93
  """
94
 
95
-
96
- if not date:
97
- now = datetime.datetime.now()
98
- else:
99
- try:
100
- now = datetime.datetime.strptime(date, "%Y-%m-%d")
101
- except ValueError:
102
- return " Invalid date format. Use YYYY-MM-DD."
103
-
104
- api_date = now.strftime("%d/%m/%y") # Format as DD/MM/YY for API
105
-
106
  try:
 
 
 
 
 
 
 
107
  url = (
108
  f"https://api.exaweb.in:3004/api/panchang/daily?"
109
  f"date={api_date}&app_language=EN&data_language={data_language}"
110
  )
111
-
112
- headers = {
113
- "api_key": "anvl_bharat_cal123",
114
- "Content-Type": "application/json"
115
- }
116
-
117
  response = requests.get(url, headers=headers)
118
  response.raise_for_status()
 
119
  data = response.json()
120
 
121
- if not data or not isinstance(data, dict):
122
- return "Empty or unexpected response."
 
123
 
124
  summary = {
125
  "date": data.get("date", "N/A"),
126
  "location": data.get("location", "N/A"),
127
- "Sunrise": data.get("Sunrise") if isinstance(data.get("Sunrise"), list) else [],
128
- "Sunset": data.get("Sunset") if isinstance(data.get("Sunset"), list) else [],
129
- "Tithi": data.get("Tithi") if isinstance(data.get("Tithi"), list) else [],
130
- "Nakshatra": data.get("Nakshatra") if isinstance(data.get("Nakshatra"), list) else [],
131
- "Yoga": data.get("Yoga") if isinstance(data.get("Yoga"), list) else [],
132
- "Karana": data.get("Karana") if isinstance(data.get("Karana"), list) else [],
133
- "Festivals": data.get("festivals") if isinstance(data.get("festivals"), list) else [],
134
  }
 
 
 
 
 
 
 
 
 
 
135
  return (
136
  f"Panchang for {summary['date']} in {summary['location']}:\n"
137
- f"🌅 Sunrise: {', '.join(summary['Sunrise'] or ['N/A'])}\n"
138
- f"🌇 Sunset: {', '.join(summary['Sunset'] or ['N/A'])}\n"
139
- f"📜 Tithi: {', '.join(summary['Tithi'] or ['N/A'])}\n"
140
- f"✨ Nakshatra: {', '.join(summary['Nakshatra'] or ['N/A'])}\n"
141
- f"🧘 Yoga: {', '.join(summary['Yoga'] or ['N/A'])}\n"
142
- f"🔺 Karana: {', '.join(summary['Karana'] or ['N/A'])}\n"
143
- f"🎉 Festivals: {', '.join(summary['Festivals'] or ['None'])}"
144
-
145
  )
146
 
 
 
 
 
 
 
 
 
147
 
148
 
149
 
150
- except Exception as e:
151
- return f" Failed to fetch Panchang for {api_date}: {str(e)}"
152
-
153
 
154
  @tool
155
- def get_holidays(year: int = None, app_language: str = "EN", data_language: str = "HI") -> str:
156
  """
157
- Fetches holidays from all categories (Hindu, Islamic, Christian) for a given year from ExaWeb API.
 
158
  Args:
159
  year: Year (e.g., 2025). Optional — defaults to current year.
160
  app_language: App language for API (default: "EN").
161
  data_language: Data language for holidays (default: "HI").
162
  """
 
163
  if not year:
164
  year = datetime.datetime.now().year
165
-
166
- params = {
167
- "app_language": app_language,
168
- "data_language": data_language,
169
- "year": year
170
- }
171
- headers = {
172
- "api_key": "anvl_bharat_cal123"
173
- }
174
 
175
  try:
176
  response = requests.get(
@@ -181,101 +200,97 @@ def get_holidays(year: int = None, app_language: str = "EN", data_language: str
181
  response.raise_for_status()
182
  data = response.json()
183
 
184
- formatted = []
 
185
 
 
 
186
  for category, groups in data.items():
187
- if category in ["year", "app_language", "data_language"]:
188
- continue # Skip non-holiday keys
189
-
190
- formatted.append(f"\n=== {category} Holidays ===")
191
-
192
- for group in groups:
193
- for holiday in group:
194
- title = holiday.get("title", "")
195
- date = holiday.get("date", "")
196
- formatted.append(f"{date}: {title}")
197
-
198
- return "\n".join(formatted) if formatted else f"No holidays found for {year}."
199
-
200
- except requests.RequestException as e:
201
- return f"Error fetching holidays: {e}"
202
 
 
 
 
 
 
 
203
 
204
  @tool
205
- def get_monthly_festivals(year: Optional[int] = None,month: Optional[str] = None,app_language: str = "EN",data_language: str = "EN") -> str:
206
  """
207
  Fetches festival data for a specific month and year from the ExaWeb API.
 
208
  Args:
209
- year: The year for which to fetch the festivals (e.g., 2025).
210
- If not provided, the current year will be used.
211
- month: The full name of the month for which to fetch the festivals (e.g., "june").
212
- If not provided, the current month will be used.
213
  app_language: The language for the application interface (default: "EN").
214
  data_language: The language for the festival names (default: "EN").
215
- Returns:
216
- A formatted string listing the festivals for the given month and year,
217
- or an error message if the data cannot be fetched.
218
  """
219
- # Set default year to the current year if not provided
 
 
 
220
  if not year:
221
  year = datetime.datetime.now().year
222
-
223
- # Set default month to the current month if not provided
224
  if not month:
225
  month = datetime.datetime.now().strftime("%B").lower()
226
  else:
227
  month = month.lower()
228
 
229
- # API endpoint and parameters
230
  api_url = "https://api.exaweb.in:3004/api/panchang/festival"
231
- params = {
232
- "year": year,
233
- "month": month,
234
- "app_language": app_language,
235
- "data_language": data_language,
236
- }
237
- headers = {
238
- "api_key": "anvl_bharat_cal123",
239
- "Content-Type": "application/json"
240
- }
241
 
242
  try:
243
- # Make the GET request to the API
244
  response = requests.get(api_url, params=params, headers=headers)
245
- # Raise an exception for bad status codes (4xx or 5xx)
246
  response.raise_for_status()
247
-
248
- # Parse the JSON response
249
  data = response.json()
250
 
251
  if not data:
252
- return f"No festival data found for {month.capitalize()} {year}."
253
-
254
- # Format the data for display
255
  formatted_lines = []
256
  for entry in data:
257
- date = entry.get("date", "Unknown date")
258
- festivals = entry.get("festivals", [])
259
-
260
- # Filter out entries where the only festival is "NA"
261
- meaningful_festivals = [f for f in festivals if f.strip().upper() != "NA"]
262
-
263
- if meaningful_festivals:
264
- # Join multiple festivals with a comma
265
- festivals_str = ", ".join(meaningful_festivals)
266
- formatted_lines.append(f"{date}: {festivals_str}")
267
 
268
  if not formatted_lines:
269
- return f"No festivals found for {month.capitalize()} {year}."
270
-
271
  return "\n".join(formatted_lines)
272
 
273
  except requests.exceptions.RequestException as e:
274
- # Handle connection errors, timeouts, etc.
275
- return f"An error occurred while fetching data from the API: {e}"
276
- except ValueError:
277
- # Handle cases where the response is not valid JSON
278
- return "Failed to decode the response from the API."
 
 
 
 
 
 
 
279
 
280
  final_answer = FinalAnswerTool()
281
 
 
41
  return f"The current local time in {timezone} is: {local_time}"
42
  except Exception as e:
43
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
44
+
45
+
46
+
47
  @tool
48
  def get_horoscope(sign: str, date: str = None, language: str = "EN") -> str:
49
+ """
50
+ Fetches the horoscope for a given zodiac sign and date.
51
  Uses the ExaWeb API. Defaults to today if no date is provided.
52
+
53
  Args:
54
  sign: Zodiac sign (e.g., Aries, Taurus, Gemini)
55
  date: Date in any format (optional)
 
57
  """
58
  try:
59
  if date:
60
+ date_obj = parser.parse(date)
61
  else:
62
  date_obj = datetime.datetime.now()
63
+
64
  formatted_date = date_obj.strftime("%d-%m-%Y")
65
+
66
  params = {
67
  "rashi": sign.upper(),
68
  "language": language,
69
+ "day": formatted_date
70
  }
 
71
  url = "https://api.exaweb.in:3004/api/rashi"
72
+
73
  response = requests.get(url, params=params)
74
+ response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
75
+
76
  data = response.json()
77
+ sign_data = data.get(sign.upper())
 
 
78
 
79
  if sign_data:
80
+ return json.dumps(sign_data) # Return the full data as a JSON string for the agent to parse
81
+
82
+ return f"INFO: No horoscope found for sign: {sign}"
83
 
84
+ except requests.exceptions.RequestException as e:
85
+ return f"ERROR: [get_horoscope]: Network error while fetching horoscope: {e}"
86
+ except json.JSONDecodeError:
87
+ return f"ERROR: [get_horoscope]: Failed to parse a valid JSON response from the API."
88
  except Exception as e:
89
+ return f"ERROR: [get_horoscope]: An unexpected error occurred: {str(e)}"
90
+
91
 
92
 
93
+
94
+
95
+
96
+
97
  @tool
98
  def get_date_panchang(date: str = None, data_language: str = "EN") -> str:
99
+ """
100
+ Fetches the Panchang data for a given date.
101
  If the user does not provide a date, use today's real date.
102
+
103
  Args:
104
+ date: Date in any format (optional).
105
  data_language: Language of the Panchang data (e.g., 'EN' for English, 'HI' for Hindi).
106
  """
107
 
 
 
 
 
 
 
 
 
 
 
 
108
  try:
109
+ if not date:
110
+ now = datetime.datetime.now()
111
+ else:
112
+ now = parser.parse(date)
113
+
114
+ api_date = now.strftime("%d/%m/%y")
115
+
116
  url = (
117
  f"https://api.exaweb.in:3004/api/panchang/daily?"
118
  f"date={api_date}&app_language=EN&data_language={data_language}"
119
  )
120
+ headers = { "api_key": "anvl_bharat_cal123",
121
+ "Content-Type": "application/json" }
122
+
 
 
 
123
  response = requests.get(url, headers=headers)
124
  response.raise_for_status()
125
+
126
  data = response.json()
127
 
128
+
129
+ if not isinstance(data, dict) or not data:
130
+ return "ERROR: [get_date_panchang]: Received empty or invalid data from API."
131
 
132
  summary = {
133
  "date": data.get("date", "N/A"),
134
  "location": data.get("location", "N/A"),
135
+ "Sunrise": data.get("Sunrise", []),
136
+ "Sunset": data.get("Sunset", []),
137
+ "Tithi": data.get("Tithi", []),
138
+ "Nakshatra": data.get("Nakshatra", []),
139
+ "Yoga": data.get("Yoga", []),
140
+ "Karana": data.get("Karana", []),
141
+ "Festivals": data.get("festivals", []),
142
  }
143
+
144
+
145
+ sunrise_str = ', '.join(map(str, summary['Sunrise'])) or 'N/A'
146
+ sunset_str = ', '.join(map(str, summary['Sunset'])) or 'N/A'
147
+ tithi_str = ', '.join(map(str, summary['Tithi'])) or 'N/A'
148
+ nakshatra_str = ', '.join(map(str, summary['Nakshatra'])) or 'N/A'
149
+ yoga_str = ', '.join(map(str, summary['Yoga'])) or 'N/A'
150
+ karana_str = ', '.join(map(str, summary['Karana'])) or 'N/A'
151
+ festivals_str = ', '.join(f for f in map(str, summary['Festivals']) if f.strip().upper() != 'NA') or 'None'
152
+
153
  return (
154
  f"Panchang for {summary['date']} in {summary['location']}:\n"
155
+ f"🌅 Sunrise: {sunrise_str}\n"
156
+ f"🌇 Sunset: {sunset_str}\n"
157
+ f"📜 Tithi: {tithi_str}\n"
158
+ f"✨ Nakshatra: {nakshatra_str}\n"
159
+ f"🧘 Yoga: {yoga_str}\n"
160
+ f"🔺 Karana: {karana_str}\n"
161
+ f"🎉 Festivals: {festivals_str}"
 
162
  )
163
 
164
+ except requests.exceptions.RequestException as e:
165
+ return f"ERROR: [get_date_panchang]: Network error while fetching Panchang: {e}"
166
+ except json.JSONDecodeError:
167
+ return f"ERROR: [get_date_panchang]: Failed to parse a valid JSON response from the API."
168
+ except Exception as e:
169
+ return f"ERROR: [get_date_panchang]: An unexpected error occurred: {str(e)}"
170
+
171
+
172
 
173
 
174
 
 
 
 
175
 
176
  @tool
177
+ def get_holidays(year: int = None, app_language: str = "EN", data_language: str = "EN") -> str:
178
  """
179
+ Fetches holidays from all categories for a given year from ExaWeb API.
180
+
181
  Args:
182
  year: Year (e.g., 2025). Optional — defaults to current year.
183
  app_language: App language for API (default: "EN").
184
  data_language: Data language for holidays (default: "HI").
185
  """
186
+
187
  if not year:
188
  year = datetime.datetime.now().year
189
+
190
+ params = { "app_language": app_language, "data_language": data_language, "year": year }
191
+ headers = { "api_key": "anvl_bharat_cal123",
192
+ "Content-Type": "application/json" }
 
 
 
 
 
193
 
194
  try:
195
  response = requests.get(
 
200
  response.raise_for_status()
201
  data = response.json()
202
 
203
+ if not isinstance(data, dict):
204
+ return f"INFO: No holiday data found for {year}."
205
 
206
+ formatted = []
207
+ # --- ROBUSTNESS: Process only keys whose values are lists (safer than a blocklist) ---
208
  for category, groups in data.items():
209
+ if isinstance(groups, list):
210
+ formatted.append(f"\n=== {category.replace('_', ' ').title()} ===")
211
+ for group in groups:
212
+ # The API structure has a nested list, ensure group is a list
213
+ if isinstance(group, list):
214
+ for holiday in group:
215
+ if isinstance(holiday, dict):
216
+ title = holiday.get("title", "N/A")
217
+ date = holiday.get("date", "N/A")
218
+ formatted.append(f"{date}: {title}")
219
+
220
+ return "\n".join(formatted) if formatted else f"INFO: No holidays found for {year}."
 
 
 
221
 
222
+ except requests.exceptions.RequestException as e:
223
+ return f"ERROR: [get_holidays]: Network error fetching holidays: {e}"
224
+ except json.JSONDecodeError:
225
+ return f"ERROR: [get_holidays]: Failed to parse a valid JSON response from the API."
226
+ except Exception as e:
227
+ return f"ERROR: [get_holidays]: An unexpected error occurred: {str(e)}"
228
 
229
  @tool
230
+ def get_monthly_festivals(year: Optional[int] = None, month: Optional[str] = None, app_language: str = "EN", data_language: str = "EN") -> str:
231
  """
232
  Fetches festival data for a specific month and year from the ExaWeb API.
233
+
234
  Args:
235
+ year: The year to fetch (e.g., 2025). Defaults to current year.
236
+ month: The full month name to fetch (e.g., "june"). Defaults to current month.
 
 
237
  app_language: The language for the application interface (default: "EN").
238
  data_language: The language for the festival names (default: "EN").
 
 
 
239
  """
240
+ api_key = os.environ.get("EXAWEB_API_KEY")
241
+ if not api_key:
242
+ return "ERROR: [get_monthly_festivals]: API key is not configured."
243
+
244
  if not year:
245
  year = datetime.datetime.now().year
 
 
246
  if not month:
247
  month = datetime.datetime.now().strftime("%B").lower()
248
  else:
249
  month = month.lower()
250
 
 
251
  api_url = "https://api.exaweb.in:3004/api/panchang/festival"
252
+ params = { "year": year, "month": month, "app_language": app_language, "data_language": data_language }
253
+ headers = { "api_key": "anvl_bharat_cal123",
254
+ "Content-Type": "application/json" }
 
 
 
 
 
 
 
255
 
256
  try:
 
257
  response = requests.get(api_url, params=params, headers=headers)
 
258
  response.raise_for_status()
 
 
259
  data = response.json()
260
 
261
  if not data:
262
+ return f"INFO: No festival data found for {month.capitalize()} {year}."
263
+
 
264
  formatted_lines = []
265
  for entry in data:
266
+ if isinstance(entry, dict):
267
+ date = entry.get("date", "Unknown date")
268
+ festivals = entry.get("festivals", [])
269
+
270
+ meaningful_festivals = [f for f in festivals if isinstance(f, str) and f.strip().upper() != "NA"]
271
+
272
+ if meaningful_festivals:
273
+ festivals_str = ", ".join(meaningful_festivals)
274
+ formatted_lines.append(f"{date}: {festivals_str}")
 
275
 
276
  if not formatted_lines:
277
+ return f"INFO: No festivals found for {month.capitalize()} {year}."
278
+
279
  return "\n".join(formatted_lines)
280
 
281
  except requests.exceptions.RequestException as e:
282
+ return f"ERROR: [get_monthly_festivals]: Network error while fetching data: {e}"
283
+ except json.JSONDecodeError:
284
+ return f"ERROR: [get_monthly_festivals]: Failed to parse a valid JSON response from the API."
285
+ except Exception as e:
286
+ return f"ERROR: [get_monthly_festivals]: An unexpected error occurred: {str(e)}"
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
 
295
  final_answer = FinalAnswerTool()
296