Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +17 -71
src/streamlit_app.py
CHANGED
|
@@ -2,21 +2,19 @@ import streamlit as st
|
|
| 2 |
import torch
|
| 3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
from urllib.parse import urlparse
|
| 5 |
-
import pandas as pd
|
| 6 |
import io
|
| 7 |
|
| 8 |
# --- CONFIGURAÇÕES ---
|
| 9 |
-
# ⚠️
|
| 10 |
-
MODEL_ID = "asilvamaia/ident_br"
|
| 11 |
|
| 12 |
-
|
| 13 |
-
st.set_page_config(page_title="Validador de Domínios .BR", page_icon="🇧🇷")
|
| 14 |
|
| 15 |
-
# --- FUNÇÃO DE LIMPEZA (V11) ---
|
| 16 |
def limpar_entrada(texto: str) -> str:
|
| 17 |
texto = str(texto).strip().lower()
|
| 18 |
if not texto: return ""
|
| 19 |
-
if "@" in texto: return texto
|
| 20 |
|
| 21 |
if "http" not in texto and "://" not in texto:
|
| 22 |
texto_temp = "http://" + texto
|
|
@@ -27,100 +25,48 @@ def limpar_entrada(texto: str) -> str:
|
|
| 27 |
parsed = urlparse(texto_temp)
|
| 28 |
dominio_limpo = parsed.netloc if parsed.netloc else texto
|
| 29 |
|
| 30 |
-
if ":" in dominio_limpo:
|
| 31 |
dominio_limpo = dominio_limpo.split(':')[0]
|
| 32 |
|
| 33 |
-
if dominio_limpo.startswith("www."):
|
| 34 |
dominio_limpo = dominio_limpo[4:]
|
| 35 |
|
| 36 |
return dominio_limpo
|
| 37 |
except:
|
| 38 |
return texto
|
| 39 |
|
| 40 |
-
# --- CARREGAMENTO DO MODELO (COM CACHE) ---
|
| 41 |
-
# O cache impede que o modelo seja recarregado a cada clique, deixando o app rápido
|
| 42 |
@st.cache_resource
|
| 43 |
def load_model():
|
| 44 |
try:
|
| 45 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 46 |
model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
|
| 47 |
-
# No Space gratuito usamos CPU
|
| 48 |
model.to("cpu")
|
| 49 |
model.eval()
|
| 50 |
return tokenizer, model
|
| 51 |
except Exception as e:
|
| 52 |
-
st.error(f"Erro ao carregar
|
| 53 |
return None, None
|
| 54 |
|
| 55 |
tokenizer, model = load_model()
|
| 56 |
|
| 57 |
-
|
| 58 |
-
st.title("🇧🇷 Validador de Domínios .BR com IA")
|
| 59 |
-
st.write("Faça upload de uma lista suja (.txt) e a IA extrairá apenas os domínios .br válidos.")
|
| 60 |
|
| 61 |
-
uploaded_file = st.file_uploader("
|
| 62 |
|
| 63 |
-
if uploaded_file
|
| 64 |
-
# Lê o arquivo
|
| 65 |
stringio = io.StringIO(uploaded_file.getvalue().decode("utf-8"))
|
| 66 |
linhas = stringio.readlines()
|
| 67 |
|
| 68 |
-
st.
|
| 69 |
-
|
| 70 |
-
if st.button("Iniciar Limpeza"):
|
| 71 |
validos = []
|
| 72 |
rejeitados = []
|
| 73 |
|
| 74 |
-
# Barra de progresso
|
| 75 |
progress_bar = st.progress(0)
|
|
|
|
| 76 |
|
| 77 |
-
# Processamento (Batch size 1 para simplicidade visual ou aumentar se precisar)
|
| 78 |
-
# Como é CPU, vamos processar linha a linha para atualizar a barra
|
| 79 |
for i, linha in enumerate(linhas):
|
| 80 |
original = linha.strip()
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
# Inferência
|
| 86 |
-
inputs = tokenizer(limpo, return_tensors="pt", truncation=True, max_length=128)
|
| 87 |
-
with torch.no_grad():
|
| 88 |
-
outputs = model(**inputs)
|
| 89 |
-
pred = torch.argmax(outputs.logits, dim=1).item()
|
| 90 |
-
|
| 91 |
-
# Regras de Validação
|
| 92 |
-
if pred == 1 and "." in limpo and "@" not in limpo:
|
| 93 |
-
validos.append(limpo)
|
| 94 |
-
else:
|
| 95 |
-
rejeitados.append(original)
|
| 96 |
-
|
| 97 |
-
# Atualiza barra a cada 10 itens para não travar a UI
|
| 98 |
-
if i % 10 == 0:
|
| 99 |
-
progress_bar.progress((i + 1) / len(linhas))
|
| 100 |
-
|
| 101 |
-
progress_bar.progress(100)
|
| 102 |
-
|
| 103 |
-
# --- RESULTADOS ---
|
| 104 |
-
st.success("Processamento Concluído!")
|
| 105 |
-
|
| 106 |
-
col1, col2 = st.columns(2)
|
| 107 |
-
with col1:
|
| 108 |
-
st.metric("✅ Aprovados", len(validos))
|
| 109 |
-
with col2:
|
| 110 |
-
st.metric("🔴 Rejeitados", len(rejeitados))
|
| 111 |
-
|
| 112 |
-
# --- DOWNLOAD ---
|
| 113 |
-
# Remove duplicatas
|
| 114 |
-
validos_unicos = sorted(list(set(validos)))
|
| 115 |
-
res_text = "\n".join(validos_unicos)
|
| 116 |
-
|
| 117 |
-
st.download_button(
|
| 118 |
-
label="⬇️ Baixar Lista Limpa (.txt)",
|
| 119 |
-
data=res_text,
|
| 120 |
-
file_name="dominios_limpos.txt",
|
| 121 |
-
mime="text/plain"
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
-
# Opcional: Mostrar amostra
|
| 125 |
-
with st.expander("Ver amostra dos aprovados"):
|
| 126 |
-
st.write(validos_unicos[:20])
|
|
|
|
| 2 |
import torch
|
| 3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
from urllib.parse import urlparse
|
|
|
|
| 5 |
import io
|
| 6 |
|
| 7 |
# --- CONFIGURAÇÕES ---
|
| 8 |
+
# ⚠️ MANTENHA O ID DO SEU MODELO AQUI
|
| 9 |
+
MODEL_ID = "asilvamaia/ident_br"
|
| 10 |
|
| 11 |
+
st.set_page_config(page_title="Validador .BR", page_icon="🇧🇷")
|
|
|
|
| 12 |
|
| 13 |
+
# --- FUNÇÃO DE LIMPEZA (V11 - IGUAL AO LOCAL) ---
|
| 14 |
def limpar_entrada(texto: str) -> str:
|
| 15 |
texto = str(texto).strip().lower()
|
| 16 |
if not texto: return ""
|
| 17 |
+
if "@" in texto: return texto
|
| 18 |
|
| 19 |
if "http" not in texto and "://" not in texto:
|
| 20 |
texto_temp = "http://" + texto
|
|
|
|
| 25 |
parsed = urlparse(texto_temp)
|
| 26 |
dominio_limpo = parsed.netloc if parsed.netloc else texto
|
| 27 |
|
| 28 |
+
if ":" in dominio_limpo:
|
| 29 |
dominio_limpo = dominio_limpo.split(':')[0]
|
| 30 |
|
| 31 |
+
if dominio_limpo.startswith("www."):
|
| 32 |
dominio_limpo = dominio_limpo[4:]
|
| 33 |
|
| 34 |
return dominio_limpo
|
| 35 |
except:
|
| 36 |
return texto
|
| 37 |
|
|
|
|
|
|
|
| 38 |
@st.cache_resource
|
| 39 |
def load_model():
|
| 40 |
try:
|
| 41 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 42 |
model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
|
|
|
|
| 43 |
model.to("cpu")
|
| 44 |
model.eval()
|
| 45 |
return tokenizer, model
|
| 46 |
except Exception as e:
|
| 47 |
+
st.error(f"Erro ao carregar modelo: {e}")
|
| 48 |
return None, None
|
| 49 |
|
| 50 |
tokenizer, model = load_model()
|
| 51 |
|
| 52 |
+
st.title("🇧🇷 Validador de Domínios .BR")
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
uploaded_file = st.file_uploader("Carregar lista suja (.txt)", type="txt")
|
| 55 |
|
| 56 |
+
if uploaded_file and tokenizer:
|
|
|
|
| 57 |
stringio = io.StringIO(uploaded_file.getvalue().decode("utf-8"))
|
| 58 |
linhas = stringio.readlines()
|
| 59 |
|
| 60 |
+
if st.button(f"Processar {len(linhas)} linhas"):
|
|
|
|
|
|
|
| 61 |
validos = []
|
| 62 |
rejeitados = []
|
| 63 |
|
|
|
|
| 64 |
progress_bar = st.progress(0)
|
| 65 |
+
total_linhas = len(linhas)
|
| 66 |
|
|
|
|
|
|
|
| 67 |
for i, linha in enumerate(linhas):
|
| 68 |
original = linha.strip()
|
| 69 |
+
# Pula linhas de metadados do arquivo (ex: )
|
| 70 |
+
if not original or original.startswith("`, ``.
|
| 71 |
+
* O script local pode estar classificando isso como "Lixo" (Rejeitado).
|
| 72 |
+
* Adicionei uma linha no código acima (`if original.startswith("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|