|
import gradio as gr |
|
import rdflib |
|
import requests |
|
from pyvis.network import Network |
|
from IPython.display import HTML |
|
|
|
|
|
def load_names_from_url(jsonld_url): |
|
response = requests.get(jsonld_url) |
|
data = response.json() |
|
|
|
names = [] |
|
for item in data: |
|
if 'name' in item: |
|
names.append(item['name']) |
|
|
|
return names |
|
|
|
|
|
names = load_names_from_url('https://huggingface.co/spaces/histlearn/ShowGraph/raw/main/datafile.jsonld') |
|
|
|
def run_query_and_visualize(qtext, jsonld_url): |
|
|
|
g = rdflib.Graph() |
|
g.parse(jsonld_url, format="json-ld") |
|
|
|
|
|
qres = g.query(qtext) |
|
|
|
|
|
net = Network(notebook=True, height="400px", width="100%", cdn_resources='remote') |
|
nodes = set() |
|
|
|
|
|
for row in qres: |
|
s, p, o = row |
|
if str(s) not in nodes: |
|
net.add_node(str(s), label=str(s)) |
|
nodes.add(str(s)) |
|
if str(o) not in nodes: |
|
net.add_node(str(o), label(str(o))) |
|
nodes.add(str(o)) |
|
net.add_edge(str(s), str(o), title=str(p)) |
|
|
|
|
|
net.show("graph.html") |
|
return HTML("graph.html") |
|
|
|
def update_query(selected_location): |
|
return f""" |
|
PREFIX schema: <http://schema.org/> |
|
SELECT * WHERE {{ |
|
?s schema:name "{selected_location}" . |
|
?s ?p ?o . |
|
}} |
|
""" |
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("# Visualização de Query SPARQL") |
|
|
|
with gr.Column(): |
|
selected_location = gr.Dropdown(choices=names, label="Selecione o Local") |
|
query_input = gr.Textbox(label="Consulta SPARQL", value=update_query(names[0]) if names else "", lines=10) |
|
run_button = gr.Button("Executar Consulta") |
|
|
|
graph_output = gr.HTML() |
|
|
|
def on_location_change(loc): |
|
return update_query(loc) |
|
|
|
selected_location.change(fn=on_location_change, inputs=selected_location, outputs=query_input) |
|
|
|
def on_run_button_click(query): |
|
return run_query_and_visualize(query, 'https://huggingface.co/spaces/histlearn/ShowGraph/raw/main/datafile.jsonld') |
|
|
|
run_button.click(fn=on_run_button_click, inputs=[query_input], outputs=graph_output) |
|
|
|
demo.launch() |
|
|