jcmachicao's picture
Create app_new.py
dca1733 verified
import gradio as gr
import networkx as nx
import matplotlib.pyplot as plt
import uuid
import requests
import json
# Configuraci贸n de AirTable
BASE_ID = "TU_BASE_ID"
TABLE_NAME = "TU_TABLA"
AIRTABLE_API_KEY = "TU_API_KEY"
# Diccionario para almacenar los aportes y sus conexiones
aportes = {}
graph = nx.Graph()
def cargar_desde_airtable():
"""Recupera los datos almacenados en AirTable y los grafica."""
global aportes, graph
url = f"https://api.airtable.com/v0/{BASE_ID}/{TABLE_NAME}"
headers = {"Authorization": f"Bearer {AIRTABLE_API_KEY}"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
records = response.json().get("records", [])
for record in records:
node_id = record["id"]
texto = record["fields"].get("json_HF", "")
aportes[node_id] = texto
graph.add_node(node_id, label=texto)
# Conectar nodos de alguna manera (ejemplo: secuencialmente)
nodes = list(aportes.keys())
for i in range(1, len(nodes)):
graph.add_edge(nodes[i - 1], nodes[i])
return visualizar_grafo()
def guardar_en_airtable(node_id, texto):
url = f"https://api.airtable.com/v0/{BASE_ID}/{TABLE_NAME}"
headers = {
"Authorization": f"Bearer {AIRTABLE_API_KEY}",
"Content-Type": "application/json"
}
data = {"fields": {"json_HF": texto}}
requests.post(url, headers=headers, json=data)
def agregar_aporte(texto):
global aportes, graph
node_id = str(uuid.uuid4())[:8]
aportes[node_id] = texto
graph.add_node(node_id, label=texto)
if len(aportes) > 1:
prev_node = list(aportes.keys())[-2]
graph.add_edge(prev_node, node_id)
guardar_en_airtable(node_id, texto)
return visualizar_grafo()
def visualizar_grafo():
plt.figure(figsize=(8, 6))
pos = nx.spring_layout(graph)
labels = nx.get_node_attributes(graph, 'label')
nx.draw(graph, pos, with_labels=True, labels=labels, node_color='lightblue', edge_color='gray', node_size=2000, font_size=10)
plt.title("Red de Aportes")
plt.savefig("graph.png")
plt.close()
return "graph.png"
# Cargar datos existentes al inicio
graph_image = cargar_desde_airtable()
iface = gr.Interface(fn=agregar_aporte, inputs="text", outputs="image", title="Foro Din谩mico con Visualizaci贸n de Red")
iface.launch()