-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2142 lines (1922 loc) · 80.2 KB
/
Copy pathapp.py
File metadata and controls
2142 lines (1922 loc) · 80.2 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import argparse
import gc
import importlib.util
import logging
import tempfile
import threading
from pathlib import Path
from typing import Dict, Generator, List, Optional, Tuple
try:
import gradio as gr
except ImportError as e:
raise ImportError(
"The LELA web UI requires gradio. Install it with:\n"
" pip install \"lela[ui]\"\n"
"or with uv:\n"
" uv sync --extra ui"
) from e
import torch
# Global cancellation event for cooperative cancellation
_cancel_event = threading.Event()
from lela import Lela
from lela.memory import get_system_resources
from lela.defaults import (
AVAILABLE_LLM_MODELS as LLM_MODEL_CHOICES,
AVAILABLE_EMBEDDING_MODELS as EMBEDDING_MODEL_CHOICES,
AVAILABLE_CROSS_ENCODER_MODELS as CROSS_ENCODER_MODEL_CHOICES,
AVAILABLE_VLLM_RERANKER_MODELS as VLLM_RERANKER_MODEL_CHOICES,
DEFAULT_VLLM_RERANKER_MODEL,
DEFAULT_GLINER_MODEL,
DEFAULT_GLINER_VRAM_GB,
DEFAULT_MAX_MODEL_LEN,
get_model_vram_gb,
)
from lela.llm_pool import clear_all_models
TITLE_HTML = """
<div style="display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin-bottom:4px;">
<h1 style="margin:0;font-size:1.8em;">LELA: An End-to-End LLM-Based Entity Linking Framework with Zero-Shot Domain Adaptation</h1>
<div style="display:flex;gap:8px;align-items:center;">
<a href="https://github.com/samyhaff/LELA" target="_blank"
style="display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:6px;background:#f3f4f6;color:#1f2937;text-decoration:none;font-size:0.85em;border:1px solid #d1d5db;">
<svg height="16" width="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>
GitHub
</a>
<a href="https://arxiv.org/abs/2601.05192" target="_blank"
style="display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:6px;background:#f3f4f6;color:#1f2937;text-decoration:none;font-size:0.85em;border:1px solid #d1d5db;">
<svg height="16" width="12" viewBox="0 0 17.732 24.269" xmlns="http://www.w3.org/2000/svg"><path d="M573.549,280.916l2.266,2.738,6.674-7.84c.353-.47.52-.717.353-1.117a1.218,1.218,0,0,0-1.061-.748h0a.953.953,0,0,0-.712.262Z" transform="translate(-566.984 -271.548)" fill="#bdb9b4"/><path d="M579.525,282.225l-10.606-10.174a1.413,1.413,0,0,0-.834-.5,1.09,1.09,0,0,0-1.027.66c-.167.4-.047.681.319,1.206l8.44,10.242h0l-6.282,7.716a1.336,1.336,0,0,0-.323,1.3,1.114,1.114,0,0,0,1.04.69A.992.992,0,0,0,571,293l8.519-7.92A1.924,1.924,0,0,0,579.525,282.225Z" transform="translate(-566.984 -271.548)" fill="#b31b1b"/><path d="M584.32,293.912l-8.525-10.275,0,0L573.53,280.9l-1.389,1.254a2.063,2.063,0,0,0,0,2.965l10.812,10.419a.925.925,0,0,0,.742.282,1.039,1.039,0,0,0,.953-.667A1.261,1.261,0,0,0,584.32,293.912Z" transform="translate(-566.984 -271.548)" fill="#bdb9b4"/></svg>
Paper
</a>
</div>
</div>
"""
LOGO = """
<div style="display: flex; justify-content: center; align-items: center; gap: 40px; margin-top: 40px;">
<img src="https://www.telecom-paris.fr/wp-content-EvDsK19/uploads/2024/01/logo_telecom_ipparis_rvb_fond_h-768x359.png" alt="Telecom Paris Logo" style="height: 80px;">
<img src="https://www.ip-paris.fr/sites/default/files/image002.png" alt="IP Paris Logo" style="height: 80px;">
<img src="https://yago-knowledge.org/assets/images/logo.png" alt="YAGO Logo" style="height: 80px;">
</div>
"""
def _is_vllm_usable() -> bool:
"""Check if vllm is installed and CUDA is available for it to run."""
vllm_installed = importlib.util.find_spec("vllm") is not None
cuda_available = False
try:
import torch
cuda_available = torch.cuda.is_available()
except ImportError:
pass
# Log for debugging
import logging
logger = logging.getLogger(__name__)
logger.info(f"vLLM check: installed={vllm_installed}, cuda={cuda_available}")
return vllm_installed and cuda_available
def get_available_components() -> Dict[str, List[str]]:
"""Get list of available spaCy pipeline components."""
# These map to spaCy factories registered in lela.spacy_components
available_disambiguators = [
"none",
"first",
"vllm",
"transformers",
"openai_api",
]
return {
"loaders": ["text", "pdf", "docx", "html", "json", "jsonl"],
"ner": ["regex", "spacy", "gliner"],
"candidates": ["none", "fuzzy", "bm25", "dense", "openai_api_dense"],
"rerankers": [
"none",
"cross_encoder",
"vllm_api_client",
"llama_server",
# "embedder_transformers",
# "embedder_vllm",
"cross_encoder_vllm",
],
"disambiguators": available_disambiguators,
"knowledge_bases": ["jsonl"],
}
GRAY_COLOR = "#D1D5DB" # Tailwind gray-300 (light gray)
# Color palette for consistent entity colors
# Based on D3 Category20 / Tableau 20 - industry standard for categorical data visualization
# First 10: saturated colors for primary distinction
# Next 10: lighter variants for additional categories
# Source: https://d3js.org/d3-scale-chromatic/categorical
ENTITY_COLORS = [
"#1F77B4", # Blue
"#FF7F0E", # Orange
"#2CA02C", # Green
"#D62728", # Red
"#9467BD", # Purple
"#8C564B", # Brown
"#E377C2", # Pink
"#BCBD22", # Olive
"#17BECF", # Cyan
"#AEC7E8", # Light Blue
"#FFBB78", # Light Orange
"#98DF8A", # Light Green
"#FF9896", # Light Red
"#C5B0D5", # Light Purple
"#C49C94", # Light Brown
"#F7B6D2", # Light Pink
"#DBDB8D", # Light Olive
"#9EDAE5", # Light Cyan
]
UNLINKED_COLOR = "#9E9E9E" # Gray for entities not linked to KB
ERROR_COLOR = "#DC2626" # Tailwind red-600
MIN_VLLM_CONTEXT_LEN = 512
MAX_VLLM_CONTEXT_LEN = 32768
VLLM_CONTEXT_LEN_STEP = 256
DEFAULT_WEB_VLLM_CONTEXT_LEN = min(4096, DEFAULT_MAX_MODEL_LEN)
def highlighted_to_html(
highlighted: List[Tuple[str, Optional[str], Optional[Dict]]],
color_map: Dict[str, str],
show_legend: bool = True,
) -> str:
"""Convert highlighted text data to HTML with inline styles, interactive hover, and popups.
This bypasses Gradio's buggy HighlightedText component.
When hovering a legend item, only entities of that type are highlighted; others turn gray.
When hovering an entity, a popup shows detailed information.
"""
import html
import hashlib
import uuid
import json
def label_to_class(label: str) -> str:
"""Convert label to a valid CSS class name."""
return "ent-" + hashlib.md5(label.encode()).hexdigest()[:8]
def escape_js_string(s: str) -> str:
"""Escape a string for use in JavaScript within HTML attributes."""
if s is None:
return ""
s = str(s)
# Escape backslashes first, then other special chars
s = s.replace("\\", "\\\\")
s = s.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
# Escape single quotes for JS BEFORE html.escape.
# html.escape converts \' to \', and the browser's HTML parser
# decodes ' back to ', yielding \' in the JS string — a valid escape.
s = s.replace("'", "\\'")
s = html.escape(s)
return s
# Generate unique container ID for this render
container_id = f"ner-output-{uuid.uuid4().hex[:8]}"
popup_id = f"popup-{container_id}"
# Collect entity info by label for legend popups (first instance + count)
label_entity_info = {} # label -> entity_info (first instance)
label_counts = {} # label -> count of occurrences
# Build text with entity marks
parts = []
for item in highlighted:
text, label = item[0], item[1]
entity_info = item[2] if len(item) > 2 else None
escaped_text = html.escape(text)
if label is None:
parts.append(escaped_text)
else:
# Use per-instance color if available, otherwise fall back to color_map
color = (
entity_info.get("display_color") if entity_info else None
) or color_map.get(label, "#808080")
css_class = label_to_class(label)
# Track count and store first entity info for each label (for legend popup)
label_counts[label] = label_counts.get(label, 0) + 1
if label not in label_entity_info and entity_info:
label_entity_info[label] = entity_info
# Build popup content for this entity
popup_lines = []
if entity_info:
if entity_info.get("kb_title"):
popup_lines.append(
f"<strong style="color:#333;">{escape_js_string(entity_info['kb_title'])}</strong>"
)
if entity_info.get("kb_id"):
popup_lines.append(
f"<em style="color:#555;">ID: {escape_js_string(entity_info['kb_id'])}</em>"
)
if entity_info.get("type"):
popup_lines.append(
f"<span style="color:#333;">Type: {escape_js_string(entity_info['type'])}</span>"
)
if entity_info.get("mention") and entity_info.get(
"mention"
) != entity_info.get("kb_title"):
popup_lines.append(
f"<span style="color:#333;">Mention: "{escape_js_string(entity_info['mention'])}"</span>"
)
if entity_info.get("kb_description"):
desc = entity_info["kb_description"]
if len(desc) > 150:
desc = desc[:150] + "..."
popup_lines.append(
f"<div style="margin-top:0.3em;font-size:0.9em;color:#666;">{escape_js_string(desc)}</div>"
)
popup_content = (
"<br>".join(popup_lines) if popup_lines else escape_js_string(label)
)
# JavaScript for showing/hiding popup (absolute positioning relative to container)
# Account for container scroll position and use viewport for bounds checking
show_popup_js = (
f"var p=document.getElementById('{popup_id}');"
f"p.innerHTML='{popup_content}';"
f"var cont=document.getElementById('{container_id}');"
f"var r=this.getBoundingClientRect();"
f"var c=cont.getBoundingClientRect();"
f"var left=r.left-c.left+cont.scrollLeft;"
f"var top=r.bottom-c.top+cont.scrollTop+5;"
f"p.style.left=left+'px';p.style.top=top+'px';"
f"p.style.display='block';"
)
hide_popup_js = (
f"document.getElementById('{popup_id}').style.display='none';"
)
parts.append(
f'<mark class="entity-mark {css_class}" '
f'data-color="{color}" '
f'style="background-color: {color}; padding: 0.1em 0.2em; '
f"border-radius: 0.2em; margin: 0 0.1em; cursor: pointer; "
f'transition: background-color 0.2s ease, opacity 0.2s ease;" '
f'onmouseenter="{show_popup_js}" '
f'onmouseleave="{hide_popup_js}">'
f"{escaped_text}</mark>"
)
# JavaScript functions for legend hover (highlight/dim entities)
hover_in_js = (
"var c=document.getElementById('{cid}');"
"c.querySelectorAll('.entity-mark').forEach(function(m){{"
"if(m.classList.contains('{cls}')){{m.style.opacity='1';}}"
"else{{m.style.backgroundColor='#E5E7EB';m.style.opacity='0.6';}}"
"}});"
)
hover_out_js = (
"var c=document.getElementById('{cid}');"
"c.querySelectorAll('.entity-mark').forEach(function(m){{"
"m.style.backgroundColor=m.getAttribute('data-color');"
"m.style.opacity='1';"
"}});"
)
# Build legend with inline hover handlers and popups
legend_parts = []
seen_labels = set()
for item in highlighted:
label = item[1]
if label and label not in seen_labels:
seen_labels.add(label)
color = color_map.get(label, "#808080")
css_class = label_to_class(label)
enter_js = hover_in_js.format(cid=container_id, cls=css_class)
leave_js = hover_out_js.format(cid=container_id)
# Build popup content for legend item (summary info, no instance-specific values)
entity_info = label_entity_info.get(label)
count = label_counts.get(label, 1)
popup_lines = []
if entity_info:
if entity_info.get("kb_title"):
popup_lines.append(
f"<strong style="color:#333;">{escape_js_string(entity_info['kb_title'])}</strong>"
)
if entity_info.get("kb_id"):
popup_lines.append(
f"<em style="color:#555;">ID: {escape_js_string(entity_info['kb_id'])}</em>"
)
if entity_info.get("type"):
popup_lines.append(
f"<span style="color:#333;">Type: {escape_js_string(entity_info['type'])}</span>"
)
# Show occurrence count for legend hover
popup_lines.append(
f"<span style="color:#333;">Mentions: {count}</span>"
)
if entity_info.get("kb_description"):
desc = entity_info["kb_description"]
if len(desc) > 150:
desc = desc[:150] + "..."
popup_lines.append(
f"<div style="margin-top:0.3em;font-size:0.9em;color:#666;">{escape_js_string(desc)}</div>"
)
popup_content = (
"<br>".join(popup_lines) if popup_lines else escape_js_string(label)
)
show_popup_js = (
f"var p=document.getElementById('{popup_id}');"
f"p.innerHTML='{popup_content}';"
f"var cont=document.getElementById('{container_id}');"
f"var r=this.getBoundingClientRect();"
f"var c=cont.getBoundingClientRect();"
f"var left=r.left-c.left+cont.scrollLeft;"
f"var top=r.bottom-c.top+cont.scrollTop+5;"
f"p.style.left=left+'px';p.style.top=top+'px';"
f"p.style.display='block';"
)
hide_popup_js = (
f"document.getElementById('{popup_id}').style.display='none';"
)
# Combine highlight JS with popup JS
combined_enter = enter_js + show_popup_js
combined_leave = leave_js + hide_popup_js
legend_parts.append(
f'<span class="legend-item" '
f'style="display: inline-block; margin-right: 1em; cursor: pointer;" '
f'onmouseenter="{combined_enter}" '
f'onmouseleave="{combined_leave}">'
f'<span style="background-color: {color}; padding: 0.1em 0.3em; '
f'border-radius: 0.2em; font-size: 0.85em;">{html.escape(label)}</span></span>'
)
legend_html = ""
if show_legend:
legend_html = (
f'<div class="entity-legend" style="margin-bottom: 0.5em; line-height: 1.8;">{"".join(legend_parts)}</div>'
if legend_parts
else ""
)
text_html = f'<div class="entity-text" style="line-height: 1.6; white-space: pre-wrap;">{"".join(parts)}</div>'
# Popup div (hidden by default, absolute positioning relative to container)
popup_html = (
f'<div id="{popup_id}" style="'
f"display: none; "
f"position: absolute; "
f"background: white; "
f"color: #333; "
f"border: 1px solid #ccc; "
f"border-radius: 6px; "
f"padding: 0.5em 0.75em; "
f"box-shadow: 0 2px 8px rgba(0,0,0,0.15); "
f"max-width: 350px; "
f"z-index: 1000; "
f"font-size: 0.9em; "
f"line-height: 1.4; "
f"pointer-events: none;"
f'"></div>'
)
return f'<div id="{container_id}" class="highlighted-container" style="position: relative;">{legend_html}{text_html}{popup_html}</div>'
def format_highlighted_text(
result: Dict,
) -> Tuple[List[Tuple[str, Optional[str], Optional[Dict]]], Dict[str, str]]:
"""Convert pipeline result to highlighted format.
Returns (highlighted_data, color_map) for use with highlighted_to_html().
Each highlighted item is (text, label, entity_info) where entity_info contains details for popup.
"""
text = result["text"]
entities = result["entities"]
if not entities:
return [(text, None, None)], {}
# Process entities: build labels in first-seen order
entity_data = []
label_order = []
label_set = set()
for entity in entities:
label_type = entity.get("label", "ENT")
if entity.get("entity_title"):
label = f"{label_type}: {entity['entity_title']}"
else:
label = f"{label_type} [NOT IN KB]"
entity_data.append((entity, label))
if label not in label_set:
label_set.add(label)
label_order.append(label)
# Build color_map: sequential palette assignment for maximum color diversity
color_map = {}
palette_idx = 0
for label in label_order:
if label == "ERROR":
color_map[label] = ERROR_COLOR
elif label.endswith("[NOT IN KB]"):
color_map[label] = UNLINKED_COLOR
else:
color_map[label] = ENTITY_COLORS[palette_idx % len(ENTITY_COLORS)]
palette_idx += 1
# Sort by position for text reconstruction
entity_data.sort(key=lambda x: x[0]["start"])
# Build highlighted text with entity info for popups
highlighted = []
last_end = 0
for entity, label in entity_data:
if entity["start"] > last_end:
highlighted.append((text[last_end : entity["start"]], None, None))
instance_color = color_map.get(label)
# Build entity info dict for popup
entity_info = {
"mention": entity["text"],
"type": entity.get("label", "ENT"),
"kb_id": entity.get("entity_id"),
"kb_title": entity.get("entity_title"),
"kb_description": entity.get("entity_description"),
"display_color": instance_color,
}
highlighted.append((entity["text"], label, entity_info))
last_end = entity["end"]
if last_end < len(text):
highlighted.append((text[last_end:], None, None))
return highlighted, color_map
def compute_linking_stats(result: Dict) -> str:
"""Compute statistics about entity linking results."""
entities = result.get("entities", [])
if not entities:
return "No entities found."
total = len(entities)
linked = sum(1 for e in entities if e.get("entity_title"))
unlinked = total - linked
stats = f"**Entity Linking Statistics**\n\n"
stats += f"- Total entities: {total}\n"
stats += f"- Linked to KB: {linked} ({100*linked/total:.1f}%)\n"
stats += f"- Not in KB: {unlinked} ({100*unlinked/total:.1f}%)\n"
return stats
def format_error_output(error_title: str, error_message: str) -> Tuple[str, str, Dict]:
"""Format an error for display in the output components.
Returns (html_output, stats, result) for consistency with run_pipeline.
"""
import traceback
# Get full traceback if available
tb = traceback.format_exc()
if tb and tb.strip() != "NoneType: None":
full_error = f"{error_message}\n\n**Traceback:**\n```\n{tb}\n```"
else:
full_error = error_message
# Create HTML error display
html_output = (
f'<div style="color: {ERROR_COLOR}; padding: 1em; '
f"border: 1px solid {ERROR_COLOR}; border-radius: 6px; "
f'background-color: #FEF2F2;">'
f"<strong>Error: {error_title}</strong></div>"
)
stats = f"**Error**\n\n{full_error}"
result = {"error": error_title, "details": error_message}
return gr.update(value=html_output), stats, result
def _run_with_heartbeat(fn, progress_fn, initial_progress, initial_desc):
"""Run fn(report) in a background thread, sending progress heartbeats.
Blocks until fn completes. Calls progress_fn every 0.5s to keep
Gradio's SSE connection alive (without yielding, which would re-render
output components and reset the UI timer).
fn receives a report(progress_value, description) callback for updates.
Returns fn's return value. Re-raises any exception from fn.
"""
import queue as _q
q = _q.Queue()
result_holder = []
error_holder = []
def report(prog, desc):
q.put((prog, desc))
def _worker():
try:
r = fn(report)
result_holder.append(r)
except Exception as e:
error_holder.append(e)
finally:
q.put(None)
worker = threading.Thread(target=_worker, daemon=True)
worker.start()
last_progress = initial_progress
last_desc = initial_desc
while True:
try:
msg = q.get(timeout=0.5)
except _q.Empty:
try:
progress_fn(last_progress, desc=last_desc)
except Exception:
pass
continue
if msg is None:
break
last_progress = msg[0]
last_desc = msg[1]
try:
progress_fn(msg[0], desc=msg[1])
except Exception:
pass
worker.join()
if error_holder:
raise error_holder[0]
return result_holder[0] if result_holder else None
def run_pipeline(
text_input: str,
file_input: Optional[gr.File],
kb_file: Optional[gr.File],
loader_type: str,
ner_type: str,
spacy_model: str,
gliner_model: str,
gliner_labels: str,
gliner_threshold: float,
labels_from_kb: bool,
simple_min_len: int,
cand_type: str,
cand_embedding_model: str,
cand_top_k: int,
cand_use_context: bool,
cand_api_base_url: str,
cand_api_key: str,
reranker_type: str,
reranker_embedding_model: str,
reranker_cross_encoder_model: str,
reranker_api_url: str,
reranker_api_port: int,
reranker_top_k: int,
reranker_gpu_mem_gb: float,
reranker_max_model_len: int,
disambig_type: str,
llm_model: str,
thinking: bool,
none_candidate: bool,
disambig_gpu_mem_gb: float,
disambig_max_model_len: int,
disambig_api_base_url: str,
disambig_api_key: str,
kb_type: str,
progress=gr.Progress(),
):
"""Run LELA with selected configuration.
This is a generator function that yields (html_output, stats, result) tuples.
Yielding allows Gradio to check for cancellation between steps.
"""
import sys
logger = logging.getLogger(__name__)
logger.info(f"=== run_pipeline ENTERED (run #{_run_counter}) ===")
sys.stderr.flush()
# Clear cancellation flag at the start of a new run
_cancel_event.clear()
# Note: We intentionally don't clear vLLM instances here - they should be
# reused across runs to avoid expensive reinitialization and resource leaks.
# Only general garbage collection is performed.
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
no_vis_change = gr.update()
no_btn_change = gr.update()
no_mode_change = gr.update()
if not kb_file:
from lela.knowledge_bases.yago_downloader import ensure_yago_kb
kb_path = _run_with_heartbeat(
lambda report: ensure_yago_kb(),
progress,
0.05,
"Resolving knowledge base...",
)
else:
kb_path = kb_file.name
if not text_input and not file_input:
yield (
*format_error_output(
"Missing Input", "Please provide either text input or upload a file."
),
no_vis_change, no_btn_change, no_mode_change,
)
return
# Check for cancellation
if _cancel_event.is_set():
logger.info("Pipeline cancelled before configuration")
yield gr.update(value=""), "*Pipeline cancelled.*", {}, no_vis_change, no_btn_change, no_mode_change
return
progress(0.1, desc="Building pipeline configuration...")
yield gr.update(value=""), "*Building configuration...*", {}, no_vis_change, no_btn_change, no_mode_change
# Build NER params based on type
ner_params = {}
if ner_type == "spacy":
ner_params["model"] = spacy_model
elif ner_type == "gliner":
ner_params["model_name"] = gliner_model
ner_params["threshold"] = gliner_threshold
ner_params["estimated_vram_gb"] = DEFAULT_GLINER_VRAM_GB
if gliner_labels:
ner_params["labels"] = [l.strip() for l in gliner_labels.split(",")]
if labels_from_kb:
ner_params["labels_from_kb"] = True
elif ner_type == "regex":
ner_params["min_len"] = simple_min_len
# Build candidate params
cand_params = {"top_k": cand_top_k}
if cand_type == "dense":
cand_params["use_context"] = cand_use_context
cand_params["model_name"] = cand_embedding_model
cand_params["estimated_vram_gb"] = get_model_vram_gb(cand_embedding_model)
elif cand_type == "openai_api_dense":
cand_params["use_context"] = cand_use_context
cand_params["model_name"] = cand_embedding_model
cand_params["base_url"] = cand_api_base_url
cand_params["api_key"] = cand_api_key
# Build reranker params
reranker_params = {"top_k": reranker_top_k}
if reranker_type in ("embedder_transformers", "embedder_vllm"):
reranker_params["model_name"] = reranker_embedding_model
if reranker_type == "cross_encoder_vllm":
reranker_params["model_name"] = reranker_cross_encoder_model
if reranker_type == "cross_encoder":
reranker_params["model_name"] = reranker_cross_encoder_model
reranker_params["estimated_vram_gb"] = get_model_vram_gb(reranker_cross_encoder_model)
if reranker_type == "vllm_api_client":
reranker_params["base_url"] = reranker_api_url
reranker_params["port"] = reranker_api_port
if reranker_type in ("embedder_vllm", "cross_encoder_vllm"):
reranker_params["gpu_memory_gb"] = reranker_gpu_mem_gb
reranker_params["max_model_len"] = int(reranker_max_model_len)
if reranker_type == "embedder_transformers":
reranker_params["estimated_vram_gb"] = get_model_vram_gb(reranker_embedding_model)
# Build disambiguator params
disambig_params = {}
if disambig_type in ("vllm", "transformers"):
disambig_params["model_name"] = llm_model
disambig_params["enable_thinking"] = thinking
disambig_params["add_none_candidate"] = none_candidate
if disambig_type == "vllm":
disambig_params["gpu_memory_gb"] = disambig_gpu_mem_gb
disambig_params["max_model_len"] = int(disambig_max_model_len)
if disambig_type == "transformers":
disambig_params["estimated_vram_gb"] = get_model_vram_gb(llm_model)
if disambig_type == "openai_api":
disambig_params["base_url"] = disambig_api_base_url
disambig_params["api_key"] = disambig_api_key or None
# Override components if candidate_generator is "none" for NER-only pipeline
if cand_type == "none":
candidate_generator_config = {"name": "none", "params": {}}
reranker_config = {"name": "none", "params": {}}
disambiguator_config = None
else:
candidate_generator_config = {"name": cand_type, "params": cand_params}
reranker_config = (
{"name": reranker_type, "params": reranker_params}
if reranker_type != "none"
else {"name": "none", "params": {}}
)
disambiguator_config = (
{"name": disambig_type, "params": disambig_params}
if disambig_type != "none"
else None
)
# Resolve labels_from_kb: extract entity types from KB and use as NER labels
if ner_params.get("labels_from_kb"):
try:
from lela.knowledge_bases.jsonl import JSONLKnowledgeBase
kb = JSONLKnowledgeBase(kb_path)
kb_types = kb.get_entity_types()
if kb_types:
ner_params["labels"] = kb_types
except Exception as e:
logger.warning(f"Failed to extract entity types from KB: {e}")
del ner_params["labels_from_kb"]
config_dict = {
"loader": {"name": loader_type, "params": {}},
"ner": {"name": ner_type, "params": ner_params},
"candidate_generator": candidate_generator_config,
"reranker": reranker_config,
"disambiguator": disambiguator_config,
"knowledge_base": {"name": kb_type, "params": {"path": kb_path}},
"cache_dir": ".ner_cache",
"batch_size": 1,
}
# Check for cancellation
if _cancel_event.is_set():
logger.info("Pipeline cancelled before initialization")
yield gr.update(value=""), "*Pipeline cancelled.*", {}, no_vis_change, no_btn_change, no_mode_change
return
progress(0.15, desc="Initializing pipeline...")
yield gr.update(value=""), "*Initializing pipeline...*", {}, no_vis_change, no_btn_change, no_mode_change
try:
def _init_pipeline(report):
def init_progress_callback(local_progress: float, description: str):
report(0.15 + local_progress * 0.2, description)
if _cancel_event.is_set():
raise InterruptedError("Pipeline cancelled by user")
return Lela(
config_dict,
progress_callback=init_progress_callback,
cancel_event=_cancel_event,
)
pipeline = _run_with_heartbeat(
_init_pipeline,
progress,
0.15,
"Initializing pipeline...",
)
except InterruptedError:
logger.info("Pipeline cancelled during initialization")
yield gr.update(value=""), "*Pipeline cancelled.*", {}, no_vis_change, no_btn_change, no_mode_change
return
except Exception as e:
logger.exception("Pipeline initialization failed")
yield (
*format_error_output("Pipeline Initialization Failed", str(e)),
no_vis_change, no_btn_change, no_mode_change,
)
return
# Check for cancellation
if _cancel_event.is_set():
logger.info("Pipeline cancelled after initialization")
yield gr.update(value=""), "*Pipeline cancelled.*", {}, no_vis_change, no_btn_change, no_mode_change
return
progress(0.4, desc="Loading document...")
yield gr.update(value=""), "*Loading document...*", {}, no_vis_change, no_btn_change, no_mode_change
try:
if file_input:
input_path = file_input.name
else:
with tempfile.NamedTemporaryFile(
mode="w", suffix=".txt", delete=False, encoding="utf-8"
) as f:
f.write(text_input)
input_path = f.name
# Load document (in background thread to keep SSE alive for large files)
docs = _run_with_heartbeat(
lambda report: list(pipeline.loader.load(input_path)),
progress,
0.4,
"Loading document...",
)
if not file_input:
os.unlink(input_path)
if not docs:
yield (
*format_error_output(
"No Documents Loaded",
"The input file was empty or could not be parsed.",
),
no_vis_change, no_btn_change, no_mode_change,
)
return
doc = docs[0]
# Check for cancellation
if _cancel_event.is_set():
logger.info("Pipeline cancelled before processing")
yield gr.update(value=""), "*Pipeline cancelled.*", {}, no_vis_change, no_btn_change, no_mode_change
return
progress(0.45, desc="Processing document...")
yield gr.update(value=""), "*Processing document...*", {}, no_vis_change, no_btn_change, no_mode_change
def _run_processing(report):
def progress_callback(local_progress: float, description: str):
report(0.45 + local_progress * 0.4, description)
if _cancel_event.is_set():
raise InterruptedError("Pipeline cancelled by user")
return pipeline.process_document_with_progress(
doc,
progress_callback=progress_callback,
base_progress=0.0,
progress_range=1.0,
)
result = _run_with_heartbeat(
_run_processing,
progress,
0.45,
"Processing document...",
)
except InterruptedError:
logger.info("Pipeline cancelled during processing")
yield gr.update(value=""), "*Pipeline cancelled.*", {}, no_vis_change, no_btn_change, no_mode_change
return
except Exception as e:
yield (*format_error_output("Pipeline Execution Failed", str(e)), no_vis_change, no_btn_change, no_mode_change)
return
logger.info("Pipeline processing complete, formatting output...")
sys.stderr.flush()
progress(0.9, desc="Formatting output...")
logger.info("Calling format_highlighted_text...")
sys.stderr.flush()
highlighted, color_map = format_highlighted_text(result)
logger.info(f"format_highlighted_text done, got {len(highlighted)} segments")
sys.stderr.flush()
# Convert to HTML for the gr.HTML component (no legend for inline preview)
html_output = highlighted_to_html(highlighted, color_map, show_legend=False)
logger.info("Calling compute_linking_stats...")
sys.stderr.flush()
stats = compute_linking_stats(result)
logger.info("compute_linking_stats done")
sys.stderr.flush()
logger.info("Calling progress(1.0, Done!)...")
sys.stderr.flush()
try:
progress(1.0, desc="Done!")
logger.info("progress(1.0) returned successfully")
except Exception as e:
logger.error(f"progress(1.0) raised exception: {e}")
sys.stderr.flush()
# Ensure all GPU operations are complete before returning
if torch.cuda.is_available():
torch.cuda.synchronize()
logger.info("CUDA synchronized")
sys.stderr.flush()
logger.info(
f"=== run_pipeline RETURNING (run #{_run_counter}, {len(result.get('entities', []))} entities) ==="
)
sys.stderr.flush()
# Final yield: show preview with results, hide text_input, show edit_btn, switch to preview mode
yield gr.update(value=html_output, visible=True), stats, result, gr.update(visible=False), gr.update(visible=True), "preview"
def update_ner_params(ner_choice: str):
"""Show/hide NER-specific parameters based on selection."""
show_gliner = ner_choice == "gliner"
vram_text = f"~{DEFAULT_GLINER_VRAM_GB:.1f} GB VRAM" if show_gliner else ""
return {
spacy_params: gr.update(visible=(ner_choice == "spacy")),
gliner_params: gr.update(visible=show_gliner),
simple_params: gr.update(visible=(ner_choice == "regex")),
ner_vram_info: gr.update(visible=show_gliner, value=vram_text),
}
def _format_vram_info(model_id: str) -> str:
"""Format VRAM info text for a model."""
vram = get_model_vram_gb(model_id)
return f"~{vram:.1f} GB VRAM"
def update_cand_params(cand_choice: str):
"""Show/hide candidate-specific parameters based on selection."""
if cand_choice == "none":
return (
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
)
show_context = cand_choice in ("dense", "openai_api_dense")
show_embedding_model = cand_choice in ("dense", "openai_api_dense")
show_openai_api_dense_params = cand_choice == "openai_api_dense"
show_vram_info = cand_choice == "dense"
return (
gr.update(visible=show_embedding_model),
gr.update(visible=show_context),
gr.update(visible=show_openai_api_dense_params),
gr.update(
visible=show_vram_info,
value=_format_vram_info("Qwen/Qwen3-Embedding-4B") if show_vram_info else "",
),
)
def update_reranker_params(reranker_choice: str):
"""Show/hide reranker-specific parameters based on selection."""
show_cross_encoder_model = reranker_choice in (
"cross_encoder",
"cross_encoder_vllm",
)
show_embedding_model = reranker_choice in (
"embedder_transformers",
"embedder_vllm",
)
show_vllm_api_client = reranker_choice in ("vllm_api_client", "llama_server")
# Slider only for vLLM backends
show_gpu_mem_slider = reranker_choice in (
"embedder_vllm",
"cross_encoder_vllm",
)
show_context_len_slider = reranker_choice in (
"embedder_vllm",
"cross_encoder_vllm",
)
# VRAM info for transformers backends
show_vram_info = reranker_choice in (
"cross_encoder",
"embedder_transformers",
)
if reranker_choice == "cross_encoder":
vram_text = _format_vram_info("tomaarsen/Qwen3-Reranker-4B-seq-cls")
elif reranker_choice == "embedder_transformers":