SiddhJagani commited on
Commit
d5bbca2
·
verified ·
1 Parent(s): 35390b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -88
app.py CHANGED
@@ -2,113 +2,90 @@ 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
- bytez_api_key = os.getenv("BYTEZ_API_KEY")
 
13
 
14
  # Persistent storage setup
15
  BASE_DIR = os.path.abspath(os.getcwd())
16
- HISTORY_DIR = os.path.join(BASE_DIR, "image_history")
17
  os.makedirs(HISTORY_DIR, exist_ok=True)
18
  ZIP_PATH = os.path.join(BASE_DIR, "image_history.zip")
19
 
20
- # Store metadata
21
  HISTORY_METADATA = os.path.join(HISTORY_DIR, "metadata.json")
22
  if not os.path.exists(HISTORY_METADATA):
23
  with open(HISTORY_METADATA, "w") as f:
24
  json.dump([], f)
25
 
26
  def load_metadata():
 
27
  with open(HISTORY_METADATA, "r") as f:
28
  return json.load(f)
29
 
30
- def save_metadata(metadata):
31
- with open(HISTORY_METADATA, "w") as f:
32
- json.dump(metadata, f, indent=2)
33
-
34
- def save_image(image: Image.Image, username, prompt):
35
  filename = os.path.join(HISTORY_DIR, f"{uuid.uuid4()}.png")
36
  image.save(filename)
 
37
  metadata = load_metadata()
 
38
  metadata.append({
39
  "path": filename,
40
  "username": username,
41
  "prompt": prompt,
42
- "timestamp": datetime.now().isoformat()
43
  })
 
44
  save_metadata(metadata)
45
  return filename
46
 
47
  def get_history(username=None):
 
48
  metadata = load_metadata()
 
 
49
  if username:
50
- metadata = [m for m in metadata if m["username"] == username]
51
- else:
52
- return [], []
53
- return [(m["path"], f"{m['username']} - {m['timestamp']}") for m in metadata]
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  def download_history():
 
56
  with zipfile.ZipFile(ZIP_PATH, "w") as zipf:
 
57
  for root, dirs, files in os.walk(HISTORY_DIR):
58
  for file in files:
59
- if file != "metadata.json":
60
- zipf.write(os.path.join(root, file), arcname=file)
61
- zipf.write(HISTORY_METADATA, arcname="metadata.json")
62
- return ZIP_PATH
63
-
64
- def generate_image(prompt, bytez_api_key, username):
65
- if not username.strip():
66
- raise gr.Error("Username cannot be empty")
67
-
68
- api_key = bytez_api_key.strip() if bytez_api_key and bytez_api_key.strip() != "" else os.environ.get("BYTEZ_API_KEY")
69
-
70
- if not api_key:
71
- raise gr.Error("No API key provided. Set BYTEZ_API_KEY environment variable or enter in UI.")
72
-
73
- headers = {
74
- "Authorization": api_key,
75
- "Content-Type": "application/json"
76
- }
77
-
78
- payload = {
79
- "text": prompt,
80
- #"aspect_ratio": "1:1" # Fixed to 1:1 ratio as requested
81
- }
82
-
83
- try:
84
- response = requests.post(
85
- "https://api.bytez.com/models/v2/google/imagen-4.0-fast-generate-001",
86
- headers=headers,
87
- json=payload,
88
- timeout=45
89
- )
90
- response.raise_for_status()
91
-
92
- result = response.json()
93
- if not result.get("results") or not isinstance(result["results"], list) or len(result["results"]) == 0:
94
- raise gr.Error("No results returned from API")
95
-
96
- # Decode base64 image
97
- img_data = base64.b64decode(result["results"][0]["base64"])
98
- img = Image.open(BytesIO(img_data))
99
-
100
- # Save to history
101
- saved_path = save_image(img, username, prompt)
102
 
103
- return saved_path
 
 
104
 
105
- except requests.exceptions.RequestException as e:
106
- error_msg = f"API request failed: {str(e)}"
107
- if hasattr(e, 'response') and e.response is not None:
108
- error_msg += f"\nStatus: {e.response.status_code}\nResponse: {e.response.text}"
109
- raise gr.Error(error_msg)
110
- except Exception as e:
111
- raise gr.Error(f"Image generation failed: {str(e)}")
112
 
113
  with gr.Blocks(title="Imagen 4.0 Generator") as demo:
114
  gr.HTML("""
@@ -122,49 +99,108 @@ with gr.Blocks(title="Imagen 4.0 Generator") as demo:
122
  </div>
123
  </div>
124
  """)
125
-
126
  with gr.Row():
127
  with gr.Column(scale=1):
128
  username_input = gr.Textbox(
129
- lines=1,
130
- placeholder="Enter your username",
131
  label="Username",
132
  info="Required for saving history"
133
  )
134
  prompt_input = gr.Textbox(
135
- lines=4,
136
- placeholder="A Raspberry Pi SBC on a wooden desk with electronic components",
137
  label="Prompt",
138
  info="Be descriptive for best results"
139
  )
140
  submit_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
141
 
142
- gr.Examples(
143
- examples=[
144
- ["A cyberpunk cat wearing neon goggles, digital art style"],
145
- ["Mountain landscape at sunset with northern lights, photorealistic"],
146
- ["Steampunk airship floating above Victorian city, detailed illustration"],
147
- ["Minimalist logo of a bird made from geometric shapes, blue and white"]
148
- ],
149
- inputs=prompt_input,
150
- label="💡 Example Prompts"
151
- )
152
-
 
 
153
  with gr.Column(scale=2):
154
- output_image = gr.Image(label="Generated Image", height=512)
155
- history_gallery = gr.Gallery(label="Your History", columns=3, preview=True)
156
 
157
- with gr.Row():
158
- download_zip_btn = gr.Button("📥 Download History ZIP")
159
  download_zip_file = gr.File(label="Download ZIP", visible=False)
160
-
161
- # Event handlers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  submit_btn.click(
163
  fn=generate_image,
164
  inputs=[prompt_input, bytez_api_key, username_input],
165
  outputs=output_image
166
  ).then(
167
- fn=get_history,
168
  inputs=username_input,
169
  outputs=history_gallery
170
  )
@@ -173,6 +209,9 @@ with gr.Blocks(title="Imagen 4.0 Generator") as demo:
173
  fn=get_history,
174
  inputs=username_input,
175
  outputs=history_gallery
 
 
 
176
  )
177
 
178
  download_zip_btn.click(
@@ -183,5 +222,21 @@ with gr.Blocks(title="Imagen 4.0 Generator") as demo:
183
  outputs=download_zip_file
184
  )
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  if __name__ == "__main__":
187
  demo.launch()
 
2
  import base64
3
  import json
4
  import requests
5
+ import gr
6
  from io import BytesIO
7
  from PIL import Image
8
  import uuid
9
  from datetime import datetime
10
  import zipfile
11
 
12
+ # Load environment variables
13
+ bytez_api_key = os.getenv("BYTEZ_API_KEY") or input("Enter Bytez API Key (press Enter for default): ")
14
 
15
  # Persistent storage setup
16
  BASE_DIR = os.path.abspath(os.getcwd())
17
+ HISTORY_DIR = os.path.join(BASE_dir, "image_history")
18
  os.makedirs(HISTORY_DIR, exist_ok=True)
19
  ZIP_PATH = os.path.join(BASE_DIR, "image_history.zip")
20
 
21
+ # Metadata file
22
  HISTORY_METADATA = os.path.join(HISTORY_DIR, "metadata.json")
23
  if not os.path.exists(HISTORY_METADATA):
24
  with open(HISTORY_METADATA, "w") as f:
25
  json.dump([], f)
26
 
27
  def load_metadata():
28
+ """Load the metadata file"""
29
  with open(HISTORY_METADATA, "r") as f:
30
  return json.load(f)
31
 
32
+ def save_image(image, username, prompt):
33
+ """Save an image and record metadata"""
 
 
 
34
  filename = os.path.join(HISTORY_DIR, f"{uuid.uuid4()}.png")
35
  image.save(filename)
36
+
37
  metadata = load_metadata()
38
+ timestamp = datetime.now().isoformat()
39
  metadata.append({
40
  "path": filename,
41
  "username": username,
42
  "prompt": prompt,
43
+ "timestamp": timestamp
44
  })
45
+
46
  save_metadata(metadata)
47
  return filename
48
 
49
  def get_history(username=None):
50
+ """Get image history by username"""
51
  metadata = load_metadata()
52
+
53
+ # Filter by username if provided
54
  if username:
55
+ metadata = [m for m in metadata if m["username"].lower() == username.lower()]
56
+
57
+ # Prepare gallery data
58
+ history_data = []
59
+ for item in metadata:
60
+ if os.path.exists(item["path"]):
61
+ with open(item["path"], "rb") as img_file:
62
+ img = Image.open(img_file)
63
+ img.load() # Required for getting size
64
+ history_data.append({
65
+ "image": img,
66
+ "username": item["username"],
67
+ "timestamp": item["timestamp"]
68
+ })
69
+
70
+ return history_data
71
 
72
  def download_history():
73
+ """Download history as ZIP file"""
74
  with zipfile.ZipFile(ZIP_PATH, "w") as zipf:
75
+ # Add all image files
76
  for root, dirs, files in os.walk(HISTORY_DIR):
77
  for file in files:
78
+ if not file.endswith(".json"):
79
+ file_path = os.path.join(root, file)
80
+ if os.path.exists(file_path):
81
+ with open(file_path, "rb") as img_file:
82
+ zipf.write(img_file, arcname=file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # Add metadata file
85
+ with open(HISTORY_METADATA, "rb") as meta_file:
86
+ zipf.write(meta_file, arcname="metadata.json")
87
 
88
+ return ZIP_PATH
 
 
 
 
 
 
89
 
90
  with gr.Blocks(title="Imagen 4.0 Generator") as demo:
91
  gr.HTML("""
 
99
  </div>
100
  </div>
101
  """)
102
+
103
  with gr.Row():
104
  with gr.Column(scale=1):
105
  username_input = gr.Textbox(
106
+ lines=1,
107
+ placeholder="Enter your username",
108
  label="Username",
109
  info="Required for saving history"
110
  )
111
  prompt_input = gr.Textbox(
112
+ lines=4,
113
+ placeholder="A Raspberry Pi SBC on a wooden desk with electronic components",
114
  label="Prompt",
115
  info="Be descriptive for best results"
116
  )
117
  submit_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
118
 
119
+ # Example prompts
120
+ with gr.Accordion("Example Prompts", open=False):
121
+ example_prompts = [
122
+ "A cyberpunk cat wearing neon goggles, digital art style",
123
+ "Mountain landscape at sunset with northern lights, photorealistic",
124
+ "Steampunk airship floating above Victorian city, detailed illustration",
125
+ "Minimalist logo of a bird made from geometric shapes, blue and white"
126
+ ]
127
+ gr.Button("🔄 Refresh Examples").click(
128
+ fn=lambda: example_prompts,
129
+ outputs=gr.HighlightedText(label="Example Prompts")
130
+ )
131
+
132
  with gr.Column(scale=2):
133
+ output_image = gr.Image(label="Generated Image", height=512, visible=True)
134
+ history_gallery = gr.Gallery(label="Your History", columns=3, preview=True, visible=True)
135
 
136
+ with gr.Row(visible=False):
137
+ download_zip_btn = gr.Button("📥 Download History ZIP", variant="secondary")
138
  download_zip_file = gr.File(label="Download ZIP", visible=False)
139
+
140
+ # Generate image function
141
+ def generate_image(prompt, bytez_api_key, username):
142
+ if not username.strip():
143
+ raise gr.Error("Username cannot be empty")
144
+
145
+ # Get API key from Bytez environment variable as fallback
146
+ api_key = bytez_api_key.strip() if bytez_api_key and bytez_api_key.strip() != "" else os.environ.get("BYTEZ_API_KEY")
147
+
148
+ if not api_key:
149
+ raise gr.Error("No API key provided. Set BYTEZ_API_KEY environment variable or enter in UI.")
150
+
151
+ # Create headers with authentication
152
+ headers = {
153
+ "Authorization": api_key,
154
+ "Content-Type": "application/json"
155
+ }
156
+
157
+ # Prepare payload
158
+ payload = {
159
+ "text": prompt
160
+ }
161
+
162
+ # Send request to Bytez API
163
+ try:
164
+ response = requests.post(
165
+ "https://api.bytez.com/models/v2/google/imagen-4.0-fast-generate-001",
166
+ headers=headers,
167
+ json=payload,
168
+ timeout=45 # Increased timeout for image generation
169
+ )
170
+
171
+ # Check response
172
+ response.raise_for_status()
173
+
174
+ # Parse JSON response
175
+ result = response.json()
176
+
177
+ # Extract image data
178
+ if not result.get("results") or not isinstance(result["results"], list) or len(result["results"]) == 0:
179
+ raise gr.Error("No results returned from API")
180
+
181
+ img_data = base64.b64decode(result["results"][0]["base64"])
182
+ img = Image.open(BytesIO(img_data))
183
+
184
+ # Save image and return path
185
+ saved_path = save_image(img, username, prompt)
186
+ return saved_path
187
+
188
+ except requests.exceptions.RequestException as e:
189
+ error_msg = f"API request failed: {str(e)}"
190
+ if hasattr(e, 'response') and e.response is not None:
191
+ error_msg += f"\nStatus: {e.response.status_code}\nResponse: {e.response.text}"
192
+ raise gr.Error(error_msg)
193
+
194
+ except Exception as e:
195
+ raise gr.Error(f"Image generation failed: {str(e)}")
196
+
197
+ # Connect functions
198
  submit_btn.click(
199
  fn=generate_image,
200
  inputs=[prompt_input, bytez_api_key, username_input],
201
  outputs=output_image
202
  ).then(
203
+ fn=update_history_display,
204
  inputs=username_input,
205
  outputs=history_gallery
206
  )
 
209
  fn=get_history,
210
  inputs=username_input,
211
  outputs=history_gallery
212
+ ).then(
213
+ fn=update_image_visibility,
214
+ outputs=[output_image, history_gallery, download_zip_btn, download_zip_file]
215
  )
216
 
217
  download_zip_btn.click(
 
222
  outputs=download_zip_file
223
  )
224
 
225
+ def update_history_display(username):
226
+ """Update the history gallery display"""
227
+ try:
228
+ history_items = get_history(username)
229
+ return [item for item in history_items if item and os.path.exists(item["path"])]
230
+ except Exception as e:
231
+ raise gr.Error(f"Failed to load history: {str(e)}")
232
+
233
+ def update_image_visibility(output_image, history_gallery, download_zip_btn, download_zip_file):
234
+ """Update visibility of components when needed"""
235
+ # Show image and hide gallery initially
236
+ if output_image is None:
237
+ return None, [], None, None
238
+ else:
239
+ return output_image, [], download_zip_btn, download_zip_file
240
+
241
  if __name__ == "__main__":
242
  demo.launch()