Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,72 +1,110 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
from transformers import T5ForConditionalGeneration, T5Tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def clean_generated_text(text):
|
| 11 |
-
"""Remove comandos e limpa o texto gerado"""
|
| 12 |
-
text = text.strip()
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"reescreva o seguinte texto",
|
| 17 |
-
"reescreva este texto",
|
| 18 |
-
"reescreva o texto",
|
| 19 |
-
"traduza",
|
| 20 |
-
"humanize:",
|
| 21 |
-
"humanizar:",
|
| 22 |
-
"em português",
|
| 23 |
-
"de forma mais natural"
|
| 24 |
-
]
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
text = text[0].upper() + text[1:]
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
def
|
| 40 |
-
"""
|
| 41 |
-
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
length_penalty=2.0 # Mantém incentivo para textos mais longos
|
| 61 |
-
)
|
| 62 |
-
result = st.session_state.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 63 |
-
result = clean_generated_text(result)
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
-
result += " " + " ".join(text.split()[-(len(text.split()) - len(result.split())):])
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
# UI Components
|
| 72 |
st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
|
|
@@ -74,18 +112,17 @@ st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
|
|
| 74 |
st.title("🤖 → 🧑 Humanizador de Texto Avançado")
|
| 75 |
st.markdown("""
|
| 76 |
Este aplicativo transforma textos robotizados em linguagem mais natural e humana,
|
| 77 |
-
mantendo todas as informações originais e
|
| 78 |
-
do mesmo tamanho que o original.
|
| 79 |
""")
|
| 80 |
|
| 81 |
-
# Input area
|
| 82 |
input_text = st.text_area(
|
| 83 |
"Cole seu texto de robô aqui:",
|
| 84 |
height=150,
|
| 85 |
help="Cole seu texto aqui para transformá-lo em uma versão mais natural e humana."
|
| 86 |
)
|
| 87 |
|
| 88 |
-
# Process button
|
| 89 |
if st.button("Humanizar", type="primary"):
|
| 90 |
if not input_text:
|
| 91 |
st.warning("⚠️ Por favor, cole um texto primeiro!")
|
|
@@ -108,8 +145,29 @@ if st.button("Humanizar", type="primary"):
|
|
| 108 |
st.info(final_text)
|
| 109 |
st.write(f"Palavras: {len(final_text.split())}")
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
except Exception as e:
|
| 112 |
st.error(f"❌ Erro no processamento: {str(e)}")
|
|
|
|
| 113 |
# Footer
|
| 114 |
st.markdown("---")
|
| 115 |
st.markdown(
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
from transformers import T5ForConditionalGeneration, T5Tokenizer
|
| 3 |
+
import torch
|
| 4 |
+
from torch.utils.data import Dataset, DataLoader
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from datetime import datetime
|
| 8 |
|
| 9 |
+
# Custom dataset for fine-tuning
|
| 10 |
+
class TextHumanizerDataset(Dataset):
|
| 11 |
+
def __init__(self, data, tokenizer, max_length=512):
|
| 12 |
+
self.data = data
|
| 13 |
+
self.tokenizer = tokenizer
|
| 14 |
+
self.max_length = max_length
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
def __len__(self):
|
| 17 |
+
return len(self.data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
def __getitem__(self, idx):
|
| 20 |
+
item = self.data[idx]
|
| 21 |
+
input_encoding = self.tokenizer(
|
| 22 |
+
f"reescreva em português natural, mantendo todas as informações: {item['input_text']}",
|
| 23 |
+
max_length=self.max_length,
|
| 24 |
+
padding='max_length',
|
| 25 |
+
truncation=True,
|
| 26 |
+
return_tensors='pt'
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
target_encoding = self.tokenizer(
|
| 30 |
+
item['output_text'],
|
| 31 |
+
max_length=self.max_length,
|
| 32 |
+
padding='max_length',
|
| 33 |
+
truncation=True,
|
| 34 |
+
return_tensors='pt'
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
return {
|
| 38 |
+
'input_ids': input_encoding['input_ids'].squeeze(),
|
| 39 |
+
'attention_mask': input_encoding['attention_mask'].squeeze(),
|
| 40 |
+
'labels': target_encoding['input_ids'].squeeze()
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
def save_feedback(input_text, output_text, rating):
|
| 44 |
+
"""Salva o feedback do usuário para futuro treinamento"""
|
| 45 |
+
feedback_data = {
|
| 46 |
+
'input_text': input_text,
|
| 47 |
+
'output_text': output_text,
|
| 48 |
+
'rating': rating,
|
| 49 |
+
'timestamp': datetime.now().isoformat()
|
| 50 |
+
}
|
| 51 |
|
| 52 |
+
# Cria diretório se não existir
|
| 53 |
+
os.makedirs('feedback_data', exist_ok=True)
|
|
|
|
| 54 |
|
| 55 |
+
# Salva em arquivo JSON
|
| 56 |
+
with open('feedback_data/feedback.json', 'a') as f:
|
| 57 |
+
f.write(json.dumps(feedback_data) + '\n')
|
| 58 |
|
| 59 |
+
def fine_tune_model():
|
| 60 |
+
"""Realiza fine-tuning do modelo com dados de feedback positivo"""
|
| 61 |
+
if not os.path.exists('feedback_data/feedback.json'):
|
| 62 |
+
return
|
| 63 |
|
| 64 |
+
# Carrega dados de feedback
|
| 65 |
+
positive_examples = []
|
| 66 |
+
with open('feedback_data/feedback.json', 'r') as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
feedback = json.loads(line)
|
| 69 |
+
if feedback['rating'] >= 4: # Usa apenas feedback positivo
|
| 70 |
+
positive_examples.append({
|
| 71 |
+
'input_text': feedback['input_text'],
|
| 72 |
+
'output_text': feedback['output_text']
|
| 73 |
+
})
|
| 74 |
+
|
| 75 |
+
if not positive_examples:
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
# Cria dataset e dataloader
|
| 79 |
+
dataset = TextHumanizerDataset(positive_examples, st.session_state.tokenizer)
|
| 80 |
+
dataloader = DataLoader(dataset, batch_size=4, shuffle=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# Configura otimizador
|
| 83 |
+
optimizer = torch.optim.AdamW(st.session_state.model.parameters(), lr=1e-5)
|
|
|
|
| 84 |
|
| 85 |
+
# Fine-tuning
|
| 86 |
+
st.session_state.model.train()
|
| 87 |
+
for batch in dataloader:
|
| 88 |
+
optimizer.zero_grad()
|
| 89 |
+
outputs = st.session_state.model(
|
| 90 |
+
input_ids=batch['input_ids'],
|
| 91 |
+
attention_mask=batch['attention_mask'],
|
| 92 |
+
labels=batch['labels']
|
| 93 |
+
)
|
| 94 |
+
loss = outputs.loss
|
| 95 |
+
loss.backward()
|
| 96 |
+
optimizer.step()
|
| 97 |
+
|
| 98 |
+
st.session_state.model.eval()
|
| 99 |
+
|
| 100 |
+
# Initialize session state
|
| 101 |
+
if 'model_loaded' not in st.session_state:
|
| 102 |
+
st.session_state.tokenizer = T5Tokenizer.from_pretrained("t5-base")
|
| 103 |
+
st.session_state.model = T5ForConditionalGeneration.from_pretrained("t5-base")
|
| 104 |
+
st.session_state.model_loaded = True
|
| 105 |
+
|
| 106 |
+
# Rest of your existing functions (clean_generated_text and humanize_text remain the same)
|
| 107 |
+
[Previous clean_generated_text and humanize_text functions remain unchanged]
|
| 108 |
|
| 109 |
# UI Components
|
| 110 |
st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
|
|
|
|
| 112 |
st.title("🤖 → 🧑 Humanizador de Texto Avançado")
|
| 113 |
st.markdown("""
|
| 114 |
Este aplicativo transforma textos robotizados em linguagem mais natural e humana,
|
| 115 |
+
mantendo todas as informações originais e incluindo sistema de feedback para melhoria contínua.
|
|
|
|
| 116 |
""")
|
| 117 |
|
| 118 |
+
# Input area
|
| 119 |
input_text = st.text_area(
|
| 120 |
"Cole seu texto de robô aqui:",
|
| 121 |
height=150,
|
| 122 |
help="Cole seu texto aqui para transformá-lo em uma versão mais natural e humana."
|
| 123 |
)
|
| 124 |
|
| 125 |
+
# Process button and results
|
| 126 |
if st.button("Humanizar", type="primary"):
|
| 127 |
if not input_text:
|
| 128 |
st.warning("⚠️ Por favor, cole um texto primeiro!")
|
|
|
|
| 145 |
st.info(final_text)
|
| 146 |
st.write(f"Palavras: {len(final_text.split())}")
|
| 147 |
|
| 148 |
+
# Feedback section
|
| 149 |
+
st.markdown("### Feedback")
|
| 150 |
+
rating = st.slider(
|
| 151 |
+
"Como você avalia a qualidade do texto humanizado?",
|
| 152 |
+
min_value=1,
|
| 153 |
+
max_value=5,
|
| 154 |
+
value=3,
|
| 155 |
+
help="1 = Muito ruim, 5 = Excelente"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
if st.button("Enviar Feedback"):
|
| 159 |
+
save_feedback(input_text, final_text, rating)
|
| 160 |
+
st.success("Feedback salvo com sucesso! Obrigado pela contribuição.")
|
| 161 |
+
|
| 162 |
+
# Trigger fine-tuning if we have enough positive feedback
|
| 163 |
+
if rating >= 4:
|
| 164 |
+
with st.spinner("Atualizando modelo com seu feedback..."):
|
| 165 |
+
fine_tune_model()
|
| 166 |
+
st.success("Modelo atualizado com sucesso!")
|
| 167 |
+
|
| 168 |
except Exception as e:
|
| 169 |
st.error(f"❌ Erro no processamento: {str(e)}")
|
| 170 |
+
|
| 171 |
# Footer
|
| 172 |
st.markdown("---")
|
| 173 |
st.markdown(
|