Update app.py
Browse files
app.py
CHANGED
|
@@ -11,26 +11,28 @@ import plotly.express as px
|
|
| 11 |
import plotly.graph_objects as go
|
| 12 |
from plotly.subplots import make_subplots
|
| 13 |
import warnings
|
|
|
|
| 14 |
warnings.filterwarnings('ignore')
|
| 15 |
|
| 16 |
-
# ========== SISTEMA DE ANÁLISE DE DADOS ==========
|
| 17 |
|
| 18 |
class AnalisadorDadosAvancado:
|
| 19 |
-
"""Sistema avançado de análise e visualização de dados"""
|
| 20 |
|
| 21 |
def __init__(self):
|
| 22 |
self.df = None
|
| 23 |
self.analises_realizadas = []
|
|
|
|
| 24 |
|
| 25 |
def carregar_dados(self, dados, tipo="json"):
|
| 26 |
-
"""Carrega dados de diferentes fontes"""
|
| 27 |
try:
|
| 28 |
if tipo == "json":
|
| 29 |
-
if hasattr(dados, 'name'):
|
| 30 |
with open(dados.name, 'r', encoding='utf-8') as f:
|
| 31 |
dados_json = json.load(f)
|
| 32 |
self.df = pd.DataFrame(dados_json)
|
| 33 |
-
else:
|
| 34 |
dados_json = json.loads(dados)
|
| 35 |
self.df = pd.DataFrame(dados_json)
|
| 36 |
|
|
@@ -39,187 +41,350 @@ class AnalisadorDadosAvancado:
|
|
| 39 |
|
| 40 |
elif tipo == "excel":
|
| 41 |
self.df = pd.read_excel(dados.name)
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
self.analises_realizadas.append(f"Dados carregados - {self.df.shape[0]} linhas × {self.df.shape[1]} colunas")
|
| 44 |
-
return True, "✅ Dados carregados com sucesso!"
|
| 45 |
|
| 46 |
except Exception as e:
|
| 47 |
return False, f"❌ Erro ao carregar dados: {str(e)}"
|
| 48 |
|
| 49 |
def analise_exploratoria(self):
|
| 50 |
-
"""Realiza análise exploratória completa"""
|
| 51 |
if self.df is None:
|
| 52 |
return "Nenhum dado carregado"
|
| 53 |
|
|
|
|
|
|
|
|
|
|
| 54 |
analise = {
|
| 55 |
'dimensoes': f"{self.df.shape[0]} linhas × {self.df.shape[1]} colunas",
|
| 56 |
'tipos_dados': self.df.dtypes.to_dict(),
|
| 57 |
'valores_nulos': self.df.isnull().sum().to_dict(),
|
| 58 |
-
'
|
| 59 |
-
'
|
| 60 |
-
'
|
| 61 |
-
'
|
|
|
|
|
|
|
| 62 |
}
|
| 63 |
|
| 64 |
self.analises_realizadas.append("Análise exploratória realizada")
|
|
|
|
| 65 |
return analise
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
def gerar_visualizacoes_interativas(self):
|
| 68 |
-
"""Gera visualizações interativas
|
| 69 |
if self.df is None:
|
| 70 |
return None, "Nenhum dado carregado"
|
| 71 |
|
| 72 |
try:
|
| 73 |
colunas_numericas = self.df.select_dtypes(include=[np.number]).columns
|
| 74 |
-
colunas_categoricas = self.df.select_dtypes(include=['object']).columns
|
| 75 |
|
| 76 |
figuras = []
|
| 77 |
|
| 78 |
-
# 1. Heatmap de correlação
|
| 79 |
if len(colunas_numericas) > 1:
|
| 80 |
corr_matrix = self.df[colunas_numericas].corr()
|
| 81 |
-
fig_corr = px.imshow(
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
figuras.append(fig_corr)
|
| 87 |
|
| 88 |
-
# 2.
|
| 89 |
if len(colunas_numericas) > 0:
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
# Histograma
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
#
|
| 109 |
if len(colunas_numericas) >= 2:
|
| 110 |
-
fig_scatter = px.
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
| 113 |
figuras.append(fig_scatter)
|
| 114 |
|
| 115 |
-
#
|
| 116 |
if len(colunas_categoricas) > 0:
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
self.analises_realizadas.append("Visualizações interativas geradas")
|
| 124 |
-
return figuras, "✅
|
| 125 |
|
| 126 |
except Exception as e:
|
| 127 |
return None, f"❌ Erro nas visualizações: {str(e)}"
|
| 128 |
|
| 129 |
-
def analise_estatistica_avancada(self):
|
| 130 |
-
"""Realiza análises estatísticas avançadas"""
|
| 131 |
-
if self.df is None:
|
| 132 |
-
return "Nenhum dado carregado"
|
| 133 |
-
|
| 134 |
-
analise_avancada = {}
|
| 135 |
-
colunas_numericas = self.df.select_dtypes(include=[np.number]).columns
|
| 136 |
-
|
| 137 |
-
for col in colunas_numericas:
|
| 138 |
-
dados = self.df[col].dropna()
|
| 139 |
-
if len(dados) > 0:
|
| 140 |
-
analise_avancada[col] = {
|
| 141 |
-
'assimetria': float(dados.skew()),
|
| 142 |
-
'curtose': float(dados.kurtosis()),
|
| 143 |
-
'variancia': float(dados.var()),
|
| 144 |
-
'coef_variacao': float(dados.std() / dados.mean() if dados.mean() != 0 else 0),
|
| 145 |
-
'intervalo': f"{float(dados.min())} - {float(dados.max())}",
|
| 146 |
-
'q1_q3': f"Q1: {float(dados.quantile(0.25))}, Q3: {float(dados.quantile(0.75))}",
|
| 147 |
-
'outliers': len(dados[(dados < dados.quantile(0.25) - 1.5*(dados.quantile(0.75)-dados.quantile(0.25))) |
|
| 148 |
-
(dados > dados.quantile(0.75) + 1.5*(dados.quantile(0.75)-dados.quantile(0.25)))])
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
self.analises_realizadas.append("Análise estatística avançada realizada")
|
| 152 |
-
return analise_avancada
|
| 153 |
-
|
| 154 |
def gerar_relatorio_executivo(self):
|
| 155 |
-
"""Gera relatório executivo em HTML"""
|
| 156 |
if self.df is None:
|
| 157 |
return "<h3>Nenhum dado carregado para análise</h3>"
|
| 158 |
|
| 159 |
analise_exp = self.analise_exploratoria()
|
| 160 |
-
|
| 161 |
|
| 162 |
html_relatorio = f"""
|
| 163 |
-
<div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width:
|
| 164 |
|
| 165 |
-
<!-- Cabeçalho -->
|
| 166 |
-
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding:
|
| 167 |
-
<h1 style="margin: 0; font-size:
|
| 168 |
-
<p style="
|
|
|
|
| 169 |
</div>
|
| 170 |
|
| 171 |
-
<!--
|
| 172 |
-
<div style="background: #
|
| 173 |
-
<h2 style="
|
| 174 |
-
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(
|
| 175 |
-
<div style="background:
|
| 176 |
-
<
|
| 177 |
-
<p style="
|
|
|
|
| 178 |
</div>
|
| 179 |
-
<div style="background:
|
| 180 |
-
<
|
| 181 |
-
<p style="
|
|
|
|
| 182 |
</div>
|
| 183 |
-
<div style="background:
|
| 184 |
-
<
|
| 185 |
-
<p style="
|
|
|
|
| 186 |
</div>
|
| 187 |
-
<div style="background:
|
| 188 |
-
<
|
| 189 |
-
<p style="
|
|
|
|
| 190 |
</div>
|
| 191 |
</div>
|
| 192 |
</div>
|
| 193 |
|
| 194 |
-
<!--
|
| 195 |
-
<div style="background: #
|
| 196 |
-
<h2 style="color:
|
| 197 |
-
<div style="overflow-x: auto;">
|
| 198 |
"""
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
html_relatorio += stats_df.to_html(classes='table table-striped', float_format='%.2f')
|
| 204 |
-
|
| 205 |
-
html_relatorio += """
|
| 206 |
-
</div>
|
| 207 |
-
</div>
|
| 208 |
|
| 209 |
-
<!-- Análise Estatística Avançada -->
|
| 210 |
-
<div style="background: #fff8e1; padding: 25px; border-radius: 10px; margin-bottom: 25px;">
|
| 211 |
-
<h2 style="color: #2c3e50;">🔬 Análise Estatística Avançada</h2>
|
| 212 |
-
"""
|
| 213 |
-
|
| 214 |
-
for col, stats in analise_estat.items():
|
| 215 |
html_relatorio += f"""
|
| 216 |
-
<div style="background: white; padding:
|
| 217 |
-
<
|
| 218 |
-
|
| 219 |
-
<
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
</div>
|
| 224 |
</div>
|
| 225 |
"""
|
|
@@ -227,28 +392,33 @@ class AnalisadorDadosAvancado:
|
|
| 227 |
html_relatorio += """
|
| 228 |
</div>
|
| 229 |
|
| 230 |
-
<!--
|
| 231 |
-
<div style="background: #
|
| 232 |
-
<h2 style="color: #2c3e50;">💡
|
| 233 |
-
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(
|
| 234 |
"""
|
| 235 |
|
| 236 |
-
# Insights automáticos
|
| 237 |
insights = self.gerar_insights_automaticos()
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
| 239 |
html_relatorio += f"""
|
| 240 |
-
<div style="background: white; padding:
|
| 241 |
-
<p style="margin: 0; color: #2c3e50;">{insight}</p>
|
| 242 |
</div>
|
| 243 |
"""
|
| 244 |
|
| 245 |
-
html_relatorio += """
|
| 246 |
</div>
|
| 247 |
</div>
|
| 248 |
|
| 249 |
<!-- Rodapé -->
|
| 250 |
-
<div style="text-align: center; margin-top:
|
| 251 |
-
<
|
|
|
|
|
|
|
|
|
|
| 252 |
</div>
|
| 253 |
|
| 254 |
</div>
|
|
@@ -257,42 +427,54 @@ class AnalisadorDadosAvancado:
|
|
| 257 |
return html_relatorio
|
| 258 |
|
| 259 |
def gerar_insights_automaticos(self):
|
| 260 |
-
"""Gera insights automáticos
|
| 261 |
insights = []
|
| 262 |
|
| 263 |
-
if self.df is None:
|
| 264 |
-
return insights
|
| 265 |
|
| 266 |
-
|
| 267 |
|
| 268 |
-
for col in
|
| 269 |
-
|
| 270 |
-
if
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
if
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
| 290 |
|
| 291 |
-
return insights
|
| 292 |
|
| 293 |
# ========== INTERFACE GRADIO ==========
|
| 294 |
|
| 295 |
-
# Inicializar analisador
|
| 296 |
analisador = AnalisadorDadosAvancado()
|
| 297 |
|
| 298 |
def interface_carregar_dados(arquivo, tipo_dados, json_texto):
|
|
@@ -310,18 +492,21 @@ def interface_carregar_dados(arquivo, tipo_dados, json_texto):
|
|
| 310 |
return None, "⚠️ Selecione um arquivo ou insira dados JSON"
|
| 311 |
|
| 312 |
if sucesso:
|
| 313 |
-
# Gerar análise exploratória inicial
|
| 314 |
analise = analisador.analise_exploratoria()
|
| 315 |
resumo = f"""
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
"""
|
| 324 |
-
return analisador.df.head(
|
| 325 |
else:
|
| 326 |
return None, mensagem
|
| 327 |
|
|
@@ -332,148 +517,362 @@ def interface_visualizacoes():
|
|
| 332 |
"""Interface para geração de visualizações"""
|
| 333 |
try:
|
| 334 |
figuras, mensagem = analisador.gerar_visualizacoes_interativas()
|
| 335 |
-
if figuras:
|
| 336 |
-
|
| 337 |
-
return figuras[0], mensagem
|
| 338 |
else:
|
| 339 |
-
return None, mensagem
|
| 340 |
except Exception as e:
|
| 341 |
-
return None, f"❌ Erro
|
| 342 |
|
| 343 |
def interface_relatorio():
|
| 344 |
"""Interface para geração de relatório"""
|
| 345 |
-
|
| 346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
|
| 348 |
def interface_analise_estatistica():
|
| 349 |
-
"""Interface para análise estatística"""
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
resultado +=
|
| 358 |
-
resultado +=
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
-
# Configuração da interface Gradio
|
| 368 |
with gr.Blocks(
|
| 369 |
theme=gr.themes.Soft(
|
| 370 |
-
primary_hue="
|
| 371 |
-
secondary_hue="
|
|
|
|
| 372 |
),
|
| 373 |
-
title="📊 DataAnalyzer Pro - Análise
|
| 374 |
css="""
|
| 375 |
.gradio-container {
|
| 376 |
-
max-width:
|
|
|
|
| 377 |
}
|
| 378 |
.table {
|
| 379 |
width: 100%;
|
| 380 |
border-collapse: collapse;
|
|
|
|
| 381 |
}
|
| 382 |
.table th, .table td {
|
| 383 |
-
border: 1px solid #
|
| 384 |
-
padding:
|
| 385 |
text-align: left;
|
| 386 |
}
|
| 387 |
.table th {
|
| 388 |
-
background
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
}
|
| 390 |
"""
|
| 391 |
) as demo:
|
| 392 |
|
| 393 |
gr.Markdown("""
|
| 394 |
-
# 📊 DataAnalyzer Pro
|
| 395 |
-
##
|
| 396 |
|
| 397 |
-
*
|
|
|
|
| 398 |
""")
|
| 399 |
|
| 400 |
-
with gr.Tab("📁 Carregar Dados"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
with gr.Row():
|
| 402 |
-
with gr.Column():
|
| 403 |
-
gr.Markdown("### 🔧 Configuração de Entrada")
|
| 404 |
tipo_dados = gr.Radio(
|
| 405 |
choices=["json_arquivo", "json_texto", "csv", "excel"],
|
| 406 |
-
label="
|
| 407 |
value="json_arquivo",
|
| 408 |
-
info="
|
| 409 |
)
|
| 410 |
|
| 411 |
arquivo_upload = gr.File(
|
| 412 |
-
label="Upload de Arquivo",
|
| 413 |
file_types=[".json", ".csv", ".xlsx", ".xls"],
|
| 414 |
visible=True
|
| 415 |
)
|
| 416 |
|
| 417 |
json_input = gr.Textbox(
|
| 418 |
-
label="Dados JSON (
|
| 419 |
-
placeholder='[{"
|
| 420 |
-
lines=
|
| 421 |
visible=False
|
| 422 |
)
|
| 423 |
|
| 424 |
-
carregar_btn = gr.Button("🚀 Carregar
|
| 425 |
|
| 426 |
-
with gr.Column():
|
| 427 |
-
gr.Markdown("### 👁️
|
| 428 |
preview_tabela = gr.Dataframe(
|
| 429 |
-
label="
|
| 430 |
interactive=False,
|
| 431 |
-
|
| 432 |
)
|
| 433 |
|
| 434 |
info_carregamento = gr.Markdown(
|
| 435 |
-
|
| 436 |
-
value="Aguardando dados..."
|
| 437 |
)
|
| 438 |
|
| 439 |
-
with gr.Tab("📈 Visualizações"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
with gr.Row():
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
info_visualizacoes = gr.Markdown(label="Status das Visualizações")
|
| 444 |
-
|
| 445 |
-
with gr.Column():
|
| 446 |
-
gr.Markdown("### 📊 Gráficos Interativos")
|
| 447 |
-
visualizacoes_output = gr.Plot(
|
| 448 |
-
label="Visualizações",
|
| 449 |
-
show_label=True
|
| 450 |
-
)
|
| 451 |
-
|
| 452 |
-
with gr.Tab("🔬 Análise Estatística"):
|
| 453 |
with gr.Row():
|
| 454 |
with gr.Column():
|
| 455 |
-
|
| 456 |
-
|
| 457 |
with gr.Column():
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
)
|
| 462 |
|
| 463 |
-
with gr.Tab("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
with gr.Row():
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
|
| 474 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
|
| 476 |
-
# Controle de visibilidade dos inputs
|
| 477 |
def atualizar_inputs(tipo_dados):
|
| 478 |
if tipo_dados == "json_texto":
|
| 479 |
return gr.update(visible=False), gr.update(visible=True)
|
|
@@ -486,77 +885,33 @@ with gr.Blocks(
|
|
| 486 |
outputs=[arquivo_upload, json_input]
|
| 487 |
)
|
| 488 |
|
| 489 |
-
# Carregar dados
|
| 490 |
carregar_btn.click(
|
| 491 |
interface_carregar_dados,
|
| 492 |
inputs=[arquivo_upload, tipo_dados, json_input],
|
| 493 |
outputs=[preview_tabela, info_carregamento]
|
| 494 |
)
|
| 495 |
|
| 496 |
-
# Gerar visualizações
|
| 497 |
gerar_viz_btn.click(
|
| 498 |
interface_visualizacoes,
|
| 499 |
-
outputs=[
|
| 500 |
)
|
| 501 |
|
| 502 |
-
# Análise estatística
|
| 503 |
analise_estat_btn.click(
|
| 504 |
interface_analise_estatistica,
|
| 505 |
outputs=[resultado_estatistica]
|
| 506 |
)
|
| 507 |
|
| 508 |
-
# Gerar relatório
|
| 509 |
gerar_relatorio_btn.click(
|
| 510 |
interface_relatorio,
|
| 511 |
outputs=[relatorio_output]
|
| 512 |
)
|
| 513 |
-
|
| 514 |
-
# ========== EXEMPLOS E INFORMAÇÕES ==========
|
| 515 |
-
|
| 516 |
-
gr.Markdown("""
|
| 517 |
-
---
|
| 518 |
-
|
| 519 |
-
## 🎯 Funcionalidades Principais
|
| 520 |
-
|
| 521 |
-
| Módulo | Descrição | Tecnologias |
|
| 522 |
-
|--------|-----------|-------------|
|
| 523 |
-
| **📁 Carregamento** | Suporte a JSON, CSV, Excel | Pandas, JSON |
|
| 524 |
-
| **📈 Visualizações** | Gráficos interativos com Plotly | Plotly, Matplotlib |
|
| 525 |
-
| **🔬 Análise Estatística** | Estatísticas descritivas e avançadas | NumPy, SciPy |
|
| 526 |
-
| **📋 Relatórios** | Relatórios executivos automáticos | HTML, CSS |
|
| 527 |
-
| **💡 Insights** | Análise automática de dados | Algoritmos estatísticos |
|
| 528 |
-
|
| 529 |
-
## 📊 Tipos de Análise Incluídas
|
| 530 |
-
|
| 531 |
-
- **Estatística Descritiva**: Média, mediana, desvio padrão, quartis
|
| 532 |
-
- **Análise de Distribuição**: Assimetria, curtose, histogramas
|
| 533 |
-
- **Detecção de Outliers**: Identificação automática de valores atípicos
|
| 534 |
-
- **Análise de Correlação**: Mapas de calor e matriz de correlação
|
| 535 |
-
- **Visualizações Interativas**: Gráficos responsivos e exploratórios
|
| 536 |
-
|
| 537 |
-
## 🚀 Como Usar
|
| 538 |
-
|
| 539 |
-
1. **Carregue seus dados** em JSON, CSV ou Excel
|
| 540 |
-
2. **Explore visualizações** interativas
|
| 541 |
-
3. **Analise estatísticas** avançadas
|
| 542 |
-
4. **Gere relatórios** executivos automáticos
|
| 543 |
-
5. **Exporte insights** para tomada de decisão
|
| 544 |
-
|
| 545 |
-
## 📋 Exemplo de Dados JSON
|
| 546 |
-
|
| 547 |
-
```json
|
| 548 |
-
[
|
| 549 |
-
{"nome": "João", "idade": 25, "salario": 50000, "departamento": "TI"},
|
| 550 |
-
{"nome": "Maria", "idade": 32, "salario": 75000, "departamento": "Vendas"},
|
| 551 |
-
{"nome": "Pedro", "idade": 28, "salario": 60000, "departamento": "Marketing"}
|
| 552 |
-
]
|
| 553 |
-
```
|
| 554 |
-
""")
|
| 555 |
|
| 556 |
# ========== EXECUÇÃO ==========
|
| 557 |
|
| 558 |
if __name__ == "__main__":
|
| 559 |
demo.launch(
|
| 560 |
server_name="0.0.0.0",
|
| 561 |
-
|
|
|
|
|
|
|
| 562 |
)
|
|
|
|
| 11 |
import plotly.graph_objects as go
|
| 12 |
from plotly.subplots import make_subplots
|
| 13 |
import warnings
|
| 14 |
+
from scipy import stats
|
| 15 |
warnings.filterwarnings('ignore')
|
| 16 |
|
| 17 |
+
# ========== SISTEMA DE ANÁLISE DE DADOS AVANÇADO ==========
|
| 18 |
|
| 19 |
class AnalisadorDadosAvancado:
|
| 20 |
+
"""Sistema avançado de análise e visualização de dados com 5-sigma de precisão"""
|
| 21 |
|
| 22 |
def __init__(self):
|
| 23 |
self.df = None
|
| 24 |
self.analises_realizadas = []
|
| 25 |
+
self.historico_analises = {}
|
| 26 |
|
| 27 |
def carregar_dados(self, dados, tipo="json"):
|
| 28 |
+
"""Carrega dados de diferentes fontes com validação robusta"""
|
| 29 |
try:
|
| 30 |
if tipo == "json":
|
| 31 |
+
if hasattr(dados, 'name'):
|
| 32 |
with open(dados.name, 'r', encoding='utf-8') as f:
|
| 33 |
dados_json = json.load(f)
|
| 34 |
self.df = pd.DataFrame(dados_json)
|
| 35 |
+
else:
|
| 36 |
dados_json = json.loads(dados)
|
| 37 |
self.df = pd.DataFrame(dados_json)
|
| 38 |
|
|
|
|
| 41 |
|
| 42 |
elif tipo == "excel":
|
| 43 |
self.df = pd.read_excel(dados.name)
|
| 44 |
+
|
| 45 |
+
# Validação de dados
|
| 46 |
+
if self.df.empty:
|
| 47 |
+
return False, "❌ Arquivo vazio - nenhum dado para processar"
|
| 48 |
+
|
| 49 |
+
# Converter colunas numéricas
|
| 50 |
+
for col in self.df.columns:
|
| 51 |
+
try:
|
| 52 |
+
self.df[col] = pd.to_numeric(self.df[col], errors='ignore')
|
| 53 |
+
except:
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
self.analises_realizadas.append(f"Dados carregados - {self.df.shape[0]} linhas × {self.df.shape[1]} colunas")
|
| 57 |
+
return True, f"✅ Dados carregados com sucesso!\n📊 {self.df.shape[0]} linhas × {self.df.shape[1]} colunas"
|
| 58 |
|
| 59 |
except Exception as e:
|
| 60 |
return False, f"❌ Erro ao carregar dados: {str(e)}"
|
| 61 |
|
| 62 |
def analise_exploratoria(self):
|
| 63 |
+
"""Realiza análise exploratória completa com estatísticas de 5-sigma"""
|
| 64 |
if self.df is None:
|
| 65 |
return "Nenhum dado carregado"
|
| 66 |
|
| 67 |
+
colunas_numericas = self.df.select_dtypes(include=[np.number]).columns.tolist()
|
| 68 |
+
colunas_categoricas = self.df.select_dtypes(include=['object', 'category']).columns.tolist()
|
| 69 |
+
|
| 70 |
analise = {
|
| 71 |
'dimensoes': f"{self.df.shape[0]} linhas × {self.df.shape[1]} colunas",
|
| 72 |
'tipos_dados': self.df.dtypes.to_dict(),
|
| 73 |
'valores_nulos': self.df.isnull().sum().to_dict(),
|
| 74 |
+
'percentual_nulos': (self.df.isnull().sum() / len(self.df) * 100).to_dict(),
|
| 75 |
+
'estatisticas_descritivas': self.df.describe().to_dict() if len(colunas_numericas) > 0 else {},
|
| 76 |
+
'colunas_numericas': colunas_numericas,
|
| 77 |
+
'colunas_categoricas': colunas_categoricas,
|
| 78 |
+
'memoria_uso': f"{self.df.memory_usage(deep=True).sum() / 1024**2:.2f} MB",
|
| 79 |
+
'valores_unicos': {col: self.df[col].nunique() for col in self.df.columns}
|
| 80 |
}
|
| 81 |
|
| 82 |
self.analises_realizadas.append("Análise exploratória realizada")
|
| 83 |
+
self.historico_analises['exploratoria'] = analise
|
| 84 |
return analise
|
| 85 |
|
| 86 |
+
def analise_estatistica_cinco_sigma(self):
|
| 87 |
+
"""Análise estatística com precisão 5-sigma (99.99994% confiança)"""
|
| 88 |
+
if self.df is None:
|
| 89 |
+
return "Nenhum dado carregado"
|
| 90 |
+
|
| 91 |
+
analise_avancada = {}
|
| 92 |
+
colunas_numericas = self.df.select_dtypes(include=[np.number]).columns
|
| 93 |
+
|
| 94 |
+
for col in colunas_numericas:
|
| 95 |
+
dados = self.df[col].dropna()
|
| 96 |
+
if len(dados) < 2:
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
# Estatísticas básicas
|
| 100 |
+
media = float(dados.mean())
|
| 101 |
+
mediana = float(dados.median())
|
| 102 |
+
desvio = float(dados.std())
|
| 103 |
+
|
| 104 |
+
# 5-sigma bounds (99.99994% confiança)
|
| 105 |
+
limite_inf_5sigma = media - 5 * desvio
|
| 106 |
+
limite_sup_5sigma = media + 5 * desvio
|
| 107 |
+
|
| 108 |
+
# 3-sigma bounds (99.7% confiança)
|
| 109 |
+
limite_inf_3sigma = media - 3 * desvio
|
| 110 |
+
limite_sup_3sigma = media + 3 * desvio
|
| 111 |
+
|
| 112 |
+
# Outliers em diferentes níveis
|
| 113 |
+
outliers_5sigma = len(dados[(dados < limite_inf_5sigma) | (dados > limite_sup_5sigma)])
|
| 114 |
+
outliers_3sigma = len(dados[(dados < limite_inf_3sigma) | (dados > limite_sup_3sigma)])
|
| 115 |
+
|
| 116 |
+
# IQR para outliers tradicionais
|
| 117 |
+
q1 = float(dados.quantile(0.25))
|
| 118 |
+
q3 = float(dados.quantile(0.75))
|
| 119 |
+
iqr = q3 - q1
|
| 120 |
+
outliers_iqr = len(dados[(dados < q1 - 1.5*iqr) | (dados > q3 + 1.5*iqr)])
|
| 121 |
+
|
| 122 |
+
# Testes de normalidade
|
| 123 |
+
shapiro_stat, shapiro_p = stats.shapiro(dados.sample(min(5000, len(dados))))
|
| 124 |
+
|
| 125 |
+
# Intervalo de confiança 99.99994% (5-sigma)
|
| 126 |
+
ic_5sigma = stats.t.interval(0.9999994, len(dados)-1,
|
| 127 |
+
loc=media,
|
| 128 |
+
scale=stats.sem(dados))
|
| 129 |
+
|
| 130 |
+
analise_avancada[col] = {
|
| 131 |
+
'media': media,
|
| 132 |
+
'mediana': mediana,
|
| 133 |
+
'desvio_padrao': desvio,
|
| 134 |
+
'assimetria': float(dados.skew()),
|
| 135 |
+
'curtose': float(dados.kurtosis()),
|
| 136 |
+
'variancia': float(dados.var()),
|
| 137 |
+
'coef_variacao': float(desvio / media * 100 if media != 0 else 0),
|
| 138 |
+
'intervalo': f"{float(dados.min()):.2f} - {float(dados.max()):.2f}",
|
| 139 |
+
'amplitude': float(dados.max() - dados.min()),
|
| 140 |
+
'q1': q1,
|
| 141 |
+
'q3': q3,
|
| 142 |
+
'iqr': iqr,
|
| 143 |
+
'outliers_iqr': outliers_iqr,
|
| 144 |
+
'outliers_3sigma': outliers_3sigma,
|
| 145 |
+
'outliers_5sigma': outliers_5sigma,
|
| 146 |
+
'limite_inf_5sigma': limite_inf_5sigma,
|
| 147 |
+
'limite_sup_5sigma': limite_sup_5sigma,
|
| 148 |
+
'ic_5sigma_inf': float(ic_5sigma[0]),
|
| 149 |
+
'ic_5sigma_sup': float(ic_5sigma[1]),
|
| 150 |
+
'normalidade_shapiro_stat': float(shapiro_stat),
|
| 151 |
+
'normalidade_shapiro_p': float(shapiro_p),
|
| 152 |
+
'eh_normal': shapiro_p > 0.05,
|
| 153 |
+
'confianca_5sigma': '99.99994%'
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
self.analises_realizadas.append("Análise 5-sigma realizada")
|
| 157 |
+
self.historico_analises['cinco_sigma'] = analise_avancada
|
| 158 |
+
return analise_avancada
|
| 159 |
+
|
| 160 |
def gerar_visualizacoes_interativas(self):
|
| 161 |
+
"""Gera visualizações interativas de alta qualidade"""
|
| 162 |
if self.df is None:
|
| 163 |
return None, "Nenhum dado carregado"
|
| 164 |
|
| 165 |
try:
|
| 166 |
colunas_numericas = self.df.select_dtypes(include=[np.number]).columns
|
| 167 |
+
colunas_categoricas = self.df.select_dtypes(include=['object', 'category']).columns
|
| 168 |
|
| 169 |
figuras = []
|
| 170 |
|
| 171 |
+
# 1. Heatmap de correlação com anotações
|
| 172 |
if len(colunas_numericas) > 1:
|
| 173 |
corr_matrix = self.df[colunas_numericas].corr()
|
| 174 |
+
fig_corr = px.imshow(
|
| 175 |
+
corr_matrix,
|
| 176 |
+
title="🔥 Mapa de Correlação - Análise 5-Sigma",
|
| 177 |
+
color_continuous_scale="RdBu_r",
|
| 178 |
+
aspect="auto",
|
| 179 |
+
text_auto='.2f'
|
| 180 |
+
)
|
| 181 |
+
fig_corr.update_layout(
|
| 182 |
+
height=600,
|
| 183 |
+
title_font_size=20,
|
| 184 |
+
title_x=0.5
|
| 185 |
+
)
|
| 186 |
figuras.append(fig_corr)
|
| 187 |
|
| 188 |
+
# 2. Distribuições com limites 5-sigma
|
| 189 |
if len(colunas_numericas) > 0:
|
| 190 |
+
for col in list(colunas_numericas)[:4]: # Primeiras 4 variáveis
|
| 191 |
+
dados = self.df[col].dropna()
|
| 192 |
+
media = dados.mean()
|
| 193 |
+
desvio = dados.std()
|
| 194 |
+
|
| 195 |
+
fig = go.Figure()
|
| 196 |
+
|
| 197 |
# Histograma
|
| 198 |
+
fig.add_trace(go.Histogram(
|
| 199 |
+
x=dados,
|
| 200 |
+
name='Distribuição',
|
| 201 |
+
nbinsx=50,
|
| 202 |
+
marker_color='lightblue',
|
| 203 |
+
opacity=0.7
|
| 204 |
+
))
|
| 205 |
+
|
| 206 |
+
# Linhas de referência (5-sigma)
|
| 207 |
+
fig.add_vline(x=media, line_dash="dash", line_color="red",
|
| 208 |
+
annotation_text="Média", annotation_position="top")
|
| 209 |
+
fig.add_vline(x=media - 5*desvio, line_dash="dot", line_color="orange",
|
| 210 |
+
annotation_text="-5σ", annotation_position="bottom left")
|
| 211 |
+
fig.add_vline(x=media + 5*desvio, line_dash="dot", line_color="orange",
|
| 212 |
+
annotation_text="+5σ", annotation_position="bottom right")
|
| 213 |
+
|
| 214 |
+
fig.update_layout(
|
| 215 |
+
title=f"📊 Distribuição com Limites 5-Sigma: {col}",
|
| 216 |
+
xaxis_title=col,
|
| 217 |
+
yaxis_title="Frequência",
|
| 218 |
+
height=500,
|
| 219 |
+
showlegend=True
|
| 220 |
+
)
|
| 221 |
+
figuras.append(fig)
|
| 222 |
+
|
| 223 |
+
# 3. Box plots comparativos
|
| 224 |
+
if len(colunas_numericas) > 0:
|
| 225 |
+
fig_box = go.Figure()
|
| 226 |
+
for col in colunas_numericas:
|
| 227 |
+
fig_box.add_trace(go.Box(
|
| 228 |
+
y=self.df[col],
|
| 229 |
+
name=col,
|
| 230 |
+
boxmean='sd'
|
| 231 |
+
))
|
| 232 |
|
| 233 |
+
fig_box.update_layout(
|
| 234 |
+
title="📦 Box Plots Comparativos - Todas as Variáveis",
|
| 235 |
+
yaxis_title="Valores",
|
| 236 |
+
height=500,
|
| 237 |
+
showlegend=True
|
| 238 |
+
)
|
| 239 |
+
figuras.append(fig_box)
|
| 240 |
|
| 241 |
+
# 4. Scatter matrix (se houver 2+ variáveis numéricas)
|
| 242 |
if len(colunas_numericas) >= 2:
|
| 243 |
+
fig_scatter = px.scatter_matrix(
|
| 244 |
+
self.df[list(colunas_numericas)[:5]], # Primeiras 5 variáveis
|
| 245 |
+
title="🎯 Matriz de Dispersão - Análise Multivariada",
|
| 246 |
+
height=800
|
| 247 |
+
)
|
| 248 |
+
fig_scatter.update_traces(diagonal_visible=False)
|
| 249 |
figuras.append(fig_scatter)
|
| 250 |
|
| 251 |
+
# 5. Gráfico de barras para categóricas
|
| 252 |
if len(colunas_categoricas) > 0:
|
| 253 |
+
for col_cat in list(colunas_categoricas)[:2]: # Primeiras 2 categóricas
|
| 254 |
+
contagem = self.df[col_cat].value_counts().head(15)
|
| 255 |
+
fig_bar = px.bar(
|
| 256 |
+
x=contagem.index,
|
| 257 |
+
y=contagem.values,
|
| 258 |
+
title=f"📊 Top 15 - {col_cat}",
|
| 259 |
+
labels={'x': col_cat, 'y': 'Contagem'},
|
| 260 |
+
color=contagem.values,
|
| 261 |
+
color_continuous_scale='Viridis'
|
| 262 |
+
)
|
| 263 |
+
fig_bar.update_layout(height=500, showlegend=False)
|
| 264 |
+
figuras.append(fig_bar)
|
| 265 |
|
| 266 |
self.analises_realizadas.append("Visualizações interativas geradas")
|
| 267 |
+
return figuras, f"✅ {len(figuras)} visualizações criadas com sucesso!"
|
| 268 |
|
| 269 |
except Exception as e:
|
| 270 |
return None, f"❌ Erro nas visualizações: {str(e)}"
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
def gerar_relatorio_executivo(self):
|
| 273 |
+
"""Gera relatório executivo completo em HTML"""
|
| 274 |
if self.df is None:
|
| 275 |
return "<h3>Nenhum dado carregado para análise</h3>"
|
| 276 |
|
| 277 |
analise_exp = self.analise_exploratoria()
|
| 278 |
+
analise_sigma = self.analise_estatistica_cinco_sigma()
|
| 279 |
|
| 280 |
html_relatorio = f"""
|
| 281 |
+
<div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 1400px; margin: 20px auto; padding: 20px; background: #ffffff; border-radius: 15px; box-shadow: 0 8px 16px rgba(0,0,0,0.1);">
|
| 282 |
|
| 283 |
+
<!-- Cabeçalho Principal -->
|
| 284 |
+
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px; border-radius: 15px; margin-bottom: 30px; text-align: center;">
|
| 285 |
+
<h1 style="margin: 0; font-size: 3em; font-weight: 700; text-shadow: 2px 2px 4px rgba(0,0,0,0.2);">📊 RELATÓRIO EXECUTIVO</h1>
|
| 286 |
+
<p style="font-size: 1.3em; opacity: 0.95; margin-top: 15px;">Análise de Dados com Precisão 5-Sigma (99.99994% Confiança)</p>
|
| 287 |
+
<p style="font-size: 1.1em; opacity: 0.85; margin-top: 10px;">📅 {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}</p>
|
| 288 |
</div>
|
| 289 |
|
| 290 |
+
<!-- KPIs Principais -->
|
| 291 |
+
<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 30px; border-radius: 15px; margin-bottom: 30px; color: white;">
|
| 292 |
+
<h2 style="margin: 0 0 20px 0; text-align: center; font-size: 2em;">🎯 Indicadores Chave (KPIs)</h2>
|
| 293 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px;">
|
| 294 |
+
<div style="background: rgba(255,255,255,0.2); backdrop-filter: blur(10px); padding: 20px; border-radius: 12px; text-align: center; border: 2px solid rgba(255,255,255,0.3);">
|
| 295 |
+
<div style="font-size: 2.5em; font-weight: bold;">📈</div>
|
| 296 |
+
<p style="margin: 10px 0 5px 0; font-size: 0.9em; opacity: 0.9;">Total de Registros</p>
|
| 297 |
+
<p style="font-size: 2em; font-weight: bold; margin: 0;">{self.df.shape[0]:,}</p>
|
| 298 |
</div>
|
| 299 |
+
<div style="background: rgba(255,255,255,0.2); backdrop-filter: blur(10px); padding: 20px; border-radius: 12px; text-align: center; border: 2px solid rgba(255,255,255,0.3);">
|
| 300 |
+
<div style="font-size: 2.5em; font-weight: bold;">🔢</div>
|
| 301 |
+
<p style="margin: 10px 0 5px 0; font-size: 0.9em; opacity: 0.9;">Variáveis Numéricas</p>
|
| 302 |
+
<p style="font-size: 2em; font-weight: bold; margin: 0;">{len(analise_exp['colunas_numericas'])}</p>
|
| 303 |
</div>
|
| 304 |
+
<div style="background: rgba(255,255,255,0.2); backdrop-filter: blur(10px); padding: 20px; border-radius: 12px; text-align: center; border: 2px solid rgba(255,255,255,0.3);">
|
| 305 |
+
<div style="font-size: 2.5em; font-weight: bold;">📝</div>
|
| 306 |
+
<p style="margin: 10px 0 5px 0; font-size: 0.9em; opacity: 0.9;">Variáveis Categóricas</p>
|
| 307 |
+
<p style="font-size: 2em; font-weight: bold; margin: 0;">{len(analise_exp['colunas_categoricas'])}</p>
|
| 308 |
</div>
|
| 309 |
+
<div style="background: rgba(255,255,255,0.2); backdrop-filter: blur(10px); padding: 20px; border-radius: 12px; text-align: center; border: 2px solid rgba(255,255,255,0.3);">
|
| 310 |
+
<div style="font-size: 2.5em; font-weight: bold;">💾</div>
|
| 311 |
+
<p style="margin: 10px 0 5px 0; font-size: 0.9em; opacity: 0.9;">Memória Utilizada</p>
|
| 312 |
+
<p style="font-size: 2em; font-weight: bold; margin: 0;">{analise_exp['memoria_uso']}</p>
|
| 313 |
</div>
|
| 314 |
</div>
|
| 315 |
</div>
|
| 316 |
|
| 317 |
+
<!-- Análise 5-Sigma -->
|
| 318 |
+
<div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); padding: 30px; border-radius: 15px; margin-bottom: 30px; color: #2c3e50;">
|
| 319 |
+
<h2 style="margin: 0 0 20px 0; text-align: center; font-size: 2em; color: white; text-shadow: 1px 1px 3px rgba(0,0,0,0.3);">🔬 ANÁLISE ESTATÍSTICA 5-SIGMA</h2>
|
|
|
|
| 320 |
"""
|
| 321 |
|
| 322 |
+
for col, stats in analise_sigma.items():
|
| 323 |
+
status_normalidade = "✅ Normal" if stats['eh_normal'] else "⚠️ Não-Normal"
|
| 324 |
+
cor_normalidade = "#27ae60" if stats['eh_normal'] else "#e74c3c"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
html_relatorio += f"""
|
| 327 |
+
<div style="background: white; padding: 25px; margin: 15px 0; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); border-left: 6px solid #3498db;">
|
| 328 |
+
<h3 style="color: #2c3e50; margin: 0 0 20px 0; font-size: 1.5em; display: flex; align-items: center; justify-content: space-between;">
|
| 329 |
+
<span>📊 {col}</span>
|
| 330 |
+
<span style="background: {cor_normalidade}; color: white; padding: 5px 15px; border-radius: 20px; font-size: 0.7em;">{status_normalidade}</span>
|
| 331 |
+
</h3>
|
| 332 |
+
|
| 333 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin-bottom: 20px;">
|
| 334 |
+
<div style="background: #ecf0f1; padding: 15px; border-radius: 8px;">
|
| 335 |
+
<strong style="color: #7f8c8d;">📈 Média:</strong> <span style="font-size: 1.2em; color: #2c3e50;">{stats['media']:.4f}</span>
|
| 336 |
+
</div>
|
| 337 |
+
<div style="background: #ecf0f1; padding: 15px; border-radius: 8px;">
|
| 338 |
+
<strong style="color: #7f8c8d;">📊 Mediana:</strong> <span style="font-size: 1.2em; color: #2c3e50;">{stats['mediana']:.4f}</span>
|
| 339 |
+
</div>
|
| 340 |
+
<div style="background: #ecf0f1; padding: 15px; border-radius: 8px;">
|
| 341 |
+
<strong style="color: #7f8c8d;">📉 Desvio Padrão:</strong> <span style="font-size: 1.2em; color: #2c3e50;">{stats['desvio_padrao']:.4f}</span>
|
| 342 |
+
</div>
|
| 343 |
+
<div style="background: #ecf0f1; padding: 15px; border-radius: 8px;">
|
| 344 |
+
<strong style="color: #7f8c8d;">📐 Coef. Variação:</strong> <span style="font-size: 1.2em; color: #2c3e50;">{stats['coef_variacao']:.2f}%</span>
|
| 345 |
+
</div>
|
| 346 |
+
</div>
|
| 347 |
+
|
| 348 |
+
<div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
|
| 349 |
+
<h4 style="margin: 0 0 10px 0; color: #856404;">🎯 Limites 5-Sigma (Confiança: {stats['confianca_5sigma']})</h4>
|
| 350 |
+
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
| 351 |
+
<div><strong>Limite Inferior:</strong> {stats['limite_inf_5sigma']:.4f}</div>
|
| 352 |
+
<div><strong>Limite Superior:</strong> {stats['limite_sup_5sigma']:.4f}</div>
|
| 353 |
+
<div><strong>IC 5σ Inferior:</strong> {stats['ic_5sigma_inf']:.4f}</div>
|
| 354 |
+
<div><strong>IC 5σ Superior:</strong> {stats['ic_5sigma_sup']:.4f}</div>
|
| 355 |
+
</div>
|
| 356 |
+
</div>
|
| 357 |
+
|
| 358 |
+
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 15px;">
|
| 359 |
+
<div style="background: #d4edda; padding: 15px; border-radius: 8px; text-align: center; border: 2px solid #28a745;">
|
| 360 |
+
<div style="font-size: 2em; font-weight: bold; color: #155724;">{stats['outliers_iqr']}</div>
|
| 361 |
+
<div style="color: #155724; font-size: 0.9em;">Outliers IQR</div>
|
| 362 |
+
</div>
|
| 363 |
+
<div style="background: #fff3cd; padding: 15px; border-radius: 8px; text-align: center; border: 2px solid #ffc107;">
|
| 364 |
+
<div style="font-size: 2em; font-weight: bold; color: #856404;">{stats['outliers_3sigma']}</div>
|
| 365 |
+
<div style="color: #856404; font-size: 0.9em;">Outliers 3σ (99.7%)</div>
|
| 366 |
+
</div>
|
| 367 |
+
<div style="background: #f8d7da; padding: 15px; border-radius: 8px; text-align: center; border: 2px solid #dc3545;">
|
| 368 |
+
<div style="font-size: 2em; font-weight: bold; color: #721c24;">{stats['outliers_5sigma']}</div>
|
| 369 |
+
<div style="color: #721c24; font-size: 0.9em;">Outliers 5σ (99.99994%)</div>
|
| 370 |
+
</div>
|
| 371 |
+
</div>
|
| 372 |
+
|
| 373 |
+
<div style="background: #e7f3ff; padding: 15px; border-radius: 8px; border-left: 4px solid #2196f3;">
|
| 374 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
|
| 375 |
+
<div><strong>Assimetria:</strong> {stats['assimetria']:.4f}</div>
|
| 376 |
+
<div><strong>Curtose:</strong> {stats['curtose']:.4f}</div>
|
| 377 |
+
<div><strong>Q1:</strong> {stats['q1']:.4f}</div>
|
| 378 |
+
<div><strong>Q3:</strong> {stats['q3']:.4f}</div>
|
| 379 |
+
<div><strong>IQR:</strong> {stats['iqr']:.4f}</div>
|
| 380 |
+
<div><strong>Amplitude:</strong> {stats['amplitude']:.4f}</div>
|
| 381 |
+
</div>
|
| 382 |
+
</div>
|
| 383 |
+
|
| 384 |
+
<div style="background: #f0f0f0; padding: 12px; border-radius: 8px; margin-top: 15px; font-size: 0.9em;">
|
| 385 |
+
<strong>📋 Teste Shapiro-Wilk:</strong>
|
| 386 |
+
Estatística = {stats['normalidade_shapiro_stat']:.6f},
|
| 387 |
+
p-valor = {stats['normalidade_shapiro_p']:.6f}
|
| 388 |
</div>
|
| 389 |
</div>
|
| 390 |
"""
|
|
|
|
| 392 |
html_relatorio += """
|
| 393 |
</div>
|
| 394 |
|
| 395 |
+
<!-- Insights Automáticos -->
|
| 396 |
+
<div style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); padding: 30px; border-radius: 15px; margin-bottom: 30px;">
|
| 397 |
+
<h2 style="margin: 0 0 20px 0; text-align: center; font-size: 2em; color: #2c3e50;">💡 INSIGHTS AUTOMÁTICOS</h2>
|
| 398 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 15px;">
|
| 399 |
"""
|
| 400 |
|
|
|
|
| 401 |
insights = self.gerar_insights_automaticos()
|
| 402 |
+
cores_insights = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c']
|
| 403 |
+
|
| 404 |
+
for i, insight in enumerate(insights):
|
| 405 |
+
cor = cores_insights[i % len(cores_insights)]
|
| 406 |
html_relatorio += f"""
|
| 407 |
+
<div style="background: white; padding: 20px; border-radius: 10px; border-left: 5px solid {cor}; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
|
| 408 |
+
<p style="margin: 0; color: #2c3e50; line-height: 1.6;">{insight}</p>
|
| 409 |
</div>
|
| 410 |
"""
|
| 411 |
|
| 412 |
+
html_relatorio += f"""
|
| 413 |
</div>
|
| 414 |
</div>
|
| 415 |
|
| 416 |
<!-- Rodapé -->
|
| 417 |
+
<div style="text-align: center; margin-top: 40px; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white;">
|
| 418 |
+
<h3 style="margin: 0 0 15px 0;">✨ DataAnalyzer Pro - Análise 5-Sigma</h3>
|
| 419 |
+
<p style="margin: 5px 0; opacity: 0.9;">Precisão Estatística de 99.99994% | Confiança de 5 Desvios Padrão</p>
|
| 420 |
+
<p style="margin: 5px 0; opacity: 0.85;">Relatório gerado em {datetime.now().strftime('%d/%m/%Y às %H:%M:%S')}</p>
|
| 421 |
+
<p style="margin: 15px 0 0 0; font-size: 0.9em; opacity: 0.75;">© 2025 DataAnalyzer Pro - Todos os direitos reservados</p>
|
| 422 |
</div>
|
| 423 |
|
| 424 |
</div>
|
|
|
|
| 427 |
return html_relatorio
|
| 428 |
|
| 429 |
def gerar_insights_automaticos(self):
|
| 430 |
+
"""Gera insights automáticos com análise 5-sigma"""
|
| 431 |
insights = []
|
| 432 |
|
| 433 |
+
if self.df is None or 'cinco_sigma' not in self.historico_analises:
|
| 434 |
+
return ["✅ Execute a análise estatística para gerar insights automáticos"]
|
| 435 |
|
| 436 |
+
analise_sigma = self.historico_analises['cinco_sigma']
|
| 437 |
|
| 438 |
+
for col, stats in analise_sigma.items():
|
| 439 |
+
# Insight sobre normalidade
|
| 440 |
+
if stats['eh_normal']:
|
| 441 |
+
insights.append(f"✅ <strong>{col}</strong>: Distribuição normal confirmada (p-valor Shapiro: {stats['normalidade_shapiro_p']:.4f}). Métodos paramétricos podem ser aplicados com segurança.")
|
| 442 |
+
else:
|
| 443 |
+
insights.append(f"⚠️ <strong>{col}</strong>: Distribuição não-normal detectada. Considere transformações ou métodos não-paramétricos.")
|
| 444 |
+
|
| 445 |
+
# Insight sobre variabilidade
|
| 446 |
+
cv = stats['coef_variacao']
|
| 447 |
+
if cv < 10:
|
| 448 |
+
insights.append(f"📊 <strong>{col}</strong>: Baixa variabilidade (CV: {cv:.2f}%) - Dados muito homogêneos.")
|
| 449 |
+
elif cv > 30:
|
| 450 |
+
insights.append(f"📈 <strong>{col}</strong>: Alta variabilidade (CV: {cv:.2f}%) - Considere segmentação dos dados.")
|
| 451 |
+
|
| 452 |
+
# Insight sobre outliers 5-sigma
|
| 453 |
+
if stats['outliers_5sigma'] > 0:
|
| 454 |
+
insights.append(f"🎯 <strong>{col}</strong>: {stats['outliers_5sigma']} valores extremos detectados fora dos limites 5-sigma (eventos raríssimos).")
|
| 455 |
+
elif stats['outliers_3sigma'] > 0:
|
| 456 |
+
insights.append(f"⚡ <strong>{col}</strong>: {stats['outliers_3sigma']} outliers moderados (fora de 3σ) mas dentro de 5σ.")
|
| 457 |
+
|
| 458 |
+
# Insight sobre assimetria
|
| 459 |
+
skew = abs(stats['assimetria'])
|
| 460 |
+
if skew > 1:
|
| 461 |
+
direcao = "positiva (cauda à direita)" if stats['assimetria'] > 0 else "negativa (cauda à esquerda)"
|
| 462 |
+
insights.append(f"📐 <strong>{col}</strong>: Assimetria {direcao} forte (|skew|={skew:.2f}). Considere transformação logarítmica.")
|
| 463 |
+
|
| 464 |
+
# Insight sobre curtose
|
| 465 |
+
if abs(stats['curtose']) > 3:
|
| 466 |
+
tipo = "leptocúrtica (caudas pesadas)" if stats['curtose'] > 0 else "platicúrtica (caudas leves)"
|
| 467 |
+
insights.append(f"📉 <strong>{col}</strong>: Distribuição {tipo} - valores extremos {'mais' if stats['curtose'] > 0 else 'menos'} prováveis que distribuição normal.")
|
| 468 |
|
| 469 |
+
# Insight geral sobre qualidade dos dados
|
| 470 |
+
total_outliers_5sigma = sum(s['outliers_5sigma'] for s in analise_sigma.values())
|
| 471 |
+
if total_outliers_5sigma == 0:
|
| 472 |
+
insights.append(f"🏆 <strong>Excelente!</strong> Nenhum outlier 5-sigma detectado em {len(analise_sigma)} variáveis. Dados de altíssima qualidade estatística.")
|
| 473 |
|
| 474 |
+
return insights[:10] # Retornar no máximo 10 insights
|
| 475 |
|
| 476 |
# ========== INTERFACE GRADIO ==========
|
| 477 |
|
|
|
|
| 478 |
analisador = AnalisadorDadosAvancado()
|
| 479 |
|
| 480 |
def interface_carregar_dados(arquivo, tipo_dados, json_texto):
|
|
|
|
| 492 |
return None, "⚠️ Selecione um arquivo ou insira dados JSON"
|
| 493 |
|
| 494 |
if sucesso:
|
|
|
|
| 495 |
analise = analisador.analise_exploratoria()
|
| 496 |
resumo = f"""
|
| 497 |
+
## ✅ Dados Carregados com Sucesso!
|
| 498 |
+
|
| 499 |
+
### 📊 Resumo Geral
|
| 500 |
+
- **Dimensões:** {analise['dimensoes']}
|
| 501 |
+
- **Variáveis Numéricas:** {len(analise['colunas_numericas'])}
|
| 502 |
+
- **Variáveis Categóricas:** {len(analise['colunas_categoricas'])}
|
| 503 |
+
- **Uso de Memória:** {analise['memoria_uso']}
|
| 504 |
+
|
| 505 |
+
### 🔍 Variáveis Detectadas
|
| 506 |
+
**Numéricas:** {', '.join(analise['colunas_numericas'][:5])}{'...' if len(analise['colunas_numericas']) > 5 else ''}
|
| 507 |
+
**Categóricas:** {', '.join(analise['colunas_categoricas'][:5])}{'...' if len(analise['colunas_categoricas']) > 5 else ''}
|
| 508 |
"""
|
| 509 |
+
return analisador.df.head(20), resumo
|
| 510 |
else:
|
| 511 |
return None, mensagem
|
| 512 |
|
|
|
|
| 517 |
"""Interface para geração de visualizações"""
|
| 518 |
try:
|
| 519 |
figuras, mensagem = analisador.gerar_visualizacoes_interativas()
|
| 520 |
+
if figuras and len(figuras) > 0:
|
| 521 |
+
return figuras[0], figuras[1] if len(figuras) > 1 else figuras[0], mensagem
|
|
|
|
| 522 |
else:
|
| 523 |
+
return None, None, mensagem
|
| 524 |
except Exception as e:
|
| 525 |
+
return None, None, f"❌ Erro: {str(e)}"
|
| 526 |
|
| 527 |
def interface_relatorio():
|
| 528 |
"""Interface para geração de relatório"""
|
| 529 |
+
try:
|
| 530 |
+
# Garantir que análise 5-sigma foi executada
|
| 531 |
+
if 'cinco_sigma' not in analisador.historico_analises:
|
| 532 |
+
analisador.analise_estatistica_cinco_sigma()
|
| 533 |
+
relatorio = analisador.gerar_relatorio_executivo()
|
| 534 |
+
return relatorio
|
| 535 |
+
except Exception as e:
|
| 536 |
+
return f"<div style='padding: 20px; color: red;'>❌ Erro ao gerar relatório: {str(e)}</div>"
|
| 537 |
|
| 538 |
def interface_analise_estatistica():
|
| 539 |
+
"""Interface para análise estatística 5-sigma"""
|
| 540 |
+
try:
|
| 541 |
+
analise = analisador.analise_estatistica_cinco_sigma()
|
| 542 |
+
|
| 543 |
+
if isinstance(analise, str):
|
| 544 |
+
return analise
|
| 545 |
+
|
| 546 |
+
resultado = "# 📊 ANÁLISE ESTATÍSTICA 5-SIGMA\n\n"
|
| 547 |
+
resultado += "*Precisão de 99.99994% de confiança estatística*\n\n"
|
| 548 |
+
resultado += "---\n\n"
|
| 549 |
+
|
| 550 |
+
for col, stats in analise.items():
|
| 551 |
+
status = "✅ Normal" if stats['eh_normal'] else "⚠️ Não-Normal"
|
| 552 |
+
resultado += f"## 📈 {col} {status}\n\n"
|
| 553 |
+
|
| 554 |
+
resultado += f"### Estatísticas Centrais\n"
|
| 555 |
+
resultado += f"- **Média:** {stats['media']:.6f}\n"
|
| 556 |
+
resultado += f"- **Mediana:** {stats['mediana']:.6f}\n"
|
| 557 |
+
resultado += f"- **Desvio Padrão:** {stats['desvio_padrao']:.6f}\n"
|
| 558 |
+
resultado += f"- **Coeficiente de Variação:** {stats['coef_variacao']:.2f}%\n\n"
|
| 559 |
+
|
| 560 |
+
resultado += f"### Análise 5-Sigma (Confiança: {stats['confianca_5sigma']})\n"
|
| 561 |
+
resultado += f"- **Limite Inferior 5σ:** {stats['limite_inf_5sigma']:.6f}\n"
|
| 562 |
+
resultado += f"- **Limite Superior 5σ:** {stats['limite_sup_5sigma']:.6f}\n"
|
| 563 |
+
resultado += f"- **IC 5σ Inferior:** {stats['ic_5sigma_inf']:.6f}\n"
|
| 564 |
+
resultado += f"- **IC 5σ Superior:** {stats['ic_5sigma_sup']:.6f}\n\n"
|
| 565 |
+
|
| 566 |
+
resultado += f"### Detecção de Outliers\n"
|
| 567 |
+
resultado += f"- **Outliers IQR (Método Tradicional):** {stats['outliers_iqr']}\n"
|
| 568 |
+
resultado += f"- **Outliers 3σ (99.7% confiança):** {stats['outliers_3sigma']}\n"
|
| 569 |
+
resultado += f"- **Outliers 5σ (99.99994% confiança):** {stats['outliers_5sigma']}\n\n"
|
| 570 |
+
|
| 571 |
+
resultado += f"### Forma da Distribuição\n"
|
| 572 |
+
resultado += f"- **Assimetria (Skewness):** {stats['assimetria']:.6f}\n"
|
| 573 |
+
resultado += f"- **Curtose (Kurtosis):** {stats['curtose']:.6f}\n"
|
| 574 |
+
resultado += f"- **Teste Shapiro-Wilk:** Estatística={stats['normalidade_shapiro_stat']:.6f}, p-valor={stats['normalidade_shapiro_p']:.6f}\n\n"
|
| 575 |
+
|
| 576 |
+
resultado += f"### Quartis e Dispersão\n"
|
| 577 |
+
resultado += f"- **Q1 (25%):** {stats['q1']:.6f}\n"
|
| 578 |
+
resultado += f"- **Q3 (75%):** {stats['q3']:.6f}\n"
|
| 579 |
+
resultado += f"- **IQR (Intervalo Interquartil):** {stats['iqr']:.6f}\n"
|
| 580 |
+
resultado += f"- **Amplitude Total:** {stats['amplitude']:.6f}\n\n"
|
| 581 |
+
|
| 582 |
+
resultado += "---\n\n"
|
| 583 |
+
|
| 584 |
+
return resultado
|
| 585 |
+
|
| 586 |
+
except Exception as e:
|
| 587 |
+
return f"❌ Erro na análise: {str(e)}"
|
| 588 |
+
|
| 589 |
+
# ========== CONFIGURAÇÃO DA INTERFACE GRADIO ==========
|
| 590 |
|
|
|
|
| 591 |
with gr.Blocks(
|
| 592 |
theme=gr.themes.Soft(
|
| 593 |
+
primary_hue="indigo",
|
| 594 |
+
secondary_hue="purple",
|
| 595 |
+
neutral_hue="slate",
|
| 596 |
),
|
| 597 |
+
title="📊 DataAnalyzer Pro - Análise 5-Sigma",
|
| 598 |
css="""
|
| 599 |
.gradio-container {
|
| 600 |
+
max-width: 1600px !important;
|
| 601 |
+
font-family: 'Inter', 'Segoe UI', sans-serif;
|
| 602 |
}
|
| 603 |
.table {
|
| 604 |
width: 100%;
|
| 605 |
border-collapse: collapse;
|
| 606 |
+
font-size: 0.9em;
|
| 607 |
}
|
| 608 |
.table th, .table td {
|
| 609 |
+
border: 1px solid #e0e0e0;
|
| 610 |
+
padding: 10px;
|
| 611 |
text-align: left;
|
| 612 |
}
|
| 613 |
.table th {
|
| 614 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 615 |
+
color: white;
|
| 616 |
+
font-weight: 600;
|
| 617 |
+
}
|
| 618 |
+
.table tr:nth-child(even) {
|
| 619 |
+
background-color: #f8f9fa;
|
| 620 |
+
}
|
| 621 |
+
.table tr:hover {
|
| 622 |
+
background-color: #e3f2fd;
|
| 623 |
}
|
| 624 |
"""
|
| 625 |
) as demo:
|
| 626 |
|
| 627 |
gr.Markdown("""
|
| 628 |
+
# 📊 DataAnalyzer Pro - Sistema de Análise 5-Sigma
|
| 629 |
+
## *Precisão Estatística de 99.99994% | Análise de Dados de Nível Científico*
|
| 630 |
|
| 631 |
+
> **5-Sigma**: O padrão ouro em análise estatística - usado em descobertas científicas como o Bóson de Higgs.
|
| 632 |
+
> Representa uma confiança de 99.99994%, equivalente a apenas 1 falso positivo em 3.5 milhões de observações.
|
| 633 |
""")
|
| 634 |
|
| 635 |
+
with gr.Tab("📁 1. Carregar Dados"):
|
| 636 |
+
gr.Markdown("""
|
| 637 |
+
### 🔧 Importação de Dados
|
| 638 |
+
Suporte completo para **JSON**, **CSV** e **Excel** com validação automática e detecção de tipos.
|
| 639 |
+
""")
|
| 640 |
+
|
| 641 |
with gr.Row():
|
| 642 |
+
with gr.Column(scale=1):
|
|
|
|
| 643 |
tipo_dados = gr.Radio(
|
| 644 |
choices=["json_arquivo", "json_texto", "csv", "excel"],
|
| 645 |
+
label="📂 Formato dos Dados",
|
| 646 |
value="json_arquivo",
|
| 647 |
+
info="Escolha o formato do seu dataset"
|
| 648 |
)
|
| 649 |
|
| 650 |
arquivo_upload = gr.File(
|
| 651 |
+
label="📤 Upload de Arquivo",
|
| 652 |
file_types=[".json", ".csv", ".xlsx", ".xls"],
|
| 653 |
visible=True
|
| 654 |
)
|
| 655 |
|
| 656 |
json_input = gr.Textbox(
|
| 657 |
+
label="📝 Dados JSON (Colar aqui)",
|
| 658 |
+
placeholder='[{"variavel1": 100, "variavel2": "categoria"}, ...]',
|
| 659 |
+
lines=8,
|
| 660 |
visible=False
|
| 661 |
)
|
| 662 |
|
| 663 |
+
carregar_btn = gr.Button("🚀 Carregar e Analisar", variant="primary", size="lg")
|
| 664 |
|
| 665 |
+
with gr.Column(scale=2):
|
| 666 |
+
gr.Markdown("### 👁️ Pré-visualização dos Dados")
|
| 667 |
preview_tabela = gr.Dataframe(
|
| 668 |
+
label="Primeiras 20 linhas do dataset",
|
| 669 |
interactive=False,
|
| 670 |
+
wrap=True
|
| 671 |
)
|
| 672 |
|
| 673 |
info_carregamento = gr.Markdown(
|
| 674 |
+
value="💡 **Aguardando dados...** Faça upload de um arquivo ou cole dados JSON."
|
|
|
|
| 675 |
)
|
| 676 |
|
| 677 |
+
with gr.Tab("📈 2. Visualizações Interativas"):
|
| 678 |
+
gr.Markdown("""
|
| 679 |
+
### 🎨 Visualizações com Plotly
|
| 680 |
+
Gráficos interativos de alta qualidade incluindo limites 5-sigma, distribuições e análises multivariadas.
|
| 681 |
+
""")
|
| 682 |
+
|
| 683 |
with gr.Row():
|
| 684 |
+
gerar_viz_btn = gr.Button("🎨 Gerar Todas as Visualizações", variant="primary", size="lg")
|
| 685 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 686 |
with gr.Row():
|
| 687 |
with gr.Column():
|
| 688 |
+
visualizacao_1 = gr.Plot(label="📊 Visualização 1")
|
|
|
|
| 689 |
with gr.Column():
|
| 690 |
+
visualizacao_2 = gr.Plot(label="📊 Visualização 2")
|
| 691 |
+
|
| 692 |
+
info_visualizacoes = gr.Markdown(value="Clique no botão acima para gerar visualizações interativas")
|
|
|
|
| 693 |
|
| 694 |
+
with gr.Tab("🔬 3. Análise Estatística 5-Sigma"):
|
| 695 |
+
gr.Markdown("""
|
| 696 |
+
### 📐 Análise com Precisão Científica
|
| 697 |
+
|
| 698 |
+
**O que é 5-Sigma?**
|
| 699 |
+
- 📊 **Confiança:** 99.99994% (praticamente certeza absoluta)
|
| 700 |
+
- 🎯 **Aplicação:** Usado em física de partículas, controle de qualidade Six Sigma
|
| 701 |
+
- ⚡ **Outliers:** Detecta apenas eventos extremamente raros
|
| 702 |
+
- 🔬 **Comparação:** 3-sigma = 99.7% | 5-sigma = 99.99994%
|
| 703 |
+
""")
|
| 704 |
+
|
| 705 |
with gr.Row():
|
| 706 |
+
analise_estat_btn = gr.Button("📐 Executar Análise 5-Sigma Completa", variant="primary", size="lg")
|
| 707 |
+
|
| 708 |
+
resultado_estatistica = gr.Markdown(
|
| 709 |
+
label="📋 Resultados da Análise",
|
| 710 |
+
value="Clique no botão para iniciar a análise estatística com precisão 5-sigma"
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
with gr.Tab("📋 4. Relatório Executivo"):
|
| 714 |
+
gr.Markdown("""
|
| 715 |
+
### 📄 Relatório Automático Completo
|
| 716 |
+
Relatório HTML profissional com todos os KPIs, estatísticas 5-sigma, visualizações e insights automáticos.
|
| 717 |
+
""")
|
| 718 |
+
|
| 719 |
+
with gr.Row():
|
| 720 |
+
gerar_relatorio_btn = gr.Button("📄 Gerar Relatório Executivo Completo", variant="primary", size="lg")
|
| 721 |
+
|
| 722 |
+
relatorio_output = gr.HTML(
|
| 723 |
+
label="📊 Relatório Interativo",
|
| 724 |
+
value="""
|
| 725 |
+
<div style='text-align: center; padding: 100px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white;'>
|
| 726 |
+
<h2 style='margin: 0; font-size: 2em;'>📊 Relatório Executivo</h2>
|
| 727 |
+
<p style='margin-top: 20px; font-size: 1.2em; opacity: 0.9;'>Clique no botão acima para gerar o relatório completo</p>
|
| 728 |
+
<p style='margin-top: 10px; opacity: 0.8;'>✨ Análise 5-Sigma | KPIs | Insights Automáticos</p>
|
| 729 |
+
</div>
|
| 730 |
+
"""
|
| 731 |
+
)
|
| 732 |
|
| 733 |
+
with gr.Tab("📚 Documentação"):
|
| 734 |
+
gr.Markdown("""
|
| 735 |
+
# 📖 Guia Completo do DataAnalyzer Pro
|
| 736 |
+
|
| 737 |
+
## 🎯 Funcionalidades Principais
|
| 738 |
+
|
| 739 |
+
| Recurso | Descrição | Tecnologia |
|
| 740 |
+
|---------|-----------|------------|
|
| 741 |
+
| **📁 Importação Universal** | JSON, CSV, Excel com validação automática | Pandas |
|
| 742 |
+
| **📊 Análise 5-Sigma** | Precisão de 99.99994% - padrão científico | SciPy, NumPy |
|
| 743 |
+
| **🎨 Visualizações** | Gráficos interativos profissionais | Plotly |
|
| 744 |
+
| **📋 Relatórios HTML** | Documentos executivos automáticos | HTML5/CSS3 |
|
| 745 |
+
| **💡 Insights IA** | Análise automática inteligente | Algoritmos estatísticos |
|
| 746 |
+
| **🔍 Detecção Outliers** | 3 níveis: IQR, 3-sigma, 5-sigma | Análise multivariada |
|
| 747 |
+
|
| 748 |
+
## 📊 Análises Incluídas
|
| 749 |
+
|
| 750 |
+
### Estatísticas Descritivas
|
| 751 |
+
- ✅ Medidas de tendência central (média, mediana, moda)
|
| 752 |
+
- ✅ Medidas de dispersão (desvio padrão, variância, amplitude)
|
| 753 |
+
- ✅ Quartis e percentis completos
|
| 754 |
+
- ✅ Coeficiente de variação
|
| 755 |
+
|
| 756 |
+
### Análise de Distribuição
|
| 757 |
+
- ✅ Assimetria (skewness) - detecta enviesamento
|
| 758 |
+
- ✅ Curtose (kurtosis) - analisa caudas da distribuição
|
| 759 |
+
- ✅ Teste Shapiro-Wilk para normalidade
|
| 760 |
+
- ✅ Histogramas com densidade
|
| 761 |
+
|
| 762 |
+
### Detecção de Outliers (3 Níveis)
|
| 763 |
+
1. **IQR (Método Tradicional)**: Q1 - 1.5×IQR e Q3 + 1.5×IQR
|
| 764 |
+
2. **3-Sigma (99.7%)**: μ ± 3σ - padrão industrial
|
| 765 |
+
3. **5-Sigma (99.99994%)**: μ ± 5σ - padrão científico
|
| 766 |
+
|
| 767 |
+
### Análise Multivariada
|
| 768 |
+
- ✅ Matriz de correlação com heatmap
|
| 769 |
+
- ✅ Scatter plots para relações bivariadas
|
| 770 |
+
- ✅ Box plots comparativos
|
| 771 |
+
- ✅ Análise de componentes principais (PCA) ready
|
| 772 |
+
|
| 773 |
+
## 🚀 Como Usar - Passo a Passo
|
| 774 |
+
|
| 775 |
+
### 1️⃣ Carregar Dados
|
| 776 |
+
```
|
| 777 |
+
1. Escolha o formato (JSON/CSV/Excel)
|
| 778 |
+
2. Faça upload do arquivo
|
| 779 |
+
3. Visualize a prévia dos dados
|
| 780 |
+
4. Confirme o carregamento
|
| 781 |
+
```
|
| 782 |
+
|
| 783 |
+
### 2️⃣ Explorar Visualizações
|
| 784 |
+
```
|
| 785 |
+
1. Clique em "Gerar Visualizações"
|
| 786 |
+
2. Explore gráficos interativos
|
| 787 |
+
3. Identifique padrões visuais
|
| 788 |
+
4. Analise correlações
|
| 789 |
+
```
|
| 790 |
+
|
| 791 |
+
### 3️⃣ Análise Estatística
|
| 792 |
+
```
|
| 793 |
+
1. Execute análise 5-Sigma
|
| 794 |
+
2. Revise estatísticas detalhadas
|
| 795 |
+
3. Identifique outliers
|
| 796 |
+
4. Valide normalidade dos dados
|
| 797 |
+
```
|
| 798 |
+
|
| 799 |
+
### 4️⃣ Gerar Relatório
|
| 800 |
+
```
|
| 801 |
+
1. Gere relatório executivo
|
| 802 |
+
2. Revise KPIs automáticos
|
| 803 |
+
3. Leia insights da IA
|
| 804 |
+
4. Exporte para apresentação
|
| 805 |
+
```
|
| 806 |
+
|
| 807 |
+
## 📋 Exemplos de Dados
|
| 808 |
+
|
| 809 |
+
### JSON Simples
|
| 810 |
+
```json
|
| 811 |
+
[
|
| 812 |
+
{"nome": "Produto A", "vendas": 1500, "lucro": 450, "categoria": "Eletrônicos"},
|
| 813 |
+
{"nome": "Produto B", "vendas": 2300, "lucro": 690, "categoria": "Livros"},
|
| 814 |
+
{"nome": "Produto C", "vendas": 1800, "lucro": 540, "categoria": "Eletrônicos"}
|
| 815 |
+
]
|
| 816 |
+
```
|
| 817 |
+
|
| 818 |
+
### CSV Exemplo
|
| 819 |
+
```csv
|
| 820 |
+
nome,idade,salario,departamento
|
| 821 |
+
João Silva,28,5500,TI
|
| 822 |
+
Maria Santos,35,7200,Vendas
|
| 823 |
+
Pedro Costa,42,8900,Gerência
|
| 824 |
+
```
|
| 825 |
+
|
| 826 |
+
## 🎓 Conceitos Estatísticos
|
| 827 |
+
|
| 828 |
+
### O que é 5-Sigma?
|
| 829 |
+
|
| 830 |
+
**5-Sigma** representa 5 desvios padrão da média. É o padrão de precisão usado em:
|
| 831 |
+
- 🔬 Descoberta do Bóson de Higgs (CERN)
|
| 832 |
+
- 🏭 Six Sigma em manufatura (Motorola, GE)
|
| 833 |
+
- 🧬 Estudos clínicos e farmacêuticos
|
| 834 |
+
- 📡 Detecção de sinais em astrofísica
|
| 835 |
+
|
| 836 |
+
**Probabilidades:**
|
| 837 |
+
- 1-Sigma (68.27%): Intervalo comum
|
| 838 |
+
- 2-Sigma (95.45%): Intervalo de confiança padrão
|
| 839 |
+
- 3-Sigma (99.73%): Controle de qualidade industrial
|
| 840 |
+
- 4-Sigma (99.9937%): Alta confiabilidade
|
| 841 |
+
- **5-Sigma (99.99994%)**: Certeza científica
|
| 842 |
+
|
| 843 |
+
### Interpretação de Outliers
|
| 844 |
+
|
| 845 |
+
- **Outliers IQR**: Valores incomuns mas não necessariamente erros
|
| 846 |
+
- **Outliers 3σ**: Valores raros que merecem investigação
|
| 847 |
+
- **Outliers 5σ**: Eventos extremamente raros - possíveis erros de medição
|
| 848 |
+
|
| 849 |
+
## 🛠️ Tecnologias Utilizadas
|
| 850 |
+
|
| 851 |
+
- **Backend:** Python 3.10+
|
| 852 |
+
- **Interface:** Gradio 4.x
|
| 853 |
+
- **Análise:** Pandas, NumPy, SciPy
|
| 854 |
+
- **Visualização:** Plotly, Matplotlib, Seaborn
|
| 855 |
+
- **Estatística:** Statsmodels, SciPy.stats
|
| 856 |
+
|
| 857 |
+
## 💡 Dicas de Uso
|
| 858 |
+
|
| 859 |
+
1. **Dados Limpos**: Remove valores nulos antes da análise
|
| 860 |
+
2. **Tamanho Amostral**: Mínimo 30 observações para estatísticas confiáveis
|
| 861 |
+
3. **Normalidade**: Verifique teste Shapiro-Wilk antes de métodos paramétricos
|
| 862 |
+
4. **Outliers**: Investigue 5-sigma outliers - podem ser erros de digitação
|
| 863 |
+
5. **Correlação ≠ Causalidade**: Correlações não implicam relação causal
|
| 864 |
+
|
| 865 |
+
## 📞 Suporte
|
| 866 |
+
|
| 867 |
+
Para dúvidas ou sugestões, consulte a documentação completa ou entre em contato com o suporte técnico.
|
| 868 |
+
|
| 869 |
+
---
|
| 870 |
+
|
| 871 |
+
**DataAnalyzer Pro v2.0** | Desenvolvido com ❤️ para análise de dados científica
|
| 872 |
+
""")
|
| 873 |
+
|
| 874 |
+
# ========== EVENTOS E INTERAÇÕES ==========
|
| 875 |
|
|
|
|
| 876 |
def atualizar_inputs(tipo_dados):
|
| 877 |
if tipo_dados == "json_texto":
|
| 878 |
return gr.update(visible=False), gr.update(visible=True)
|
|
|
|
| 885 |
outputs=[arquivo_upload, json_input]
|
| 886 |
)
|
| 887 |
|
|
|
|
| 888 |
carregar_btn.click(
|
| 889 |
interface_carregar_dados,
|
| 890 |
inputs=[arquivo_upload, tipo_dados, json_input],
|
| 891 |
outputs=[preview_tabela, info_carregamento]
|
| 892 |
)
|
| 893 |
|
|
|
|
| 894 |
gerar_viz_btn.click(
|
| 895 |
interface_visualizacoes,
|
| 896 |
+
outputs=[visualizacao_1, visualizacao_2, info_visualizacoes]
|
| 897 |
)
|
| 898 |
|
|
|
|
| 899 |
analise_estat_btn.click(
|
| 900 |
interface_analise_estatistica,
|
| 901 |
outputs=[resultado_estatistica]
|
| 902 |
)
|
| 903 |
|
|
|
|
| 904 |
gerar_relatorio_btn.click(
|
| 905 |
interface_relatorio,
|
| 906 |
outputs=[relatorio_output]
|
| 907 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 908 |
|
| 909 |
# ========== EXECUÇÃO ==========
|
| 910 |
|
| 911 |
if __name__ == "__main__":
|
| 912 |
demo.launch(
|
| 913 |
server_name="0.0.0.0",
|
| 914 |
+
server_port=7860,
|
| 915 |
+
share=True,
|
| 916 |
+
show_error=True
|
| 917 |
)
|