enpaiva commited on
Commit
403eaaa
·
verified ·
1 Parent(s): 4f8bb6f

app.py con almacenamiento en memoria

Browse files
Files changed (1) hide show
  1. app.py +35 -43
app.py CHANGED
@@ -1,29 +1,20 @@
1
  import gradio as gr
2
  import spacy
3
  from graphviz import Digraph
4
- import os
5
- import uuid
6
  import pandas as pd
7
 
8
  # Cargar modelo de spaCy
9
  nlp = spacy.load("es_dep_news_trf")
10
 
11
- # Carpeta persistente para imágenes
12
- os.makedirs("outputs", exist_ok=True)
13
-
14
- def limpiar_outputs():
15
- for archivo in os.listdir("outputs"):
16
- ruta = os.path.join("outputs", archivo)
17
- if os.path.isfile(ruta):
18
- os.remove(ruta)
19
-
20
  def generar_grafico_dependencia(texto):
21
- # Limpiar la carpeta de imágenes antes de generar nuevas
22
- limpiar_outputs()
23
 
24
  doc = nlp(texto)
25
  raices = [token for token in doc if token.head == token]
26
- rutas_imagenes = []
27
 
28
  for i, raiz in enumerate(raices):
29
  dot = Digraph(comment=f"Árbol {i+1}")
@@ -42,10 +33,12 @@ def generar_grafico_dependencia(texto):
42
 
43
  agregar_nodo(raiz)
44
 
45
- # Guardar archivo con nombre único
46
- nombre_archivo = f"outputs/arbol_{uuid.uuid4().hex}.png"
47
- dot.render(filename=nombre_archivo, format='png', cleanup=True)
48
- rutas_imagenes.append(nombre_archivo + ".png") # Graphviz añade extensión
 
 
49
 
50
  # Crear tabla de atributos
51
  df = pd.DataFrame([{
@@ -68,7 +61,7 @@ def generar_grafico_dependencia(texto):
68
  "is_sent_start": str(token.is_sent_start) if token.is_sent_start is not None else "None"
69
  } for token in doc])
70
 
71
- return rutas_imagenes, df
72
 
73
  # Ejemplos
74
  ejemplos = [
@@ -93,32 +86,31 @@ with gr.Blocks(title="Visualización de Dependencias Sintácticas", theme=gr.the
93
 
94
  with gr.Row():
95
  with gr.Column(scale=1):
96
- texto_input = gr.Textbox(lines=4, label="Texto en español", placeholder="Escribe aquí tu frase...")
97
- boton = gr.Button("Generar gráfico")
98
- gr.Examples(
99
- examples=ejemplos,
100
- inputs=texto_input,
101
- # outputs=galeria,
102
- fn=generar_grafico_dependencia,
103
- label="Ejemplos de texto"
104
- )
105
 
106
  with gr.Column(scale=2):
107
- with gr.Tab("visualización"):
108
- galeria = gr.Gallery(label="Gráfico(s) generado(s)", show_label=True, columns=4, height="auto", elem_id="gallery")
109
- with gr.Tab("tabla"):
110
- tabla = gr.Dataframe(
111
- headers=[
112
- "idx", "text", "lemma_", "pos_", "tag_", "dep_", "head", "morph",
113
- "ent_type_", "ent_iob_", "shape_", "is_alpha", "is_ascii",
114
- "is_digit", "is_punct", "like_num", "is_sent_start"
115
- ],
116
- label="Atributos de tokens",
117
- interactive=False,
118
- type="pandas",
119
- row_count=5,
120
- max_height="600"
121
- )
122
 
123
  boton.click(fn=generar_grafico_dependencia, inputs=texto_input, outputs=[galeria, tabla])
124
 
 
1
  import gradio as gr
2
  import spacy
3
  from graphviz import Digraph
4
+ import io
5
+ from PIL import Image
6
  import pandas as pd
7
 
8
  # Cargar modelo de spaCy
9
  nlp = spacy.load("es_dep_news_trf")
10
 
 
 
 
 
 
 
 
 
 
11
  def generar_grafico_dependencia(texto):
12
+ if not texto or texto.strip() == "":
13
+ return [], pd.DataFrame()
14
 
15
  doc = nlp(texto)
16
  raices = [token for token in doc if token.head == token]
17
+ imagenes = []
18
 
19
  for i, raiz in enumerate(raices):
20
  dot = Digraph(comment=f"Árbol {i+1}")
 
33
 
34
  agregar_nodo(raiz)
35
 
36
+ # Generar imagen en memoria (bytes)
37
+ png_bytes = dot.pipe(format='png')
38
+
39
+ # Convertir bytes a imagen PIL
40
+ imagen = Image.open(io.BytesIO(png_bytes))
41
+ imagenes.append(imagen)
42
 
43
  # Crear tabla de atributos
44
  df = pd.DataFrame([{
 
61
  "is_sent_start": str(token.is_sent_start) if token.is_sent_start is not None else "None"
62
  } for token in doc])
63
 
64
+ return imagenes, df
65
 
66
  # Ejemplos
67
  ejemplos = [
 
86
 
87
  with gr.Row():
88
  with gr.Column(scale=1):
89
+ texto_input = gr.Textbox(lines=4, label="Texto en español", placeholder="Escribe aquí tu frase...")
90
+ boton = gr.Button("Generar gráfico")
91
+ gr.Examples(
92
+ examples=ejemplos,
93
+ inputs=texto_input,
94
+ fn=generar_grafico_dependencia,
95
+ label="Ejemplos de texto"
96
+ )
 
97
 
98
  with gr.Column(scale=2):
99
+ with gr.Tab("visualización"):
100
+ galeria = gr.Gallery(label="Gráfico(s) generado(s)", show_label=True, columns=4, height="auto", elem_id="gallery")
101
+ with gr.Tab("tabla"):
102
+ tabla = gr.Dataframe(
103
+ headers=[
104
+ "idx", "text", "lemma_", "pos_", "tag_", "dep_", "head", "morph",
105
+ "ent_type_", "ent_iob_", "shape_", "is_alpha", "is_ascii",
106
+ "is_digit", "is_punct", "like_num", "is_sent_start"
107
+ ],
108
+ label="Atributos de tokens",
109
+ interactive=False,
110
+ type="pandas",
111
+ row_count=5,
112
+ max_height="600"
113
+ )
114
 
115
  boton.click(fn=generar_grafico_dependencia, inputs=texto_input, outputs=[galeria, tabla])
116