Dmitry1313 commited on
Commit
7e9df69
·
verified ·
1 Parent(s): 698cf0c

Create enhancement.py

Browse files
Files changed (1) hide show
  1. services/enhancement.py +104 -0
services/enhancement.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # services/enhancement.py
2
+ """
3
+ 🎨 Image Enhancement Services
4
+ Post-processing for better quality
5
+ """
6
+ import io
7
+ import logging
8
+ from PIL import Image, ImageEnhance, ImageFilter
9
+ from typing import Optional
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ def enhance_image_quality(
14
+ image_bytes: bytes,
15
+ sharpness: float = 1.3,
16
+ contrast: float = 1.1,
17
+ brightness: float = 1.05,
18
+ quality: int = 95
19
+ ) -> bytes:
20
+ """Улучшение качества изображения"""
21
+ try:
22
+ img = Image.open(io.BytesIO(image_bytes))
23
+
24
+ # Увеличение резкости
25
+ if sharpness != 1.0:
26
+ enhancer = ImageEnhance.Sharpness(img)
27
+ img = enhancer.enhance(sharpness)
28
+
29
+ # Увеличение контраста
30
+ if contrast != 1.0:
31
+ enhancer = ImageEnhance.Contrast(img)
32
+ img = enhancer.enhance(contrast)
33
+
34
+ # Увеличение яркости
35
+ if brightness != 1.0:
36
+ enhancer = ImageEnhance.Brightness(img)
37
+ img = enhancer.enhance(brightness)
38
+
39
+ # Сохранение с высоким качеством
40
+ out = io.BytesIO()
41
+ img.save(out, format="JPEG", quality=quality, optimize=True)
42
+ return out.getvalue()
43
+
44
+ except Exception as e:
45
+ logger.error(f"❌ Enhancement error: {e}")
46
+ return image_bytes
47
+
48
+ def reduce_noise(image_bytes: bytes, radius: float = 1.0) -> bytes:
49
+ """Уменьшение шума"""
50
+ try:
51
+ img = Image.open(io.BytesIO(image_bytes))
52
+ img = img.filter(ImageFilter.GaussianBlur(radius=radius))
53
+
54
+ out = io.BytesIO()
55
+ img.save(out, format="JPEG", quality=95, optimize=True)
56
+ return out.getvalue()
57
+
58
+ except Exception as e:
59
+ logger.error(f"❌ Noise reduction error: {e}")
60
+ return image_bytes
61
+
62
+ def upscale_image(image_bytes: bytes, scale: int = 2) -> bytes:
63
+ """Увеличение разрешения изображения"""
64
+ try:
65
+ img = Image.open(io.BytesIO(image_bytes))
66
+ width, height = img.size
67
+
68
+ new_width = width * scale
69
+ new_height = height * scale
70
+
71
+ img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
72
+
73
+ out = io.BytesIO()
74
+ img.save(out, format="JPEG", quality=95, optimize=True)
75
+ return out.getvalue()
76
+
77
+ except Exception as e:
78
+ logger.error(f"❌ Upscale error: {e}")
79
+ return image_bytes
80
+
81
+ def validate_image_quality(image_bytes: bytes) -> tuple[bool, str]:
82
+ """Проверка качества изображения"""
83
+ try:
84
+ img = Image.open(io.BytesIO(image_bytes))
85
+ w, h = img.size
86
+
87
+ # Минимальный размер
88
+ if w < 512 or h < 512:
89
+ return False, "❌ Изображение слишком маленькое (минимум 512x512)"
90
+
91
+ # Проверка на артефакты
92
+ pixels = list(img.convert("RGB").getdata())
93
+ avg_brightness = sum(sum(p[:3]) for p in pixels) / (len(pixels) * 3)
94
+
95
+ if avg_brightness < 20:
96
+ return False, "❌ Изображение слишком тёмное"
97
+ if avg_brightness > 240:
98
+ return False, "❌ Изображение слишком светлое"
99
+
100
+ return True, ""
101
+
102
+ except Exception as e:
103
+ logger.error(f"❌ Validation error: {e}")
104
+ return False, f"❌ Ошибка проверки: {str(e)}"