sumityadav329 commited on
Commit
6c59c0b
·
verified ·
1 Parent(s): 8626742

download button removed

Browse files
Files changed (1) hide show
  1. app.py +9 -85
app.py CHANGED
@@ -3,7 +3,6 @@ import gradio as gr
3
  from PIL import Image
4
  import io
5
  import requests
6
- import tempfile
7
  from typing import Optional, Tuple
8
 
9
  def load_environment():
@@ -21,44 +20,6 @@ def load_environment():
21
 
22
  return os.getenv("HF_TOKEN")
23
 
24
- def convert_image(image: Image.Image, format: str = 'png') -> bytes:
25
- """
26
- Convert PIL Image to specified format in memory.
27
-
28
- Args:
29
- image (Image.Image): Input PIL Image
30
- format (str): Desired output format (png, jpg, webp)
31
-
32
- Returns:
33
- bytes: Image converted to specified format
34
- """
35
- # Supported formats with their MIME types
36
- supported_formats = {
37
- 'png': 'image/png',
38
- 'jpg': 'image/jpeg',
39
- 'jpeg': 'image/jpeg',
40
- 'webp': 'image/webp'
41
- }
42
-
43
- # Normalize format
44
- format = format.lower()
45
-
46
- # Validate format
47
- if format not in supported_formats:
48
- raise ValueError(f"Unsupported format. Choose from: {', '.join(supported_formats.keys())}")
49
-
50
- # Convert image
51
- byte_array = io.BytesIO()
52
-
53
- # Special handling for JPEG to ensure no alpha channel
54
- if format in ['jpg', 'jpeg']:
55
- image = image.convert('RGB')
56
-
57
- # Save image to byte array
58
- image.save(byte_array, format=format)
59
-
60
- return byte_array.getvalue()
61
-
62
  def craft_realistic_prompt(base_prompt: str) -> str:
63
  """
64
  Enhance prompts for more photorealistic results
@@ -146,22 +107,21 @@ def query_hf_api(
146
 
147
  raise RuntimeError("Unexpected error in image generation")
148
 
149
- def generate_image(prompt: str, output_format: str = 'png') -> Tuple[Optional[Image.Image], str, Optional[bytes]]:
150
  """
151
  Generate an image from a text prompt.
152
 
153
  Args:
154
  prompt (str): Text description for image generation
155
- output_format (str): Desired output format
156
 
157
  Returns:
158
- Tuple[Optional[Image.Image], str, Optional[bytes]]:
159
- Generated PIL Image, status message, and downloadable image bytes
160
  """
161
  try:
162
  # Validate prompt
163
  if not prompt or not prompt.strip():
164
- return None, "Error: Prompt cannot be empty", None
165
 
166
  # Generate image bytes
167
  image_bytes = query_hf_api(prompt)
@@ -169,14 +129,11 @@ def generate_image(prompt: str, output_format: str = 'png') -> Tuple[Optional[Im
169
  # Convert to PIL Image
170
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
171
 
172
- # Convert image to specified format
173
- downloadable_image = convert_image(image, output_format)
174
-
175
- return image, "Image generated successfully!", downloadable_image
176
 
177
  except Exception as e:
178
  print(f"Image generation error: {e}")
179
- return None, f"Error: {str(e)}", None
180
 
181
  def create_gradio_interface():
182
  """
@@ -193,9 +150,6 @@ def create_gradio_interface():
193
  gr.Markdown("# 🎨 AI Image Generator")
194
  gr.Markdown("Generate stunning images from your text prompts using AI!")
195
 
196
- # State to store generated image bytes
197
- image_bytes_state = gr.State(None)
198
-
199
  # Input and Output Components
200
  with gr.Row():
201
  with gr.Column(scale=3):
@@ -206,18 +160,8 @@ def create_gradio_interface():
206
  lines=3
207
  )
208
 
209
- # Format Selection Dropdown
210
- format_dropdown = gr.Dropdown(
211
- choices=['PNG', 'JPEG', 'WebP'],
212
- value='PNG',
213
- label="Output Image Format"
214
- )
215
-
216
  # Generate Button
217
  generate_button = gr.Button("✨ Generate Image", variant="primary")
218
-
219
- # Download Button
220
- download_button = gr.Button("💾 Download Image", variant="secondary")
221
 
222
  # Output Image Display
223
  with gr.Column(scale=4):
@@ -231,30 +175,10 @@ def create_gradio_interface():
231
  status_output = gr.Textbox(label="Status")
232
 
233
  # Event Handlers
234
- generate_result = generate_button.click(
235
  fn=generate_image,
236
- inputs=[text_input, format_dropdown],
237
- outputs=[output_image, status_output, image_bytes_state]
238
- )
239
-
240
- # Download event handler
241
- def download_image(image_bytes):
242
- if image_bytes is None:
243
- return None
244
-
245
- # Create a temporary file
246
- with tempfile.NamedTemporaryFile(
247
- delete=False,
248
- suffix='.png', # Default to PNG
249
- prefix='ai_generated_'
250
- ) as temp_file:
251
- temp_file.write(image_bytes)
252
- return temp_file.name
253
-
254
- download_button.click(
255
- fn=download_image,
256
- inputs=[image_bytes_state],
257
- outputs=gr.File(label="Download Generated Image")
258
  )
259
 
260
  return demo
 
3
  from PIL import Image
4
  import io
5
  import requests
 
6
  from typing import Optional, Tuple
7
 
8
  def load_environment():
 
20
 
21
  return os.getenv("HF_TOKEN")
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def craft_realistic_prompt(base_prompt: str) -> str:
24
  """
25
  Enhance prompts for more photorealistic results
 
107
 
108
  raise RuntimeError("Unexpected error in image generation")
109
 
110
+ def generate_image(prompt: str) -> Tuple[Optional[Image.Image], str]:
111
  """
112
  Generate an image from a text prompt.
113
 
114
  Args:
115
  prompt (str): Text description for image generation
 
116
 
117
  Returns:
118
+ Tuple[Optional[Image.Image], str]:
119
+ Generated PIL Image and status message
120
  """
121
  try:
122
  # Validate prompt
123
  if not prompt or not prompt.strip():
124
+ return None, "Error: Prompt cannot be empty"
125
 
126
  # Generate image bytes
127
  image_bytes = query_hf_api(prompt)
 
129
  # Convert to PIL Image
130
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
131
 
132
+ return image, "Image generated successfully!"
 
 
 
133
 
134
  except Exception as e:
135
  print(f"Image generation error: {e}")
136
+ return None, f"Error: {str(e)}"
137
 
138
  def create_gradio_interface():
139
  """
 
150
  gr.Markdown("# 🎨 AI Image Generator")
151
  gr.Markdown("Generate stunning images from your text prompts using AI!")
152
 
 
 
 
153
  # Input and Output Components
154
  with gr.Row():
155
  with gr.Column(scale=3):
 
160
  lines=3
161
  )
162
 
 
 
 
 
 
 
 
163
  # Generate Button
164
  generate_button = gr.Button("✨ Generate Image", variant="primary")
 
 
 
165
 
166
  # Output Image Display
167
  with gr.Column(scale=4):
 
175
  status_output = gr.Textbox(label="Status")
176
 
177
  # Event Handlers
178
+ generate_button.click(
179
  fn=generate_image,
180
+ inputs=[text_input],
181
+ outputs=[output_image, status_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  )
183
 
184
  return demo