Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,75 +1,178 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import ViTImageProcessor, ViTForImageClassification
|
3 |
from PIL import Image
|
|
|
|
|
4 |
import torch
|
|
|
5 |
import warnings
|
6 |
warnings.filterwarnings("ignore")
|
7 |
|
8 |
class IridologyAnalyzer:
|
9 |
def __init__(self):
|
10 |
-
|
11 |
-
print("Carregando modelo...")
|
12 |
-
|
13 |
-
# ViT model - Modelo público para análise de imagens
|
14 |
-
self.processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
|
15 |
-
self.model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
|
16 |
|
17 |
# Características de iridologia para análise
|
18 |
-
self.iris_features =
|
19 |
-
"Textura da íris",
|
20 |
-
"Coloração",
|
21 |
-
"Marcas ou manchas",
|
22 |
-
"Anéis ou círculos",
|
23 |
-
"Condição da pupila",
|
24 |
-
"Linhas radiais",
|
25 |
-
"Pigmentação",
|
26 |
-
"Clareza geral",
|
27 |
-
"Estrutura do tecido",
|
28 |
-
"Marcas brancas",
|
29 |
-
"Fibras da íris",
|
30 |
-
"Borda da íris"
|
31 |
-
|
32 |
|
33 |
-
print("
|
34 |
|
35 |
-
def
|
36 |
-
"""
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
confidence = probs.max().item()
|
41 |
|
42 |
-
#
|
43 |
-
if
|
44 |
-
|
45 |
-
elif confidence > 0.5:
|
46 |
-
return "Presença/intensidade moderada"
|
47 |
else:
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
-
def
|
51 |
-
"""
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
-
for
|
55 |
-
try:
|
56 |
-
analysis = self.analyze_image_feature(image, feature)
|
57 |
-
results.append({
|
58 |
-
"feature": feature,
|
59 |
-
"analysis": analysis
|
60 |
-
})
|
61 |
-
except Exception as e:
|
62 |
-
print(f"Erro ao analisar '{feature}': {str(e)}")
|
63 |
-
continue
|
64 |
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
def create_gradio_interface():
|
75 |
analyzer = IridologyAnalyzer()
|
@@ -77,25 +180,16 @@ def create_gradio_interface():
|
|
77 |
def process_image(image):
|
78 |
if image is None:
|
79 |
return "Por favor, faça o upload de uma imagem."
|
80 |
-
|
81 |
-
# Converter para PIL Image se necessário
|
82 |
-
if not isinstance(image, Image.Image):
|
83 |
-
image = Image.fromarray(image)
|
84 |
-
|
85 |
-
# Realizar análise
|
86 |
-
try:
|
87 |
-
return analyzer.comprehensive_analysis(image)
|
88 |
-
except Exception as e:
|
89 |
-
return f"Erro durante a análise: {str(e)}"
|
90 |
|
91 |
# Interface Gradio
|
92 |
iface = gr.Interface(
|
93 |
fn=process_image,
|
94 |
-
inputs=gr.Image(type="
|
95 |
outputs=gr.Textbox(label="Resultados da Análise", lines=20),
|
96 |
title="Analisador de Iridologia com IA",
|
97 |
description="""
|
98 |
-
Este sistema analisa imagens de íris usando
|
99 |
Faça o upload de uma imagem clara do olho para análise.
|
100 |
|
101 |
Recomendações para melhores resultados:
|
|
|
1 |
import gradio as gr
|
|
|
2 |
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
import cv2
|
5 |
import torch
|
6 |
+
from transformers import ViTFeatureExtractor
|
7 |
import warnings
|
8 |
warnings.filterwarnings("ignore")
|
9 |
|
10 |
class IridologyAnalyzer:
|
11 |
def __init__(self):
|
12 |
+
print("Inicializando analisador...")
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
# Características de iridologia para análise
|
15 |
+
self.iris_features = {
|
16 |
+
"Textura da íris": self._analyze_texture,
|
17 |
+
"Coloração": self._analyze_color,
|
18 |
+
"Marcas ou manchas": self._analyze_spots,
|
19 |
+
"Anéis ou círculos": self._analyze_rings,
|
20 |
+
"Condição da pupila": self._analyze_pupil,
|
21 |
+
"Linhas radiais": self._analyze_lines,
|
22 |
+
"Pigmentação": self._analyze_pigmentation,
|
23 |
+
"Clareza geral": self._analyze_clarity,
|
24 |
+
"Estrutura do tecido": self._analyze_tissue,
|
25 |
+
"Marcas brancas": self._analyze_white_marks,
|
26 |
+
"Fibras da íris": self._analyze_fibers,
|
27 |
+
"Borda da íris": self._analyze_border
|
28 |
+
}
|
29 |
|
30 |
+
print("Analisador inicializado com sucesso!")
|
31 |
|
32 |
+
def _preprocess_image(self, image):
|
33 |
+
"""Pré-processa a imagem para análise."""
|
34 |
+
# Converter para array numpy se necessário
|
35 |
+
if isinstance(image, Image.Image):
|
36 |
+
image = np.array(image)
|
|
|
37 |
|
38 |
+
# Converter para escala de cinza se for colorida
|
39 |
+
if len(image.shape) == 3:
|
40 |
+
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
|
|
|
|
41 |
else:
|
42 |
+
gray = image
|
43 |
+
|
44 |
+
# Aplicar equalização de histograma adaptativa
|
45 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
46 |
+
enhanced = clahe.apply(gray)
|
47 |
+
|
48 |
+
return enhanced, image
|
49 |
|
50 |
+
def _analyze_texture(self, image, enhanced):
|
51 |
+
"""Analisa a textura da íris."""
|
52 |
+
# Calcular métricas de textura usando GLCM
|
53 |
+
glcm = cv2.GaussianBlur(enhanced, (5,5), 0)
|
54 |
+
mean_val = np.mean(glcm)
|
55 |
+
std_val = np.std(glcm)
|
56 |
+
|
57 |
+
if std_val > 40:
|
58 |
+
return "Alta texturização", std_val
|
59 |
+
elif std_val > 20:
|
60 |
+
return "Texturização moderada", std_val
|
61 |
+
else:
|
62 |
+
return "Baixa texturização", std_val
|
63 |
+
|
64 |
+
def _analyze_color(self, image, enhanced):
|
65 |
+
"""Analisa a coloração da íris."""
|
66 |
+
if len(image.shape) == 3:
|
67 |
+
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
68 |
+
hue_mean = np.mean(hsv[:,:,0])
|
69 |
+
sat_mean = np.mean(hsv[:,:,1])
|
70 |
+
|
71 |
+
if sat_mean > 100:
|
72 |
+
return "Coloração intensa", sat_mean
|
73 |
+
elif sat_mean > 50:
|
74 |
+
return "Coloração moderada", sat_mean
|
75 |
+
else:
|
76 |
+
return "Coloração suave", sat_mean
|
77 |
+
return "Não foi possível analisar coloração", 0
|
78 |
+
|
79 |
+
def _analyze_spots(self, image, enhanced):
|
80 |
+
"""Analisa manchas na íris."""
|
81 |
+
# Detectar manchas usando thresholding adaptativo
|
82 |
+
thresh = cv2.adaptiveThreshold(enhanced, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
83 |
+
cv2.THRESH_BINARY, 11, 2)
|
84 |
+
contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
85 |
|
86 |
+
spot_count = len([c for c in contours if 10 < cv2.contourArea(c) < 100])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
+
if spot_count > 10:
|
89 |
+
return f"Múltiplas manchas detectadas ({spot_count})", spot_count
|
90 |
+
elif spot_count > 5:
|
91 |
+
return f"Algumas manchas detectadas ({spot_count})", spot_count
|
92 |
+
else:
|
93 |
+
return f"Poucas ou nenhuma mancha detectada ({spot_count})", spot_count
|
94 |
+
|
95 |
+
def _analyze_rings(self, image, enhanced):
|
96 |
+
"""Analisa anéis na íris."""
|
97 |
+
circles = cv2.HoughCircles(enhanced, cv2.HOUGH_GRADIENT, 1, 20,
|
98 |
+
param1=50, param2=30, minRadius=10, maxRadius=30)
|
99 |
+
|
100 |
+
if circles is not None:
|
101 |
+
circle_count = len(circles[0])
|
102 |
+
return f"Detectados {circle_count} anéis/círculos", circle_count
|
103 |
+
return "Nenhum anel/círculo detectado", 0
|
104 |
+
|
105 |
+
def _analyze_lines(self, image, enhanced):
|
106 |
+
"""Analisa linhas radiais."""
|
107 |
+
edges = cv2.Canny(enhanced, 50, 150, apertureSize=3)
|
108 |
+
lines = cv2.HoughLines(edges, 1, np.pi/180, 100)
|
109 |
|
110 |
+
if lines is not None:
|
111 |
+
line_count = len(lines)
|
112 |
+
return f"Detectadas {line_count} linhas radiais", line_count
|
113 |
+
return "Poucas linhas radiais detectadas", 0
|
114 |
+
|
115 |
+
def _analyze_clarity(self, image, enhanced):
|
116 |
+
"""Analisa a clareza geral da imagem."""
|
117 |
+
laplacian_var = cv2.Laplacian(enhanced, cv2.CV_64F).var()
|
118 |
+
|
119 |
+
if laplacian_var > 500:
|
120 |
+
return "Alta clareza", laplacian_var
|
121 |
+
elif laplacian_var > 100:
|
122 |
+
return "Clareza moderada", laplacian_var
|
123 |
+
else:
|
124 |
+
return "Baixa clareza", laplacian_var
|
125 |
+
|
126 |
+
# Implementações simplificadas para os demais métodos
|
127 |
+
def _analyze_pupil(self, image, enhanced):
|
128 |
+
return self._analyze_clarity(image, enhanced)
|
129 |
+
|
130 |
+
def _analyze_pigmentation(self, image, enhanced):
|
131 |
+
return self._analyze_color(image, enhanced)
|
132 |
+
|
133 |
+
def _analyze_tissue(self, image, enhanced):
|
134 |
+
return self._analyze_texture(image, enhanced)
|
135 |
+
|
136 |
+
def _analyze_white_marks(self, image, enhanced):
|
137 |
+
return self._analyze_spots(image, enhanced)
|
138 |
+
|
139 |
+
def _analyze_fibers(self, image, enhanced):
|
140 |
+
return self._analyze_lines(image, enhanced)
|
141 |
+
|
142 |
+
def _analyze_border(self, image, enhanced):
|
143 |
+
return self._analyze_rings(image, enhanced)
|
144 |
+
|
145 |
+
def comprehensive_analysis(self, image):
|
146 |
+
"""Realiza uma análise completa da íris."""
|
147 |
+
try:
|
148 |
+
enhanced, original = self._preprocess_image(image)
|
149 |
+
|
150 |
+
results = []
|
151 |
+
for feature, analysis_func in self.iris_features.items():
|
152 |
+
try:
|
153 |
+
description, value = analysis_func(original, enhanced)
|
154 |
+
results.append({
|
155 |
+
"feature": feature,
|
156 |
+
"analysis": description,
|
157 |
+
"value": value
|
158 |
+
})
|
159 |
+
except Exception as e:
|
160 |
+
print(f"Erro ao analisar '{feature}': {str(e)}")
|
161 |
+
continue
|
162 |
+
|
163 |
+
# Formatar resultados
|
164 |
+
formatted_results = "Análise Detalhada de Iridologia:\n\n"
|
165 |
+
for result in results:
|
166 |
+
formatted_results += f"Característica: {result['feature']}\n"
|
167 |
+
formatted_results += f"Análise: {result['analysis']}\n"
|
168 |
+
if result['value'] > 0:
|
169 |
+
formatted_results += f"Intensidade: {result['value']:.2f}\n"
|
170 |
+
formatted_results += "-" * 50 + "\n"
|
171 |
+
|
172 |
+
return formatted_results
|
173 |
+
|
174 |
+
except Exception as e:
|
175 |
+
return f"Erro durante a análise: {str(e)}"
|
176 |
|
177 |
def create_gradio_interface():
|
178 |
analyzer = IridologyAnalyzer()
|
|
|
180 |
def process_image(image):
|
181 |
if image is None:
|
182 |
return "Por favor, faça o upload de uma imagem."
|
183 |
+
return analyzer.comprehensive_analysis(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
184 |
|
185 |
# Interface Gradio
|
186 |
iface = gr.Interface(
|
187 |
fn=process_image,
|
188 |
+
inputs=gr.Image(type="numpy", label="Upload da Imagem do Olho"),
|
189 |
outputs=gr.Textbox(label="Resultados da Análise", lines=20),
|
190 |
title="Analisador de Iridologia com IA",
|
191 |
description="""
|
192 |
+
Este sistema analisa imagens de íris usando técnicas avançadas de processamento de imagem.
|
193 |
Faça o upload de uma imagem clara do olho para análise.
|
194 |
|
195 |
Recomendações para melhores resultados:
|