File size: 3,971 Bytes
72dbbd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import networkx as nx
import matplotlib.pyplot as plt
import json
import textwrap
import requests
import pandas as pd
import os

api_key = os.getenv("AIRT_KEY")
AIRT_DBASEx = os.getenv("AIRT_DBASE")
AIRT_TABLEx = os.getenv("AIRT_TABLE")

G = nx.DiGraph()

url = f"https://api.airtable.com/v0/{AIRT_DBASEx}/{AIRT_TABLEx}"
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

def cargar_normativas():
    with open('normativas.json', 'r', encoding='utf-8') as f:
        return json.load(f)

def cargar_estudiantes():
    with open('estudiantes.json', 'r', encoding='utf-8') as f:
        return json.load(f)

def crear_html(normativa):
    return f"""
    <div style="padding: 16px; border: 1px solid #ddd; border-radius: 8px;">
        <h2>{normativa["nombre"]}</h2>
        <h3>{normativa["titulo"]} ({normativa["a帽o"]})</h3>
        <p><strong>ID:</strong> {normativa["id"]}</p>
        <p><strong>Descripci贸n:</strong> {normativa["descripcion"]}</p>
        <p><strong>Enfoque de Gesti贸n:</strong> {normativa["enfoque_riesgo"]}</p>
        <p><strong>Opini贸n Docente:</strong> {normativa["opinion_docente"]}</p>
        <p><strong>M谩s informaci贸n: <a href='{normativa["url"]}' target='_blank'>Sitio Web</a></strong></p>
    </div>
    """

def mostrar_detalles(normativa_seleccionada):
    if not normativa_seleccionada:
        return "<p>Por favor selecciona una normativa</p>", ""

    normativas = cargar_normativas()
    id_normativa = normativa_seleccionada

    for normativa in normativas["normativa_peruana_gestion_riesgos"]:
        if id_normativa == normativa['nombre']:
            return crear_html(normativa), normativa["nombre"]

    return "<p>No se encontr贸 la normativa</p>", ""

def cargar_desde_airtable():
    response = requests.get(url, headers=headers)
    
    if response.status_code != 200:
        print(f"Error: {response.status_code} - {response.text}")
        return pd.DataFrame(columns=["Nombre", "Enfoque", "Norma", "Texto_HF"])

    records = response.json().get("records", [])

    aportes = [
        [record["fields"].get("Nombre", ""), 
         record["fields"].get("Enfoque", ""), 
         record["fields"].get("Norma", ""), 
         record["fields"].get("Texto_HF", "")] for record in records
    ]

    return pd.DataFrame(aportes, columns=["Nombre", "Enfoque", "Norma", "Texto_HF"])

def wrap_text(text, width=10):
    return "\n".join(textwrap.wrap(text, width=width))

def inicializar_grafo():
    df = cargar_desde_airtable()
    
    G.add_node("Determinista", color='red')
    G.add_node("Sist茅mico", color='blue')

    for _, row in df.iterrows():
        nombre, enfoque, norma, texto = row["Nombre"], row["Enfoque"], row["Norma"], row["Texto_HF"]
        textox = wrap_text(f"{nombre}: {texto}")

        if not G.has_node(norma):
            G.add_node(norma, color='gray')
        if not G.has_edge(norma, enfoque):
            G.add_edge(norma, enfoque, label=textox)

def guardar_en_airtable(nombre, enfoque, norma, texto): 
    data = {"fields": {"Nombre": nombre, "Enfoque": enfoque, "Norma": norma, "Texto_HF": texto}}
    requests.post(url, headers=headers, json=data)

def agregar_aporte(nombre, enfoque, norma, texto):
    textox = wrap_text(f"{nombre}: {texto}")
    
    if not G.has_node(norma):
        G.add_node(norma, color='gray')
    if not G.has_edge(norma, enfoque):
        G.add_edge(norma, enfoque, label=textox)

    guardar_en_airtable(nombre, enfoque, norma, texto)  
    return visualizar_grafo()

def visualizar_grafo():
    plt.figure(figsize=(8, 8))
    pos = nx.spring_layout(G)

    edge_labels = nx.get_edge_attributes(G, 'label')
    
    nx.draw(G, pos, with_labels=True, node_color='lightblue', edge_color='gray', node_size=2000, font_size=10)
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=8)

    plt.title("Red de Aportes")
    plt.savefig("graph.png")
    plt.close()
    return "graph.png"