Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,12 +9,9 @@ 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(
|
| 18 |
os.makedirs(HISTORY_DIR, exist_ok=True)
|
| 19 |
ZIP_PATH = os.path.join(BASE_DIR, "image_history.zip")
|
| 20 |
|
|
@@ -26,8 +23,16 @@ if not os.path.exists(HISTORY_METADATA):
|
|
| 26 |
|
| 27 |
def load_metadata():
|
| 28 |
"""Load the metadata file"""
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
def save_image(image, username, prompt):
|
| 33 |
"""Save an image and record metadata"""
|
|
@@ -51,41 +56,98 @@ def get_history(username=None):
|
|
| 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 |
-
|
| 59 |
for item in metadata:
|
| 60 |
if os.path.exists(item["path"]):
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 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 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
# Add metadata file
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
with gr.Blocks(title="Imagen 4.0 Generator") as demo:
|
| 91 |
gr.HTML("""
|
|
@@ -117,90 +179,31 @@ with gr.Blocks(title="Imagen 4.0 Generator") as demo:
|
|
| 117 |
submit_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
|
| 118 |
|
| 119 |
# Example prompts
|
| 120 |
-
|
| 121 |
-
|
| 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 |
-
|
| 128 |
-
|
| 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 |
-
|
| 172 |
-
|
| 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 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 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,
|
| 201 |
outputs=output_image
|
| 202 |
).then(
|
| 203 |
-
fn=
|
| 204 |
inputs=username_input,
|
| 205 |
outputs=history_gallery
|
| 206 |
)
|
|
@@ -209,34 +212,16 @@ with gr.Blocks(title="Imagen 4.0 Generator") as demo:
|
|
| 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(
|
| 218 |
fn=download_history,
|
|
|
|
| 219 |
outputs=download_zip_file
|
| 220 |
).then(
|
| 221 |
lambda: gr.update(visible=True),
|
| 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()
|
|
|
|
| 9 |
from datetime import datetime
|
| 10 |
import zipfile
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
# Persistent storage setup
|
| 13 |
BASE_DIR = os.path.abspath(os.getcwd())
|
| 14 |
+
HISTORY_DIR = os.path.join(BASE_DIR, "image_history") # Fixed typo: BASE_dir -> BASE_DIR
|
| 15 |
os.makedirs(HISTORY_DIR, exist_ok=True)
|
| 16 |
ZIP_PATH = os.path.join(BASE_DIR, "image_history.zip")
|
| 17 |
|
|
|
|
| 23 |
|
| 24 |
def load_metadata():
|
| 25 |
"""Load the metadata file"""
|
| 26 |
+
try:
|
| 27 |
+
with open(HISTORY_METADATA, "r") as f:
|
| 28 |
+
return json.load(f)
|
| 29 |
+
except (json.JSONDecodeError, FileNotFoundError):
|
| 30 |
+
return []
|
| 31 |
+
|
| 32 |
+
def save_metadata(metadata):
|
| 33 |
+
"""Save metadata to file"""
|
| 34 |
+
with open(HISTORY_METADATA, "w") as f:
|
| 35 |
+
json.dump(metadata, f, indent=2)
|
| 36 |
|
| 37 |
def save_image(image, username, prompt):
|
| 38 |
"""Save an image and record metadata"""
|
|
|
|
| 56 |
metadata = load_metadata()
|
| 57 |
|
| 58 |
# Filter by username if provided
|
| 59 |
+
if username and username.strip():
|
| 60 |
+
metadata = [m for m in metadata if m["username"].lower() == username.lower().strip()]
|
| 61 |
|
| 62 |
+
# Prepare gallery data - return list of (image_path, label) tuples
|
| 63 |
+
gallery_data = []
|
| 64 |
for item in metadata:
|
| 65 |
if os.path.exists(item["path"]):
|
| 66 |
+
label = f"{item['username']} - {item['timestamp'].split('T')[0]}"
|
| 67 |
+
gallery_data.append((item["path"], label))
|
| 68 |
+
|
| 69 |
+
return gallery_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
def download_history(username=None):
|
| 72 |
"""Download history as ZIP file"""
|
| 73 |
+
zip_path = os.path.join(BASE_DIR, f"{username or 'all'}_history.zip")
|
| 74 |
+
|
| 75 |
+
with zipfile.ZipFile(zip_path, "w") as zipf:
|
| 76 |
+
metadata = load_metadata()
|
| 77 |
+
|
| 78 |
+
# Filter by username if provided
|
| 79 |
+
if username and username.strip():
|
| 80 |
+
metadata = [m for m in metadata if m["username"].lower() == username.lower().strip()]
|
| 81 |
+
|
| 82 |
+
# Add image files
|
| 83 |
+
for item in metadata:
|
| 84 |
+
if os.path.exists(item["path"]):
|
| 85 |
+
arcname = os.path.basename(item["path"])
|
| 86 |
+
zipf.write(item["path"], arcname=arcname)
|
| 87 |
|
| 88 |
# Add metadata file
|
| 89 |
+
metadata_str = json.dumps(metadata, indent=2)
|
| 90 |
+
zipf.writestr("metadata.json", metadata_str)
|
| 91 |
+
|
| 92 |
+
return zip_path
|
| 93 |
+
|
| 94 |
+
def generate_image(prompt, username):
|
| 95 |
+
"""Generate image using Imagen 4.0 API"""
|
| 96 |
+
if not username or not username.strip():
|
| 97 |
+
raise gr.Error("Username cannot be empty")
|
| 98 |
+
|
| 99 |
+
if not prompt or not prompt.strip():
|
| 100 |
+
raise gr.Error("Prompt cannot be empty")
|
| 101 |
|
| 102 |
+
# Get API key from environment variable
|
| 103 |
+
api_key = os.environ.get("BYTEZ_API_KEY")
|
| 104 |
+
if not api_key:
|
| 105 |
+
raise gr.Error("BYTEZ_API_KEY environment variable not set")
|
| 106 |
+
|
| 107 |
+
headers = {
|
| 108 |
+
"Authorization": api_key,
|
| 109 |
+
"Content-Type": "application/json"
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
payload = {
|
| 113 |
+
"text": prompt.strip(),
|
| 114 |
+
"aspect_ratio": "1:1"
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
response = requests.post(
|
| 119 |
+
"https://api.bytez.com/models/v2/google/imagen-4.0-fast-generate-001",
|
| 120 |
+
headers=headers,
|
| 121 |
+
json=payload,
|
| 122 |
+
timeout=60
|
| 123 |
+
)
|
| 124 |
+
response.raise_for_status()
|
| 125 |
+
|
| 126 |
+
result = response.json()
|
| 127 |
+
if not result.get("results") or not isinstance(result["results"], list) or len(result["results"]) == 0:
|
| 128 |
+
raise gr.Error("API returned no results")
|
| 129 |
+
|
| 130 |
+
# Decode base64 image
|
| 131 |
+
img_data = base64.b64decode(result["results"][0]["base64"])
|
| 132 |
+
img = Image.open(BytesIO(img_data))
|
| 133 |
+
|
| 134 |
+
# Save to history
|
| 135 |
+
saved_path = save_image(img, username.strip(), prompt.strip())
|
| 136 |
+
return saved_path
|
| 137 |
+
|
| 138 |
+
except requests.exceptions.RequestException as e:
|
| 139 |
+
error_msg = f"API request failed: {str(e)}"
|
| 140 |
+
if hasattr(e, 'response') and e.response is not None:
|
| 141 |
+
try:
|
| 142 |
+
error_detail = e.response.json().get('error', {}).get('message', '')
|
| 143 |
+
if error_detail:
|
| 144 |
+
error_msg += f"\n{error_detail}"
|
| 145 |
+
except:
|
| 146 |
+
error_msg += f"\nStatus {e.response.status_code}: {e.response.text[:200]}"
|
| 147 |
+
raise gr.Error(error_msg)
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
raise gr.Error(f"Image generation failed: {str(e)}")
|
| 151 |
|
| 152 |
with gr.Blocks(title="Imagen 4.0 Generator") as demo:
|
| 153 |
gr.HTML("""
|
|
|
|
| 179 |
submit_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
|
| 180 |
|
| 181 |
# Example prompts
|
| 182 |
+
gr.Examples(
|
| 183 |
+
examples=[
|
| 184 |
+
["A cyberpunk cat wearing neon goggles, digital art style"],
|
| 185 |
+
["Mountain landscape at sunset with northern lights, photorealistic"],
|
| 186 |
+
["Steampunk airship floating above Victorian city, detailed illustration"],
|
| 187 |
+
["Minimalist logo of a bird made from geometric shapes, blue and white"]
|
| 188 |
+
],
|
| 189 |
+
inputs=prompt_input,
|
| 190 |
+
label="💡 Example Prompts"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
)
|
| 192 |
|
| 193 |
+
download_zip_btn = gr.Button("📥 Download Your History ZIP", variant="secondary")
|
| 194 |
+
download_zip_file = gr.File(label="Download ZIP", visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
with gr.Column(scale=2):
|
| 197 |
+
output_image = gr.Image(label="Generated Image", height=512)
|
| 198 |
+
history_gallery = gr.Gallery(label="Your History", columns=3, preview=True, object_fit="contain")
|
| 199 |
+
|
| 200 |
+
# Event handlers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
submit_btn.click(
|
| 202 |
fn=generate_image,
|
| 203 |
+
inputs=[prompt_input, username_input],
|
| 204 |
outputs=output_image
|
| 205 |
).then(
|
| 206 |
+
fn=get_history,
|
| 207 |
inputs=username_input,
|
| 208 |
outputs=history_gallery
|
| 209 |
)
|
|
|
|
| 212 |
fn=get_history,
|
| 213 |
inputs=username_input,
|
| 214 |
outputs=history_gallery
|
|
|
|
|
|
|
|
|
|
| 215 |
)
|
| 216 |
|
| 217 |
download_zip_btn.click(
|
| 218 |
fn=download_history,
|
| 219 |
+
inputs=username_input,
|
| 220 |
outputs=download_zip_file
|
| 221 |
).then(
|
| 222 |
lambda: gr.update(visible=True),
|
| 223 |
outputs=download_zip_file
|
| 224 |
)
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
if __name__ == "__main__":
|
| 227 |
demo.launch()
|