SiddhJagani commited on
Commit
16ecd77
·
verified ·
1 Parent(s): 7ca28b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -73
app.py CHANGED
@@ -1,14 +1,13 @@
1
  import os
2
  import base64
3
- import zipfile
4
- import tempfile
5
- import uuid
6
  import json
7
  import requests
8
- from datetime import datetime
9
- from PIL import Image
10
  import gradio as gr
11
  from io import BytesIO
 
 
 
 
12
 
13
  # Persistent storage setup
14
  BASE_DIR = os.path.abspath(os.getcwd())
@@ -49,7 +48,7 @@ def get_history(username=None):
49
  metadata = [m for m in metadata if m["username"] == username]
50
  else:
51
  return [], []
52
- return [(m["path"], f"{m['username']} - {m['timestamp']}") for m in metadata], [(m["path"], f"{m['username']} - {m['timestamp']}") for m in metadata]
53
 
54
  def download_history():
55
  with zipfile.ZipFile(ZIP_PATH, "w") as zipf:
@@ -60,11 +59,14 @@ def download_history():
60
  zipf.write(HISTORY_METADATA, arcname="metadata.json")
61
  return ZIP_PATH
62
 
63
- def generate_image(prompt, bytez_api_key, aspect_ratio="1:1"):
 
 
 
64
  api_key = bytez_api_key.strip() if bytez_api_key and bytez_api_key.strip() != "" else os.environ.get("BYTEZ_API_KEY")
65
 
66
  if not api_key:
67
- raise ValueError("No API key provided. Set BYTEZ_API_KEY environment variable or enter in UI.")
68
 
69
  headers = {
70
  "Authorization": api_key,
@@ -73,7 +75,7 @@ def generate_image(prompt, bytez_api_key, aspect_ratio="1:1"):
73
 
74
  payload = {
75
  "text": prompt,
76
- "aspect_ratio": aspect_ratio
77
  }
78
 
79
  try:
@@ -87,55 +89,40 @@ def generate_image(prompt, bytez_api_key, aspect_ratio="1:1"):
87
 
88
  result = response.json()
89
  if not result.get("results") or not isinstance(result["results"], list) or len(result["results"]) == 0:
90
- raise ValueError("No results returned from API")
91
 
92
  # Decode base64 image
93
  img_data = base64.b64decode(result["results"][0]["base64"])
94
  img = Image.open(BytesIO(img_data))
95
- return img
 
 
 
 
96
 
97
  except requests.exceptions.RequestException as e:
98
  error_msg = f"API request failed: {str(e)}"
99
  if hasattr(e, 'response') and e.response is not None:
100
  error_msg += f"\nStatus: {e.response.status_code}\nResponse: {e.response.text}"
101
- raise Exception(error_msg)
102
  except Exception as e:
103
- raise Exception(f"Image generation failed: {str(e)}")
104
 
105
- def process_prompt(prompt, bytez_api_key, username, aspect_ratio):
106
- if not username.strip():
107
- raise ValueError("Username cannot be empty")
108
-
109
- # Generate image using Imagen API
110
- result_img = generate_image(prompt, bytez_api_key, aspect_ratio)
111
-
112
- # Save to history
113
- saved_path = save_image(result_img, username, prompt)
114
-
115
- # Return for gallery display
116
- return Image.open(saved_path), [(saved_path, f"{username}: {prompt}")]
117
-
118
- with gr.Blocks() as demo:
119
  gr.HTML("""
120
- <div style='display: flex; align-items: center; justify-content: center; gap: 20px'>
121
- <div style="background-color: var(--block-background-fill); border-radius: 8px">
122
- <img src="https://api.bytez.com/favicon.ico" style="width: 100px; height: 100px;">
123
  </div>
124
  <div>
125
- <h1>Imagen 4.0 Fast Generator</h1>
126
- <p>Text-to-image generation using Google's Imagen 4.0 model</p>
127
  </div>
128
  </div>
129
  """)
130
 
131
  with gr.Row():
132
- with gr.Column():
133
- bytez_api_key = gr.Textbox(
134
- lines=1,
135
- placeholder="Enter Bytez API Key (optional)",
136
- label="Bytez API Key",
137
- type="password"
138
- )
139
  username_input = gr.Textbox(
140
  lines=1,
141
  placeholder="Enter your username",
@@ -143,62 +130,56 @@ with gr.Blocks() as demo:
143
  info="Required for saving history"
144
  )
145
  prompt_input = gr.Textbox(
146
- lines=3,
147
  placeholder="A Raspberry Pi SBC on a wooden desk with electronic components",
148
  label="Prompt",
149
  info="Be descriptive for best results"
150
  )
151
- aspect_ratio = gr.Dropdown(
152
- choices=["1:1", "16:9", "9:16"],
153
- value="1:1",
154
- label="Aspect Ratio"
 
 
 
 
 
 
 
155
  )
156
- submit_btn = gr.Button("✨ Generate Image", variant="primary")
157
 
158
- with gr.Column():
159
- output_image = gr.Image(
160
- label="Generated Image",
161
- interactive=False
162
- )
163
- history_gallery = gr.Gallery(
164
- label="Your History",
165
- columns=2,
166
- preview=True
167
- )
168
  with gr.Row():
169
  download_zip_btn = gr.Button("📥 Download History ZIP")
170
- download_zip_file = gr.File(label="Download ZIP")
171
 
172
  # Event handlers
173
  submit_btn.click(
174
- fn=process_prompt,
175
- inputs=[prompt_input, bytez_api_key, username_input, aspect_ratio],
176
- outputs=[output_image, history_gallery],
177
- api_name="generate"
 
 
 
178
  )
179
 
180
  username_input.change(
181
  fn=get_history,
182
  inputs=username_input,
183
- outputs=[history_gallery, history_gallery]
184
  )
185
 
186
  download_zip_btn.click(
187
  fn=download_history,
188
  outputs=download_zip_file
 
 
 
189
  )
190
 
191
- # Add examples section
192
- gr.Examples(
193
- examples=[
194
- ["A cyberpunk cat wearing neon goggles, digital art style", "1:1"],
195
- ["Mountain landscape at sunset with northern lights, photorealistic", "16:9"],
196
- ["Steampunk airship floating above Victorian city, detailed illustration", "9:16"],
197
- ["Minimalist logo of a bird made from geometric shapes, blue and white", "1:1"]
198
- ],
199
- inputs=[prompt_input, aspect_ratio],
200
- label="💡 Example Prompts"
201
- )
202
-
203
  if __name__ == "__main__":
204
  demo.launch()
 
1
  import os
2
  import base64
 
 
 
3
  import json
4
  import requests
 
 
5
  import gradio as gr
6
  from io import BytesIO
7
+ from PIL import Image
8
+ import uuid
9
+ from datetime import datetime
10
+ import zipfile
11
 
12
  # Persistent storage setup
13
  BASE_DIR = os.path.abspath(os.getcwd())
 
48
  metadata = [m for m in metadata if m["username"] == username]
49
  else:
50
  return [], []
51
+ return [(m["path"], f"{m['username']} - {m['timestamp']}") for m in metadata]
52
 
53
  def download_history():
54
  with zipfile.ZipFile(ZIP_PATH, "w") as zipf:
 
59
  zipf.write(HISTORY_METADATA, arcname="metadata.json")
60
  return ZIP_PATH
61
 
62
+ def generate_image(prompt, bytez_api_key, username):
63
+ if not username.strip():
64
+ raise gr.Error("Username cannot be empty")
65
+
66
  api_key = bytez_api_key.strip() if bytez_api_key and bytez_api_key.strip() != "" else os.environ.get("BYTEZ_API_KEY")
67
 
68
  if not api_key:
69
+ raise gr.Error("No API key provided. Set BYTEZ_API_KEY environment variable or enter in UI.")
70
 
71
  headers = {
72
  "Authorization": api_key,
 
75
 
76
  payload = {
77
  "text": prompt,
78
+ #"aspect_ratio": "1:1" # Fixed to 1:1 ratio as requested
79
  }
80
 
81
  try:
 
89
 
90
  result = response.json()
91
  if not result.get("results") or not isinstance(result["results"], list) or len(result["results"]) == 0:
92
+ raise gr.Error("No results returned from API")
93
 
94
  # Decode base64 image
95
  img_data = base64.b64decode(result["results"][0]["base64"])
96
  img = Image.open(BytesIO(img_data))
97
+
98
+ # Save to history
99
+ saved_path = save_image(img, username, prompt)
100
+
101
+ return saved_path
102
 
103
  except requests.exceptions.RequestException as e:
104
  error_msg = f"API request failed: {str(e)}"
105
  if hasattr(e, 'response') and e.response is not None:
106
  error_msg += f"\nStatus: {e.response.status_code}\nResponse: {e.response.text}"
107
+ raise gr.Error(error_msg)
108
  except Exception as e:
109
+ raise gr.Error(f"Image generation failed: {str(e)}")
110
 
111
+ with gr.Blocks(title="Imagen 4.0 Generator") as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  gr.HTML("""
113
+ <div style='display: flex; align-items: center; justify-content: center; gap: 20px; margin-bottom: 20px'>
114
+ <div style="background-color: var(--block-background-fill); border-radius: 8px; padding: 10px">
115
+ <img src="https://api.bytez.com/favicon.ico" style="width: 80px; height: 80px;">
116
  </div>
117
  <div>
118
+ <h1 style="margin-bottom: 5px">Imagen 4.0 Fast Generator</h1>
119
+ <p style="margin-top: 0; color: var(--body-text-color-subdued)">Text-to-image generation using Google's Imagen 4.0 model</p>
120
  </div>
121
  </div>
122
  """)
123
 
124
  with gr.Row():
125
+ with gr.Column(scale=1):
 
 
 
 
 
 
126
  username_input = gr.Textbox(
127
  lines=1,
128
  placeholder="Enter your username",
 
130
  info="Required for saving history"
131
  )
132
  prompt_input = gr.Textbox(
133
+ lines=4,
134
  placeholder="A Raspberry Pi SBC on a wooden desk with electronic components",
135
  label="Prompt",
136
  info="Be descriptive for best results"
137
  )
138
+ submit_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
139
+
140
+ gr.Examples(
141
+ examples=[
142
+ ["A cyberpunk cat wearing neon goggles, digital art style"],
143
+ ["Mountain landscape at sunset with northern lights, photorealistic"],
144
+ ["Steampunk airship floating above Victorian city, detailed illustration"],
145
+ ["Minimalist logo of a bird made from geometric shapes, blue and white"]
146
+ ],
147
+ inputs=prompt_input,
148
+ label="💡 Example Prompts"
149
  )
 
150
 
151
+ with gr.Column(scale=2):
152
+ output_image = gr.Image(label="Generated Image", height=512)
153
+ history_gallery = gr.Gallery(label="Your History", columns=3, preview=True)
154
+
 
 
 
 
 
 
155
  with gr.Row():
156
  download_zip_btn = gr.Button("📥 Download History ZIP")
157
+ download_zip_file = gr.File(label="Download ZIP", visible=False)
158
 
159
  # Event handlers
160
  submit_btn.click(
161
+ fn=generate_image,
162
+ inputs=[prompt_input, bytez_api_key, username_input],
163
+ outputs=output_image
164
+ ).then(
165
+ fn=get_history,
166
+ inputs=username_input,
167
+ outputs=history_gallery
168
  )
169
 
170
  username_input.change(
171
  fn=get_history,
172
  inputs=username_input,
173
+ outputs=history_gallery
174
  )
175
 
176
  download_zip_btn.click(
177
  fn=download_history,
178
  outputs=download_zip_file
179
+ ).then(
180
+ lambda: gr.update(visible=True),
181
+ outputs=download_zip_file
182
  )
183
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  if __name__ == "__main__":
185
  demo.launch()