BugZoid commited on
Commit
aeb2715
·
verified ·
1 Parent(s): 4739dfa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -62
app.py CHANGED
@@ -1,72 +1,110 @@
1
  import streamlit as st
2
  from transformers import T5ForConditionalGeneration, T5Tokenizer
 
 
 
 
 
3
 
4
- # Initialize session state for model if not already done
5
- if 'model_loaded' not in st.session_state:
6
- st.session_state.tokenizer = T5Tokenizer.from_pretrained("t5-base")
7
- st.session_state.model = T5ForConditionalGeneration.from_pretrained("t5-base")
8
- st.session_state.model_loaded = True
9
-
10
- def clean_generated_text(text):
11
- """Remove comandos e limpa o texto gerado"""
12
- text = text.strip()
13
 
14
- # Lista de prefixos de comando para remover
15
- prefixes = [
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
- # Remove os prefixos de comando
27
- text_lower = text.lower()
28
- for prefix in prefixes:
29
- if text_lower.startswith(prefix):
30
- text = text[len(prefix):].strip()
31
- text_lower = text.lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- # Capitaliza a primeira letra
34
- if text:
35
- text = text[0].upper() + text[1:]
36
 
37
- return text
 
 
38
 
39
- def humanize_text(text):
40
- """Humaniza o texto mantendo coerência e tamanho"""
41
- prompt = f"reescreva em português natural, mantendo todas as informações: {text}"
 
42
 
43
- input_ids = st.session_state.tokenizer(
44
- prompt,
45
- return_tensors="pt",
46
- max_length=1024,
47
- truncation=True
48
- ).input_ids
49
-
50
- # Parâmetros ajustados para melhor coerência
51
- outputs = st.session_state.model.generate(
52
- input_ids,
53
- max_length=1024, # 512
54
- min_length=len(text.split()), # min_length=min_length,
55
- do_sample=True,
56
- temperature=0.1, # Reduzido para maior coerência
57
- top_p=0.95, # Ajustado para melhor seleção de palavras
58
- num_beams=3, # Reduzido para maior velocidade
59
- repetition_penalty=1.2,
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
- # Garante tamanho mínimo
66
- while len(result.split()) < len(text.split()):
67
- result += " " + " ".join(text.split()[-(len(text.split()) - len(result.split())):])
68
 
69
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 garantindo que o texto final seja pelo menos
78
- do mesmo tamanho que o original.
79
  """)
80
 
81
- # Input area with expanded capabilities
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(