File size: 2,479 Bytes
b511d75
8d1bd48
 
9d3c685
8d1bd48
 
b511d75
 
9d3c685
 
 
8d1bd48
9d3c685
8d1bd48
9d3c685
 
 
b511d75
8d1bd48
9d3c685
 
 
 
 
b511d75
9d3c685
 
b511d75
9d3c685
b33083d
9d3c685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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)