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

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -0
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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())
15
+ HISTORY_DIR = os.path.join(BASE_DIR, "image_history")
16
+ os.makedirs(HISTORY_DIR, exist_ok=True)
17
+ ZIP_PATH = os.path.join(BASE_DIR, "image_history.zip")
18
+
19
+ # Store metadata
20
+ HISTORY_METADATA = os.path.join(HISTORY_DIR, "metadata.json")
21
+ if not os.path.exists(HISTORY_METADATA):
22
+ with open(HISTORY_METADATA, "w") as f:
23
+ json.dump([], f)
24
+
25
+ def load_metadata():
26
+ with open(HISTORY_METADATA, "r") as f:
27
+ return json.load(f)
28
+
29
+ def save_metadata(metadata):
30
+ with open(HISTORY_METADATA, "w") as f:
31
+ json.dump(metadata, f, indent=2)
32
+
33
+ def save_image(image: Image.Image, username, prompt):
34
+ filename = os.path.join(HISTORY_DIR, f"{uuid.uuid4()}.png")
35
+ image.save(filename)
36
+ metadata = load_metadata()
37
+ metadata.append({
38
+ "path": filename,
39
+ "username": username,
40
+ "prompt": prompt,
41
+ "timestamp": datetime.now().isoformat()
42
+ })
43
+ save_metadata(metadata)
44
+ return filename
45
+
46
+ def get_history(username=None):
47
+ metadata = load_metadata()
48
+ if username:
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:
56
+ for root, dirs, files in os.walk(HISTORY_DIR):
57
+ for file in files:
58
+ if file != "metadata.json":
59
+ zipf.write(os.path.join(root, file), arcname=file)
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,
71
+ "Content-Type": "application/json"
72
+ }
73
+
74
+ payload = {
75
+ "text": prompt,
76
+ "aspect_ratio": aspect_ratio
77
+ }
78
+
79
+ try:
80
+ response = requests.post(
81
+ "https://api.bytez.com/models/v2/google/imagen-4.0-fast-generate-001",
82
+ headers=headers,
83
+ json=payload,
84
+ timeout=45
85
+ )
86
+ response.raise_for_status()
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",
142
+ label="Username",
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()