Spaces:
Sleeping
Sleeping
import os | |
import gradio as gr | |
import google.generativeai as genai | |
from PIL import Image | |
import io | |
import base64 | |
import time | |
# Configuration optimized for Hugging Face | |
MAX_RETRIES = 3 | |
TIMEOUT = 10 # Keep under 20s Hugging Face limit | |
# Simplified style instructions for faster processing | |
STYLE_INSTRUCTIONS = { | |
"General": "Describe as Flux prompt focusing on key elements", | |
"Vector": "Clean vector style with sharp lines and B&W", | |
"Realistic": "Photorealistic details with accurate textures", | |
} | |
def optimize_image(img): | |
"""Fast image optimization for web""" | |
img = img.convert("RGB") | |
img.thumbnail((512, 512)) # Reduce image size | |
return img | |
def generate_prompt(image, api_key, style): | |
for attempt in range(MAX_RETRIES): | |
try: | |
start_time = time.time() | |
# Configure API | |
genai.configure(api_key=api_key) | |
model = genai.GenerativeModel('gemini-pro-vision') | |
# Optimize image | |
img = optimize_image(image) | |
img_byte_arr = io.BytesIO() | |
img.save(img_byte_arr, format='JPEG', quality=85) | |
# Timeout control | |
if time.time() - start_time > TIMEOUT - 2: | |
raise TimeoutError("Image processing too slow") | |
response = model.generate_content([ | |
STYLE_INSTRUCTIONS[style], | |
{"mime_type": "image/jpeg", "data": img_byte_arr.getvalue()} | |
], request_options={"timeout": TIMEOUT}) | |
return response.text | |
except Exception as e: | |
if attempt == MAX_RETRIES - 1: | |
return f"Error: {str(e)}" | |
time.sleep(1) | |
# Hugging Face optimized interface | |
with gr.Blocks() as app: | |
gr.Markdown("## π HF-Friendly Flux Generator") | |
with gr.Row(): | |
api_key = gr.Textbox(label="Gemini Key", type="password") | |
style = gr.Dropdown(list(STYLE_INSTRUCTIONS), label="Style") | |
image_input = gr.Image(type="pil", label="Upload Design") | |
generate_btn = gr.Button("Generate", variant="primary") | |
output = gr.Textbox(label="Prompt", interactive=False) | |
generate_btn.click( | |
generate_prompt, | |
inputs=[image_input, api_key, style], | |
outputs=output, | |
concurrency_limit=3 # Better HF resource management | |
) | |
# HF-specific launch settings | |
app.queue(concurrency_count=3, max_size=20).launch(debug=True) |