histlearn commited on
Commit
695363c
·
verified ·
1 Parent(s): feb8296

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import rdflib
3
+ import json
4
+
5
+ # Função para carregar e extrair os nomes do arquivo JSON-LD
6
+ def load_names_from_jsonld(jsonld_file):
7
+ with open(jsonld_file, 'r', encoding='utf-8') as f:
8
+ data = json.load(f)
9
+
10
+ names = []
11
+ for item in data['@graph']:
12
+ if 'name' in item:
13
+ names.append(item['name'])
14
+
15
+ return names
16
+
17
+ # Carregar nomes do arquivo JSON-LD
18
+ names = load_names_from_jsonld('datafile.jsonld')
19
+
20
+ def run_query_and_visualize(qtext, turtle_file):
21
+ # Carrega o arquivo Turtle
22
+ g = rdflib.Graph()
23
+ g.parse(turtle_file, format="turtle")
24
+
25
+ # Executa a consulta SPARQL
26
+ qres = g.query(qtext)
27
+
28
+ # Prepara o gráfico com recursos remotos
29
+ net = Network(notebook=True, height="400px", width="100%", cdn_resources='remote')
30
+ nodes = set()
31
+
32
+ # Processa os resultados da consulta
33
+ for row in qres:
34
+ s, p, o = row
35
+ if str(s) not in nodes:
36
+ net.add_node(str(s), label=str(s))
37
+ nodes.add(str(s))
38
+ if str(o) not in nodes:
39
+ net.add_node(str(o), label=str(o))
40
+ nodes.add(str(o))
41
+ net.add_edge(str(s), str(o), title=str(p))
42
+
43
+ # Gera o gráfico e o exibe diretamente na célula do notebook
44
+ net.show("graph.html")
45
+ return "graph.html"
46
+
47
+ def update_query(selected_location):
48
+ return f"""
49
+ PREFIX schema: <http://schema.org/>
50
+
51
+ SELECT * WHERE {{
52
+ ?s schema:name "{selected_location}" .
53
+ ?s ?p ?o .
54
+ }}
55
+ """
56
+
57
+ with gr.Blocks() as demo:
58
+ gr.Markdown("# Visualização de Query SPARQL")
59
+
60
+ with gr.Column():
61
+ selected_location = gr.Dropdown(choices=names, label="Selecione o Local")
62
+ query_input = gr.Textbox(label="Consulta SPARQL", value=update_query(names[0]), lines=10)
63
+ turtle_file_input = gr.File(label="Arquivo Turtle")
64
+ run_button = gr.Button("Executar Consulta")
65
+
66
+ graph_output = gr.HTML()
67
+
68
+ def on_location_change(loc):
69
+ query_input.value = update_query(loc)
70
+
71
+ selected_location.change(fn=on_location_change, inputs=selected_location, outputs=query_input)
72
+
73
+ def on_run_button_click(query, turtle_file):
74
+ return run_query_and_visualize(query, turtle_file.name)
75
+
76
+ run_button.click(fn=on_run_button_click, inputs=[query_input, turtle_file_input], outputs=graph_output)
77
+
78
+ demo.launch()