File size: 5,927 Bytes
459b368
5aa5b65
 
5df9578
 
5aa5b65
3344589
3837c00
3344589
 
 
459b368
3344589
 
 
 
 
459b368
3344589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b65
3344589
5aa5b65
3344589
5aa5b65
459b368
3837c00
3344589
 
5aa5b65
 
 
 
3344589
5aa5b65
3344589
 
5aa5b65
3837c00
3344589
 
 
 
 
 
 
5aa5b65
3344589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b65
3344589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459b368
3344589
 
 
 
 
 
a54b29f
3344589
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import gradio as gr
import random
from PIL import Image, ImageDraw, ImageFont
import requests
from io import BytesIO
import os
import time

# Configuration
HF_TOKEN = "hf_..."  # Remplacez par votre token Hugging Face
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"

STYLES = {
    "signage": "Signalétique Professionnelle",
    "poster": "Affiche Artistique",
    "silhouette": "Silhouette Décorative"
}

FORMATS = ["A4", "A3", "A2", "A1"]
MATERIALS = ["Lisse", "Ondulé", "Kraft"]

PROMPT_SUGGESTIONS = {
    "signage": [
        "Panneau directionnel moderne en carton recyclé, style minimaliste",
        "Présentoir écologique pour boutique, motifs naturels",
        "Signalétique murale en carton kraft, design épuré"
    ],
    "poster": [
        "Affiche artistique sur carton texturé, thème environnemental",
        "Poster graphique moderne, motifs géométriques en relief",
        "Design abstrait sur carton ondulé, couleurs naturelles"
    ],
    "silhouette": [
        "Découpe décorative florale en carton, style organique",
        "Silhouette architecturale moderne en carton recyclé",
        "Motif géométrique découpé, effet d'ombre et lumière"
    ]
}

STYLE_PROMPTS = {
    "signage": "professional signage design, minimalist, clean, photorealistic",
    "poster": "artistic poster design, creative, expressive, highly detailed",
    "silhouette": "decorative silhouette, elegant cutout design, clear shape"
}

def create_error_image(message):
    """Crée une image d'erreur avec un message."""
    img = Image.new('RGB', (512, 512), color='lightgray')
    d = ImageDraw.Draw(img)
    font = ImageFont.load_default()
    d.text((10,10), message, fill=(0,0,0), font=font)
    return img

def generate_image(prompt, style, format_size, material):
    """Génère une image via l'API Hugging Face avec gestion des erreurs et retries."""
    enhanced_prompt = f"a {material} cardboard {style} design showing {prompt}, {STYLE_PROMPTS[style]}, professional photography, 8k uhd, detailed"
    
    payload = {
        "inputs": enhanced_prompt,
        "negative_prompt": "low quality, blurry, bad anatomy, distorted, disfigured, pixelated",
        "num_inference_steps": 40,
        "guidance_scale": 7.5,
        "width": 768,
        "height": 768
    }

    headers = {"Authorization": f"Bearer {HF_TOKEN}"}

    max_retries = 3
    for attempt in range(max_retries):
        try:
            response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            return Image.open(BytesIO(response.content))
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                print(f"Erreur API après {max_retries} tentatives: {str(e)}")
                return create_error_image(f"Erreur API: {str(e)}")
            time.sleep(2 ** attempt)  # Attente exponentielle entre les tentatives

def update_suggestions(style):
    """Met à jour les suggestions de prompts selon le style choisi."""
    return gr.Dropdown(choices=PROMPT_SUGGESTIONS.get(style, []))

def apply_watermark(image):
    """Applique un filigrane à l'image générée."""
    draw = ImageDraw.Draw(image)
    font = ImageFont.load_default()
    text = "Equity Creation Studio"
    textwidth, textheight = draw.textsize(text, font)
    width, height = image.size
    x = width - textwidth - 10
    y = height - textheight - 10
    draw.text((x, y), text, font=font, fill=(255, 255, 255, 128))
    return image

def generate_and_process(prompt, style, format_size, material):
    """Génère l'image et applique le post-traitement."""
    image = generate_image(prompt, style, format_size, material)
    return apply_watermark(image)

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # 🎨 Equity Creation Studio
        ### Studio de Design Éco-responsable
        Transformez vos idées en créations durables avec notre générateur d'images IA
        """
    )
    
    with gr.Row():
        with gr.Column(scale=1):
            style = gr.Radio(
                choices=list(STYLES.keys()),
                value="signage",
                label="Style de Création",
                info="Choisissez le type de design souhaité"
            )
            
            format_size = gr.Radio(
                choices=FORMATS,
                value="A4",
                label="Format",
                info="Sélectionnez la taille de votre création"
            )
            
            material = gr.Radio(
                choices=MATERIALS,
                value="Lisse",
                label="Type de Carton",
                info="Choisissez votre matériau"
            )
            
            prompt = gr.Textbox(
                lines=3,
                label="Description",
                placeholder="Décrivez votre vision..."
            )
            
            suggestions = gr.Dropdown(
                choices=PROMPT_SUGGESTIONS["signage"],
                label="Suggestions de prompts",
                info="Sélectionnez une suggestion ou écrivez votre propre description"
            )
            
            generate_btn = gr.Button("🪄 Générer", variant="primary")

        with gr.Column(scale=2):
            output = gr.Image(label="Image générée")

    style.change(fn=update_suggestions, inputs=[style], outputs=[suggestions])
    suggestions.change(fn=lambda x: x, inputs=[suggestions], outputs=[prompt])
    generate_btn.click(
        fn=generate_and_process,
        inputs=[prompt, style, format_size, material],
        outputs=[output]
    )

    gr.Markdown(
        """
        ### 🌿 Design Éco-responsable
        Equity Creation Studio transforme vos déchets carton en œuvres d'art
        """
    )

if __name__ == "__main__":
    demo.launch()