Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import rdflib
|
| 3 |
import requests
|
|
@@ -6,98 +39,123 @@ import networkx as nx
|
|
| 6 |
from io import BytesIO
|
| 7 |
import base64
|
| 8 |
|
| 9 |
-
# Função para carregar e extrair os nomes do arquivo JSON-LD a partir de uma URL
|
| 10 |
def load_names_from_url(jsonld_url):
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
|
|
|
| 24 |
|
| 25 |
def build_graph_from_jsonld(jsonld_url, selected_name):
|
| 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 |
def run_query_and_visualize(selected_location, jsonld_url):
|
| 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 |
-
plt.close()
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
|
|
|
|
| 89 |
with gr.Blocks() as demo:
|
| 90 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
with gr.Column():
|
| 93 |
-
selected_location = gr.Dropdown(
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
graph_output = gr.HTML(
|
|
|
|
|
|
|
| 97 |
|
| 98 |
def on_run_button_click(selected_location):
|
| 99 |
return run_query_and_visualize(selected_location, jsonld_url)
|
| 100 |
|
| 101 |
-
run_button.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import pkg_resources
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
def update_gradio():
|
| 7 |
+
"""Atualiza o Gradio para a versão mais recente."""
|
| 8 |
+
try:
|
| 9 |
+
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'gradio'])
|
| 10 |
+
print("Gradio atualizado com sucesso!")
|
| 11 |
+
print("Reiniciando aplicação...")
|
| 12 |
+
time.sleep(2)
|
| 13 |
+
python = sys.executable
|
| 14 |
+
subprocess.Popen([python] + sys.argv)
|
| 15 |
+
sys.exit(0)
|
| 16 |
+
except Exception as e:
|
| 17 |
+
print(f"Erro ao atualizar Gradio: {e}")
|
| 18 |
+
|
| 19 |
+
# Verifica e atualiza o Gradio se necessário
|
| 20 |
+
try:
|
| 21 |
+
current_version = pkg_resources.get_distribution('gradio').version
|
| 22 |
+
latest_version = subprocess.check_output([sys.executable, '-m', 'pip', 'index', 'versions', 'gradio']).decode().split('\n')[0].split(' ')[-1]
|
| 23 |
+
|
| 24 |
+
if current_version != latest_version:
|
| 25 |
+
print(f"Atualizando Gradio: {current_version} -> {latest_version}")
|
| 26 |
+
update_gradio()
|
| 27 |
+
else:
|
| 28 |
+
print(f"Gradio já está na versão mais recente: {current_version}")
|
| 29 |
+
except:
|
| 30 |
+
print("Instalando Gradio...")
|
| 31 |
+
update_gradio()
|
| 32 |
+
|
| 33 |
+
# Importações necessárias
|
| 34 |
import gradio as gr
|
| 35 |
import rdflib
|
| 36 |
import requests
|
|
|
|
| 39 |
from io import BytesIO
|
| 40 |
import base64
|
| 41 |
|
|
|
|
| 42 |
def load_names_from_url(jsonld_url):
|
| 43 |
+
"""Carrega e extrai os nomes do arquivo JSON-LD a partir de uma URL."""
|
| 44 |
+
try:
|
| 45 |
+
response = requests.get(jsonld_url)
|
| 46 |
+
data = response.json()
|
| 47 |
+
|
| 48 |
+
names = []
|
| 49 |
+
for item in data:
|
| 50 |
+
if 'name' in item:
|
| 51 |
+
names.append(item['name'])
|
| 52 |
+
|
| 53 |
+
return sorted(names) # Retorna nomes ordenados alfabeticamente
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"Erro ao carregar dados: {e}")
|
| 56 |
+
return []
|
| 57 |
|
| 58 |
def build_graph_from_jsonld(jsonld_url, selected_name):
|
| 59 |
+
"""Constrói o grafo a partir dos dados JSON-LD."""
|
| 60 |
+
try:
|
| 61 |
+
response = requests.get(jsonld_url)
|
| 62 |
+
data = response.json()
|
| 63 |
+
|
| 64 |
+
selected_data = next((item for item in data if item['name'] == selected_name), None)
|
| 65 |
+
|
| 66 |
+
if not selected_data:
|
| 67 |
+
return "Local não encontrado."
|
| 68 |
+
|
| 69 |
+
G = nx.DiGraph()
|
| 70 |
+
|
| 71 |
+
# Adicionar nó do Place
|
| 72 |
+
place_id = selected_data['@id']
|
| 73 |
+
place_label = f"schema:Place\nName: {selected_data['name']}\nDescription: {selected_data['description'][:30]}..."
|
| 74 |
+
G.add_node(place_id, label=place_label)
|
| 75 |
+
|
| 76 |
+
# Adicionar nó de GeoCoordinates
|
| 77 |
+
geo_data = selected_data['geo']
|
| 78 |
+
geo_id = geo_data['@id']
|
| 79 |
+
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']}"
|
| 80 |
+
G.add_node(geo_id, label=geo_label)
|
| 81 |
+
G.add_edge(place_id, geo_id, label="schema:geo")
|
| 82 |
+
|
| 83 |
+
# Adicionar nós de CreativeWork
|
| 84 |
+
for work in selected_data.get('subjectOf', []):
|
| 85 |
+
work_id = work['@id']
|
| 86 |
+
work_label = f"schema:CreativeWork\nHeadline: {work['headline']}\nGenre: {work['genre']}\nDatePublished: {work['datePublished']}\nText: {work['text'][:30]}...\nLanguage: {work['inLanguage']}"
|
| 87 |
+
G.add_node(work_id, label=work_label)
|
| 88 |
+
G.add_edge(place_id, work_id, label="schema:subjectOf")
|
| 89 |
+
|
| 90 |
+
return G
|
| 91 |
+
except Exception as e:
|
| 92 |
+
return f"Erro ao construir grafo: {e}"
|
| 93 |
|
| 94 |
def run_query_and_visualize(selected_location, jsonld_url):
|
| 95 |
+
"""Executa a consulta e visualiza o resultado."""
|
| 96 |
+
try:
|
| 97 |
+
if not selected_location:
|
| 98 |
+
return '<div style="text-align: center; padding: 20px;">Selecione um local para visualizar o grafo</div>'
|
| 99 |
+
|
| 100 |
+
G = build_graph_from_jsonld(jsonld_url, selected_location)
|
| 101 |
|
| 102 |
+
if isinstance(G, str): # Caso de erro
|
| 103 |
+
return f'<div style="color: red; text-align: center; padding: 20px;">{G}</div>'
|
| 104 |
+
|
| 105 |
+
plt.figure(figsize=(15, 10))
|
| 106 |
+
pos = nx.spring_layout(G)
|
| 107 |
+
|
| 108 |
+
nx.draw_networkx_nodes(G, pos, node_size=3000, node_color="skyblue", alpha=0.9)
|
| 109 |
+
nx.draw_networkx_edges(G, pos, width=2, alpha=0.5, edge_color='gray')
|
| 110 |
+
nx.draw_networkx_labels(G, pos, labels=nx.get_node_attributes(G, 'label'), font_size=9, font_color="black")
|
| 111 |
+
nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes(G, 'label'), font_size=9, font_color="red")
|
| 112 |
+
|
| 113 |
+
plt.title(f"Grafo para: {selected_location}", size=15)
|
| 114 |
+
plt.axis('off')
|
| 115 |
+
|
| 116 |
+
buf = BytesIO()
|
| 117 |
+
plt.savefig(buf, format='png', dpi=300, bbox_inches='tight')
|
| 118 |
+
buf.seek(0)
|
| 119 |
+
img_str = base64.b64encode(buf.read()).decode()
|
| 120 |
+
plt.close()
|
| 121 |
+
|
| 122 |
+
return f'<img src="data:image/png;base64,{img_str}" style="width: 100%; max-width: 1200px;"/>'
|
| 123 |
+
except Exception as e:
|
| 124 |
+
return f'<div style="color: red; text-align: center; padding: 20px;">Erro ao gerar visualização: {e}</div>'
|
|
|
|
| 125 |
|
| 126 |
+
# URL do arquivo JSON-LD
|
| 127 |
+
jsonld_url = 'https://huggingface.co/spaces/histlearn/ShowGraph/raw/main/datafile.jsonld'
|
| 128 |
+
|
| 129 |
+
# Carrega os nomes iniciais
|
| 130 |
+
names = load_names_from_url(jsonld_url)
|
| 131 |
|
| 132 |
+
# Interface Gradio
|
| 133 |
with gr.Blocks() as demo:
|
| 134 |
+
gr.Markdown("""
|
| 135 |
+
# Visualização de Grafos de Localidades
|
| 136 |
+
Selecione um local para visualizar seu grafo de relacionamentos.
|
| 137 |
+
""")
|
| 138 |
|
| 139 |
with gr.Column():
|
| 140 |
+
selected_location = gr.Dropdown(
|
| 141 |
+
choices=names,
|
| 142 |
+
label="Selecione o Local",
|
| 143 |
+
info="Escolha um local para ver suas relações"
|
| 144 |
+
)
|
| 145 |
+
run_button = gr.Button("Visualizar Grafo", variant="primary")
|
| 146 |
|
| 147 |
+
graph_output = gr.HTML(
|
| 148 |
+
value='<div style="text-align: center; padding: 20px;">Selecione um local e clique em "Visualizar Grafo"</div>'
|
| 149 |
+
)
|
| 150 |
|
| 151 |
def on_run_button_click(selected_location):
|
| 152 |
return run_query_and_visualize(selected_location, jsonld_url)
|
| 153 |
|
| 154 |
+
run_button.click(
|
| 155 |
+
fn=on_run_button_click,
|
| 156 |
+
inputs=[selected_location],
|
| 157 |
+
outputs=graph_output
|
| 158 |
+
)
|
| 159 |
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
demo.launch()
|