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"] nombre = record["fields"].get("Nombre", "") enfoque = record["fields"].get("Enfoque", "") texto = record["fields"].get("json_HF", "") label = f"{nombre} ({enfoque})\n{texto}" aportes[node_id] = (nombre, enfoque, texto) graph.add_node(node_id, label=label, enfoque=enfoque) # Conectar nodos por enfoque for node1 in aportes: for node2 in aportes: if node1 != node2 and aportes[node1][1] == aportes[node2][1]: graph.add_edge(node1, node2) return visualizar_grafo() def guardar_en_airtable(node_id, nombre, enfoque, 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": {"Nombre": nombre, "Enfoque": enfoque, "json_HF": texto}} requests.post(url, headers=headers, json=data) def agregar_aporte(nombre, enfoque, texto): global aportes, graph node_id = str(uuid.uuid4())[:8] label = f"{nombre} ({enfoque})\n{texto}" aportes[node_id] = (nombre, enfoque, texto) graph.add_node(node_id, label=label, enfoque=enfoque) # Conectar con nodos que tengan el mismo enfoque for node in aportes: if node != node_id and aportes[node][1] == enfoque: graph.add_edge(node, node_id) guardar_en_airtable(node_id, nombre, enfoque, 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 por Enfoque") 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", gr.Radio(["Determinista", "Sistémico"], label="Enfoque"), "text"], outputs="image", title="Foro Dinámico con Visualización de Red" ) iface.launch()