Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,144 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import
|
3 |
-
from transformers import T5Tokenizer # Import T5Tokenizer directly
|
4 |
import torch
|
5 |
|
6 |
-
#
|
7 |
-
|
8 |
-
# Use T5Tokenizer directly instead of AutoTokenizer
|
9 |
-
simplifier_tokenizer = T5Tokenizer.from_pretrained(simplifier_model_name)
|
10 |
-
simplifier_model = AutoModelForSeq2SeqLM.from_pretrained(simplifier_model_name)
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
}
|
18 |
-
prompt = f"{niveles[nivel]}\n\n{texto}"
|
19 |
-
inputs = simplifier_tokenizer(prompt, return_tensors="pt", truncation=True)
|
20 |
-
outputs = simplifier_model.generate(
|
21 |
-
**inputs,
|
22 |
-
max_new_tokens=120,
|
23 |
-
num_beams=4,
|
24 |
-
temperature=0.7,
|
25 |
-
repetition_penalty=1.2,
|
26 |
-
early_stopping=True
|
27 |
-
)
|
28 |
-
resultado = simplifier_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
29 |
-
return resultado
|
30 |
|
31 |
-
#
|
32 |
-
|
33 |
-
|
34 |
-
predictor_model = AutoModelForCausalLM.from_pretrained(predictor_model_name)
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
texto_generado = predictor_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
40 |
-
return texto_generado[len(texto_inicial):] # Solo mostrar lo nuevo
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
with gr.
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
|
|
3 |
import torch
|
4 |
|
5 |
+
# Configurar el dispositivo (CPU)
|
6 |
+
device = torch.device("cpu")
|
|
|
|
|
|
|
7 |
|
8 |
+
# Cargar el modelo y tokenizer
|
9 |
+
print("Cargando modelo DistilGPT-2...")
|
10 |
+
model_name = "distilgpt2"
|
11 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
12 |
+
model = GPT2LMHeadModel.from_pretrained(model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
# Mover modelo a CPU y ponerlo en modo evaluaci贸n
|
15 |
+
model.to(device)
|
16 |
+
model.eval()
|
|
|
17 |
|
18 |
+
# Configurar pad_token si no existe
|
19 |
+
if tokenizer.pad_token is None:
|
20 |
+
tokenizer.pad_token = tokenizer.eos_token
|
|
|
|
|
21 |
|
22 |
+
def autocomplete_text(input_text, max_tokens=20):
|
23 |
+
"""
|
24 |
+
Autocompleta el texto de entrada usando DistilGPT-2
|
25 |
+
|
26 |
+
Args:
|
27 |
+
input_text (str): Texto inicial a completar
|
28 |
+
max_tokens (int): N煤mero m谩ximo de tokens a generar
|
29 |
+
|
30 |
+
Returns:
|
31 |
+
str: Solo la parte nueva generada (sin el input original)
|
32 |
+
"""
|
33 |
+
if not input_text.strip():
|
34 |
+
return "Por favor, ingresa alg煤n texto para completar."
|
35 |
+
|
36 |
+
try:
|
37 |
+
# Tokenizar el texto de entrada
|
38 |
+
inputs = tokenizer.encode(input_text, return_tensors="pt", padding=True)
|
39 |
+
inputs = inputs.to(device)
|
40 |
+
|
41 |
+
# Generar texto
|
42 |
+
with torch.no_grad():
|
43 |
+
outputs = model.generate(
|
44 |
+
inputs,
|
45 |
+
max_new_tokens=max_tokens,
|
46 |
+
num_return_sequences=1,
|
47 |
+
temperature=0.7,
|
48 |
+
do_sample=True,
|
49 |
+
pad_token_id=tokenizer.eos_token_id,
|
50 |
+
eos_token_id=tokenizer.eos_token_id,
|
51 |
+
attention_mask=torch.ones_like(inputs)
|
52 |
+
)
|
53 |
+
|
54 |
+
# Decodificar el resultado completo
|
55 |
+
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
56 |
+
|
57 |
+
# Extraer solo la parte nueva (sin el input original)
|
58 |
+
new_text = generated_text[len(input_text):].strip()
|
59 |
+
|
60 |
+
if not new_text:
|
61 |
+
return "No se pudo generar texto adicional."
|
62 |
+
|
63 |
+
return new_text
|
64 |
+
|
65 |
+
except Exception as e:
|
66 |
+
return f"Error al generar texto: {str(e)}"
|
67 |
|
68 |
+
def create_autocomplete_interface():
|
69 |
+
"""
|
70 |
+
Crea la interfaz de autocompletar dentro de gr.Blocks()
|
71 |
+
"""
|
72 |
+
|
73 |
+
with gr.Blocks(title="Autocompletar Texto") as demo:
|
74 |
+
|
75 |
+
gr.Markdown("# 馃 Autocompletar Texto")
|
76 |
+
gr.Markdown("Escribe el inicio de una frase y la IA la completar谩 por ti.")
|
77 |
+
|
78 |
+
with gr.Tab("Autocompletar"):
|
79 |
+
with gr.Row():
|
80 |
+
with gr.Column():
|
81 |
+
input_textbox = gr.Textbox(
|
82 |
+
label="Texto a completar",
|
83 |
+
placeholder="Escribe el inicio de tu frase aqu铆...",
|
84 |
+
lines=3,
|
85 |
+
max_lines=5
|
86 |
+
)
|
87 |
+
|
88 |
+
generate_btn = gr.Button("Completar Texto", variant="primary")
|
89 |
+
|
90 |
+
with gr.Column():
|
91 |
+
output_textbox = gr.Textbox(
|
92 |
+
label="Texto generado",
|
93 |
+
placeholder="Aqu铆 aparecer谩 la continuaci贸n...",
|
94 |
+
lines=3,
|
95 |
+
max_lines=5,
|
96 |
+
interactive=False
|
97 |
+
)
|
98 |
+
|
99 |
+
# Conectar el bot贸n con la funci贸n
|
100 |
+
generate_btn.click(
|
101 |
+
fn=autocomplete_text,
|
102 |
+
inputs=[input_textbox],
|
103 |
+
outputs=[output_textbox]
|
104 |
+
)
|
105 |
+
|
106 |
+
# Tambi茅n permitir Enter para generar
|
107 |
+
input_textbox.submit(
|
108 |
+
fn=autocomplete_text,
|
109 |
+
inputs=[input_textbox],
|
110 |
+
outputs=[output_textbox]
|
111 |
+
)
|
112 |
+
|
113 |
+
# Pesta帽a adicional con ejemplos
|
114 |
+
with gr.Tab("Ejemplos"):
|
115 |
+
gr.Markdown("""
|
116 |
+
### Ejemplos de uso:
|
117 |
+
|
118 |
+
**Entrada:** "El clima de hoy est谩"
|
119 |
+
**Salida:** "muy agradable y soleado"
|
120 |
+
|
121 |
+
**Entrada:** "Me gusta mucho"
|
122 |
+
**Salida:** "pasar tiempo con mi familia"
|
123 |
+
|
124 |
+
**Entrada:** "Para hacer una buena comida necesitas"
|
125 |
+
**Salida:** "ingredientes frescos y mucha paciencia"
|
126 |
+
""")
|
127 |
+
|
128 |
+
return demo
|
129 |
|
130 |
+
# Crear y lanzar la aplicaci贸n
|
131 |
+
if __name__ == "__main__":
|
132 |
+
print("Iniciando aplicaci贸n de autocompletar...")
|
133 |
+
|
134 |
+
# Crear la interfaz
|
135 |
+
app = create_autocomplete_interface()
|
136 |
+
|
137 |
+
# Lanzar la aplicaci贸n
|
138 |
+
app.launch(
|
139 |
+
share=False, # Cambiar a True si quieres compartir p煤blicamente
|
140 |
+
server_name="0.0.0.0", # Permite acceso desde otras m谩quinas en la red local
|
141 |
+
server_port=7860, # Puerto por defecto de Gradio
|
142 |
+
show_error=True,
|
143 |
+
debug=False
|
144 |
+
)
|