File size: 4,736 Bytes
695363c
 
f3dbd83
64c5ee5
 
 
 
695363c
2e7c89d
 
 
f3dbd83
695363c
 
2d000f8
2e7c89d
 
695363c
 
 
2e7c89d
9d8c9ea
 
695363c
176d12a
 
 
7b61abf
176d12a
 
 
 
 
7b61abf
64c5ee5
176d12a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695363c
048e9c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec020e
048e9c7
 
 
 
 
 
 
 
176d12a
dec020e
176d12a
 
64c5ee5
176d12a
8a2ba4f
 
 
 
 
048e9c7
f274747
64c5ee5
 
 
 
 
 
 
 
 
 
7b61abf
a12b796
695363c
048e9c7
 
 
 
 
 
 
 
 
695363c
 
 
 
 
048e9c7
 
695363c
 
 
048e9c7
 
 
 
 
 
 
695363c
048e9c7
695363c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import gradio as gr
import rdflib
import requests
import matplotlib.pyplot as plt
import networkx as nx
from io import BytesIO
import base64

# Função para carregar e extrair os nomes do arquivo JSON-LD a partir de uma URL
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

# Carregar nomes do arquivo JSON-LD
jsonld_url = 'https://huggingface.co/spaces/histlearn/ShowGraph/raw/main/datafile.jsonld'
names = load_names_from_url(jsonld_url)

def build_graph_from_jsonld(jsonld_url, selected_name):
    response = requests.get(jsonld_url)
    data = response.json()
    
    # Filtrar o local selecionado
    selected_data = next((item for item in data if item['name'] == selected_name), None)
    
    if not selected_data:
        return "Local não encontrado."
    
    G = nx.DiGraph()
    
    # Adicionar nó do Place
    place_id = selected_data['@id']
    place_label = f"schema:Place\nName: {selected_data['name']}\nDescription: {selected_data['description'][:30]}..."
    G.add_node(place_id, label=place_label)
    
    # Adicionar nó de GeoCoordinates
    geo_data = selected_data['geo']
    geo_id = geo_data['@id']
    geo_label = f"geo:SpatialThing\nLat: {geo_data['lat']}\nLong: {geo_data['long']}\nFeatureCode: {geo_data['gn:featureCode']}\nFeatureCodeName: {geo_data['gn:featureCodeName']}\nName: {geo_data['gn:name']}"
    G.add_node(geo_id, label=geo_label)
    G.add_edge(place_id, geo_id, label="schema:geo")
    
    # Adicionar nós de CreativeWork
    for work in selected_data.get('subjectOf', []):
        work_id = work['@id']
        work_label = f"schema:CreativeWork\nHeadline: {work['headline']}\nGenre: {work['genre']}\nDatePublished: {work['datePublished']}\nText: {work['text'][:30]}...\nLanguage: {work['inLanguage']}"
        G.add_node(work_id, label=work_label)
        G.add_edge(place_id, work_id, label="schema:subjectOf")
    
    return G

def run_query_and_visualize(qtext, jsonld_url):
    print("Executando consulta SPARQL...")
    print(f"Consulta SPARQL: {qtext}")
    
    # Carrega o arquivo JSON-LD
    g = rdflib.Graph()
    g.parse(jsonld_url, format="json-ld")
    
    print("Consulta SPARQL carregada...")

    # Executa a consulta SPARQL
    qres = g.query(qtext)

    # Cria o gráfico de rede
    G = nx.DiGraph()

    print("Processando resultados da consulta...")

    # Processa os resultados da consulta
    for row in qres:
        s, p, o = row
        G.add_node(str(s), label=str(s).split('/')[-1])  # Usar o último segmento da URI como rótulo
        G.add_node(str(o), label=str(o).split('/')[-1])
        G.add_edge(str(s), str(o), label=str(p).split('/')[-1])
    
    # Define posições específicas para os nós importantes
    pos = nx.spring_layout(G)
    
    # Desenha o gráfico usando NetworkX e Matplotlib
    plt.figure(figsize=(15, 10))
    nx.draw_networkx_nodes(G, pos, node_size=3000, node_color="skyblue", alpha=0.9)
    nx.draw_networkx_edges(G, pos, width=2, alpha=0.5, edge_color='gray')
    nx.draw_networkx_labels(G, pos, labels=nx.get_node_attributes(G, 'label'), font_size=9, font_color="black")
    nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes(G, 'label'), font_size=9, font_color="red")

    plt.title("Resultado da Consulta SPARQL", size=15)
    plt.axis('off')
    
    # Salva o gráfico em um arquivo
    buf = BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    img_str = base64.b64encode(buf.read()).decode()
    graph_html = f'<img src="data:image/png;base64,{img_str}"/>'
    
    plt.close()

    print("Gráfico gerado com sucesso.")
    return 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, jsonld_url)

    run_button.click(fn=on_run_button_click, inputs=[query_input], outputs=graph_output)

demo.launch()