Equityone commited on
Commit
68ba86b
·
verified ·
1 Parent(s): 92215a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -56
app.py CHANGED
@@ -124,15 +124,62 @@ class ImageGenerator:
124
  logger.info("ImageGenerator initialisé")
125
 
126
  def _build_prompt(self, params: Dict[str, Any]) -> str:
127
- """Construction de prompt améliorée avec le PromptEnhancer"""
128
  try:
129
- # Initialisation du PromptEnhancer
130
  enhancer = PromptEnhancer()
131
-
132
- # Récupération du style
133
  style_info = ART_STYLES.get(params["style"], ART_STYLES["Art Moderne"])
134
 
135
- # Construction du contexte de style
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  style_context = {
137
  "prompt_prefix": style_info['prompt_prefix'],
138
  "layout": COMPOSITION_PARAMS['Layouts'][params['layout']],
@@ -140,68 +187,44 @@ class ImageGenerator:
140
  "palette": COMPOSITION_PARAMS['Palette'][params['palette']]
141
  }
142
 
143
- # Préparation du prompt initial
144
  base_prompt = f"{params['subject']}"
145
  if params.get('title'):
146
  base_prompt += f", with text '{params['title']}'"
147
-
148
- # Amélioration du prompt
149
  enhanced_prompt = enhancer.enhance_prompt(base_prompt, style_context)
150
-
151
- # Analyse de l'efficacité du prompt
152
- prompt_analysis = enhancer.analyze_prompt_effectiveness(enhanced_prompt)
153
- logger.debug(f"Analyse du prompt: {json.dumps(prompt_analysis, indent=2)}")
154
-
155
  return enhanced_prompt
156
 
157
  except Exception as e:
158
  logger.error(f"Erreur dans la construction du prompt: {str(e)}")
159
- # Fallback sur le prompt basique en cas d'erreur
160
  return f"{style_info['prompt_prefix']}, {params['subject']}"
161
 
162
- def generate(self, params: Dict[str, Any]) -> Tuple[Optional[Image.Image], str]:
163
- try:
164
- logger.info(f"Début de génération avec paramètres: {json.dumps(params, indent=2)}")
165
-
166
- if 'Bearer None' in self.headers['Authorization']:
167
- return None, "⚠️ Erreur: Token Hugging Face non configuré"
 
 
 
 
 
 
 
 
168
 
169
- prompt = self._build_prompt(params)
170
-
171
- payload = {
172
- "inputs": prompt,
173
- "parameters": {
174
- "negative_prompt": ART_STYLES[params["style"]]["negative_prompt"],
175
- "num_inference_steps": min(int(35 * (params["quality"]/100)), 40),
176
- "guidance_scale": min(7.5 * (params["creativity"]/10), 10.0),
177
- "width": 768,
178
- "height": 768 if params["orientation"] == "Portrait" else 512
179
- }
180
- }
181
-
182
- logger.debug(f"Payload: {json.dumps(payload, indent=2)}")
183
-
184
- response = requests.post(
185
- self.API_URL,
186
- headers=self.headers,
187
- json=payload,
188
- timeout=30
189
- )
190
-
191
- if response.status_code == 200:
192
- image = Image.open(io.BytesIO(response.content))
193
- return image, "✨ Création réussie!"
194
- else:
195
- error_msg = f"⚠️ Erreur API {response.status_code}: {response.text}"
196
- logger.error(error_msg)
197
- return None, error_msg
198
-
199
- except Exception as e:
200
- error_msg = f"⚠️ Erreur: {str(e)}"
201
- logger.exception("Erreur pendant la génération:")
202
- return None, error_msg
203
- finally:
204
- gc.collect()
205
 
206
  def create_interface():
207
  logger.info("Création de l'interface Gradio")
 
124
  logger.info("ImageGenerator initialisé")
125
 
126
  def _build_prompt(self, params: Dict[str, Any]) -> str:
 
127
  try:
 
128
  enhancer = PromptEnhancer()
 
 
129
  style_info = ART_STYLES.get(params["style"], ART_STYLES["Art Moderne"])
130
 
131
+ # Détection du type de contenu
132
+ content_type = self._detect_content_type(params["subject"])
133
+
134
+ # Adaptation du style selon le contenu
135
+ style_adjustments = {
136
+ "anime_manga": {
137
+ "prompt_prefix": "high quality anime artwork, detailed anime illustration, studio anime quality, professional anime art",
138
+ "negative_prompt": "low quality, simple, poorly drawn, blurry"
139
+ },
140
+ "art_digital": {
141
+ "prompt_prefix": "professional digital artwork, detailed digital illustration, modern digital art",
142
+ "negative_prompt": "traditional art, poor quality, amateur"
143
+ },
144
+ "art_traditionnel": {
145
+ "prompt_prefix": "traditional art masterpiece, fine art painting, artistic technique, professional artwork",
146
+ "negative_prompt": "digital art, 3d render, poor quality"
147
+ },
148
+ "photo_realiste": {
149
+ "prompt_prefix": "ultra realistic photograph, professional photography, high end photo, studio quality",
150
+ "negative_prompt": "drawing, painting, artificial, digital art"
151
+ },
152
+ "graphisme": {
153
+ "prompt_prefix": "professional graphic design, clean modern design, commercial quality artwork",
154
+ "negative_prompt": "amateur, messy, unrefined"
155
+ },
156
+ "fantastique": {
157
+ "prompt_prefix": "fantasy art masterpiece, mythical artwork, magical atmosphere, epic fantasy illustration",
158
+ "negative_prompt": "realistic, mundane, ordinary"
159
+ },
160
+ "sci_fi": {
161
+ "prompt_prefix": "futuristic sci-fi artwork, high tech aesthetic, advanced technology, science fiction art",
162
+ "negative_prompt": "vintage, retro, traditional"
163
+ },
164
+ "art_abstrait": {
165
+ "prompt_prefix": "abstract art composition, non-representational artwork, artistic expression",
166
+ "negative_prompt": "realistic, figurative, literal"
167
+ },
168
+ "art_pop": {
169
+ "prompt_prefix": "pop art style, bold colors, graphic art, contemporary pop culture",
170
+ "negative_prompt": "classical, traditional, subtle"
171
+ },
172
+ "art_conceptuel": {
173
+ "prompt_prefix": "concept art, professional design, detailed visualization, production quality",
174
+ "negative_prompt": "amateur, unrefined, sketch"
175
+ }
176
+ }
177
+
178
+ # Ajustement du style en fonction du contenu détecté
179
+ if content_type in style_adjustments:
180
+ style_info = style_adjustments[content_type]
181
+
182
+ # Construction du contexte
183
  style_context = {
184
  "prompt_prefix": style_info['prompt_prefix'],
185
  "layout": COMPOSITION_PARAMS['Layouts'][params['layout']],
 
187
  "palette": COMPOSITION_PARAMS['Palette'][params['palette']]
188
  }
189
 
 
190
  base_prompt = f"{params['subject']}"
191
  if params.get('title'):
192
  base_prompt += f", with text '{params['title']}'"
193
+
 
194
  enhanced_prompt = enhancer.enhance_prompt(base_prompt, style_context)
 
 
 
 
 
195
  return enhanced_prompt
196
 
197
  except Exception as e:
198
  logger.error(f"Erreur dans la construction du prompt: {str(e)}")
 
199
  return f"{style_info['prompt_prefix']}, {params['subject']}"
200
 
201
+ def _detect_content_type(self, subject: str) -> str:
202
+ """Détecte le type de contenu demandé pour adapter le style"""
203
+ content_types = {
204
+ "anime_manga": ["manga", "anime", "dragon ball", "naruto", "one piece", "pokemon"],
205
+ "art_digital": ["pixel art", "digital", "vectoriel", "3d", "game art"],
206
+ "art_traditionnel": ["peinture", "aquarelle", "huile", "acrylique", "dessin"],
207
+ "photo_realiste": ["photo", "portrait", "paysage", "architecture", "produit"],
208
+ "graphisme": ["logo", "affiche", "flyer", "branding", "typographie"],
209
+ "fantastique": ["fantasy", "dragon", "magie", "heroic fantasy", "mythologie"],
210
+ "sci_fi": ["science fiction", "futuriste", "cyberpunk", "space", "robot"],
211
+ "art_abstrait": ["abstrait", "géométrique", "non-figuratif", "minimaliste"],
212
+ "art_pop": ["pop art", "comics", "bande dessinée", "cartoon", "graffiti"],
213
+ "art_conceptuel": ["concept art", "character design", "environment design", "matte painting"]
214
+ }
215
 
216
+ subject_lower = subject.lower()
217
+ detected_types = []
218
+
219
+ for content_type, keywords in content_types.items():
220
+ if any(keyword in subject_lower for keyword in keywords):
221
+ detected_types.append(content_type)
222
+
223
+ if len(detected_types) > 1:
224
+ if "photo_realiste" in detected_types and any(t in detected_types for t in ["art_digital", "anime_manga"]):
225
+ return "photo_realiste"
226
+
227
+ return detected_types[0] if detected_types else "general"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
  def create_interface():
230
  logger.info("Création de l'interface Gradio")