Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,11 @@
|
|
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 code-autocomplete-gpt2-base...")
|
10 |
model_name = "shibing624/code-autocomplete-gpt2-base"
|
11 |
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
@@ -19,6 +19,16 @@ model.eval()
|
|
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/c贸digo de entrada usando code-autocomplete-gpt2-base
|
@@ -65,15 +75,67 @@ def autocomplete_text(input_text, max_tokens=20):
|
|
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
|
71 |
"""
|
72 |
|
73 |
-
with gr.Blocks(title="
|
74 |
|
75 |
-
gr.Markdown("# 馃
|
76 |
-
gr.Markdown("
|
77 |
|
78 |
with gr.Tab("Autocompletar"):
|
79 |
with gr.Row():
|
@@ -110,10 +172,46 @@ def create_autocomplete_interface():
|
|
110 |
outputs=[output_textbox]
|
111 |
)
|
112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
# Pesta帽a adicional con ejemplos
|
114 |
with gr.Tab("Ejemplos"):
|
115 |
gr.Markdown("""
|
116 |
-
### Ejemplos de
|
117 |
|
118 |
**Entrada:** "def fibonacci(n):"
|
119 |
**Salida:** "\\n if n <= 1:\\n return n\\n return fibonacci(n-1) + fibonacci(n-2)"
|
@@ -124,15 +222,22 @@ def create_autocomplete_interface():
|
|
124 |
**Entrada:** "import pandas as pd\\ndf = pd.read_csv("
|
125 |
**Salida:** "'data.csv')\\nprint(df.head())"
|
126 |
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
""")
|
130 |
|
131 |
return demo
|
132 |
|
133 |
# Crear y lanzar la aplicaci贸n
|
134 |
if __name__ == "__main__":
|
135 |
-
print("Iniciando aplicaci贸n de
|
136 |
|
137 |
# Crear la interfaz
|
138 |
app = create_autocomplete_interface()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer, BartForConditionalGeneration, BartTokenizer
|
3 |
import torch
|
4 |
|
5 |
# Configurar el dispositivo (CPU)
|
6 |
device = torch.device("cpu")
|
7 |
|
8 |
+
# Cargar el modelo y tokenizer para autocompletar c贸digo
|
9 |
print("Cargando modelo code-autocomplete-gpt2-base...")
|
10 |
model_name = "shibing624/code-autocomplete-gpt2-base"
|
11 |
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
|
|
19 |
if tokenizer.pad_token is None:
|
20 |
tokenizer.pad_token = tokenizer.eos_token
|
21 |
|
22 |
+
# Cargar BART para simplificaci贸n de texto
|
23 |
+
print("Cargando modelo BART para simplificaci贸n...")
|
24 |
+
bart_model_name = "facebook/bart-base"
|
25 |
+
bart_tokenizer = BartTokenizer.from_pretrained(bart_model_name)
|
26 |
+
bart_model = BartForConditionalGeneration.from_pretrained(bart_model_name)
|
27 |
+
|
28 |
+
# Mover BART a CPU y ponerlo en modo evaluaci贸n
|
29 |
+
bart_model.to(device)
|
30 |
+
bart_model.eval()
|
31 |
+
|
32 |
def autocomplete_text(input_text, max_tokens=20):
|
33 |
"""
|
34 |
Autocompleta el texto/c贸digo de entrada usando code-autocomplete-gpt2-base
|
|
|
75 |
except Exception as e:
|
76 |
return f"Error al generar texto: {str(e)}"
|
77 |
|
78 |
+
def simplify_text(input_text, max_length=150):
|
79 |
+
"""
|
80 |
+
Simplifica texto complejo usando BART
|
81 |
+
|
82 |
+
Args:
|
83 |
+
input_text (str): Texto complejo a simplificar
|
84 |
+
max_length (int): Longitud m谩xima del texto simplificado
|
85 |
+
|
86 |
+
Returns:
|
87 |
+
str: Texto simplificado con palabras m谩s sencillas
|
88 |
+
"""
|
89 |
+
if not input_text.strip():
|
90 |
+
return "Por favor, ingresa alg煤n texto para simplificar."
|
91 |
+
|
92 |
+
try:
|
93 |
+
# Crear un prompt para guiar la simplificaci贸n
|
94 |
+
prompt = f"Simplify this text using easier words: {input_text}"
|
95 |
+
|
96 |
+
# Tokenizar el texto
|
97 |
+
inputs = bart_tokenizer.encode(prompt, return_tensors="pt", max_length=512, truncation=True)
|
98 |
+
inputs = inputs.to(device)
|
99 |
+
|
100 |
+
# Generar texto simplificado
|
101 |
+
with torch.no_grad():
|
102 |
+
outputs = bart_model.generate(
|
103 |
+
inputs,
|
104 |
+
max_length=max_length,
|
105 |
+
min_length=20,
|
106 |
+
num_return_sequences=1,
|
107 |
+
temperature=0.7,
|
108 |
+
do_sample=True,
|
109 |
+
early_stopping=True,
|
110 |
+
no_repeat_ngram_size=2,
|
111 |
+
pad_token_id=bart_tokenizer.pad_token_id,
|
112 |
+
eos_token_id=bart_tokenizer.eos_token_id
|
113 |
+
)
|
114 |
+
|
115 |
+
# Decodificar el resultado
|
116 |
+
simplified_text = bart_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
117 |
+
|
118 |
+
# Limpiar el texto (remover el prompt si aparece)
|
119 |
+
if simplified_text.startswith("Simplify this text using easier words:"):
|
120 |
+
simplified_text = simplified_text.replace("Simplify this text using easier words:", "").strip()
|
121 |
+
|
122 |
+
if not simplified_text:
|
123 |
+
return "No se pudo simplificar el texto."
|
124 |
+
|
125 |
+
return simplified_text
|
126 |
+
|
127 |
+
except Exception as e:
|
128 |
+
return f"Error al simplificar texto: {str(e)}"
|
129 |
+
|
130 |
def create_autocomplete_interface():
|
131 |
"""
|
132 |
+
Crea la interfaz con autocompletar y simplificaci贸n dentro de gr.Blocks()
|
133 |
"""
|
134 |
|
135 |
+
with gr.Blocks(title="Asistente de Texto y C贸digo") as demo:
|
136 |
|
137 |
+
gr.Markdown("# 馃 Asistente de Texto y C贸digo")
|
138 |
+
gr.Markdown("Herramientas para autocompletar c贸digo y simplificar textos complejos.")
|
139 |
|
140 |
with gr.Tab("Autocompletar"):
|
141 |
with gr.Row():
|
|
|
172 |
outputs=[output_textbox]
|
173 |
)
|
174 |
|
175 |
+
# Nueva pesta帽a para simplificar texto
|
176 |
+
with gr.Tab("Simplificar Texto"):
|
177 |
+
with gr.Row():
|
178 |
+
with gr.Column():
|
179 |
+
text_input = gr.Textbox(
|
180 |
+
label="Texto complejo a simplificar",
|
181 |
+
placeholder="Ingresa aqu铆 el texto dif铆cil de entender...",
|
182 |
+
lines=6,
|
183 |
+
max_lines=12
|
184 |
+
)
|
185 |
+
|
186 |
+
simplify_btn = gr.Button("Simplificar Texto", variant="secondary")
|
187 |
+
|
188 |
+
with gr.Column():
|
189 |
+
simplified_output = gr.Textbox(
|
190 |
+
label="Texto simplificado",
|
191 |
+
placeholder="Aqu铆 aparecer谩 el texto m谩s f谩cil de entender...",
|
192 |
+
lines=6,
|
193 |
+
max_lines=12,
|
194 |
+
interactive=False
|
195 |
+
)
|
196 |
+
|
197 |
+
# Conectar el bot贸n de simplificar
|
198 |
+
simplify_btn.click(
|
199 |
+
fn=simplify_text,
|
200 |
+
inputs=[text_input],
|
201 |
+
outputs=[simplified_output]
|
202 |
+
)
|
203 |
+
|
204 |
+
# Tambi茅n permitir Enter para simplificar
|
205 |
+
text_input.submit(
|
206 |
+
fn=simplify_text,
|
207 |
+
inputs=[text_input],
|
208 |
+
outputs=[simplified_output]
|
209 |
+
)
|
210 |
+
|
211 |
# Pesta帽a adicional con ejemplos
|
212 |
with gr.Tab("Ejemplos"):
|
213 |
gr.Markdown("""
|
214 |
+
### Ejemplos de Autocompletado de C贸digo:
|
215 |
|
216 |
**Entrada:** "def fibonacci(n):"
|
217 |
**Salida:** "\\n if n <= 1:\\n return n\\n return fibonacci(n-1) + fibonacci(n-2)"
|
|
|
222 |
**Entrada:** "import pandas as pd\\ndf = pd.read_csv("
|
223 |
**Salida:** "'data.csv')\\nprint(df.head())"
|
224 |
|
225 |
+
---
|
226 |
+
|
227 |
+
### Ejemplos de Simplificaci贸n de Texto:
|
228 |
+
|
229 |
+
**Texto complejo:** "La implementaci贸n de algoritmos de machine learning requiere una comprensi贸n profunda de estructuras de datos y t茅cnicas de optimizaci贸n."
|
230 |
+
**Texto simple:** "Para usar inteligencia artificial necesitas entender bien c贸mo organizar datos y mejorar programas."
|
231 |
+
|
232 |
+
**Texto complejo:** "El protocolo de comunicaci贸n as铆ncrona permite la transmisi贸n de datos sin sincronizaci贸n temporal."
|
233 |
+
**Texto simple:** "Este m茅todo permite enviar informaci贸n sin esperar a que termine el env铆o anterior."
|
234 |
""")
|
235 |
|
236 |
return demo
|
237 |
|
238 |
# Crear y lanzar la aplicaci贸n
|
239 |
if __name__ == "__main__":
|
240 |
+
print("Iniciando aplicaci贸n de asistente de texto y c贸digo...")
|
241 |
|
242 |
# Crear la interfaz
|
243 |
app = create_autocomplete_interface()
|