KingNish commited on
Commit
88c8796
·
verified ·
1 Parent(s): 0cf5240

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -49
app.py CHANGED
@@ -4,15 +4,24 @@ import random
4
  import json
5
  import os
6
 
 
7
  PIXABAY_API_KEY = os.environ.get('PIXABAY_API_KEY')
8
  IMAGE_API_URL = 'https://pixabay.com/api/'
9
  VIDEO_API_URL = 'https://pixabay.com/api/videos/'
10
- PER_PAGE = 5
11
-
12
- def search_pixabay(query: str, media_type: str, image_type: str = 'all', orientation: str = 'all', video_type: str = 'all'):
 
 
 
 
 
13
  if not query:
14
  return None, None, "Please enter a search query."
15
 
 
 
 
16
  params = {
17
  'key': PIXABAY_API_KEY,
18
  'q': query,
@@ -21,6 +30,7 @@ def search_pixabay(query: str, media_type: str, image_type: str = 'all', orienta
21
  'safesearch': 'true'
22
  }
23
 
 
24
  if media_type == "Image":
25
  api_url = IMAGE_API_URL
26
  params['image_type'] = image_type
@@ -29,12 +39,13 @@ def search_pixabay(query: str, media_type: str, image_type: str = 'all', orienta
29
  api_url = VIDEO_API_URL
30
  params['video_type'] = video_type
31
  else:
 
32
  return None, None, "Invalid media type selected."
33
 
34
  try:
35
  response = requests.get(api_url, params=params)
36
- response.raise_for_status()
37
- data = response.json()
38
 
39
  if data.get('totalHits', 0) == 0:
40
  return None, None, f"No results found for '{query}'."
@@ -43,23 +54,30 @@ def search_pixabay(query: str, media_type: str, image_type: str = 'all', orienta
43
  if not hits:
44
  return None, None, f"No results found for '{query}'."
45
 
 
46
  selected_hit = random.choice(hits)
47
 
 
48
  if media_type == "Image":
 
49
  image_url = selected_hit.get('largeImageURL')
50
  if image_url:
 
51
  return image_url, None, ""
52
  else:
53
  return None, None, "Could not retrieve large image URL."
54
 
55
  elif media_type == "Video":
 
56
  video_urls = selected_hit.get('videos', {})
57
  large_video = video_urls.get('large', {})
58
  video_url = large_video.get('url')
59
 
60
  if video_url:
 
61
  return None, video_url, ""
62
  else:
 
63
  medium_video = video_urls.get('medium', {})
64
  video_url = medium_video.get('url')
65
  if video_url:
@@ -72,51 +90,65 @@ def search_pixabay(query: str, media_type: str, image_type: str = 'all', orienta
72
  except json.JSONDecodeError:
73
  return None, None, "Error decoding API response."
74
  except Exception as e:
 
75
  return None, None, f"An unexpected error occurred: {e}"
76
 
77
- # Gradio input components
78
- image_type_input = gr.Radio(["all", "photo", "illustration", "vector"], label="Image Type", value="all", visible=True)
79
- orientation_input = gr.Radio(["all", "horizontal", "vertical"], label="Orientation", value="all", visible=True)
80
- video_type_input = gr.Radio(["all", "film", "animation"], label="Video Type", value="all", visible=False)
81
- media_type_radio = gr.Radio(["Image", "Video"], label="Media Type", value="Image")
82
 
83
- # Function to toggle input visibility
84
- def update_inputs(media_type):
85
- if media_type == "Image":
86
- return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
87
- elif media_type == "Video":
88
- return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
89
- else:
90
- return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
91
-
92
- media_type_radio.change(
93
- fn=update_inputs,
94
- inputs=media_type_radio,
95
- outputs=[image_type_input, orientation_input, video_type_input]
96
- )
97
-
98
- # Gradio output components
99
- output_components = [
100
- gr.Image(label="Result URL", type="filepath", interactive=False),
101
- gr.Video(label="Result URL", interactive=False),
102
- gr.Textbox(label="Status", interactive=False)
103
- ]
104
-
105
- # Define the Gradio interface
106
- interface = gr.Interface(
107
- fn=search_pixabay,
108
- inputs=[
109
- gr.Textbox(label="Search Query", placeholder="e.g., yellow flowers"),
110
- media_type_radio,
111
- image_type_input,
112
- orientation_input,
113
- video_type_input
114
- ],
115
- outputs=output_components,
116
- title="Pixabay Random Media Explorer (URL Output)",
117
- description="Get a random media result from Pixabay (URL output)."
118
- )
119
-
120
- # Launch the app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  if __name__ == "__main__":
122
- interface.launch()
 
4
  import json
5
  import os
6
 
7
+ # --- Pixabay API Configuration ---
8
  PIXABAY_API_KEY = os.environ.get('PIXABAY_API_KEY')
9
  IMAGE_API_URL = 'https://pixabay.com/api/'
10
  VIDEO_API_URL = 'https://pixabay.com/api/videos/'
11
+ PER_PAGE = 5
12
+
13
+ # --- Function to search Pixabay ---
14
+ def search_pixabay(query: str, media_type: str, image_type: str, orientation: str, video_type: str):
15
+ """
16
+ Searches Pixabay API and returns a random result URL and status message.
17
+ Takes all type/orientation inputs, but uses them based on media_type.
18
+ """
19
  if not query:
20
  return None, None, "Please enter a search query."
21
 
22
+ if not PIXABAY_API_KEY:
23
+ return None, None, "API Key not found. Please set the PIXABAY_API_KEY environment variable."
24
+
25
  params = {
26
  'key': PIXABAY_API_KEY,
27
  'q': query,
 
30
  'safesearch': 'true'
31
  }
32
 
33
+ # Determine API endpoint and add media-specific parameters
34
  if media_type == "Image":
35
  api_url = IMAGE_API_URL
36
  params['image_type'] = image_type
 
39
  api_url = VIDEO_API_URL
40
  params['video_type'] = video_type
41
  else:
42
+ # This case should not be reachable with the Gradio Radio component
43
  return None, None, "Invalid media type selected."
44
 
45
  try:
46
  response = requests.get(api_url, params=params)
47
+ response.raise_for_status() # Check for HTTP errors (like 404, 429, 500)
48
+ data = response.json() # Parse the JSON response
49
 
50
  if data.get('totalHits', 0) == 0:
51
  return None, None, f"No results found for '{query}'."
 
54
  if not hits:
55
  return None, None, f"No results found for '{query}'."
56
 
57
+ # Randomly select one result from the retrieved items (max 5)
58
  selected_hit = random.choice(hits)
59
 
60
+ # Extract the URL based on media type
61
  if media_type == "Image":
62
+ # Get the URL for the large image
63
  image_url = selected_hit.get('largeImageURL')
64
  if image_url:
65
+ # Return the image URL, None for video, and an empty status message
66
  return image_url, None, ""
67
  else:
68
  return None, None, "Could not retrieve large image URL."
69
 
70
  elif media_type == "Video":
71
+ # Get the URL for the large video stream
72
  video_urls = selected_hit.get('videos', {})
73
  large_video = video_urls.get('large', {})
74
  video_url = large_video.get('url')
75
 
76
  if video_url:
77
+ # Return None for image, the video URL, and an empty status message
78
  return None, video_url, ""
79
  else:
80
+ # Fallback to medium quality if large is not available
81
  medium_video = video_urls.get('medium', {})
82
  video_url = medium_video.get('url')
83
  if video_url:
 
90
  except json.JSONDecodeError:
91
  return None, None, "Error decoding API response."
92
  except Exception as e:
93
+ # Catch any other unexpected errors
94
  return None, None, f"An unexpected error occurred: {e}"
95
 
96
+ # --- Gradio Blocks Interface Definition ---
97
+ with gr.Blocks(title="Pixabay Random Media Explorer") as demo:
98
+ gr.Markdown("## Pixabay Random Media Explorer (URL Output)")
99
+ gr.Markdown("Enter a search query, select media type and options, and get the URL for a random result from Pixabay.")
 
100
 
101
+ with gr.Row():
102
+ query_input = gr.Textbox(label="Search Query", placeholder="e.g., yellow flowers", scale=2)
103
+ media_type_radio = gr.Radio(["Image", "Video"], label="Media Type", value="Image", scale=1)
104
+ search_button = gr.Button("Search")
105
+
106
+ # Containers to hold media-specific inputs, initially hidden or shown
107
+ with gr.Column(visible=True) as image_options_col:
108
+ image_type_input = gr.Radio(["all", "photo", "illustration", "vector"], label="Image Type", value="all")
109
+ orientation_input = gr.Radio(["all", "horizontal", "vertical"], label="Orientation", value="all")
110
+
111
+ with gr.Column(visible=False) as video_options_col:
112
+ video_type_input = gr.Radio(["all", "film", "animation"], label="Video Type", value="all")
113
+
114
+ status_output = gr.Textbox(label="Status", interactive=False)
115
+
116
+ # Outputs will appear side-by-side in a row
117
+ with gr.Row():
118
+ image_output = gr.Image(label="Result URL", type="filepath", interactive=False)
119
+ video_output = gr.Video(label="Result URL", interactive=False)
120
+
121
+ # Logic to toggle visibility of input columns based on media type selection
122
+ def update_inputs_blocks(media_type):
123
+ if media_type == "Image":
124
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) # show image cols, hide video cols, show image outputs, hide video outputs
125
+ elif media_type == "Video":
126
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=True) # hide image cols, show video cols, hide image outputs, show video outputs
127
+ else:
128
+ # Default state
129
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
130
+
131
+ # Trigger the update_inputs_blocks function when media_type_radio changes
132
+ media_type_radio.change(
133
+ fn=update_inputs_blocks,
134
+ inputs=media_type_radio,
135
+ outputs=[image_options_col, video_options_col, image_output, video_output] # Update visibility of columns AND output components
136
+ )
137
+
138
+ # Trigger the search_pixabay function when the search button is clicked
139
+ # Pass all relevant inputs, even if some are hidden
140
+ search_button.click(
141
+ fn=search_pixabay,
142
+ inputs=[
143
+ query_input,
144
+ media_type_radio,
145
+ image_type_input,
146
+ orientation_input,
147
+ video_type_input
148
+ ],
149
+ outputs=[image_output, video_output, status_output] # Map function outputs to Gradio components
150
+ )
151
+
152
+ # --- Launch the Gradio app ---
153
  if __name__ == "__main__":
154
+ demo.launch()