|
import subprocess |
|
import pkg_resources |
|
import sys |
|
import time |
|
|
|
def update_gradio(): |
|
"""Atualiza o Gradio para a versão mais recente.""" |
|
try: |
|
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'gradio']) |
|
print("Gradio atualizado com sucesso!") |
|
print("Reiniciando aplicação...") |
|
time.sleep(2) |
|
python = sys.executable |
|
subprocess.Popen([python] + sys.argv) |
|
sys.exit(0) |
|
except Exception as e: |
|
print(f"Erro ao atualizar Gradio: {e}") |
|
|
|
|
|
try: |
|
current_version = pkg_resources.get_distribution('gradio').version |
|
latest_version = subprocess.check_output([sys.executable, '-m', 'pip', 'index', 'versions', 'gradio']).decode().split('\n')[0].split(' ')[-1] |
|
|
|
if current_version != latest_version: |
|
print(f"Atualizando Gradio: {current_version} -> {latest_version}") |
|
update_gradio() |
|
else: |
|
print(f"Gradio já está na versão mais recente: {current_version}") |
|
except: |
|
print("Instalando Gradio...") |
|
update_gradio() |
|
|
|
|
|
import gradio as gr |
|
import rdflib |
|
import requests |
|
import matplotlib.pyplot as plt |
|
import networkx as nx |
|
from io import BytesIO |
|
import base64 |
|
|
|
def load_names_from_url(jsonld_url): |
|
"""Carrega e extrai os nomes do arquivo JSON-LD a partir de uma URL.""" |
|
try: |
|
response = requests.get(jsonld_url) |
|
data = response.json() |
|
|
|
names = [] |
|
for item in data: |
|
if 'name' in item: |
|
names.append(item['name']) |
|
|
|
return sorted(names) |
|
except Exception as e: |
|
print(f"Erro ao carregar dados: {e}") |
|
return [] |
|
|
|
def build_graph_from_jsonld(jsonld_url, selected_name): |
|
"""Constrói o grafo a partir dos dados JSON-LD.""" |
|
try: |
|
response = requests.get(jsonld_url) |
|
data = response.json() |
|
|
|
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() |
|
|
|
|
|
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) |
|
|
|
|
|
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") |
|
|
|
|
|
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 |
|
except Exception as e: |
|
return f"Erro ao construir grafo: {e}" |
|
|
|
def run_query_and_visualize(selected_location, jsonld_url): |
|
"""Executa a consulta e visualiza o resultado.""" |
|
try: |
|
if not selected_location: |
|
return '<div style="text-align: center; padding: 20px;">Selecione um local para visualizar o grafo</div>' |
|
|
|
G = build_graph_from_jsonld(jsonld_url, selected_location) |
|
|
|
if isinstance(G, str): |
|
return f'<div style="color: red; text-align: center; padding: 20px;">{G}</div>' |
|
|
|
plt.figure(figsize=(15, 10)) |
|
pos = nx.spring_layout(G) |
|
|
|
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(f"Grafo para: {selected_location}", size=15) |
|
plt.axis('off') |
|
|
|
buf = BytesIO() |
|
plt.savefig(buf, format='png', dpi=300, bbox_inches='tight') |
|
buf.seek(0) |
|
img_str = base64.b64encode(buf.read()).decode() |
|
plt.close() |
|
|
|
return f'<img src="data:image/png;base64,{img_str}" style="width: 100%; max-width: 1200px;"/>' |
|
except Exception as e: |
|
return f'<div style="color: red; text-align: center; padding: 20px;">Erro ao gerar visualização: {e}</div>' |
|
|
|
|
|
jsonld_url = 'https://huggingface.co/spaces/histlearn/ShowGraph/raw/main/datafile.jsonld' |
|
|
|
|
|
names = load_names_from_url(jsonld_url) |
|
|
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown(""" |
|
# Visualização de Grafos de Localidades |
|
Selecione um local para visualizar seu grafo de relacionamentos. |
|
""") |
|
|
|
with gr.Column(): |
|
selected_location = gr.Dropdown( |
|
choices=names, |
|
label="Selecione o Local", |
|
info="Escolha um local para ver suas relações" |
|
) |
|
run_button = gr.Button("Visualizar Grafo", variant="primary") |
|
|
|
graph_output = gr.HTML( |
|
value='<div style="text-align: center; padding: 20px;">Selecione um local e clique em "Visualizar Grafo"</div>' |
|
) |
|
|
|
def on_run_button_click(selected_location): |
|
return run_query_and_visualize(selected_location, jsonld_url) |
|
|
|
run_button.click( |
|
fn=on_run_button_click, |
|
inputs=[selected_location], |
|
outputs=graph_output |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |