generart / app.py
Equityone's picture
Update app.py
ec700e0 verified
raw
history blame
10.1 kB
import gradio as gr
import os
from PIL import Image, ImageDraw, ImageFont
import requests
import io
# Configuration des styles artistiques
ART_STYLES = {
"Renaissance": {
"prompt_prefix": "ultra-detailed renaissance style artwork, masterful anatomical details, dramatic chiaroscuro lighting",
"guidance": 15.0,
"steps": 80,
"negative_prompt": "blurry, low quality, flat lighting, cartoon, modern"
},
"Impressionnisme": {
"prompt_prefix": "impressionist art style, vibrant brushstrokes, atmospheric lighting, monet-like technique",
"guidance": 12.0,
"steps": 65,
"negative_prompt": "sharp details, photorealistic, digital art"
},
"Art Moderne": {
"prompt_prefix": "modern art composition, bold geometric shapes, abstract elements, strong visual impact",
"guidance": 11.0,
"steps": 60,
"negative_prompt": "realistic, traditional, detailed texture"
},
"Illustration Pro": {
"prompt_prefix": "professional editorial illustration, sophisticated art style, high-end magazine quality",
"guidance": 13.5,
"steps": 70,
"negative_prompt": "amateur, basic, photographic"
},
"Néo Vintage": {
"prompt_prefix": "vintage poster design, retro aesthetic, limited color palette, screen printing style",
"guidance": 12.5,
"steps": 65,
"negative_prompt": "modern, digital, photorealistic"
},
"Encre Artistique": {
"prompt_prefix": "artistic ink illustration, dynamic brushwork, high contrast black and white, expressive strokes",
"guidance": 14.0,
"steps": 75,
"negative_prompt": "color, photographic, digital"
},
"Pop Art": {
"prompt_prefix": "pop art style, bold colors, halftone dots, comic book aesthetic, Warhol-inspired",
"guidance": 11.5,
"steps": 60,
"negative_prompt": "realistic, painterly, subtle"
},
"Dark Fantasy": {
"prompt_prefix": "dark fantasy art, atmospheric mood, dramatic lighting, mythological elements",
"guidance": 13.0,
"steps": 70,
"negative_prompt": "bright, cheerful, realistic photo"
}
}
# Collections thématiques
COLLECTIONS = {
"Nature Artistique": {
"prompts": ["artistic nature illustration", "stylized botanical elements"],
"styles": ["organic composition", "natural textures", "dynamic flow"],
"negative": "artificial, synthetic, urban"
},
"Portraits Expressifs": {
"prompts": ["expressive portrait art", "emotional character illustration"],
"styles": ["dramatic lighting", "powerful expression", "artistic interpretation"],
"negative": "flat lighting, emotionless, stiff pose"
},
"Urbain Stylisé": {
"prompts": ["stylized urban art", "city aesthetic interpretation"],
"styles": ["architectural elements", "urban textures", "street art influence"],
"negative": "rural, natural, realistic photo"
},
"Fantaisie Épique": {
"prompts": ["epic fantasy artwork", "mythological interpretation"],
"styles": ["magical elements", "dramatic atmosphere", "legendary creatures"],
"negative": "mundane, realistic, modern"
}
}
# CSS personnalisé
CUSTOM_CSS = """
.container { max-width: 1200px; margin: auto; }
.welcome { text-align: center; margin: 20px 0; padding: 20px; background: #1e293b; border-radius: 10px; }
.quality-controls { margin: 10px 0; padding: 10px; background: #2d3748; border-radius: 5px; }
"""
def create_interface():
def generate_image(format_size, orientation, prompt, style, quality, creativity, collection=None):
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
headers = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_TOKEN')}"}
try:
# Dimensions de base optimisées
base_width = 1024
base_height = 1024
if orientation == "Portrait":
if format_size in ["A4", "A3"]:
base_width = 768
base_height = 1024
else:
if format_size in ["A4", "A3"]:
base_width = 1024
base_height = 768
# Récupération des paramètres du style
style_config = ART_STYLES[style]
enhanced_prompt = f"{style_config['prompt_prefix']}, {prompt}"
if collection and collection in COLLECTIONS:
collection_data = COLLECTIONS[collection]
collection_elements = collection_data["prompts"] + collection_data["styles"]
enhanced_prompt += f", {', '.join(collection_elements)}"
negative_prompt = f"{style_config['negative_prompt']}, {collection_data['negative']}"
else:
negative_prompt = style_config['negative_prompt']
# Configuration de la génération
payload = {
"inputs": enhanced_prompt,
"parameters": {
"negative_prompt": negative_prompt,
"num_inference_steps": int(style_config['steps'] * (quality/100)),
"guidance_scale": style_config['guidance'] * (creativity/10),
"width": base_width,
"height": base_height
}
}
print(f"Génération avec paramètres: {payload}")
response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
if response.status_code == 200:
image = Image.open(io.BytesIO(response.content))
return image, f"✨ Création {style} réussie!"
else:
print(f"Erreur API: {response.text}")
return None, f"⚠️ Erreur {response.status_code}: Ajustez les paramètres"
except Exception as e:
print(f"Exception: {str(e)}")
return None, f"⚠️ Erreur: {str(e)}"
with gr.Blocks(css=CUSTOM_CSS) as app:
gr.HTML("""
<div class="welcome">
<h1>🤖 Equity Artisan 3.0</h1>
<p>Créez des affiches professionnelles étape par étape avec notre assistant créatif augmenté.</p>
</div>
""")
with gr.Column(elem_classes="container"):
# Étape 1: Format
with gr.Group():
gr.Markdown("### 📏 Étape 1: Format et Orientation")
with gr.Row():
format_choice = gr.Dropdown(
choices=["A4", "A3", "A2", "A1", "A0"],
value="A4",
label="Format"
)
orientation = gr.Radio(
choices=["Portrait", "Paysage"],
value="Portrait",
label="Orientation"
)
# Étape 2: Création
with gr.Group():
gr.Markdown("### 🎨 Étape 2: Création Visuelle")
with gr.Row():
with gr.Column():
style = gr.Dropdown(
choices=list(ART_STYLES.keys()),
value="Renaissance",
label="Style artistique"
)
collection = gr.Dropdown(
choices=list(COLLECTIONS.keys()),
label="Collection (optionnel)",
info="Thèmes artistiques spécialisés"
)
prompt = gr.Textbox(
lines=3,
label="Description",
placeholder="Décrivez votre vision artistique..."
)
with gr.Group(elem_classes="quality-controls"):
quality = gr.Slider(
minimum=30,
maximum=50,
value=35,
step=5,
label="Qualité",
info="Influence le niveau de détail"
)
creativity = gr.Slider(
minimum=5,
maximum=15,
value=7.5,
step=0.5,
label="Créativité",
info="Balance entre fidélité et créativité"
)
generate_btn = gr.Button("✨ Générer", variant="primary")
clear_btn = gr.Button("🗑️ Effacer", variant="secondary")
image_output = gr.Image(
label="Aperçu",
type="pil"
)
# Statut
status = gr.Textbox(
label="Status",
interactive=False,
value="Prêt à générer"
)
# Événements
generate_btn.click(
generate_image,
inputs=[
format_choice,
orientation,
prompt,
style,
quality,
creativity,
collection
],
outputs=[image_output, status]
)
clear_btn.click(
lambda: (None, "Image effacée"),
outputs=[image_output, status]
)
return app
if __name__ == "__main__":
app = create_interface()
app.launch()