Anupam202224 commited on
Commit
36b25bf
·
verified ·
1 Parent(s): 8f00e0d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -77
app.py CHANGED
@@ -1,46 +1,28 @@
 
1
  import gradio as gr
2
  import pandas as pd
3
  import requests
4
  from typing import List, Dict, Any
5
- import os
6
- import time # For rate limiting
7
 
8
- # TMDB API Configuration (Environment Variables)
9
- TMDB_API_KEY = os.environ.get("TMDB_API_KEY", "YOUR_API_KEY")
10
- TMDB_API_TOKEN = os.environ.get("TMDB_API_TOKEN", "YOUR_API_TOKEN")
11
  TMDB_BASE_URL = "https://api.themoviedb.org/3"
12
  TMDB_IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500"
13
 
14
- def make_api_request(url, headers, params=None, max_retries=3, delay=2):
15
- """Makes a request to the TMDb API with retries and rate limiting."""
16
- retries = 0
17
- while retries < max_retries:
18
- try:
19
- response = requests.get(url, headers=headers, params=params)
20
- response.raise_for_status() # Raise an exception for HTTP errors
21
- return response
22
- except requests.exceptions.RequestException as e:
23
- print(f"API request failed: {e}")
24
- retries += 1
25
- if retries < max_retries:
26
- print(f"Retrying in {delay} seconds...")
27
- time.sleep(delay)
28
- return None
29
-
30
  def fetch_genres() -> List[Dict[str, Any]]:
31
  """Fetch movie genres from TMDB"""
32
  headers = {
33
  "Authorization": f"Bearer {TMDB_API_TOKEN}",
34
  "accept": "application/json"
35
  }
36
- response = make_api_request(f"{TMDB_BASE_URL}/genre/movie/list", headers=headers)
37
- if response:
38
- try:
39
- return response.json()["genres"] # Handle potential errors
40
- except KeyError:
41
- print("Error: 'genres' key not found in the TMDb response.")
42
- return []
43
- return []
44
 
45
  def fetch_movies_by_genre(genre_id: str = None) -> pd.DataFrame:
46
  """Fetch movies from TMDB, optionally filtered by genre"""
@@ -60,31 +42,32 @@ def fetch_movies_by_genre(genre_id: str = None) -> pd.DataFrame:
60
  if genre_id and genre_id != "All":
61
  params["with_genres"] = genre_id
62
 
63
- response = make_api_request(f"{TMDB_BASE_URL}/discover/movie", headers=headers, params=params)
64
- if response:
 
65
  movies = response.json()["results"]
66
- else:
67
- movies = []
68
-
69
- # Convert to DataFrame
70
- movie_data = {
71
- "title": [],
72
- "poster_url": [],
73
- "overview": [],
74
- "rating": [],
75
- "id": []
76
- }
77
-
78
- for movie in movies:
79
- movie_data["title"].append(movie["title"])
80
- movie_data["poster_url"].append(
81
- f"{TMDB_IMAGE_BASE_URL}{movie['poster_path']}" if movie['poster_path'] else None
82
- )
83
- movie_data["overview"].append(movie["overview"])
84
- movie_data["rating"].append(movie["vote_average"])
85
- movie_data["id"].append(movie["id"])
86
-
87
- return pd.DataFrame(movie_data)
88
 
89
  def get_movie_trailer(movie_id: int) -> str:
90
  """Fetch movie trailer URL from TMDB"""
@@ -93,24 +76,24 @@ def get_movie_trailer(movie_id: int) -> str:
93
  "accept": "application/json"
94
  }
95
 
96
- response = make_api_request(
97
- f"{TMDB_BASE_URL}/movie/{movie_id}/videos",
98
- headers=headers
99
- )
100
-
101
- if response:
102
  videos = response.json().get("results", [])
103
- else:
104
- videos = []
105
-
106
- trailer = next(
107
- (v for v in videos if v["type"] == "Trailer" and v["site"] == "YouTube"),
108
- None
109
- )
110
-
111
- if trailer:
112
- return f"https://www.youtube.com/watch?v={trailer['key']}"
113
- return None
114
 
115
  # Initialize global variables
116
  genres = fetch_genres()
@@ -131,10 +114,10 @@ def get_movie_info(evt: gr.SelectData) -> tuple:
131
  return None, None, None
132
 
133
  selected_movie = content_df.iloc[selected_idx]
134
- trailer_url = get_movie_trailer(selected_movie["id"])
135
 
136
  return (
137
- trailer_url,
138
  selected_movie["title"],
139
  f"{selected_movie['title']}\n\nRating: {selected_movie['rating']}/10\n\n{selected_movie['overview']}"
140
  )
@@ -149,7 +132,11 @@ def rate_movie(movie_title: str, rating: float) -> str:
149
 
150
  # Gradio UI
151
  with gr.Blocks(theme=gr.themes.Soft()) as movie_app:
152
- gr.Markdown("# 🎬 Movie Streaming App")
 
 
 
 
153
 
154
  with gr.Row():
155
  genre_dropdown = gr.Dropdown(
@@ -169,7 +156,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as movie_app:
169
  )
170
 
171
  with gr.Row():
172
- video_player = gr.Video(label="Trailer")
173
 
174
  with gr.Row():
175
  with gr.Column():
@@ -190,7 +177,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as movie_app:
190
 
191
  gallery.select(
192
  fn=get_movie_info,
193
- outputs=[video_player, selected_movie_title, movie_info]
194
  )
195
 
196
  rate_button.click(
@@ -199,6 +186,5 @@ with gr.Blocks(theme=gr.themes.Soft()) as movie_app:
199
  outputs=rating_output
200
  )
201
 
202
- # Launch app
203
  if __name__ == "__main__":
204
- movie_app.launch(share=True)
 
1
+ import os
2
  import gradio as gr
3
  import pandas as pd
4
  import requests
5
  from typing import List, Dict, Any
 
 
6
 
7
+ # TMDB API Configuration - Using environment variables for security
8
+ TMDB_API_KEY = os.getenv("TMDB_API_KEY", "2818694258d166d0644b0f75a1b93e59")
9
+ TMDB_API_TOKEN = os.getenv("TMDB_API_TOKEN", "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIyODE4Njk0MjU4ZDE2NmQwNjQ0YjBmNzVhMWI5M2U1OSIsIm5iZiI6MTczMDYxNjE4Mi4xODY5MDI4LCJzdWIiOiI2NzI3MWExYjM5OGM5MDQzZjgwZDEwOGEiLCJzY29wZXMiOlsiYXBpX3JlYWQiXSwidmVyc2lvbiI6MX0.G-pLEQKK3o5ISpb0CEztamPFGlsmpnPqPagawMve9dY")
10
  TMDB_BASE_URL = "https://api.themoviedb.org/3"
11
  TMDB_IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500"
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  def fetch_genres() -> List[Dict[str, Any]]:
14
  """Fetch movie genres from TMDB"""
15
  headers = {
16
  "Authorization": f"Bearer {TMDB_API_TOKEN}",
17
  "accept": "application/json"
18
  }
19
+ try:
20
+ response = requests.get(f"{TMDB_BASE_URL}/genre/movie/list", headers=headers)
21
+ response.raise_for_status()
22
+ return response.json()["genres"]
23
+ except Exception as e:
24
+ print(f"Error fetching genres: {e}")
25
+ return []
 
26
 
27
  def fetch_movies_by_genre(genre_id: str = None) -> pd.DataFrame:
28
  """Fetch movies from TMDB, optionally filtered by genre"""
 
42
  if genre_id and genre_id != "All":
43
  params["with_genres"] = genre_id
44
 
45
+ try:
46
+ response = requests.get(f"{TMDB_BASE_URL}/discover/movie", headers=headers, params=params)
47
+ response.raise_for_status()
48
  movies = response.json()["results"]
49
+
50
+ movie_data = {
51
+ "title": [],
52
+ "poster_url": [],
53
+ "overview": [],
54
+ "rating": [],
55
+ "id": []
56
+ }
57
+
58
+ for movie in movies:
59
+ movie_data["title"].append(movie["title"])
60
+ movie_data["poster_url"].append(
61
+ f"{TMDB_IMAGE_BASE_URL}{movie['poster_path']}" if movie.get('poster_path') else None
62
+ )
63
+ movie_data["overview"].append(movie.get("overview", "No overview available"))
64
+ movie_data["rating"].append(movie.get("vote_average", 0))
65
+ movie_data["id"].append(movie["id"])
66
+
67
+ return pd.DataFrame(movie_data)
68
+ except Exception as e:
69
+ print(f"Error fetching movies: {e}")
70
+ return pd.DataFrame(columns=["title", "poster_url", "overview", "rating", "id"])
71
 
72
  def get_movie_trailer(movie_id: int) -> str:
73
  """Fetch movie trailer URL from TMDB"""
 
76
  "accept": "application/json"
77
  }
78
 
79
+ try:
80
+ response = requests.get(
81
+ f"{TMDB_BASE_URL}/movie/{movie_id}/videos",
82
+ headers=headers
83
+ )
84
+ response.raise_for_status()
85
  videos = response.json().get("results", [])
86
+ trailer = next(
87
+ (v for v in videos if v["type"] == "Trailer" and v["site"] == "YouTube"),
88
+ None
89
+ )
90
+
91
+ if trailer:
92
+ return f'<iframe width="100%" height="400" src="https://www.youtube.com/embed/{trailer["key"]}" frameborder="0" allowfullscreen></iframe>'
93
+ return '<p>No trailer available</p>'
94
+ except Exception as e:
95
+ print(f"Error fetching trailer: {e}")
96
+ return '<p>Error loading trailer</p>'
97
 
98
  # Initialize global variables
99
  genres = fetch_genres()
 
114
  return None, None, None
115
 
116
  selected_movie = content_df.iloc[selected_idx]
117
+ trailer_html = get_movie_trailer(selected_movie["id"])
118
 
119
  return (
120
+ gr.HTML(value=trailer_html),
121
  selected_movie["title"],
122
  f"{selected_movie['title']}\n\nRating: {selected_movie['rating']}/10\n\n{selected_movie['overview']}"
123
  )
 
132
 
133
  # Gradio UI
134
  with gr.Blocks(theme=gr.themes.Soft()) as movie_app:
135
+ gr.Markdown("""
136
+ # 🎬 Movie Explorer
137
+
138
+ Browse popular movies, watch trailers, and explore different genres!
139
+ """)
140
 
141
  with gr.Row():
142
  genre_dropdown = gr.Dropdown(
 
156
  )
157
 
158
  with gr.Row():
159
+ trailer_html = gr.HTML(label="Trailer")
160
 
161
  with gr.Row():
162
  with gr.Column():
 
177
 
178
  gallery.select(
179
  fn=get_movie_info,
180
+ outputs=[trailer_html, selected_movie_title, movie_info]
181
  )
182
 
183
  rate_button.click(
 
186
  outputs=rating_output
187
  )
188
 
 
189
  if __name__ == "__main__":
190
+ movie_app.launch()