Spaces:
Runtime error
Runtime error
Update models.py
Browse files
models.py
CHANGED
|
@@ -2,128 +2,109 @@ import torch
|
|
| 2 |
from diffusers import (
|
| 3 |
StableDiffusionImg2ImgPipeline,
|
| 4 |
StableDiffusionInpaintPipeline,
|
| 5 |
-
DPMSolverMultistepScheduler,
|
| 6 |
-
EulerDiscreteScheduler,
|
| 7 |
DDIMScheduler,
|
| 8 |
-
PNDMScheduler
|
|
|
|
| 9 |
)
|
| 10 |
-
from PIL import Image
|
| 11 |
import numpy as np
|
| 12 |
-
from typing import List, Optional, Union
|
| 13 |
-
import
|
| 14 |
|
| 15 |
class InteriorDesignerPro:
|
| 16 |
-
"""Профессиональный AI дизайнер интерьеров"""
|
| 17 |
-
|
| 18 |
def __init__(self):
|
| 19 |
-
"""Инициализация моделей
|
| 20 |
-
self.device = torch.device(
|
| 21 |
-
self.
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
self.safety_checker = None
|
| 39 |
-
|
| 40 |
-
self._load_models()
|
| 41 |
-
|
| 42 |
-
def _load_models(self):
|
| 43 |
-
"""Загрузка моделей"""
|
| 44 |
try:
|
| 45 |
-
|
| 46 |
-
self.pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
|
| 47 |
-
self.model_id,
|
| 48 |
-
torch_dtype=torch.float16 if self.is_gpu else torch.float32,
|
| 49 |
-
safety_checker=None,
|
| 50 |
-
requires_safety_checker=False
|
| 51 |
-
)
|
| 52 |
-
self.pipe = self.pipe.to(self.device)
|
| 53 |
-
|
| 54 |
-
# Пайплайн для inpainting
|
| 55 |
self.inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
|
| 56 |
"runwayml/stable-diffusion-inpainting",
|
| 57 |
-
torch_dtype=torch.float16 if self.
|
| 58 |
safety_checker=None,
|
| 59 |
-
requires_safety_checker=False
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
try:
|
| 75 |
self.pipe.enable_xformers_memory_efficient_attention()
|
| 76 |
-
|
| 77 |
except:
|
| 78 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
|
| 86 |
"""Применение стиля к изображению"""
|
| 87 |
from design_styles import DESIGN_STYLES
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
negative_prompt = f"{style_data.get('negative', '')}, low quality, blurry, distorted"
|
| 94 |
-
|
| 95 |
-
# Применяем стиль
|
| 96 |
-
result = self.pipe(
|
| 97 |
-
prompt=base_prompt,
|
| 98 |
-
negative_prompt=negative_prompt,
|
| 99 |
-
image=image,
|
| 100 |
-
strength=strength * style_data.get('strength', 0.75),
|
| 101 |
-
num_inference_steps=30,
|
| 102 |
-
guidance_scale=7.5
|
| 103 |
-
).images[0]
|
| 104 |
-
|
| 105 |
-
return result
|
| 106 |
-
|
| 107 |
-
def apply_style_pro(self, image: Image.Image, style: str, room_type: str = "living room",
|
| 108 |
-
strength: float = 0.8, quality: str = "balanced") -> Image.Image:
|
| 109 |
-
"""Применение стиля с учетом качества"""
|
| 110 |
-
from design_styles import DESIGN_STYLES, get_detailed_prompt
|
| 111 |
-
|
| 112 |
-
# Получаем детальный промпт
|
| 113 |
-
prompt = get_detailed_prompt(style, room_type, quality=quality)
|
| 114 |
-
style_data = DESIGN_STYLES.get(style, {})
|
| 115 |
-
negative_prompt = style_data.get('negative', 'low quality, blurry')
|
| 116 |
|
| 117 |
-
# Настройки
|
| 118 |
quality_settings = {
|
| 119 |
"fast": {"steps": 20, "guidance": 7.5},
|
| 120 |
"balanced": {"steps": 35, "guidance": 8.5},
|
| 121 |
-
"ultra": {"steps": 50, "guidance": 10}
|
| 122 |
}
|
| 123 |
|
| 124 |
settings = quality_settings.get(quality, quality_settings["balanced"])
|
| 125 |
|
| 126 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
result = self.pipe(
|
| 128 |
prompt=prompt,
|
| 129 |
negative_prompt=negative_prompt,
|
|
@@ -135,109 +116,131 @@ class InteriorDesignerPro:
|
|
| 135 |
|
| 136 |
return result
|
| 137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
def create_variations(self, image: Image.Image, num_variations: int = 4) -> List[Image.Image]:
|
| 139 |
"""Создание вариаций дизайна"""
|
| 140 |
variations = []
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
for i in range(min(num_variations,
|
| 147 |
-
# Устанавливаем seed для воспроизводимости
|
| 148 |
-
generator = torch.Generator(device=self.device).manual_seed(seeds[i])
|
| 149 |
-
|
| 150 |
variation = self.pipe(
|
| 151 |
-
prompt=
|
| 152 |
image=image,
|
| 153 |
-
strength=
|
| 154 |
-
num_inference_steps=
|
| 155 |
-
guidance_scale=7.5
|
| 156 |
-
generator=generator
|
| 157 |
).images[0]
|
| 158 |
-
|
| 159 |
variations.append(variation)
|
| 160 |
-
|
| 161 |
return variations
|
| 162 |
|
| 163 |
def create_hdr_lighting(self, image: Image.Image, intensity: float = 0.3) -> Image.Image:
|
| 164 |
-
"""
|
| 165 |
# Конвертируем в numpy
|
| 166 |
-
|
| 167 |
|
| 168 |
# Создаем HDR эффект
|
| 169 |
# Увеличиваем контраст в светлых областях
|
| 170 |
-
|
| 171 |
-
|
| 172 |
|
| 173 |
-
#
|
| 174 |
-
|
| 175 |
-
|
| 176 |
|
| 177 |
-
#
|
| 178 |
-
|
| 179 |
|
| 180 |
-
#
|
| 181 |
-
|
|
|
|
| 182 |
|
| 183 |
-
#
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
hdr = hdr + glow * intensity * 0.3
|
| 187 |
|
| 188 |
-
|
| 189 |
-
hdr = np.clip(hdr, 0, 1)
|
| 190 |
-
hdr = (hdr * 255).astype(np.uint8)
|
| 191 |
-
|
| 192 |
-
return Image.fromarray(hdr)
|
| 193 |
|
| 194 |
def enhance_details(self, image: Image.Image) -> Image.Image:
|
| 195 |
"""Улучшение деталей изображения"""
|
| 196 |
-
# Конвертируем в numpy
|
| 197 |
-
img_np = np.array(image)
|
| 198 |
-
|
| 199 |
# Увеличиваем резкость
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
[-1,-1,-1]])
|
| 203 |
-
sharpened = cv2.filter2D(img_np, -1, kernel)
|
| 204 |
-
|
| 205 |
-
# Смешиваем с оригиналом
|
| 206 |
-
result = cv2.addWeighted(img_np, 0.7, sharpened, 0.3, 0)
|
| 207 |
|
| 208 |
# Улучшаем цвета
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
# Улучшаем яркость
|
| 213 |
-
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
|
| 214 |
-
l = clahe.apply(l)
|
| 215 |
|
| 216 |
-
#
|
| 217 |
-
|
| 218 |
-
enhanced =
|
| 219 |
|
| 220 |
-
return
|
| 221 |
|
| 222 |
def change_element(self, image: Image.Image, element: str, value: str,
|
| 223 |
strength: float = 0.7) -> Image.Image:
|
| 224 |
"""Изменение отдельного элемента интерьера"""
|
| 225 |
from design_styles import ROOM_ELEMENTS
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
|
|
|
|
|
|
| 229 |
|
| 230 |
-
#
|
| 231 |
-
prompt = f"interior
|
| 232 |
-
|
| 233 |
|
| 234 |
# Применяем изменения
|
| 235 |
result = self.pipe(
|
| 236 |
prompt=prompt,
|
| 237 |
-
negative_prompt=
|
| 238 |
image=image,
|
| 239 |
strength=strength,
|
| 240 |
-
num_inference_steps=
|
| 241 |
guidance_scale=8.0
|
| 242 |
).images[0]
|
| 243 |
|
|
@@ -245,64 +248,77 @@ class InteriorDesignerPro:
|
|
| 245 |
|
| 246 |
def create_style_comparison(self, image: Image.Image, styles: List[str],
|
| 247 |
room_type: str = "living room") -> Image.Image:
|
| 248 |
-
"""Создание сравнения
|
| 249 |
styled_images = []
|
| 250 |
|
| 251 |
for style in styles:
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
if
|
| 266 |
-
|
| 267 |
-
elif n <= 4:
|
| 268 |
-
rows, cols = 2, 2
|
| 269 |
-
elif n <= 6:
|
| 270 |
-
rows, cols = 2, 3
|
| 271 |
else:
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
grid_height = rows * (img_height + title_height) + (rows + 1) * padding
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
| 287 |
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
-
#
|
| 291 |
-
for idx, (img, title) in enumerate(
|
| 292 |
row = idx // cols
|
| 293 |
col = idx % cols
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
-
# Изменяем размер
|
| 296 |
-
img_resized = img.resize((img_width, img_height), Image.Resampling.LANCZOS)
|
| 297 |
-
|
| 298 |
-
# Позиция
|
| 299 |
-
x = col * (img_width + padding) + padding
|
| 300 |
-
y = row * (img_height + title_height + padding) + padding
|
| 301 |
-
|
| 302 |
-
if original is not None:
|
| 303 |
-
y += img_height + title_height + padding
|
| 304 |
-
|
| 305 |
-
# Вставляем изображение
|
| 306 |
-
grid.paste(img_resized, (x, y))
|
| 307 |
-
|
| 308 |
return grid
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from diffusers import (
|
| 3 |
StableDiffusionImg2ImgPipeline,
|
| 4 |
StableDiffusionInpaintPipeline,
|
|
|
|
|
|
|
| 5 |
DDIMScheduler,
|
| 6 |
+
PNDMScheduler,
|
| 7 |
+
EulerDiscreteScheduler
|
| 8 |
)
|
| 9 |
+
from PIL import Image, ImageDraw, ImageFilter, ImageEnhance
|
| 10 |
import numpy as np
|
| 11 |
+
from typing import List, Optional, Union, Tuple
|
| 12 |
+
import os
|
| 13 |
|
| 14 |
class InteriorDesignerPro:
|
|
|
|
|
|
|
| 15 |
def __init__(self):
|
| 16 |
+
"""Инициализация моделей для дизайна интерьеров"""
|
| 17 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
self.model_name = "stabilityai/stable-diffusion-2-1"
|
| 19 |
+
|
| 20 |
+
# Определяем мощность GPU
|
| 21 |
+
self.is_powerful_gpu = self._check_gpu_capability()
|
| 22 |
+
|
| 23 |
+
print(f"🚀 Инициализация InteriorDesignerPro на {self.device}")
|
| 24 |
+
print(f"💪 Мощный GPU: {'Да' if self.is_powerful_gpu else 'Нет'}")
|
| 25 |
+
|
| 26 |
+
# Основная модель для img2img
|
| 27 |
+
self.pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
|
| 28 |
+
self.model_name,
|
| 29 |
+
torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32,
|
| 30 |
+
safety_checker=None,
|
| 31 |
+
requires_safety_checker=False
|
| 32 |
+
).to(self.device)
|
| 33 |
+
|
| 34 |
+
# Модель для inpainting с обработкой ошибок
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
try:
|
| 36 |
+
print("🎨 Загрузка модели для удаления объектов...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
self.inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
|
| 38 |
"runwayml/stable-diffusion-inpainting",
|
| 39 |
+
torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32,
|
| 40 |
safety_checker=None,
|
| 41 |
+
requires_safety_checker=False,
|
| 42 |
+
local_files_only=False,
|
| 43 |
+
resume_download=True
|
| 44 |
+
).to(self.device)
|
| 45 |
+
print("✅ Модель inpainting загружена успешно")
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"⚠️ Не удалось загрузить модель inpainting: {e}")
|
| 48 |
+
print("📌 Используем основную модель как альтернативу")
|
| 49 |
+
# Используем основную модель для inpainting
|
| 50 |
+
self.inpaint_pipe = self.pipe
|
| 51 |
+
|
| 52 |
+
# Оптимизация памяти
|
| 53 |
+
if self.device.type == "cuda":
|
| 54 |
+
self.pipe.enable_attention_slicing()
|
| 55 |
+
if hasattr(self.pipe, 'enable_xformers_memory_efficient_attention'):
|
| 56 |
try:
|
| 57 |
self.pipe.enable_xformers_memory_efficient_attention()
|
| 58 |
+
print("✅ xFormers оптимизация включена")
|
| 59 |
except:
|
| 60 |
pass
|
| 61 |
+
|
| 62 |
+
# Настройка планировщиков
|
| 63 |
+
self.schedulers = {
|
| 64 |
+
"DDIM": DDIMScheduler,
|
| 65 |
+
"PNDM": PNDMScheduler,
|
| 66 |
+
"Euler": EulerDiscreteScheduler
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# Установка дефолтного планировщика
|
| 70 |
+
self.pipe.scheduler = DDIMScheduler.from_config(self.pipe.scheduler.config)
|
| 71 |
+
|
| 72 |
+
def _check_gpu_capability(self):
|
| 73 |
+
"""Проверка мощности GPU"""
|
| 74 |
+
if self.device.type != "cuda":
|
| 75 |
+
return False
|
| 76 |
|
| 77 |
+
# Проверяем доступную память
|
| 78 |
+
try:
|
| 79 |
+
mem_gb = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
| 80 |
+
return mem_gb >= 12 # 12GB+ считаем мощным GPU
|
| 81 |
+
except:
|
| 82 |
+
return False
|
| 83 |
|
| 84 |
+
def apply_style_pro(self, image: Image.Image, style_name: str, room_type: str,
|
| 85 |
+
strength: float = 0.75, quality: str = "balanced") -> Image.Image:
|
| 86 |
"""Применение стиля к изображению"""
|
| 87 |
from design_styles import DESIGN_STYLES
|
| 88 |
|
| 89 |
+
if style_name not in DESIGN_STYLES:
|
| 90 |
+
raise ValueError(f"Неизвестный стиль: {style_name}")
|
| 91 |
+
|
| 92 |
+
style = DESIGN_STYLES[style_name]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
# Настройки качества
|
| 95 |
quality_settings = {
|
| 96 |
"fast": {"steps": 20, "guidance": 7.5},
|
| 97 |
"balanced": {"steps": 35, "guidance": 8.5},
|
| 98 |
+
"ultra": {"steps": 50, "guidance": 10.0}
|
| 99 |
}
|
| 100 |
|
| 101 |
settings = quality_settings.get(quality, quality_settings["balanced"])
|
| 102 |
|
| 103 |
+
# Генерация промпта
|
| 104 |
+
prompt = f"{room_type}, {style['prompt']}"
|
| 105 |
+
negative_prompt = style.get('negative', '')
|
| 106 |
+
|
| 107 |
+
# Применение стиля
|
| 108 |
result = self.pipe(
|
| 109 |
prompt=prompt,
|
| 110 |
negative_prompt=negative_prompt,
|
|
|
|
| 116 |
|
| 117 |
return result
|
| 118 |
|
| 119 |
+
def remove_objects(self, image: Image.Image, mask: Image.Image,
|
| 120 |
+
inpaint_prompt: str = None) -> Image.Image:
|
| 121 |
+
"""Удаление объектов с изображения"""
|
| 122 |
+
if inpaint_prompt is None:
|
| 123 |
+
inpaint_prompt = "empty room, clean walls, seamless texture"
|
| 124 |
+
|
| 125 |
+
# Проверяем тип модели
|
| 126 |
+
if hasattr(self.inpaint_pipe, 'components') and 'vae' in self.inpaint_pipe.components:
|
| 127 |
+
# Это настоящая inpainting модель
|
| 128 |
+
result = self.inpaint_pipe(
|
| 129 |
+
prompt=inpaint_prompt,
|
| 130 |
+
negative_prompt="objects, furniture, people",
|
| 131 |
+
image=image,
|
| 132 |
+
mask_image=mask,
|
| 133 |
+
strength=0.99,
|
| 134 |
+
num_inference_steps=50,
|
| 135 |
+
guidance_scale=7.5
|
| 136 |
+
).images[0]
|
| 137 |
+
else:
|
| 138 |
+
# Fallback на img2img с маской
|
| 139 |
+
# Создаем композитное изображение
|
| 140 |
+
masked_image = Image.composite(
|
| 141 |
+
Image.new('RGB', image.size, (255, 255, 255)),
|
| 142 |
+
image,
|
| 143 |
+
mask.convert('L').point(lambda x: 0 if x > 128 else 255)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
result = self.pipe(
|
| 147 |
+
prompt=inpaint_prompt,
|
| 148 |
+
negative_prompt="objects, furniture, people",
|
| 149 |
+
image=masked_image,
|
| 150 |
+
strength=0.95,
|
| 151 |
+
num_inference_steps=50,
|
| 152 |
+
guidance_scale=7.5
|
| 153 |
+
).images[0]
|
| 154 |
+
|
| 155 |
+
return result
|
| 156 |
+
|
| 157 |
def create_variations(self, image: Image.Image, num_variations: int = 4) -> List[Image.Image]:
|
| 158 |
"""Создание вариаций дизайна"""
|
| 159 |
variations = []
|
| 160 |
|
| 161 |
+
prompts = [
|
| 162 |
+
"modern interior design, professional photo",
|
| 163 |
+
"cozy interior design, warm lighting",
|
| 164 |
+
"luxury interior design, high-end materials",
|
| 165 |
+
"minimalist interior design, clean space"
|
| 166 |
+
]
|
| 167 |
|
| 168 |
+
for i in range(min(num_variations, len(prompts))):
|
|
|
|
|
|
|
|
|
|
| 169 |
variation = self.pipe(
|
| 170 |
+
prompt=prompts[i],
|
| 171 |
image=image,
|
| 172 |
+
strength=0.5 + (i * 0.1),
|
| 173 |
+
num_inference_steps=30,
|
| 174 |
+
guidance_scale=7.5
|
|
|
|
| 175 |
).images[0]
|
|
|
|
| 176 |
variations.append(variation)
|
| 177 |
+
|
| 178 |
return variations
|
| 179 |
|
| 180 |
def create_hdr_lighting(self, image: Image.Image, intensity: float = 0.3) -> Image.Image:
|
| 181 |
+
"""Улучшение освещения (HDR эффект)"""
|
| 182 |
# Конвертируем в numpy
|
| 183 |
+
img_array = np.array(image).astype(np.float32)
|
| 184 |
|
| 185 |
# Создаем HDR эффект
|
| 186 |
# Увеличиваем контраст в светлых областях
|
| 187 |
+
bright_mask = img_array > 200
|
| 188 |
+
img_array[bright_mask] = img_array[bright_mask] * (1 + intensity)
|
| 189 |
|
| 190 |
+
# Усиливаем тени
|
| 191 |
+
dark_mask = img_array < 50
|
| 192 |
+
img_array[dark_mask] = img_array[dark_mask] * (1 - intensity * 0.5)
|
| 193 |
|
| 194 |
+
# Нормализация
|
| 195 |
+
img_array = np.clip(img_array, 0, 255).astype(np.uint8)
|
| 196 |
|
| 197 |
+
# Применяем дополнительные фильтры
|
| 198 |
+
enhanced = Image.fromarray(img_array)
|
| 199 |
+
enhanced = enhanced.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3))
|
| 200 |
|
| 201 |
+
# Настройка яркости и контраста
|
| 202 |
+
enhancer = ImageEnhance.Contrast(enhanced)
|
| 203 |
+
enhanced = enhancer.enhance(1.1)
|
|
|
|
| 204 |
|
| 205 |
+
return enhanced
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
def enhance_details(self, image: Image.Image) -> Image.Image:
|
| 208 |
"""Улучшение деталей изображения"""
|
|
|
|
|
|
|
|
|
|
| 209 |
# Увеличиваем резкость
|
| 210 |
+
enhanced = image.filter(ImageFilter.SHARPEN)
|
| 211 |
+
enhanced = enhanced.filter(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=3))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
# Улучшаем цвета
|
| 214 |
+
color_enhancer = ImageEnhance.Color(enhanced)
|
| 215 |
+
enhanced = color_enhancer.enhance(1.1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
+
# Увеличиваем четкость
|
| 218 |
+
sharpness_enhancer = ImageEnhance.Sharpness(enhanced)
|
| 219 |
+
enhanced = sharpness_enhancer.enhance(1.2)
|
| 220 |
|
| 221 |
+
return enhanced
|
| 222 |
|
| 223 |
def change_element(self, image: Image.Image, element: str, value: str,
|
| 224 |
strength: float = 0.7) -> Image.Image:
|
| 225 |
"""Изменение отдельного элемента интерьера"""
|
| 226 |
from design_styles import ROOM_ELEMENTS
|
| 227 |
|
| 228 |
+
if element not in ROOM_ELEMENTS:
|
| 229 |
+
raise ValueError(f"Неизвестный элемент: {element}")
|
| 230 |
+
|
| 231 |
+
element_info = ROOM_ELEMENTS[element]
|
| 232 |
|
| 233 |
+
# Создаем промпт для изменения
|
| 234 |
+
prompt = f"interior design, {element_info['prompt_add']}, {value}"
|
| 235 |
+
negative_prompt = "blurry, distorted"
|
| 236 |
|
| 237 |
# Применяем изменения
|
| 238 |
result = self.pipe(
|
| 239 |
prompt=prompt,
|
| 240 |
+
negative_prompt=negative_prompt,
|
| 241 |
image=image,
|
| 242 |
strength=strength,
|
| 243 |
+
num_inference_steps=40,
|
| 244 |
guidance_scale=8.0
|
| 245 |
).images[0]
|
| 246 |
|
|
|
|
| 248 |
|
| 249 |
def create_style_comparison(self, image: Image.Image, styles: List[str],
|
| 250 |
room_type: str = "living room") -> Image.Image:
|
| 251 |
+
"""Создание сравнения стилей"""
|
| 252 |
styled_images = []
|
| 253 |
|
| 254 |
for style in styles:
|
| 255 |
+
try:
|
| 256 |
+
styled = self.apply_style_pro(
|
| 257 |
+
image, style, room_type,
|
| 258 |
+
strength=0.75, quality="fast"
|
| 259 |
+
)
|
| 260 |
+
styled_images.append((styled, style))
|
| 261 |
+
except Exception as e:
|
| 262 |
+
print(f"Ошибка при применении стиля {style}: {e}")
|
| 263 |
+
|
| 264 |
+
if not styled_images:
|
| 265 |
+
return image
|
| 266 |
+
|
| 267 |
+
# Используем метод из процессора
|
| 268 |
+
if hasattr(self, '_create_comparison_grid'):
|
| 269 |
+
return self._create_comparison_grid(styled_images)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
else:
|
| 271 |
+
# Простая сетка
|
| 272 |
+
return self._simple_grid(styled_images)
|
| 273 |
+
|
| 274 |
+
def _simple_grid(self, images_with_titles: List[Tuple[Image.Image, str]]) -> Image.Image:
|
| 275 |
+
"""Создание простой сетки изображений"""
|
| 276 |
+
if not images_with_titles:
|
| 277 |
+
return None
|
| 278 |
+
|
| 279 |
+
images = [img for img, _ in images_with_titles]
|
| 280 |
+
titles = [title for _, title in images_with_titles]
|
|
|
|
| 281 |
|
| 282 |
+
# Размеры
|
| 283 |
+
img_width, img_height = images[0].size
|
| 284 |
+
cols = min(3, len(images))
|
| 285 |
+
rows = (len(images) + cols - 1) // cols
|
| 286 |
|
| 287 |
+
# Создаем сетку
|
| 288 |
+
grid_width = img_width * cols
|
| 289 |
+
grid_height = img_height * rows
|
| 290 |
+
grid = Image.new('RGB', (grid_width, grid_height), 'white')
|
| 291 |
|
| 292 |
+
# Размещаем изображения
|
| 293 |
+
for idx, (img, title) in enumerate(images_with_titles):
|
| 294 |
row = idx // cols
|
| 295 |
col = idx % cols
|
| 296 |
+
x = col * img_width
|
| 297 |
+
y = row * img_height
|
| 298 |
+
grid.paste(img, (x, y))
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
return grid
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# Дополнительный класс для удаления объектов
|
| 304 |
+
class ObjectRemover:
|
| 305 |
+
def __init__(self, device):
|
| 306 |
+
self.device = device
|
| 307 |
+
|
| 308 |
+
def generate_mask_from_text(self, image: Image.Image, text: str, precision: float) -> Image.Image:
|
| 309 |
+
"""Генерация маски на основе текстового описания"""
|
| 310 |
+
# Простая реализация - создаем маску в центре
|
| 311 |
+
width, height = image.size
|
| 312 |
+
mask = Image.new('L', (width, height), 0)
|
| 313 |
+
draw = ImageDraw.Draw(mask)
|
| 314 |
+
|
| 315 |
+
# Размер области зависит от precision
|
| 316 |
+
margin = int(min(width, height) * (1 - precision) / 2)
|
| 317 |
+
|
| 318 |
+
# Рисуем белую область в центре
|
| 319 |
+
draw.ellipse([margin, margin, width-margin, height-margin], fill=255)
|
| 320 |
+
|
| 321 |
+
# Размываем для плавных краев
|
| 322 |
+
mask = mask.filter(ImageFilter.GaussianBlur(radius=20))
|
| 323 |
+
|
| 324 |
+
return mask
|