BugZoid commited on
Commit
21bb05d
·
verified ·
1 Parent(s): 223938e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -47
app.py CHANGED
@@ -18,76 +18,94 @@ if 'models_loaded' not in st.session_state:
18
 
19
  st.session_state.models_loaded = True
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 paraphrase_text(text, original_text):
32
  """
33
- Apply paraphrasing to the input text using BART model
34
  """
35
- min_length = len(original_text.split())
 
 
 
 
 
36
 
37
- inputs = st.session_state.paraphrase_tokenizer.encode(
38
- text,
39
  return_tensors="pt",
40
  max_length=1024,
41
  truncation=True
42
- )
43
 
44
- outputs = st.session_state.paraphrase_model.generate(
45
- inputs,
46
  max_length=1024,
47
- min_length=min_length, # Força o tamanho mínimo igual ao original
48
  do_sample=True,
49
- temperature=0.3,
50
- top_p=0.95,
51
- repetition_penalty=1.2,
52
- length_penalty=2.0 # Aumentado para favorecer textos mais longos
 
 
53
  )
54
 
55
- result = st.session_state.paraphrase_tokenizer.decode(outputs[0], skip_special_tokens=True)
56
- return ensure_minimum_length(result, original_text)
57
 
58
- def humanize_text(text):
59
  """
60
- Humanize the input text using T5 model
61
  """
62
- min_length = len(text.split())
63
-
64
- prompt = (
65
- f"reescreva o seguinte texto em português de forma mais natural e humana, "
66
- f"mantendo todas as informações e expandindo com detalhes relevantes: {text}"
67
- )
68
-
69
- input_ids = st.session_state.t5_tokenizer(
70
- prompt,
71
  return_tensors="pt",
72
  max_length=1024,
73
  truncation=True
74
- ).input_ids
75
 
76
- outputs = st.session_state.t5_model.generate(
77
- input_ids,
78
  max_length=1024,
79
- min_length=min_length, # Força o tamanho mínimo igual ao original
80
  do_sample=True,
81
- temperature=0.3,
82
  top_p=0.95,
83
- num_beams=5,
84
- no_repeat_ngram_size=3,
85
  repetition_penalty=1.2,
86
- length_penalty=2.0 # Aumentado para favorecer textos mais longos
87
  )
88
 
89
- result = st.session_state.t5_tokenizer.decode(outputs[0], skip_special_tokens=True)
90
- return ensure_minimum_length(result, text)
91
 
92
  # UI Components
93
  st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
@@ -95,8 +113,7 @@ st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
95
  st.title("🤖 → 🧑 Humanizador de Texto Avançado")
96
  st.markdown("""
97
  Este aplicativo transforma textos robotizados em linguagem mais natural e humana,
98
- mantendo todas as informações originais e garantindo que o texto final seja pelo menos
99
- do mesmo tamanho que o original.
100
  """)
101
 
102
  # Input area with expanded capabilities
@@ -112,7 +129,6 @@ with st.sidebar:
112
  use_paraphrase = st.checkbox("Ativar Paráfrase", value=True)
113
  show_original = st.checkbox("Mostrar Texto Original", value=False)
114
 
115
- # Adicionar informações sobre o texto
116
  if input_text:
117
  st.write("Informações do texto:")
118
  st.write(f"Palavras no original: {len(input_text.split())}")
@@ -129,7 +145,7 @@ if st.button("Humanizar", type="primary"):
129
 
130
  # Optional paraphrasing pass
131
  if use_paraphrase:
132
- final_text = paraphrase_text(humanized_text, input_text)
133
  else:
134
  final_text = humanized_text
135
 
 
18
 
19
  st.session_state.models_loaded = True
20
 
21
+ def clean_generated_text(text):
22
  """
23
+ Remove comandos e limpa o texto gerado
24
  """
25
+ # Lista de prefixos de comando para remover
26
+ command_prefixes = [
27
+ "reescreva o seguinte texto",
28
+ "reescreva este texto",
29
+ "reescreva o texto",
30
+ "traduza o seguinte texto",
31
+ "traduza este texto",
32
+ "traduza o texto",
33
+ "humanize:",
34
+ "humanizar:",
35
+ "em português de forma mais natural e humana",
36
+ "de forma mais natural e humana"
37
+ ]
38
+
39
+ # Remove os prefixos de comando
40
+ cleaned_text = text.lower()
41
+ for prefix in command_prefixes:
42
+ if cleaned_text.startswith(prefix.lower()):
43
+ cleaned_text = cleaned_text[len(prefix):].strip()
44
+
45
+ # Capitaliza a primeira letra
46
+ if cleaned_text:
47
+ cleaned_text = cleaned_text[0].upper() + cleaned_text[1:]
48
+
49
+ return cleaned_text
50
 
51
+ def humanize_text(text):
52
  """
53
+ Humanize the input text using T5 model with improved coherence
54
  """
55
+ # Prepara o texto com contexto específico para melhor coerência
56
+ context = (
57
+ f"Contexto: Este é um texto técnico ou formal que precisa ser reescrito "
58
+ f"de forma mais natural, mantendo todas as informações importantes. "
59
+ f"Texto original: {text}"
60
+ )
61
 
62
+ input_ids = st.session_state.t5_tokenizer(
63
+ context,
64
  return_tensors="pt",
65
  max_length=1024,
66
  truncation=True
67
+ ).input_ids
68
 
69
+ outputs = st.session_state.t5_model.generate(
70
+ input_ids,
71
  max_length=1024,
72
+ min_length=len(text.split()), # Mantém tamanho mínimo
73
  do_sample=True,
74
+ temperature=0.7, # Ajustado para melhor equilíbrio
75
+ top_p=0.9,
76
+ num_beams=4,
77
+ no_repeat_ngram_size=2,
78
+ repetition_penalty=1.5,
79
+ length_penalty=1.2
80
  )
81
 
82
+ result = st.session_state.t5_tokenizer.decode(outputs[0], skip_special_tokens=True)
83
+ return clean_generated_text(result)
84
 
85
+ def paraphrase_text(text):
86
  """
87
+ Refina o texto humanizado mantendo a coerência
88
  """
89
+ inputs = st.session_state.paraphrase_tokenizer.encode(
90
+ text,
 
 
 
 
 
 
 
91
  return_tensors="pt",
92
  max_length=1024,
93
  truncation=True
94
+ )
95
 
96
+ outputs = st.session_state.paraphrase_model.generate(
97
+ inputs,
98
  max_length=1024,
99
+ min_length=len(text.split()),
100
  do_sample=True,
101
+ temperature=0.3, # Reduzido para maior coerência
102
  top_p=0.95,
 
 
103
  repetition_penalty=1.2,
104
+ length_penalty=1.2
105
  )
106
 
107
+ result = st.session_state.paraphrase_tokenizer.decode(outputs[0], skip_special_tokens=True)
108
+ return clean_generated_text(result)
109
 
110
  # UI Components
111
  st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
 
113
  st.title("🤖 → 🧑 Humanizador de Texto Avançado")
114
  st.markdown("""
115
  Este aplicativo transforma textos robotizados em linguagem mais natural e humana,
116
+ mantendo todas as informações originais.
 
117
  """)
118
 
119
  # Input area with expanded capabilities
 
129
  use_paraphrase = st.checkbox("Ativar Paráfrase", value=True)
130
  show_original = st.checkbox("Mostrar Texto Original", value=False)
131
 
 
132
  if input_text:
133
  st.write("Informações do texto:")
134
  st.write(f"Palavras no original: {len(input_text.split())}")
 
145
 
146
  # Optional paraphrasing pass
147
  if use_paraphrase:
148
+ final_text = paraphrase_text(humanized_text)
149
  else:
150
  final_text = humanized_text
151