KingNish commited on
Commit
7dbf05f
·
verified ·
1 Parent(s): 7dd0946

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -58
app.py CHANGED
@@ -3,18 +3,29 @@ import requests
3
  import random
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 the Pixabay API for royalty-free stock images or videos based on user query and filters.
17
-
18
  Args:
19
  query (str): The search term for finding media. If empty, an error is returned.
20
  media_type (str): Specifies the type of media to search for.
@@ -30,7 +41,7 @@ def search_pixabay(query: str, media_type: str, image_type: str, orientation: st
30
  return None, None, "Please enter a search query."
31
 
32
  if not PIXABAY_API_KEY:
33
- return None, None, "API Key not found. Please set the PIXABAY_API_KEY environment variable."
34
 
35
  params = {
36
  'key': PIXABAY_API_KEY,
@@ -40,7 +51,6 @@ def search_pixabay(query: str, media_type: str, image_type: str, orientation: st
40
  'safesearch': 'true'
41
  }
42
 
43
- # Determine API endpoint and add media-specific parameters
44
  if media_type == "Image":
45
  api_url = IMAGE_API_URL
46
  params['image_type'] = image_type
@@ -54,8 +64,8 @@ def search_pixabay(query: str, media_type: str, image_type: str, orientation: st
54
 
55
  try:
56
  response = requests.get(api_url, params=params)
57
- response.raise_for_status() # Check for HTTP errors (like 404, 429, 500)
58
- data = response.json() # Parse the JSON response
59
 
60
  if data.get('totalHits', 0) == 0:
61
  return None, None, f"No results found for '{query}'."
@@ -64,12 +74,9 @@ def search_pixabay(query: str, media_type: str, image_type: str, orientation: st
64
  if not hits:
65
  return None, None, f"No results found for '{query}'."
66
 
67
- # Randomly select one result from the retrieved items (max 5)
68
  selected_hit = random.choice(hits)
69
 
70
- # Extract the URL based on media type
71
  if media_type == "Image":
72
- # Get the URL for the large image
73
  image_url = selected_hit.get('largeImageURL')
74
  if image_url:
75
  # Return the image URL, None for video, and an empty status message
@@ -78,7 +85,6 @@ def search_pixabay(query: str, media_type: str, image_type: str, orientation: st
78
  return None, None, "Could not retrieve large image URL."
79
 
80
  elif media_type == "Video":
81
- # Get the URL for the large video stream
82
  video_urls = selected_hit.get('videos', {})
83
  large_video = video_urls.get('large', {})
84
  video_url = large_video.get('url')
@@ -103,61 +109,155 @@ def search_pixabay(query: str, media_type: str, image_type: str, orientation: st
103
  # Catch any other unexpected errors
104
  return None, None, f"An unexpected error occurred: {e}"
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  # --- Gradio Blocks Interface Definition ---
107
- with gr.Blocks(title="Pixabay Random Media Explorer") as demo:
108
- gr.Markdown("## Pixabay Random Media Explorer (URL Output)")
109
- gr.Markdown("Enter a search query, select media type and options, and get the URL for a random result from Pixabay.")
110
 
111
- with gr.Row():
112
- query_input = gr.Textbox(label="Search Query", placeholder="e.g., yellow flowers", scale=2)
113
- media_type_radio = gr.Radio(["Image", "Video"], label="Media Type", value="Image", scale=1)
114
- search_button = gr.Button("Search")
 
 
 
115
 
116
- # Containers to hold media-specific inputs, initially hidden or shown
117
- with gr.Column(visible=True) as image_options_col:
118
- image_type_input = gr.Radio(["all", "photo", "illustration", "vector"], label="Image Type", value="all")
119
- orientation_input = gr.Radio(["all", "horizontal", "vertical"], label="Orientation", value="all")
120
 
121
- with gr.Column(visible=False) as video_options_col:
122
- video_type_input = gr.Radio(["all", "film", "animation"], label="Video Type", value="all")
123
 
124
- status_output = gr.Textbox(label="Status", interactive=False)
125
 
126
- # Outputs will appear side-by-side in a row
127
- with gr.Row():
128
- image_output = gr.Image(label="Result URL", type="filepath", interactive=False)
129
- video_output = gr.Video(label="Result URL", interactive=False)
130
 
131
- # Logic to toggle visibility of input columns based on media type selection
132
- def update_inputs_blocks(media_type):
133
- if media_type == "Image":
134
- 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
135
- elif media_type == "Video":
136
- 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
137
- else:
138
- # Default state
139
- return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
140
-
141
- # Trigger the update_inputs_blocks function when media_type_radio changes
142
- media_type_radio.change(
143
- fn=update_inputs_blocks,
144
- inputs=media_type_radio,
145
- outputs=[image_options_col, video_options_col, image_output, video_output] # Update visibility of columns AND output components
146
- )
147
-
148
- # Trigger the search_pixabay function when the search button is clicked
149
- # Pass all relevant inputs, even if some are hidden
150
- search_button.click(
151
- fn=search_pixabay,
152
- inputs=[
153
- query_input,
154
- media_type_radio,
155
- image_type_input,
156
- orientation_input,
157
- video_type_input
158
- ],
159
- outputs=[image_output, video_output, status_output] # Map function outputs to Gradio components
160
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  # --- Launch the Gradio app ---
163
  if __name__ == "__main__":
 
3
  import random
4
  import json
5
  import os
6
+ from together import Together
7
+ import base64
8
+ from PIL import Image
9
+ import io
10
+
11
+ # --- Environment Variable for Together API Key ---
12
+ TOGETHER_API_KEY = os.environ.get('TOGETHER_API_KEY')
13
+
14
+ # --- Together API Client Configuration ---
15
+ # Initialize the Together client only if the API key is available
16
+ client = Together(api_key=TOGETHER_API_KEY) if TOGETHER_API_KEY else None
17
 
18
  # --- Pixabay API Configuration ---
19
  PIXABAY_API_KEY = os.environ.get('PIXABAY_API_KEY')
20
  IMAGE_API_URL = 'https://pixabay.com/api/'
21
  VIDEO_API_URL = 'https://pixabay.com/api/videos/'
22
+ PER_PAGE = 5
23
 
24
  # --- Function to search Pixabay ---
25
  def search_pixabay(query: str, media_type: str, image_type: str, orientation: str, video_type: str):
26
  """
27
  Searches the Pixabay API for royalty-free stock images or videos based on user query and filters.
28
+
29
  Args:
30
  query (str): The search term for finding media. If empty, an error is returned.
31
  media_type (str): Specifies the type of media to search for.
 
41
  return None, None, "Please enter a search query."
42
 
43
  if not PIXABAY_API_KEY:
44
+ return None, None, "Pixabay API Key not found. Please set the PIXABAY_API_KEY environment variable."
45
 
46
  params = {
47
  'key': PIXABAY_API_KEY,
 
51
  'safesearch': 'true'
52
  }
53
 
 
54
  if media_type == "Image":
55
  api_url = IMAGE_API_URL
56
  params['image_type'] = image_type
 
64
 
65
  try:
66
  response = requests.get(api_url, params=params)
67
+ response.raise_for_status()
68
+ data = response.json()
69
 
70
  if data.get('totalHits', 0) == 0:
71
  return None, None, f"No results found for '{query}'."
 
74
  if not hits:
75
  return None, None, f"No results found for '{query}'."
76
 
 
77
  selected_hit = random.choice(hits)
78
 
 
79
  if media_type == "Image":
 
80
  image_url = selected_hit.get('largeImageURL')
81
  if image_url:
82
  # Return the image URL, None for video, and an empty status message
 
85
  return None, None, "Could not retrieve large image URL."
86
 
87
  elif media_type == "Video":
 
88
  video_urls = selected_hit.get('videos', {})
89
  large_video = video_urls.get('large', {})
90
  video_url = large_video.get('url')
 
109
  # Catch any other unexpected errors
110
  return None, None, f"An unexpected error occurred: {e}"
111
 
112
+ # --- Together AI Image Generation Functions ---
113
+ def together_text_to_image(prompt: str):
114
+ """
115
+ Generates an image from text using the Together AI API.
116
+
117
+ Args:
118
+ prompt (str): The text prompt for image generation.
119
+
120
+ Returns:
121
+ str: The URL of the generated image, or an error message.
122
+ """
123
+ if not client:
124
+ return "Together AI client not initialized. Please set the TOGETHER_API_KEY environment variable."
125
+ if not prompt:
126
+ return "Please enter a prompt for text-to-image generation."
127
+
128
+ try:
129
+ image_completion = client.images.generate(
130
+ model="black-forest-labs/FLUX.1.1-pro", # Hardcoded model as requested
131
+ width=1024,
132
+ height=768,
133
+ steps=40, # Hardcoded steps as requested
134
+ prompt=prompt,
135
+ )
136
+ return image_completion.data[0].url
137
+ except Exception as e:
138
+ return f"Error generating image from text: {e}"
139
+
140
+ def together_image_to_image(image_numpy, prompt: str):
141
+ """
142
+ Transforms an image based on a text prompt using the Together AI API.
143
+
144
+ Args:
145
+ image_numpy (numpy.ndarray): The input image as a NumPy array (provided by Gradio).
146
+ prompt (str): The text prompt for image transformation.
147
+
148
+ Returns:
149
+ str: The URL of the transformed image, or an error message.
150
+ """
151
+ if not client:
152
+ return "Together AI client not initialized. Please set the TOGETHER_API_KEY environment variable."
153
+ if image_numpy is None:
154
+ return "Please upload or paste an image for image-to-image transformation."
155
+ if not prompt:
156
+ return "Please enter a prompt for image transformation."
157
+
158
+ try:
159
+ # Convert the NumPy array image to a PIL Image
160
+ img = Image.fromarray(image_numpy.astype('uint8'), 'RGB')
161
+
162
+ # Convert the PIL Image to base64
163
+ buffered = io.BytesIO()
164
+ img.save(buffered, format="PNG")
165
+ img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
166
+
167
+ image_completion = client.images.generate(
168
+ model="black-forest-labs/FLUX.1-kontext-max", # Hardcoded model as requested
169
+ steps=40, # Hardcoded steps as requested
170
+ prompt=prompt,
171
+ image_base64=img_base64
172
+ )
173
+ return image_completion.data[0].url
174
+ except Exception as e:
175
+ return f"Error transforming image: {e}"
176
+
177
+
178
  # --- Gradio Blocks Interface Definition ---
179
+ with gr.Blocks(title="Media Generation and Search Explorer") as demo:
180
+ gr.Markdown("## Media Generation and Search Explorer")
181
+ gr.Markdown("Explore royalty-free media from Pixabay and generate/transform images using Together AI.")
182
 
183
+ with gr.Tab("Pixabay Search"):
184
+ gr.Markdown("Search for royalty-free images and videos on Pixabay.")
185
+ gr.Warning("This requires setting the PIXABAY_API_KEY environment variable.")
186
+ with gr.Row():
187
+ pixabay_query_input = gr.Textbox(label="Search Query", placeholder="e.g., yellow flowers", scale=2)
188
+ pixabay_media_type_radio = gr.Radio(["Image", "Video"], label="Media Type", value="Image", scale=1)
189
+ pixabay_search_button = gr.Button("Search")
190
 
191
+ with gr.Column(visible=True) as pixabay_image_options_col:
192
+ pixabay_image_type_input = gr.Radio(["all", "photo", "illustration", "vector"], label="Image Type", value="all")
193
+ pixabay_orientation_input = gr.Radio(["all", "horizontal", "vertical"], label="Orientation", value="all")
 
194
 
195
+ with gr.Column(visible=False) as pixabay_video_options_col:
196
+ pixabay_video_type_input = gr.Radio(["all", "film", "animation"], label="Video Type", value="all")
197
 
198
+ pixabay_status_output = gr.Textbox(label="Status", interactive=False)
199
 
200
+ with gr.Row():
201
+ pixabay_image_output = gr.Image(label="Result Image (URL)", type="filepath", interactive=False)
202
+ pixabay_video_output = gr.Video(label="Result Video (URL)", type="filepath", interactive=False)
 
203
 
204
+ # Logic to toggle visibility of input columns and output components based on media type selection
205
+ def update_pixabay_inputs_blocks(media_type):
206
+ if media_type == "Image":
207
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
208
+ elif media_type == "Video":
209
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)
210
+ else:
211
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
212
+
213
+ # Trigger the update_pixabay_inputs_blocks function when media_type_radio changes
214
+ pixabay_media_type_radio.change(
215
+ fn=update_pixabay_inputs_blocks,
216
+ inputs=pixabay_media_type_radio,
217
+ outputs=[pixabay_image_options_col, pixabay_video_options_col, pixabay_image_output, pixabay_video_output]
218
+ )
219
+
220
+ # Trigger the search_pixabay function when the search button is clicked
221
+ pixabay_search_button.click(
222
+ fn=search_pixabay,
223
+ inputs=[
224
+ pixabay_query_input,
225
+ pixabay_media_type_radio,
226
+ pixabay_image_type_input,
227
+ pixabay_orientation_input,
228
+ pixabay_video_type_input
229
+ ],
230
+ outputs=[pixabay_image_output, pixabay_video_output, pixabay_status_output]
231
+ )
232
+
233
+ with gr.Tab("Together AI - Text to Image"):
234
+ gr.Markdown("Generate an image from a text prompt using Together AI.")
235
+ gr.Warning("This requires setting the TOGETHER_API_KEY environment variable.")
236
+ with gr.Row():
237
+ together_text_to_image_prompt = gr.Textbox(label="Enter your prompt", scale=2)
238
+ together_text_to_image_button = gr.Button("Generate Image", scale=1)
239
+ together_text_to_image_output = gr.Image(label="Generated Image (URL)", type="filepath", interactive=False)
240
+
241
+ together_text_to_image_button.click(
242
+ fn=together_text_to_image,
243
+ inputs=together_text_to_image_prompt,
244
+ outputs=together_text_to_image_output,
245
+ )
246
+
247
+ with gr.Tab("Together AI - Image to Image"):
248
+ gr.Markdown("Transform an uploaded image based on a text prompt using Together AI.")
249
+ gr.Warning("This requires setting the TOGETHER_API_KEY environment variable.")
250
+ with gr.Row():
251
+ together_image_input = gr.Image(label="Upload or paste an image", scale=2)
252
+ together_image_to_image_prompt = gr.Textbox(label="Enter your transformation prompt", scale=2)
253
+ together_image_to_image_button = gr.Button("Transform Image", scale=1)
254
+ together_image_to_image_output = gr.Image(label="Transformed Image (URL)", type="filepath", interactive=False)
255
+
256
+ together_image_to_image_button.click(
257
+ fn=together_image_to_image,
258
+ inputs=[together_image_input, together_image_to_image_prompt],
259
+ outputs=together_image_to_image_output,
260
+ )
261
 
262
  # --- Launch the Gradio app ---
263
  if __name__ == "__main__":