BugZoid commited on
Commit
223938e
·
verified ·
1 Parent(s): 8bf558e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -19
app.py CHANGED
@@ -18,37 +18,52 @@ if 'models_loaded' not in st.session_state:
18
 
19
  st.session_state.models_loaded = True
20
 
21
- def paraphrase_text(text):
 
 
 
 
 
 
 
 
 
 
22
  """
23
  Apply paraphrasing to the input text using BART model
24
  """
 
 
25
  inputs = st.session_state.paraphrase_tokenizer.encode(
26
  text,
27
  return_tensors="pt",
28
- max_length=1024, # Aumentado para textos maiores
29
  truncation=True
30
  )
31
 
32
  outputs = st.session_state.paraphrase_model.generate(
33
  inputs,
34
  max_length=1024,
35
- min_length=len(text.split()) - 10, # Garante tamanho mínimo próximo ao original
36
  do_sample=True,
37
- temperature=0.3, # Reduzido para manter mais fiel ao original
38
- top_p=0.95, # Aumentado para mais diversidade controlada
39
- repetition_penalty=1.2 # Evita repetições
 
40
  )
41
 
42
- return st.session_state.paraphrase_tokenizer.decode(outputs[0], skip_special_tokens=True)
 
43
 
44
  def humanize_text(text):
45
  """
46
  Humanize the input text using T5 model
47
  """
48
- # Modificado o prompt para enfatizar português e manter o contexto
 
49
  prompt = (
50
  f"reescreva o seguinte texto em português de forma mais natural e humana, "
51
- f"mantendo todas as informações originais: {text}"
52
  )
53
 
54
  input_ids = st.session_state.t5_tokenizer(
@@ -61,17 +76,18 @@ def humanize_text(text):
61
  outputs = st.session_state.t5_model.generate(
62
  input_ids,
63
  max_length=1024,
64
- min_length=len(text.split()) - 10, # Garante tamanho mínimo próximo ao original
65
  do_sample=True,
66
- temperature=0.3, # Reduzido para manter mais fiel ao original
67
- top_p=0.95, # Aumentado para mais diversidade controlada
68
- num_beams=5, # Aumentado para melhor qualidade
69
- no_repeat_ngram_size=3, # Evita repetições de trigramas
70
- repetition_penalty=1.2, # Penalidade para repetições
71
- length_penalty=1.0 # Incentiva manter o tamanho similar
72
  )
73
 
74
- return st.session_state.t5_tokenizer.decode(outputs[0], skip_special_tokens=True)
 
75
 
76
  # UI Components
77
  st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
@@ -79,7 +95,8 @@ st.set_page_config(page_title="Advanced Text Humanizer", page_icon="🤖")
79
  st.title("🤖 → 🧑 Humanizador de Texto Avançado")
80
  st.markdown("""
81
  Este aplicativo transforma textos robotizados em linguagem mais natural e humana,
82
- mantendo todas as informações originais.
 
83
  """)
84
 
85
  # Input area with expanded capabilities
@@ -94,6 +111,11 @@ with st.sidebar:
94
  st.header("Configurações Avançadas")
95
  use_paraphrase = st.checkbox("Ativar Paráfrase", value=True)
96
  show_original = st.checkbox("Mostrar Texto Original", value=False)
 
 
 
 
 
97
 
98
  # Process button with error handling
99
  if st.button("Humanizar", type="primary"):
@@ -107,7 +129,7 @@ if st.button("Humanizar", type="primary"):
107
 
108
  # Optional paraphrasing pass
109
  if use_paraphrase:
110
- final_text = paraphrase_text(humanized_text)
111
  else:
112
  final_text = humanized_text
113
 
@@ -116,8 +138,10 @@ if st.button("Humanizar", type="primary"):
116
  if show_original:
117
  st.text("Texto original:")
118
  st.info(input_text)
 
119
  st.markdown("**Resultado:**")
120
  st.write(final_text)
 
121
 
122
  except Exception as e:
123
  st.error(f"❌ Ocorreu um erro durante o processamento: {str(e)}")
 
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(
 
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
  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
 
111
  st.header("Configurações Avançadas")
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())}")
119
 
120
  # Process button with error handling
121
  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
 
 
138
  if show_original:
139
  st.text("Texto original:")
140
  st.info(input_text)
141
+ st.write(f"Palavras no original: {len(input_text.split())}")
142
  st.markdown("**Resultado:**")
143
  st.write(final_text)
144
+ st.write(f"Palavras no resultado: {len(final_text.split())}")
145
 
146
  except Exception as e:
147
  st.error(f"❌ Ocorreu um erro durante o processamento: {str(e)}")