nharshavardhana commited on
Commit
883c056
·
1 Parent(s): 1734c7b
Files changed (2) hide show
  1. app.py +319 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import gradio as gr
4
+ from dotenv import load_dotenv
5
+ import re
6
+ from typing import Optional
7
+ import base64
8
+ from time import sleep
9
+
10
+
11
+ def get_book_recommendations(prompt: str) -> str:
12
+ """
13
+ Fetches a book recommendation from Google Books API.
14
+ Args:
15
+ prompt: User search query, e.g., "thriller novel by Gillian Flynn"
16
+ Returns:
17
+ Top book recommendation in formatted text.
18
+ """
19
+ load_dotenv() # Make sure this is called before accessing environment variables
20
+
21
+ api_key = os.getenv("GOOGLE_BOOKS_API_KEY")
22
+ if not api_key:
23
+ return "API key not found."
24
+
25
+ search_query = prompt.strip()
26
+ url = f"https://www.googleapis.com/books/v1/volumes?q={search_query}&key={api_key}"
27
+
28
+ try:
29
+ response = requests.get(url, timeout=10)
30
+ response.raise_for_status()
31
+ books = response.json().get("items", [])
32
+ if not books:
33
+ return "No books found."
34
+
35
+ volume_info = books[0].get("volumeInfo", {})
36
+ title = volume_info.get("title", "Unknown Title")
37
+ authors = ", ".join(volume_info.get("authors", ["Unknown Author"]))
38
+ description = volume_info.get("description", "No description available.")
39
+
40
+ return f"📚 **{title}** by *{authors}*\n\n{description}"
41
+ except Exception as e:
42
+ return f"Error: {str(e)}"
43
+
44
+
45
+ def get_random_recipe(tags: str = "", exclude_ingredients: str = "") -> str:
46
+ """
47
+ Fetches a random recipe using the Spoonacular API and returns it in a formatted string.
48
+
49
+ Args:
50
+ tags (str): Comma-separated tags like 'vegetarian,dessert'.
51
+ exclude_ingredients (str): Comma-separated ingredients to exclude.
52
+
53
+ Returns:
54
+ str: A formatted string with title, preparation time, ingredients, and cooking steps.
55
+
56
+ """
57
+ load_dotenv()
58
+
59
+ recipe_api_key = os.getenv("SPOONACULAR_API_KEY")
60
+ if not recipe_api_key:
61
+ return "❌ API key not found in environment."
62
+
63
+ url = "https://api.spoonacular.com/recipes/random"
64
+ params = {
65
+ "number": 1,
66
+ "tags": tags,
67
+ "excludeIngredients": exclude_ingredients,
68
+ "apiKey": recipe_api_key
69
+ }
70
+
71
+ try:
72
+ response = requests.get(url, params=params, timeout=10)
73
+ data = response.json()
74
+ except Exception:
75
+ return "❌ Failed to parse JSON from API response."
76
+
77
+ if response.status_code != 200:
78
+ return f"❌ API Error: {data.get('message', 'Unknown error')}"
79
+
80
+ if not data.get("recipes"):
81
+ return "❌ No recipes returned."
82
+
83
+ recipe = data["recipes"][0]
84
+
85
+ title = recipe.get("title", "Unknown")
86
+ ready_in = recipe.get("readyInMinutes", "?")
87
+ ingredients = [i["name"] for i in recipe.get("extendedIngredients", [])]
88
+
89
+ steps = []
90
+ for block in recipe.get("analyzedInstructions", []):
91
+ for step in block.get("steps", []):
92
+ steps.append(step["step"])
93
+
94
+ formatted = f"🍽️ **Title**: {title}\n"
95
+ formatted += f"🕒 **Ready in**: {ready_in} minutes\n"
96
+ formatted += f"📋 **Ingredients**: {', '.join(ingredients) if ingredients else 'N/A'}\n"
97
+ formatted += "👨‍🍳 **Steps**:\n"
98
+ for idx, step in enumerate(steps, 1):
99
+ formatted += f" {idx}. {step.strip()}\n"
100
+
101
+ return formatted.strip()
102
+
103
+
104
+
105
+
106
+ def get_now_playing_movies(retries=3) -> str:
107
+ api_key = os.getenv("TMDB_API_KEY")
108
+ url = f"https://api.themoviedb.org/3/movie/now_playing?api_key={api_key}&language=en-US&page=1"
109
+
110
+ for attempt in range(1, retries + 1):
111
+ try:
112
+ response = requests.get(url, timeout=10)
113
+ response.raise_for_status()
114
+ movies = response.json().get("results", [])
115
+ if not movies:
116
+ return "No movies currently playing."
117
+
118
+ formatted = []
119
+ for movie in movies[:5]:
120
+ title = movie.get("title", "Untitled")
121
+ overview = movie.get("overview", "No description available.")
122
+ formatted.append(f"🎬 **{title}**\n{overview}\n")
123
+ return "\n".join(formatted)
124
+
125
+ except Exception as e:
126
+ if attempt == retries:
127
+ return f"❌ Failed after {retries} attempts: {e}"
128
+ sleep(1) # Wait before retrying
129
+
130
+ def get_music_recommendations(prompt: str, num_songs: int = 3, min_popularity: int = 0, year: str = "") -> str:
131
+ """
132
+ Fetches multiple music recommendations from Spotify API.
133
+
134
+ Args:
135
+ prompt: Search query (genre, mood, etc.)
136
+ num_songs: Number of song recommendations to return.
137
+ min_popularity: Minimum popularity score (0–100).
138
+ year: Optional release year filter, e.g., '2022' or '2010-2020'.
139
+
140
+ Returns:
141
+ Markdown-formatted string of top song recommendations.
142
+ """
143
+ load_dotenv()
144
+ client_id = os.getenv("SPOTIFY_CLIENT_ID")
145
+ client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
146
+
147
+ if not client_id or not client_secret:
148
+ return "Spotify API credentials not found."
149
+
150
+ # Encode client_id:client_secret
151
+ auth_str = f"{client_id}:{client_secret}"
152
+ b64_auth_str = base64.b64encode(auth_str.encode()).decode()
153
+
154
+ try:
155
+ token_response = requests.post(
156
+ "https://accounts.spotify.com/api/token",
157
+ data={"grant_type": "client_credentials"},
158
+ headers={"Authorization": f"Basic {b64_auth_str}"}
159
+ )
160
+ token_response.raise_for_status()
161
+ access_token = token_response.json().get("access_token")
162
+ except Exception as e:
163
+ return f"Token Error: {str(e)}"
164
+
165
+ try:
166
+ # Append year filter if provided
167
+ search_query = prompt.strip()
168
+ if year:
169
+ search_query += f" year:{year}"
170
+
171
+ url = f"https://api.spotify.com/v1/search?q={search_query}&type=track&limit={num_songs}"
172
+ headers = {"Authorization": f"Bearer {access_token}"}
173
+
174
+ response = requests.get(url, headers=headers, timeout=10)
175
+ response.raise_for_status()
176
+ tracks = response.json().get("tracks", {}).get("items", [])
177
+
178
+ if not tracks:
179
+ return "No songs found."
180
+
181
+ # Filter by popularity and format results
182
+ filtered_tracks = [
183
+ track for track in tracks if track["popularity"] >= min_popularity
184
+ ]
185
+
186
+ if not filtered_tracks:
187
+ return f"No songs found with popularity ≥ {min_popularity}."
188
+
189
+ output_lines = []
190
+ for track in filtered_tracks:
191
+ name = track["name"]
192
+ artist = ", ".join(artist["name"] for artist in track["artists"])
193
+ popularity = track["popularity"]
194
+ spotify_url = track["external_urls"]["spotify"]
195
+ preview_url = track.get("preview_url")
196
+
197
+ entry = f"🎵 **{name}** by *{artist}* (Popularity: {popularity})\n[Listen on Spotify]({spotify_url})"
198
+ if preview_url:
199
+ entry += f"\nPreview: {preview_url}"
200
+ output_lines.append(entry)
201
+
202
+ return "\n\n---\n\n".join(output_lines)
203
+ except Exception as e:
204
+ return f"Error: {str(e)}"
205
+
206
+
207
+
208
+ def get_current_weather(location: str) -> str:
209
+ """
210
+ Fetches current weather for a given city name or coordinates using OpenWeatherMap API.
211
+
212
+ Args:
213
+ location: A city name (e.g., "New York") or "lat,lon" format (e.g., "44.34,10.99")
214
+
215
+ Returns:
216
+ A formatted weather report string.
217
+ """
218
+ load_dotenv()
219
+
220
+ api_key = os.getenv("OPENWEATHER_API_KEY")
221
+ if not api_key:
222
+ return "OpenWeatherMap API key not found."
223
+
224
+ try:
225
+ # Check if input is coordinates
226
+ if "," in location:
227
+ lat, lon = map(str.strip, location.split(","))
228
+ else:
229
+ # Use geocoding API to get coordinates from city name
230
+ geo_url = f"http://api.openweathermap.org/geo/1.0/direct?q={location}&limit=1&appid={api_key}"
231
+ geo_resp = requests.get(geo_url, timeout=10)
232
+ geo_resp.raise_for_status()
233
+ geo_data = geo_resp.json()
234
+ if not geo_data:
235
+ return f"Could not find location: {location}"
236
+ lat = geo_data[0]["lat"]
237
+ lon = geo_data[0]["lon"]
238
+
239
+ # Get weather
240
+ weather_url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
241
+ weather_resp = requests.get(weather_url, timeout=10)
242
+ weather_resp.raise_for_status()
243
+ data = weather_resp.json()
244
+
245
+ city = f"{data.get('name', 'Unknown')}, {data['sys'].get('country', '')}"
246
+ condition = data["weather"][0]["description"].capitalize()
247
+ temp = data["main"]["temp"]
248
+ feels_like = data["main"]["feels_like"]
249
+ humidity = data["main"]["humidity"]
250
+ wind = data["wind"]["speed"]
251
+
252
+ return (
253
+ f"🌤 **Weather in {city}**\n"
254
+ f"Condition: {condition}\n"
255
+ f"🌡 Temperature: {temp}°C (Feels like {feels_like}°C)\n"
256
+ f"💧 Humidity: {humidity}%\n"
257
+ f"🌬 Wind Speed: {wind} m/s"
258
+ )
259
+
260
+ except Exception as e:
261
+ return f"Error fetching weather: {str(e)}"
262
+
263
+
264
+ # Define Gradio interface
265
+ book_interface = gr.Interface(
266
+ fn=get_book_recommendations,
267
+ inputs=gr.Textbox(label="Enter your book query"),
268
+ outputs=gr.Markdown(label="Top Recommendation"),
269
+ api_name="get_book_recommendations"
270
+ )
271
+
272
+ recipe_interface = gr.Interface(
273
+ fn=get_random_recipe,
274
+ inputs=[
275
+ gr.Textbox(label="Tags (e.g., vegetarian,dessert)", placeholder="Enter tags or leave blank"),
276
+ gr.Textbox(label="Exclude Ingredients", placeholder="e.g., nuts,gluten")
277
+ ],
278
+ outputs=gr.Markdown(label="Random Recipe"),
279
+ api_name="get_random_recipe" # This is critical for Hugging Face MCP endpoints
280
+ )
281
+
282
+ movie_interface = gr.Interface(
283
+ fn=get_now_playing_movies,
284
+ inputs=[], # No input needed for now-playing movies
285
+ outputs=gr.Markdown(label="Now Playing Movies"),
286
+ api_name="get_now_playing_movies"
287
+ )
288
+
289
+ music_interface = gr.Interface(
290
+ fn=get_music_recommendations,
291
+ inputs=[
292
+ gr.Textbox(label="Enter your music query (e.g., 'lofi beats', 'happy pop')"),
293
+ gr.Slider(minimum=1, maximum=10, value=3, label="Number of Songs"),
294
+ gr.Slider(minimum=0, maximum=100, value=0, label="Minimum Popularity"),
295
+ gr.Textbox(label="Release Year (e.g., 2022 or 2015-2020)", placeholder="Optional")
296
+ ],
297
+ outputs=gr.Markdown(label="Song Recommendations"),
298
+ api_name="get_music_recommendations"
299
+ )
300
+
301
+ weather_interface = gr.Interface(
302
+ fn=get_current_weather,
303
+ inputs=gr.Textbox(label="Enter a location (e.g., 'New York' or '44.34,10.99')"),
304
+ outputs=gr.Markdown(label="Current Weather"),
305
+ api_name="get_current_weather"
306
+ )
307
+
308
+
309
+ # Combine with other interfaces if needed
310
+ demo = gr.TabbedInterface(
311
+ [
312
+ book_interface, recipe_interface, movie_interface, music_interface, weather_interface
313
+ # add more tools here as you expand your agent system
314
+ ],
315
+ ["Book Finder", "Random Recipe", "Now Playing Movies", "Music Recommendations", "Current Weather"]
316
+ )
317
+
318
+ if __name__ == "__main__":
319
+ demo.launch(mcp_server=True)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ requests
3
+ python-dotenv