Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,127 +1,72 @@
|
|
1 |
import streamlit as st
|
2 |
-
from transformers import
|
3 |
-
AutoTokenizer,
|
4 |
-
AutoModelForSeq2SeqLM,
|
5 |
-
T5ForConditionalGeneration,
|
6 |
-
T5Tokenizer
|
7 |
-
)
|
8 |
|
9 |
-
# Initialize session state for
|
10 |
-
if '
|
11 |
-
|
12 |
-
st.session_state.
|
13 |
-
st.session_state.
|
14 |
-
|
15 |
-
# Load the paraphrasing model and tokenizer
|
16 |
-
st.session_state.paraphrase_tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
|
17 |
-
st.session_state.paraphrase_model = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn")
|
18 |
|
19 |
-
|
|
|
|
|
20 |
|
21 |
-
def ensure_minimum_length(text, original_text):
|
22 |
-
"""
|
23 |
-
Garante que o texto gerado tenha pelo menos o mesmo tamanho do original
|
24 |
-
"""
|
25 |
-
while len(text.split()) < len(original_text.split()):
|
26 |
-
missing_words = len(original_text.split()) - len(text.split())
|
27 |
-
if missing_words > 0:
|
28 |
-
text = text + " " + original_text[-missing_words:]
|
29 |
-
return text
|
30 |
-
|
31 |
-
def clean_generated_text(text):
|
32 |
-
"""
|
33 |
-
Remove comandos e limpa o texto gerado
|
34 |
-
"""
|
35 |
# Lista de prefixos de comando para remover
|
36 |
-
|
37 |
"reescreva o seguinte texto",
|
38 |
"reescreva este texto",
|
39 |
"reescreva o texto",
|
40 |
-
"traduza
|
41 |
-
"traduza este texto",
|
42 |
-
"traduza o texto",
|
43 |
"humanize:",
|
44 |
"humanizar:",
|
45 |
-
"em português
|
46 |
-
"de forma mais natural
|
47 |
]
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
for prefix in
|
52 |
-
if
|
53 |
-
|
|
|
54 |
|
55 |
# Capitaliza a primeira letra
|
56 |
-
if
|
57 |
-
|
58 |
|
59 |
-
return
|
60 |
|
61 |
-
def humanize_text(text):
|
62 |
-
"""
|
63 |
-
|
64 |
-
"""
|
65 |
-
min_length = len(text.split())
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
f"Contexto: Este é um texto técnico ou formal que precisa ser reescrito "
|
70 |
-
f"de forma mais natural, mantendo todas as informações importantes e expandindo "
|
71 |
-
f"com detalhes relevantes. Texto original: {text}"
|
72 |
-
)
|
73 |
-
|
74 |
-
input_ids = st.session_state.t5_tokenizer(
|
75 |
-
context,
|
76 |
return_tensors="pt",
|
77 |
-
max_length=
|
78 |
truncation=True
|
79 |
).input_ids
|
80 |
-
|
81 |
-
|
|
|
82 |
input_ids,
|
83 |
-
max_length=1024,
|
84 |
-
min_length=
|
85 |
do_sample=True,
|
86 |
-
temperature=0.
|
87 |
-
top_p=0.
|
88 |
-
num_beams=
|
89 |
-
|
90 |
-
|
91 |
-
length_penalty=2.0 # Aumentado para favorecer textos mais longos
|
92 |
)
|
93 |
-
|
94 |
-
result = st.session_state.t5_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
95 |
result = clean_generated_text(result)
|
96 |
-
return ensure_minimum_length(result, text)
|
97 |
-
|
98 |
-
def paraphrase_text(text, original_text):
|
99 |
-
"""
|
100 |
-
Refina o texto humanizado mantendo a coerência e tamanho
|
101 |
-
"""
|
102 |
-
min_length = len(original_text.split())
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
max_length=1024,
|
108 |
-
truncation=True
|
109 |
-
)
|
110 |
-
|
111 |
-
outputs = st.session_state.paraphrase_model.generate(
|
112 |
-
inputs,
|
113 |
-
max_length=1024,
|
114 |
-
min_length=min_length, # Força o tamanho mínimo igual ao original
|
115 |
-
do_sample=True,
|
116 |
-
temperature=0.3, # Reduzido para maior coerência
|
117 |
-
top_p=0.95,
|
118 |
-
repetition_penalty=1.2,
|
119 |
-
length_penalty=2.0 # Aumentado para favorecer textos mais longos
|
120 |
-
)
|
121 |
|
122 |
-
result
|
123 |
-
result = clean_generated_text(result)
|
124 |
-
return ensure_minimum_length(result, original_text)
|
125 |
|
126 |
# UI Components
|
127 |
st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
|
@@ -140,45 +85,31 @@ input_text = st.text_area(
|
|
140 |
help="Cole seu texto aqui para transformá-lo em uma versão mais natural e humana."
|
141 |
)
|
142 |
|
143 |
-
#
|
144 |
-
with st.sidebar:
|
145 |
-
st.header("Configurações Avançadas")
|
146 |
-
use_paraphrase = st.checkbox("Ativar Paráfrase", value=True)
|
147 |
-
show_original = st.checkbox("Mostrar Texto Original", value=False)
|
148 |
-
|
149 |
-
if input_text:
|
150 |
-
st.write("Informações do texto:")
|
151 |
-
st.write(f"Palavras no original: {len(input_text.split())}")
|
152 |
-
|
153 |
-
# Process button with error handling
|
154 |
if st.button("Humanizar", type="primary"):
|
155 |
if not input_text:
|
156 |
-
st.warning("⚠️ Por favor, cole um texto
|
157 |
else:
|
158 |
with st.spinner("Processando o texto..."):
|
159 |
try:
|
160 |
-
|
161 |
-
humanized_text = humanize_text(input_text)
|
162 |
-
|
163 |
-
# Optional paraphrasing pass
|
164 |
-
if use_paraphrase:
|
165 |
-
final_text = paraphrase_text(humanized_text, input_text)
|
166 |
-
else:
|
167 |
-
final_text = humanized_text
|
168 |
|
169 |
# Display results
|
170 |
st.success("✨ Texto humanizado:")
|
171 |
-
|
172 |
-
|
|
|
|
|
173 |
st.info(input_text)
|
174 |
-
st.write(f"Palavras
|
175 |
-
|
176 |
-
|
177 |
-
|
|
|
|
|
178 |
|
179 |
except Exception as e:
|
180 |
-
st.error(f"❌
|
181 |
-
|
182 |
# Footer
|
183 |
st.markdown("---")
|
184 |
st.markdown(
|
|
|
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=512,
|
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.3, # 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="🤖")
|
|
|
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!")
|
92 |
else:
|
93 |
with st.spinner("Processando o texto..."):
|
94 |
try:
|
95 |
+
final_text = humanize_text(input_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
# Display results
|
98 |
st.success("✨ Texto humanizado:")
|
99 |
+
col1, col2 = st.columns(2)
|
100 |
+
|
101 |
+
with col1:
|
102 |
+
st.text("Original:")
|
103 |
st.info(input_text)
|
104 |
+
st.write(f"Palavras: {len(input_text.split())}")
|
105 |
+
|
106 |
+
with col2:
|
107 |
+
st.text("Resultado:")
|
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(
|