Equityone commited on
Commit
cf5b603
·
verified ·
1 Parent(s): e3f6b93

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -112
app.py CHANGED
@@ -10,6 +10,8 @@ import logging
10
  from dotenv import load_dotenv
11
  import numpy as np
12
  import cv2
 
 
13
 
14
  # Configuration du logging
15
  logging.basicConfig(
@@ -23,100 +25,122 @@ logging.basicConfig(
23
  logger = logging.getLogger(__name__)
24
  load_dotenv()
25
 
26
- # 1. STYLES EQUITY (basés sur les 8 documents)
27
  ART_STYLES = {
28
- "Renaissance Technologique": {
29
- "prompt_prefix": """ultra-detailed technical drawing, da vinci style engineering precision,
30
- anatomical accuracy, golden ratio proportions, scientific illustration quality,
31
- masterful light and shadow, highest level of detail, museum quality artwork""",
32
- "negative_prompt": "simple sketch, imprecise, cartoon, abstract, low detail",
33
  "quality_boost": 1.5,
34
- "style_params": {
35
- "detail_level": "maximum",
36
- "technical_precision": True,
37
- "historical_accuracy": True
 
38
  }
39
  },
40
  "Innovation Moderne": {
41
- "prompt_prefix": """cutting-edge technological design, futuristic engineering visual,
42
- advanced mechanical detail, precise technical schematic, innovative concept art,
43
- professional industrial visualization, high-tech aesthetic""",
44
- "negative_prompt": "vintage, retro, simplified, abstract",
45
  "quality_boost": 1.4,
46
- "style_params": {
47
- "tech_detail": "ultra",
48
- "innovation_focus": True
 
49
  }
50
  },
51
- "Photographie Analytique": {
52
- "prompt_prefix": """professional analytical photography, ansel adams zone system,
53
- ultra sharp detail, perfect exposure, museum grade quality, technical perfection,
54
- masterful composition, extreme clarity""",
55
- "negative_prompt": "blurry, artistic, painterly, low quality",
56
  "quality_boost": 1.5,
57
- "style_params": {
58
- "photographic_precision": True,
59
- "detail_preservation": "maximum"
 
60
  }
61
  },
62
  "Vision Futuriste": {
63
- "prompt_prefix": """advanced technological concept, future engineering visualization,
64
- innovative architectural design, sci-fi technical precision, ultra modern aesthetic,
65
- professional technical illustration""",
66
- "negative_prompt": "historical, vintage, traditional, hand-drawn",
67
  "quality_boost": 1.4,
68
- "style_params": {
69
- "future_tech": True,
70
- "concept_clarity": "high"
 
71
  }
72
  }
73
  }
74
 
75
- # 2. OPTIMISATION DE LA QUALITÉ
76
  class ImageEnhancer:
 
 
77
  def __init__(self):
78
- self.enhancement_pipeline = {
79
- "technical_detail": self._enhance_technical_detail,
80
- "color_refinement": self._refine_colors,
81
- "sharpness_boost": self._boost_sharpness,
82
- "contrast_optimization": self._optimize_contrast
83
- }
 
 
 
 
 
 
84
 
85
- def _enhance_technical_detail(self, image: np.ndarray) -> np.ndarray:
86
- kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
 
 
 
87
  return cv2.filter2D(image, -1, kernel)
88
 
89
- def _refine_colors(self, image: np.ndarray) -> np.ndarray:
90
- lab = cv2.cvtColor(image, cv2.COLOR_BGR2Lab)
91
- l, a, b = cv2.split(lab)
92
- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
93
- l = clahe.apply(l)
94
- lab = cv2.merge((l,a,b))
95
- return cv2.cvtColor(lab, cv2.COLOR_Lab2BGR)
96
-
97
- def _boost_sharpness(self, image: np.ndarray) -> np.ndarray:
98
- blurred = cv2.GaussianBlur(image, (0, 0), 3)
99
- return cv2.addWeighted(image, 1.5, blurred, -0.5, 0)
100
-
101
- def _optimize_contrast(self, image: np.ndarray) -> np.ndarray:
102
- lab = cv2.cvtColor(image, cv2.COLOR_BGR2Lab)
103
- l, a, b = cv2.split(lab)
104
- clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
105
- l = clahe.apply(l)
106
- lab = cv2.merge((l,a,b))
107
- return cv2.cvtColor(lab, cv2.COLOR_Lab2BGR)
108
-
109
- def enhance_image(self, image: Image.Image, style_params: Dict) -> Image.Image:
110
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
111
-
112
- for enhancement, should_apply in style_params.items():
113
- if should_apply and enhancement in self.enhancement_pipeline:
114
- cv_image = self.enhancement_pipeline[enhancement](cv_image)
115
-
 
 
 
 
 
 
 
 
 
 
116
  return Image.fromarray(cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB))
117
 
118
- # 3. GÉNÉRATEUR D'IMAGES PRINCIPAL
119
  class ImageGenerator:
 
 
120
  def __init__(self):
121
  self.API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
122
  self.enhancer = ImageEnhancer()
@@ -126,26 +150,36 @@ class ImageGenerator:
126
  self.headers = {"Authorization": f"Bearer {token}"}
127
  logger.info("ImageGenerator initialisé")
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  def generate(self, params: Dict[str, Any]) -> Tuple[Optional[Image.Image], str]:
 
130
  try:
131
  style_info = ART_STYLES.get(params["style"])
132
  if not style_info:
133
  return None, "⚠️ Style non trouvé"
134
 
135
- # Construction du prompt optimisé
136
- prompt = f"{params['subject']}, {style_info['prompt_prefix']}"
137
- if params.get('title'):
138
- prompt += f", with text: {params['title']}"
139
 
140
  payload = {
141
  "inputs": prompt,
142
- "parameters": {
143
- "negative_prompt": style_info["negative_prompt"],
144
- "num_inference_steps": int(50 * style_info["quality_boost"]),
145
- "guidance_scale": min(9.0 * style_info["quality_boost"], 12.0),
146
- "width": 1024 if params.get("quality", 35) > 40 else 768,
147
- "height": 1024 if params["orientation"] == "Portrait" else 768
148
- }
149
  }
150
 
151
  response = requests.post(
@@ -158,8 +192,8 @@ class ImageGenerator:
158
  if response.status_code == 200:
159
  image = Image.open(io.BytesIO(response.content))
160
  enhanced_image = self.enhancer.enhance_image(
161
- image,
162
- style_info["style_params"]
163
  )
164
  return enhanced_image, "✨ Création réussie!"
165
  else:
@@ -174,31 +208,11 @@ class ImageGenerator:
174
  finally:
175
  gc.collect()
176
 
177
- # 4. INTERFACE UTILISATEUR
178
  def create_interface():
 
179
  generator = ImageGenerator()
180
 
181
- # Style CSS personnalisé
182
- css = """
183
- .container { max-width: 1200px; margin: auto; }
184
- .welcome {
185
- text-align: center;
186
- margin: 20px 0;
187
- padding: 20px;
188
- background: linear-gradient(135deg, #1e293b, #334155);
189
- border-radius: 10px;
190
- color: white;
191
- }
192
- .controls-group {
193
- background: #2d3748;
194
- padding: 15px;
195
- border-radius: 5px;
196
- margin: 10px 0;
197
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
198
- }
199
- """
200
-
201
- with gr.Blocks(css=css) as app:
202
  gr.HTML("""
203
  <div class="welcome">
204
  <h1>🎨 Equity Artisan 3.0</h1>
@@ -207,7 +221,6 @@ def create_interface():
207
  """)
208
 
209
  with gr.Column(elem_classes="container"):
210
- # Format et Style
211
  with gr.Group(elem_classes="controls-group"):
212
  with gr.Row():
213
  format_size = gr.Dropdown(
@@ -222,15 +235,14 @@ def create_interface():
222
  )
223
  style = gr.Dropdown(
224
  choices=list(ART_STYLES.keys()),
225
- value="Renaissance Technologique",
226
- label="Style Artistique"
227
  )
228
 
229
- # Description
230
  with gr.Group(elem_classes="controls-group"):
231
  subject = gr.Textbox(
232
  label="Description",
233
- placeholder="Décrivez votre vision technique ou artistique...",
234
  lines=3
235
  )
236
  title = gr.Textbox(
@@ -238,14 +250,13 @@ def create_interface():
238
  placeholder="Titre à inclure dans l'image..."
239
  )
240
 
241
- # Paramètres avancés
242
  with gr.Group(elem_classes="controls-group"):
243
  with gr.Row():
244
  quality = gr.Slider(
245
  minimum=30,
246
  maximum=50,
247
  value=40,
248
- label="Qualité"
249
  )
250
  detail_level = gr.Slider(
251
  minimum=1,
@@ -255,12 +266,10 @@ def create_interface():
255
  label="Niveau de Détail"
256
  )
257
 
258
- # Boutons
259
  with gr.Row():
260
  generate_btn = gr.Button("✨ Générer", variant="primary")
261
  clear_btn = gr.Button("🗑️ Effacer")
262
 
263
- # Résultat
264
  image_output = gr.Image(label="Résultat")
265
  status = gr.Textbox(label="Status", interactive=False)
266
 
 
10
  from dotenv import load_dotenv
11
  import numpy as np
12
  import cv2
13
+ from skimage import exposure
14
+ import torch
15
 
16
  # Configuration du logging
17
  logging.basicConfig(
 
25
  logger = logging.getLogger(__name__)
26
  load_dotenv()
27
 
28
+ # Définition des styles Equity avec paramètres d'optimisation avancés
29
  ART_STYLES = {
30
+ "Ultra Technique": {
31
+ "prompt_prefix": """ultra detailed technical drawing, engineering precision,
32
+ scientific accuracy, professional schematic, architectural detail, perfect measurements,
33
+ masterful technical illustration, 8k UHD quality, professional engineering visualization""",
34
+ "negative_prompt": "artistic, painterly, imprecise, blurry, sketchy",
35
  "quality_boost": 1.5,
36
+ "image_params": {
37
+ "sharpness": 1.4,
38
+ "technical_detail": True,
39
+ "contrast": 1.2,
40
+ "denoise": 0.3
41
  }
42
  },
43
  "Innovation Moderne": {
44
+ "prompt_prefix": """cutting-edge technological design, modern engineering aesthetic,
45
+ innovative technical concept, futuristic schematic, professional industrial visualization,
46
+ high-tech blueprint, advanced technical detail, ultra modern technical drawing""",
47
+ "negative_prompt": "vintage, traditional, hand-drawn, artistic",
48
  "quality_boost": 1.4,
49
+ "image_params": {
50
+ "sharpness": 1.3,
51
+ "contrast": 1.3,
52
+ "clarity": True
53
  }
54
  },
55
+ "Précision Scientifique": {
56
+ "prompt_prefix": """scientific visualization, mathematical accuracy,
57
+ precise technical detail, analytical illustration, professional documentation,
58
+ engineering excellence, technical mastery, detailed scientific diagram""",
59
+ "negative_prompt": "artistic interpretation, abstract, undefined",
60
  "quality_boost": 1.5,
61
+ "image_params": {
62
+ "detail_enhancement": True,
63
+ "precision": 1.4,
64
+ "clarity": True
65
  }
66
  },
67
  "Vision Futuriste": {
68
+ "prompt_prefix": """future technology concept, advanced engineering design,
69
+ next-generation technical visualization, innovative blueprint style,
70
+ high-tech schematic art, professional futuristic documentation""",
71
+ "negative_prompt": "retro, vintage, traditional technique",
72
  "quality_boost": 1.4,
73
+ "image_params": {
74
+ "tech_enhancement": True,
75
+ "modern_look": True,
76
+ "sharpness": 1.3
77
  }
78
  }
79
  }
80
 
 
81
  class ImageEnhancer:
82
+ """Classe de traitement et d'amélioration d'image avancée"""
83
+
84
  def __init__(self):
85
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
86
+
87
+ def _apply_clahe(self, image: np.ndarray) -> np.ndarray:
88
+ """Amélioration adaptative du contraste"""
89
+ if len(image.shape) == 3:
90
+ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
91
+ l, a, b = cv2.split(lab)
92
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
93
+ l = clahe.apply(l)
94
+ lab = cv2.merge((l,a,b))
95
+ return cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
96
+ return image
97
 
98
+ def _enhance_details(self, image: np.ndarray) -> np.ndarray:
99
+ """Amélioration des détails techniques"""
100
+ kernel = np.array([[-1,-1,-1],
101
+ [-1, 9,-1],
102
+ [-1,-1,-1]])
103
  return cv2.filter2D(image, -1, kernel)
104
 
105
+ def _reduce_noise(self, image: np.ndarray, strength: float = 0.3) -> np.ndarray:
106
+ """Réduction du bruit adaptative"""
107
+ return cv2.fastNlMeansDenoisingColored(
108
+ image,
109
+ None,
110
+ h=10 * strength,
111
+ hColor=10,
112
+ templateWindowSize=7,
113
+ searchWindowSize=21
114
+ )
115
+
116
+ def _adjust_gamma(self, image: np.ndarray, gamma: float = 1.0) -> np.ndarray:
117
+ """Ajustement gamma pour l'optimisation des tons"""
118
+ return exposure.adjust_gamma(image, gamma)
119
+
120
+ def enhance_image(self, image: Image.Image, params: Dict) -> Image.Image:
121
+ """Pipeline complet d'amélioration d'image"""
122
+ # Conversion en format CV2
 
 
 
123
  cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
124
+
125
+ # Application des améliorations selon les paramètres
126
+ if params.get('technical_detail', False):
127
+ cv_image = self._enhance_details(cv_image)
128
+
129
+ if params.get('clarity', False):
130
+ cv_image = self._apply_clahe(cv_image)
131
+
132
+ if params.get('denoise', 0) > 0:
133
+ cv_image = self._reduce_noise(cv_image, params['denoise'])
134
+
135
+ if params.get('gamma', 1.0) != 1.0:
136
+ cv_image = self._adjust_gamma(cv_image, params['gamma'])
137
+
138
+ # Reconversion en format PIL
139
  return Image.fromarray(cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB))
140
 
 
141
  class ImageGenerator:
142
+ """Générateur d'images principal avec optimisations Equity"""
143
+
144
  def __init__(self):
145
  self.API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
146
  self.enhancer = ImageEnhancer()
 
150
  self.headers = {"Authorization": f"Bearer {token}"}
151
  logger.info("ImageGenerator initialisé")
152
 
153
+ def _prepare_prompt(self, params: Dict[str, Any], style_info: Dict) -> str:
154
+ """Prépare le prompt optimisé"""
155
+ base_prompt = params['subject']
156
+ if params.get('title'):
157
+ base_prompt += f", with text: {params['title']}"
158
+ return f"{base_prompt}, {style_info['prompt_prefix']}"
159
+
160
+ def _get_generation_params(self, params: Dict[str, Any], style_info: Dict) -> Dict:
161
+ """Configure les paramètres de génération optimaux"""
162
+ return {
163
+ "negative_prompt": style_info["negative_prompt"],
164
+ "num_inference_steps": int(50 * style_info["quality_boost"]),
165
+ "guidance_scale": min(9.0 * style_info["quality_boost"], 12.0),
166
+ "width": 1024 if params.get("quality", 35) > 40 else 768,
167
+ "height": 1024 if params["orientation"] == "Portrait" else 768
168
+ }
169
+
170
  def generate(self, params: Dict[str, Any]) -> Tuple[Optional[Image.Image], str]:
171
+ """Génération d'image avec optimisations Equity"""
172
  try:
173
  style_info = ART_STYLES.get(params["style"])
174
  if not style_info:
175
  return None, "⚠️ Style non trouvé"
176
 
177
+ prompt = self._prepare_prompt(params, style_info)
178
+ generation_params = self._get_generation_params(params, style_info)
 
 
179
 
180
  payload = {
181
  "inputs": prompt,
182
+ "parameters": generation_params
 
 
 
 
 
 
183
  }
184
 
185
  response = requests.post(
 
192
  if response.status_code == 200:
193
  image = Image.open(io.BytesIO(response.content))
194
  enhanced_image = self.enhancer.enhance_image(
195
+ image,
196
+ style_info["image_params"]
197
  )
198
  return enhanced_image, "✨ Création réussie!"
199
  else:
 
208
  finally:
209
  gc.collect()
210
 
 
211
  def create_interface():
212
+ """Création de l'interface utilisateur Equity"""
213
  generator = ImageGenerator()
214
 
215
+ with gr.Blocks(css="style.css") as app:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  gr.HTML("""
217
  <div class="welcome">
218
  <h1>🎨 Equity Artisan 3.0</h1>
 
221
  """)
222
 
223
  with gr.Column(elem_classes="container"):
 
224
  with gr.Group(elem_classes="controls-group"):
225
  with gr.Row():
226
  format_size = gr.Dropdown(
 
235
  )
236
  style = gr.Dropdown(
237
  choices=list(ART_STYLES.keys()),
238
+ value="Ultra Technique",
239
+ label="Style Technique"
240
  )
241
 
 
242
  with gr.Group(elem_classes="controls-group"):
243
  subject = gr.Textbox(
244
  label="Description",
245
+ placeholder="Décrivez votre vision technique...",
246
  lines=3
247
  )
248
  title = gr.Textbox(
 
250
  placeholder="Titre à inclure dans l'image..."
251
  )
252
 
 
253
  with gr.Group(elem_classes="controls-group"):
254
  with gr.Row():
255
  quality = gr.Slider(
256
  minimum=30,
257
  maximum=50,
258
  value=40,
259
+ label="Qualité Technique"
260
  )
261
  detail_level = gr.Slider(
262
  minimum=1,
 
266
  label="Niveau de Détail"
267
  )
268
 
 
269
  with gr.Row():
270
  generate_btn = gr.Button("✨ Générer", variant="primary")
271
  clear_btn = gr.Button("🗑️ Effacer")
272
 
 
273
  image_output = gr.Image(label="Résultat")
274
  status = gr.Textbox(label="Status", interactive=False)
275