Spaces:
Paused

File size: 22,840 Bytes
8f4b741
e0fbc94
 
614205a
 
 
 
 
8f4b741
 
 
 
 
 
 
 
 
 
 
 
332382a
8f4b741
332382a
 
 
8f4b741
 
 
614205a
 
 
 
332382a
614205a
 
 
 
 
 
332382a
 
614205a
 
 
67e78f6
 
 
 
14c3500
 
 
 
67e78f6
 
 
 
 
 
14c3500
67e78f6
332382a
 
 
 
 
 
14c3500
 
67e78f6
 
 
 
 
 
5cb58d3
 
 
 
 
 
332382a
 
 
 
5cb58d3
 
8f4b741
 
 
 
 
 
332382a
 
 
 
e0fbc94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332382a
 
 
 
e0fbc94
 
 
8f4b741
 
 
 
 
 
 
 
 
 
 
 
332382a
8f4b741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614205a
 
a1e2231
614205a
 
 
 
 
 
 
 
 
a1e2231
614205a
 
a1e2231
614205a
 
 
 
a1e2231
8f4b741
614205a
a1e2231
 
614205a
 
 
332382a
614205a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f4b741
614205a
8f4b741
 
 
14c3500
 
 
 
 
 
 
 
 
8f4b741
14c3500
332382a
14c3500
 
332382a
14c3500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0fbc94
332382a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614205a
 
 
332382a
 
614205a
 
 
332382a
614205a
332382a
e0fbc94
332382a
 
 
 
8f4b741
332382a
614205a
 
332382a
14c3500
 
332382a
 
 
 
 
 
 
 
14c3500
 
 
 
 
 
 
 
 
 
 
 
 
a1e2231
14c3500
614205a
14c3500
332382a
 
a1e2231
 
14c3500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f4b741
 
332382a
 
 
 
 
 
 
 
 
 
614205a
332382a
614205a
 
 
 
332382a
f465b10
8f4b741
 
14c3500
614205a
 
f465b10
614205a
 
 
 
 
332382a
 
 
 
 
 
 
 
 
614205a
 
 
 
 
 
 
 
332382a
614205a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332382a
614205a
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import os
import json
import gzip
import uuid

# ECharts page the graph is rendered into (placeholders __ELEMENTS__, __KINDS__, __QUERY__, __PREDICTED__)
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'kg_graph_template.html'), encoding='utf-8') as _f:
    _GRAPH_TEMPLATE = _f.read()

NODE_TYPE_COLORS = {
 'Disease': '#079dbb',
 'HPO': '#58d0e8',
 'Drug': '#815ac0',
 'Compound': '#d2b7e5',
 'Domain': '#6bbf59',
 'GO_term_P': '#ff8800',
 'GO_term_F': '#ffaa00',
 'GO_term_C': '#ffc300',
 'Pathway': '#720026',
 'kegg_Pathway': '#720026',
 # EC number (L4) and its classes (L1-L3), darkening from L4 up to the top class.
 'EC_number': '#ce4257',
 'EC_class_3': '#a53546',
 'EC_class_2': '#842a38',
 'EC_class_1': '#69222d',
 'Protein': '#3aa6a4'
}

EDGE_KIND_COLORS = {
    'confirmed': '#8338ec',   # predicted and annotated in the KG
    'novel': '#c1121f',       # predicted, not annotated in the KG
    'annotation': '#219ebc',  # annotated in the KG, not among the shown predictions
    'hierarchy': '#b5838d',   # EC taxonomy link between predicted EC levels
    'other': '#666666',
}

EDGE_KIND_LABELS = {
    'confirmed': 'Confirmed prediction (in KG)',
    'novel': 'Novel prediction',
    'annotation': 'Known annotation (in KG)',
    'hierarchy': 'EC hierarchy',
    'other': 'Other relationship',
}

EDGE_LABEL_TRANSLATION = {
    'Orthology': 'is ortholog to',
    'Pathway': 'takes part in',
    'kegg_path_prot': 'takes part in',
    ('domain_function', 'GO_term_F'): 'enables',
    ('domain_function', 'GO_term_P'): 'is involved in',
    ('domain_function', 'GO_term_C'): 'localizes to', 
    'function_function': 'ontological relationship',   
    'protein_domain': 'has',
    'PPI': 'interacts with',
    'HPO': 'is associated with',
    'kegg_dis_prot': 'is related to',
    'Disease': 'is related to',
    'Drug': 'targets',
    'kegg_dis_path': 'modulates',
    'protein_ec': 'catalyzes',
    'protein_ec1': 'catalyzes',
    'protein_ec2': 'catalyzes',
    'protein_ec3': 'catalyzes',
    'ec_parent_1': 'is a subclass of',
    'ec_parent_2': 'is a subclass of',
    'ec_parent_3': 'is a subclass of',
    'hpodis': 'is associated with',
    'kegg_dis_drug': 'treats',
    'Chembl': 'targets',
    ('protein_function', 'GO_term_F'): 'enables',
    ('protein_function', 'GO_term_P'): 'is involved in',
    ('protein_function', 'GO_term_C'): 'localizes to',    
}

NODE_LABEL_TRANSLATION = {
    'HPO': 'Phenotype',
    'GO_term_P': 'Biological Process',
    'GO_term_F': 'Molecular Function',
    'GO_term_C': 'Cellular Component',
    'kegg_Pathway': 'Pathway',
    'EC_number': 'EC L4',
    'EC_class_3': 'EC L3',
    'EC_class_2': 'EC L2',
    'EC_class_1': 'EC L1',
}

GO_CATEGORY_MAPPING = {
    'Biological Process': 'GO_term_P',
    'Molecular Function': 'GO_term_F',
    'Cellular Component': 'GO_term_C'
}

# Edge relations not shown in the view: protein_similar is a sequence-similarity device the EC model
# uses internally, not a biologically interpretable relationship to display.
EXCLUDED_EDGE_RELATIONS = {'protein_similar'}

def get_node_url(node_type, node_id):
    """Get the URL for a node based on its type and ID"""
    if node_type.startswith('GO_term'):
        return f"https://www.ebi.ac.uk/QuickGO/term/{node_id}"
    elif node_type == 'Protein':
        return f"https://www.uniprot.org/uniprotkb/{node_id}/entry"
    elif node_type == 'Disease':
        if ':' in node_id:
            ontology = node_id.split(':')[0]
            if ontology == 'EFO':
                return f"http://www.ebi.ac.uk/efo/EFO_{node_id.split(':')[1]}"
            elif ontology == 'MONDO':
                return f'http://purl.obolibrary.org/obo/MONDO_{node_id.split(":")[1]}'
            elif ontology == 'Orphanet':
                return f"http://www.orpha.net/ORDO/Orphanet_{node_id.split(':')[1]}"
        else:
            return f"https://www.genome.jp/entry/{node_id}"
    elif node_type == 'HPO':
        return f"https://hpo.jax.org/browse/term/{node_id}"
    elif node_type == 'Drug':
        return f"https://go.drugbank.com/drugs/{node_id}"
    elif node_type == 'Compound':
        return f"https://www.ebi.ac.uk/chembl/explore/compound/{node_id}"
    elif node_type == 'Domain':
        return f"https://www.ebi.ac.uk/interpro/entry/InterPro/{node_id}"
    elif node_type == 'Pathway':
        return f"https://reactome.org/content/detail/{node_id}"
    elif node_type == 'kegg_Pathway':
        return f"https://www.genome.jp/pathway/{node_id}"
    elif node_type == 'EC_number' or node_type.startswith('EC_class'):
        parts = node_id.split('.')
        parts += ['-'] * (4 - len(parts))  # pad class prefixes to the full EC form
        return f"https://enzyme.expasy.org/EC/{'.'.join(parts)}"
    else:
        return None

def _gather_protein_edges(data, protein_id):

    protein_idx = data['Protein']['id_mapping'][protein_id]
    reverse_id_mapping = {}
    for node_type in data.node_types:
        reverse_id_mapping[node_type] = {v:k for k, v in data[node_type]['id_mapping'].items()}
    
    protein_edges = {}

    print(f'Gathering edges for {protein_id}...')

    for edge_type in data.edge_types:
        if 'rev' not in edge_type[1] and edge_type[1] not in EXCLUDED_EDGE_RELATIONS:
            if edge_type not in protein_edges:
                protein_edges[edge_type] = []
            if edge_type[0] == 'Protein':
                print(f'Gathering edges for {edge_type}...')
                # append the edges with protein_idx as source node
                edges = data[edge_type].edge_index[:, data[edge_type].edge_index[0] == protein_idx]
                protein_edges[edge_type].extend(edges.T.tolist())
            elif edge_type[2] == 'Protein':
                print(f'Gathering edges for {edge_type}...')
                # append the edges with protein_idx as target node
                edges = data[edge_type].edge_index[:, data[edge_type].edge_index[1] == protein_idx]
                protein_edges[edge_type].extend(edges.T.tolist())
    
    for edge_type in protein_edges.keys():
        if protein_edges[edge_type]:
            mapped_edges = set()
            for edge in protein_edges[edge_type]:
                # Get source and target node types from edge_type
                source_type, _, target_type = edge_type
                # Map indices back to original IDs
                source_id = reverse_id_mapping[source_type][edge[0]]
                target_id = reverse_id_mapping[target_type][edge[1]]
                mapped_edges.add((source_id, target_id))
            protein_edges[edge_type] = mapped_edges
        
    return protein_edges

def _filter_edges(protein_id, protein_edges, prediction_df, limit=10, is_second_degree=False,
                  second_degree_limit=3, prediction_limit=5):
    """
    Select the edges to draw for one node.

    Returns {edge_type: [((source, target), probability, kind), ...]}, where kind is
      'confirmed'  - predicted GO term that is also annotated in the KG (purple); includes annotated terms
                     predicted below the top `prediction_limit` terms
      'novel'      - one of the top `prediction_limit` predicted GO terms, not annotated in the KG (red)
      'annotation' - protein-GO annotation in the KG that was not predicted (blue); probability is None
      'other'      - any other relationship, incl. domain-GO and GO-GO edges (gray)

    Args:
        protein_id: ID of the node whose edges are filtered
        protein_edges: {edge_type: set of (source, target)} from the KG
        prediction_df: DataFrame containing predictions
        limit: Maximum number of KG edges per edge type for first-degree connections
        is_second_degree: Whether these are second-degree edges (KG only, no predictions)
        second_degree_limit: Maximum number of edges per edge type for second-degree connections
        prediction_limit: Maximum number of predicted GO terms per predicted category
    """
    filtered_edges = {}

    # Use appropriate limit based on edge degree
    current_limit = second_degree_limit if is_second_degree else limit

    # Predictions are drawn for the query protein only; second-degree edges show the KG as is.
    predicted = {}
    if not is_second_degree and prediction_df is not None:
        rows = prediction_df[prediction_df['UniProt_ID'] == protein_id]
        for category, group in rows.groupby('GO_category'):
            predicted[GO_CATEGORY_MAPPING[category]] = group.sort_values(
                by=['Probability', 'GO_ID'], ascending=[False, True])

    # Include predicted categories even when the protein has no KG annotation in them
    edge_types = {edge_type for edge_type, edges in protein_edges.items() if edges}
    edge_types |= {('Protein', 'protein_function', category) for category in predicted}

    for edge_type in sorted(edge_types):
        # Sorted so the same subset is shown on every run (set order varies between processes)
        edges = sorted(protein_edges.get(edge_type) or [])

        if edge_type[1] == 'protein_function' and edge_type[2] in predicted:
            kg_edges = set(edges)
            scores = dict(zip(predicted[edge_type[2]]['GO_ID'], predicted[edge_type[2]]['Probability']))
            top_terms = list(scores)[:prediction_limit]
            shown = [((protein_id, term), scores[term],
                      'confirmed' if (protein_id, term) in kg_edges else 'novel') for term in top_terms]
            # KG annotations outside the top predictions, under the regular neighbour limit: purple if the model
            # also predicted them (any rank above the threshold, highest scores first), blue if it did not
            rest = [edge for edge in edges if edge[1] not in top_terms]
            rest.sort(key=lambda edge: -scores.get(edge[1], -1))
            shown += [(edge, scores[edge[1]], 'confirmed') if edge[1] in scores else (edge, None, 'annotation')
                      for edge in rest[:current_limit]]
            filtered_edges[edge_type] = shown
        elif edge_type[1] == 'protein_function':
            filtered_edges[edge_type] = [(edge, None, 'annotation') for edge in edges[:current_limit]]
        else:
            filtered_edges[edge_type] = [(edge, None, 'other') for edge in edges[:current_limit]]

    return filtered_edges

def _gather_neighbor_edges(data, node_id, node_type, exclude_node_id):
    """Gather edges for a neighbor node, excluding edges back to the original query protein"""
    
    node_idx = data[node_type]['id_mapping'][node_id]
    reverse_id_mapping = {}
    for ntype in data.node_types:
        reverse_id_mapping[ntype] = {v:k for k, v in data[ntype]['id_mapping'].items()}
    
    neighbor_edges = {}

    for edge_type in data.edge_types:
        if 'rev' not in edge_type[1] and edge_type[1] not in EXCLUDED_EDGE_RELATIONS:
            if edge_type not in neighbor_edges:
                neighbor_edges[edge_type] = []

            if edge_type[0] == node_type:
                # Get edges where neighbor is source
                edges = data[edge_type].edge_index[:, data[edge_type].edge_index[0] == node_idx]
                edges = edges.T.tolist()
                # Filter out edges going back to the query protein
                edges = [edge for edge in edges if reverse_id_mapping[edge_type[2]][edge[1]] != exclude_node_id]
                neighbor_edges[edge_type].extend(edges)
                
            elif edge_type[2] == node_type:
                # Get edges where neighbor is target
                edges = data[edge_type].edge_index[:, data[edge_type].edge_index[1] == node_idx]
                edges = edges.T.tolist()
                # Filter out edges coming from the query protein
                edges = [edge for edge in edges if reverse_id_mapping[edge_type[0]][edge[0]] != exclude_node_id]
                neighbor_edges[edge_type].extend(edges)
    
    # Map indices back to IDs
    for edge_type in neighbor_edges.keys():
        if neighbor_edges[edge_type]:
            mapped_edges = set()
            for edge in neighbor_edges[edge_type]:
                source_type, _, target_type = edge_type
                source_id = reverse_id_mapping[source_type][edge[0]]
                target_id = reverse_id_mapping[target_type][edge[1]]
                mapped_edges.add((source_id, target_id))
            neighbor_edges[edge_type] = mapped_edges
            
    return neighbor_edges

# EC prediction overlay: the protein->EC edge per level, and the EC taxonomy chain.
EC_LEVEL_EDGE = {
    'L1': ('Protein', 'protein_ec1', 'EC_class_1'),
    'L2': ('Protein', 'protein_ec2', 'EC_class_2'),
    'L3': ('Protein', 'protein_ec3', 'EC_class_3'),
    'L4': ('Protein', 'protein_ec', 'EC_number'),
}
EC_PARENT_EDGE = {
    'EC_number': ('EC_number', 'ec_parent_3', 'EC_class_3'),
    'EC_class_3': ('EC_class_3', 'ec_parent_2', 'EC_class_2'),
    'EC_class_2': ('EC_class_2', 'ec_parent_1', 'EC_class_1'),
}


def _best_ec_chain_rows(rows):
    """Keep only the single highest-scoring EC chain: the best L1, then the best L2 among its children,
    and so on, so the kept rows form one connected L1 -> L4 path."""
    kept, parent = {}, None
    for level in ('L1', 'L2', 'L3', 'L4'):
        lv = rows[rows['EC_level'] == level]
        if parent is not None:
            lv = lv[lv['EC'].map(lambda t: '.'.join(str(t).split('.')[:-1])) == parent]
        if lv.empty:
            break
        kept[level] = str(lv.sort_values('Probability', ascending=False).iloc[0]['EC'])
        parent = kept[level]
    return rows[rows.apply(lambda r: kept.get(r['EC_level']) == str(r['EC']), axis=1)]


def _ec_overlay_edges(protein_id, protein_edges, ec_df, top1_per_level=False):
    """Edges for the EC prediction overlay: protein -> each predicted EC node (confirmed if the KG has
    that protein_ec* edge, novel otherwise), known KG EC annotations that were not predicted, and the
    EC taxonomy chain (ec_parent) linking the predicted EC nodes L4 -> L3 -> L2 -> L1.

    top1_per_level: keep only the single best EC chain (one prediction per level) instead of every EC
    above the threshold."""
    out = {}
    rows = ec_df[ec_df['UniProt_ID'] == protein_id]
    if top1_per_level:
        rows = _best_ec_chain_rows(rows)
    predicted_nodes = set()  # (ec_token, node_type)
    for level, et in EC_LEVEL_EDGE.items():
        lv = rows[rows['EC_level'] == level].sort_values('Probability', ascending=False)
        kg_edges = protein_edges.get(et, set())  # {(protein, ec_token)}
        pred_toks, items = [], []
        for _, r in lv.iterrows():
            tok, prob = str(r['EC']), float(r['Probability'])
            kind = 'confirmed' if (protein_id, tok) in kg_edges else 'novel'
            items.append(((protein_id, tok), prob, kind))
            predicted_nodes.add((tok, et[2]))
            pred_toks.append(tok)
        if not top1_per_level:  # KG EC annotations the model did not predict
            for (p, tok) in sorted(kg_edges):
                if tok not in pred_toks:
                    items.append(((p, tok), None, 'annotation'))
        if items:
            out[et] = items
    pred_toks_all = {tok for tok, _ in predicted_nodes}
    for tok, ntype in predicted_nodes:  # chain each predicted node to its predicted parent prefix
        if ntype == 'EC_class_1':
            continue
        parent_tok = '.'.join(tok.split('.')[:-1])
        if parent_tok in pred_toks_all:
            out.setdefault(EC_PARENT_EDGE[ntype], []).append(((tok, parent_tok), None, 'hierarchy'))
    return out


def visualize_protein_subgraph(data, protein_id, go_df=None, ec_df=None, show_go=True, show_ec=True,
                               limit=10, second_degree_limit=3, include_second_degree=False,
                               prediction_limit=5, predicted_categories=None, ec_top1=False):
    """
    Build the knowledge-graph view around one protein and save it as an HTML file.

    Overlays GO predictions (go_df, when show_go) and/or EC predictions (ec_df, when show_ec); all other
    KG neighbours are drawn as context. predicted_categories are the GO categories the run predicted.
    Returns (file_path, visualized_edges).
    """
    from run_prothgt_app import load_name_info  # cached loader; avoids re-reading 24 MB per call
    from run_prothgt_ec_app import load_ec_class_names
    name_info = load_name_info()
    ec_class_names = load_ec_class_names()

    use_go = show_go and go_df is not None
    use_ec = show_ec and ec_df is not None

    # Get the first-degree edges and filter them (GO overlay + context)
    protein_edges = _gather_protein_edges(data, protein_id)
    first_degree_edges = _filter_edges(protein_id, protein_edges, go_df if use_go else None,
                                     limit=limit, is_second_degree=False,
                                     prediction_limit=prediction_limit)

    # Initialize all_edges with first degree edges
    all_edges = first_degree_edges.copy()

    if use_ec:
        # the EC overlay replaces the generic protein_ec* context edges
        for et in [e for e in all_edges if e[1] in ('protein_ec', 'protein_ec1', 'protein_ec2', 'protein_ec3')]:
            del all_edges[et]
        for et, items in _ec_overlay_edges(protein_id, protein_edges, ec_df, top1_per_level=ec_top1).items():
            all_edges.setdefault(et, []).extend(items)

    if include_second_degree:
        # Collect neighbor nodes from first-degree edges
        neighbor_nodes = set()
        for edge_type, edges in first_degree_edges.items():
            source_type, _, target_type = edge_type
            for edge_info in edges:
                edge = edge_info[0]
                source, target = edge
                if source != protein_id:
                    neighbor_nodes.add((source, source_type))
                if target != protein_id:
                    neighbor_nodes.add((target, target_type))
        
        # Gather and filter second-degree edges with the smaller limit
        second_degree_edges = {}
        for neighbor_id, neighbor_type in sorted(neighbor_nodes):
            neighbor_edges = _gather_neighbor_edges(data, neighbor_id, neighbor_type, protein_id)
            filtered_neighbor_edges = _filter_edges(neighbor_id, neighbor_edges, go_df if use_go else None,
                                                 limit=limit,
                                                 is_second_degree=True,
                                                 second_degree_limit=second_degree_limit)
            
            # Merge filtered neighbor edges into second_degree_edges
            for edge_type, edges in filtered_neighbor_edges.items():
                if edge_type not in second_degree_edges:
                    second_degree_edges[edge_type] = []
                second_degree_edges[edge_type].extend(edges)
        
        # Merge first and second degree edges
        for edge_type, edges in second_degree_edges.items():
            if edge_type in all_edges:
                all_edges[edge_type].extend(edges)
            else:
                all_edges[edge_type] = edges

    # Update visualized_edges with all edges
    visualized_edges = all_edges
    
    print(f'Edges to be visualized: {visualized_edges}')

    # Which node-type labels are prediction targets in this view (for the legend)
    predicted_labels = []
    if use_go:
        predicted_labels += (sorted(NODE_LABEL_TRANSLATION[c] for c in predicted_categories)
                             if predicted_categories is not None
                             else sorted(go_df['GO_category'].unique().tolist()))
    if use_ec:
        predicted_labels += [NODE_LABEL_TRANSLATION[t] for t in
                             ('EC_class_1', 'EC_class_2', 'EC_class_3', 'EC_number')]

    # Render with the ECharts template (radial layout, see kg_graph_template.html)
    elements = _build_graph_elements(protein_id, visualized_edges, name_info, ec_class_names)
    html = _GRAPH_TEMPLATE \
        .replace('__ELEMENTS__', _json_for_script(elements)) \
        .replace('__KINDS__', _json_for_script(EDGE_KIND_LABELS)) \
        .replace('__QUERY__', _json_for_script(protein_id)) \
        .replace('__PREDICTED__', _json_for_script(predicted_labels))

    # Save graph to a protein-specific file in a temporary directory
    os.makedirs('temp_viz', exist_ok=True)
    suffix = "_with_2nd_degree" if include_second_degree else "_1st_degree"
    # Unique per call: the app caches one file per setting combination and the Space is shared
    file_path = os.path.join('temp_viz', f'{protein_id}_graph{suffix}_{uuid.uuid4().hex[:8]}.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html)

    return file_path, visualized_edges


def _node_name(node_id, node_type, name_info, ec_class_names):
    if node_type.startswith('GO_term'):
        return name_info['GO_term'].get(node_id, node_id)
    if node_type.startswith('EC_class'):
        return ec_class_names.get(node_id, node_id)
    return name_info.get(node_type, {}).get(node_id, node_id)


def _build_graph_elements(protein_id, visualized_edges, name_info, ec_class_names):
    """Nodes and edges for the graph template, as [{'data': {...}}, ...] (nodes first)."""
    nodes, edges = {}, []

    def add_node(node_id, node_type):
        if node_id in nodes:
            return
        nodes[node_id] = {'data': {
            'id': node_id,
            'name': _node_name(node_id, node_type, name_info, ec_class_names),
            'type': NODE_LABEL_TRANSLATION.get(node_type, node_type),
            'color': NODE_TYPE_COLORS[node_type],
            'url': get_node_url(node_type, node_id) or '',
            'role': 'query' if node_id == protein_id else '',
        }}

    add_node(protein_id, 'Protein')
    for (source_type, relation, target_type), items in visualized_edges.items():
        key = (relation, target_type) if relation in ('protein_function', 'domain_function') else relation
        for (source, target), probability, kind in items:
            source, target = str(source), str(target)
            add_node(source, source_type)
            add_node(target, target_type)
            edges.append({'data': {
                'source': source, 'target': target,
                'type': f'{source_type}_{relation}_{target_type}',  # key used in the edges JSON download
                'relation': EDGE_LABEL_TRANSLATION.get(key, relation),
                'kind': kind,
                'color': EDGE_KIND_COLORS[kind],
                'prob': None if probability is None else float(probability),
            }})
    return list(nodes.values()) + edges


def _json_for_script(value):
    """JSON that is safe to inline in a <script> block."""
    return json.dumps(value).replace('</', '<\\/')