Repository navigation
Expand file tree
/
Copy pathvfb_queries.py
More file actions
7892 lines (6930 loc) · 397 KB
/
Copy pathvfb_queries.py
File metadata and controls
7892 lines (6930 loc) · 397 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 pysolr
from .term_info_queries import deserialize_term_info
# Replace VfbConnect import with our new SimpleVFBConnect
from .owlery_client import SimpleVFBConnect
# Keep dict_cursor if it's used elsewhere - lazy import to avoid GUI issues
from marshmallow import Schema, fields, post_load
from typing import List, Tuple, Dict, Any, Union
import pandas as pd
from marshmallow import ValidationError
import json
import numpy as np
from urllib.parse import unquote
import hashlib
from .solr_result_cache import (with_solr_cache, solr_caching_disabled,
PREVIEW_STATUS_PENDING, PREVIEW_STATUS_COMPLETE,
preview_is_resolved)
import time
import threading
from concurrent.futures import ThreadPoolExecutor
import re
import requests
import logging
import inspect
import os
import warnings
import concurrent.futures
# --- Bounded term-info sub-query execution -------------------------------
# Generic high-level terms (e.g. a top-level anatomy class with a huge subclass
# closure) used to hang term-info: a saturated preview triggered an unbounded
# limit=-1 re-run purely to count rows, materialising every row with full
# markdown/thumbnail encoding. The cold computation never returned, so the
# v3-cached proxy never populated either. Two guards make the response always
# resolve (and therefore cache):
# * COUNT_CAP bounds any count re-run; beyond it the exact total is not worth
# the cost and we report -1 ("many").
# * SUBQUERY_TIMEOUT_S is a per-sub-query wall-clock budget; on overrun we
# abandon that sub-query (empty preview, count -1) and carry on.
SUBQUERY_TIMEOUT_S = int(os.environ.get("VFBQUERY_SUBQUERY_TIMEOUT_S", "600"))
COUNT_CAP = int(os.environ.get("VFBQUERY_COUNT_CAP", "1000"))
def _run_with_timeout(func, args=(), kwargs=None, timeout=None):
"""Run ``func`` with a wall-clock budget and return its result.
The call runs in a worker thread; if it overruns ``timeout`` seconds we
raise ``concurrent.futures.TimeoutError`` and stop waiting. Python cannot
forcibly kill the worker, but we no longer block on it, so a slow
Neo4j/Solr/Owlery round-trip cannot stall the whole term-info response; the
thread drains in the background when its I/O finally returns.
"""
kwargs = kwargs or {}
if timeout is None:
timeout = SUBQUERY_TIMEOUT_S
ex = concurrent.futures.ThreadPoolExecutor(max_workers=1)
fut = ex.submit(func, *args, **kwargs)
try:
return fut.result(timeout=timeout)
finally:
# Never block on a runaway call; let the pool drain in the background.
ex.shutdown(wait=False)
# Custom JSON encoder to handle NumPy and pandas types
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, np.bool_):
return bool(obj)
elif hasattr(obj, 'item'): # Handle pandas scalar types
return obj.item()
return super(NumpyEncoder, self).default(obj)
def safe_to_dict(df, sort_by_id=True):
"""Convert DataFrame to dict with numpy types converted to native Python types"""
if isinstance(df, pd.DataFrame):
# Convert numpy dtypes to native Python types
df_copy = df.copy()
for col in df_copy.columns:
if df_copy[col].dtype.name.startswith('int'):
df_copy[col] = df_copy[col].astype('object')
elif df_copy[col].dtype.name.startswith('float'):
df_copy[col] = df_copy[col].astype('object')
# Sort by id column in descending order if it exists and sort_by_id is True
if sort_by_id and 'id' in df_copy.columns:
df_copy = df_copy.sort_values('id', ascending=False)
return df_copy.to_dict("records")
return df
# Lazy import for dict_cursor to avoid GUI library issues
def get_dict_cursor():
"""Lazy import dict_cursor to avoid import issues during testing"""
try:
from .neo4j_client import dict_cursor
return dict_cursor
except ImportError as e:
raise ImportError(f"Could not import dict_cursor: {e}")
# Connect to the VFB SOLR server
vfb_solr = pysolr.Solr('http://solr.virtualflybrain.org/solr/vfb_json/', always_commit=False, timeout=990)
logger = logging.getLogger(__name__)
# Replace VfbConnect with SimpleVFBConnect
vc = SimpleVFBConnect()
# ---------------------------------------------------------------------------
# Canonical VFB term link
# ---------------------------------------------------------------------------
# Public, environment-independent permalink base for a VFB term. This resolves
# to the term's report page outside the app and is recognised as an internal
# link by the v2 query-results table (MarkdownLinkComponent parses the
# short_form out of the `/reports/<id>` path). Never hard-code an app URL such
# as https://v2.virtualflybrain.org/org.geppetto.frontend/geppetto?id=<id> into
# query output -- that pins results to one deployment. Build every VFB term
# link from here (or via the helpers below) so the form is defined in one place.
VFB_REPORT_BASE = "https://virtualflybrain.org/reports/"
def vfb_report_url(short_form: str) -> str:
"""Public permalink for a VFB term id, e.g. .../reports/VFB_00101567."""
return f"{VFB_REPORT_BASE}{short_form}"
def vfb_term_link(label: str, short_form: str) -> str:
"""Markdown link for a VFB term: [label](https://virtualflybrain.org/reports/<id>)."""
return f"[{label}]({vfb_report_url(short_form)})"
def initialize_vfb_connect():
"""
Initialize VFB_connect by triggering the lazy load of the vfb and nc properties.
This causes VFB_connect to cache all terms, which takes ~95 seconds on first call.
Subsequent calls to functions using vc.nc will be fast.
:return: True if initialization successful, False otherwise
"""
try:
# Access the properties to trigger lazy loading
_ = vc.vfb
_ = vc.nc
return True
except Exception as e:
print(f"Failed to initialize VFB_connect: {e}")
return False
class Query:
def __init__(self, query, label, function, takes, preview=0, preview_columns=[], preview_results=[], output_format="table", count=-1):
self.query = query
self.label = label
self.function = function
self.takes = takes
self.preview = preview
self.preview_columns = preview_columns
self.preview_results = preview_results
self.output_format = output_format
self.count = count
def __str__(self):
return f"Query: {self.query}, Label: {self.label}, Function: {self.function}, Takes: {self.takes}, Preview: {self.preview}, Preview Columns: {self.preview_columns}, Preview Results: {self.preview_results}, Count: {self.count}"
def to_dict(self):
return {
"query": self.query,
"label": self.label,
"function": self.function,
"takes": self.takes,
"preview": self.preview,
"preview_columns": self.preview_columns,
"preview_results": self.preview_results,
"output_format": self.output_format,
"count": self.count,
}
@classmethod
def from_dict(cls, data):
return cls(
query=data["query"],
label=data["label"],
function=data["function"],
takes=data["takes"],
preview=data["preview"],
preview_columns=data["preview_columns"],
preview_results=data["preview_results"],
output_format=data.get("output_format", 'table'),
count=data["count"],
)
class TakesSchema(Schema):
short_form = fields.Raw(required=True)
default = fields.Raw(required=False, allow_none=True)
class QuerySchema(Schema):
query = fields.String(required=True)
label = fields.String(required=True)
function = fields.String(required=True)
takes = fields.Nested(TakesSchema(), required=False, missing={})
preview = fields.Integer(required=False, missing=0)
preview_columns = fields.List(fields.String(), required=False, load_default=[])
preview_results = fields.List(fields.Dict(), required=False, load_default=[])
output_format = fields.String(required=False, load_default='table')
count = fields.Integer(required=False, load_default=-1)
class License:
def __init__(self, iri, short_form, label, icon, source, source_iri):
self.iri = iri
self.short_form = short_form
self.label = label
self.icon = icon
self.source = source
self.source_iri = source_iri
class LicenseSchema(Schema):
iri = fields.String(required=True)
short_form = fields.String(required=True)
label = fields.String(required=True)
icon = fields.String(required=True)
source = fields.String(required=True)
source_iri = fields.String(required=True)
class LicenseField(fields.Nested):
def __init__(self, **kwargs):
super().__init__(LicenseSchema(), **kwargs)
def _serialize(self, value, attr, obj, **kwargs):
if value is None:
return value
if not isinstance(value, License):
raise ValidationError("Invalid input")
return {"iri": value.iri
, "short_form": value.short_form
, "label": value.label
,"icon": value.icon
, "source": value.source
, "source_iri": value.source_iri}
def _deserialize(self, value, attr, data, **kwargs):
if value is None:
return value
return LicenseSchema().load(value)
class Coordinates:
def __init__(self, X, Y, Z):
self.X = X
self.Y = Y
self.Z = Z
class CoordinatesSchema(Schema):
X = fields.Float(required=True)
Y = fields.Float(required=True)
Z = fields.Float(required=True)
def _serialize(self, obj, **kwargs):
return {"X": obj.X, "Y": obj.Y, "Z": obj.Z}
def _deserialize(self, value, attr=None, data=None, **kwargs):
return {"X":value.X, "Y":value.Y, "Z":value.Z}
class CoordinatesField(fields.Nested):
def __init__(self, **kwargs):
super().__init__(CoordinatesSchema(), **kwargs)
def _serialize(self, value, attr, obj, **kwargs):
if value is None:
return value
if not isinstance(value, Coordinates):
raise ValidationError("Invalid input")
return {"X": value.X, "Y": value.Y, "Z": value.Z}
def _deserialize(self, value, attr=None, data=None, **kwargs):
if value is None:
return value
return f"X={value.X}, Y={value.Y}, Z={value.Z}"
class Image:
def __init__(self, id, label, thumbnail=None, thumbnail_transparent=None, nrrd=None, wlz=None, obj=None, swc=None, index=None, center=None, extent=None, voxel=None, orientation=None, type_id=None, type_label=None):
self.id = id
self.label = label
self.thumbnail = thumbnail
self.thumbnail_transparent = thumbnail_transparent
self.nrrd = nrrd
self.wlz = wlz
self.obj = obj
self.swc = swc
self.index = index
self.center = center
self.extent = extent
self.voxel = voxel
self.orientation = orientation
self.type_label = type_label
self.type_id = type_id
class ImageSchema(Schema):
id = fields.String(required=True)
label = fields.String(required=True)
thumbnail = fields.String(required=False, allow_none=True)
thumbnail_transparent = fields.String(required=False, allow_none=True)
nrrd = fields.String(required=False, allow_none=True)
wlz = fields.String(required=False, allow_none=True)
obj = fields.String(required=False, allow_none=True)
swc = fields.String(required=False, allow_none=True)
index = fields.Integer(required=False, allow_none=True)
center = fields.Nested(CoordinatesSchema(), required=False, allow_none=True)
extent = fields.Nested(CoordinatesSchema(), required=False, allow_none=True)
voxel = fields.Nested(CoordinatesSchema(), required=False, allow_none=True)
orientation = fields.String(required=False, allow_none=True)
type_label = fields.String(required=False, allow_none=True)
type_id = fields.String(required=False, allow_none=True)
class ImageField(fields.Nested):
def __init__(self, **kwargs):
super().__init__(ImageSchema(), **kwargs)
def _serialize(self, value, attr, obj, **kwargs):
if value is None:
return value
return {"id": value.id
, "label": value.label
, "thumbnail": value.thumbnail
, "thumbnail_transparent": value.thumbnail_transparent
, "nrrd": value.nrrd
, "wlz": value.wlz
, "obj": value.obj
, "swc": value.swc
, "index": value.index
, "center": value.center
, "extent": value.extent
, "voxel": value.voxel
, "orientation": value.orientation
, "type_id": value.type_id
, "type_label": value.type_label
}
def _deserialize(self, value, attr, data, **kwargs):
if value is None:
return value
return ImageSchema().load(value)
class QueryField(fields.Field):
def _serialize(self, value, attr, obj, **kwargs):
if value is None:
return None
return value.to_dict()
def _deserialize(self, value, attr, data, **kwargs):
if not isinstance(value, dict):
raise ValidationError("Invalid input type.")
return Query.from_dict(value)
class TermInfoOutputSchema(Schema):
Name = fields.String(required=True)
Id = fields.String(required=True)
SuperTypes = fields.List(fields.String(), required=True)
Meta = fields.Dict(keys=fields.String(), values=fields.String(), required=True)
Tags = fields.List(fields.String(), required=True)
Queries = fields.List(QueryField(), required=False)
# RelatedTools: MCP tools (other than run_query) that are useful for this entity.
# Each entry: {"tool": "<tool_name>", "label": "...", "default_args": {...}}.
# Distinct from Queries because these are not dispatched via run_query — the
# client should call the named tool directly with default_args.
RelatedTools = fields.List(fields.Dict(), required=False)
IsIndividual = fields.Bool(missing=False, required=False)
Images = fields.Dict(keys=fields.String(), values=fields.List(fields.Nested(ImageSchema()), missing={}), required=False, allow_none=True)
IsClass = fields.Bool(missing=False, required=False)
Examples = fields.Dict(keys=fields.String(), values=fields.List(fields.Nested(ImageSchema()), missing={}), required=False, allow_none=True)
IsTemplate = fields.Bool(missing=False, required=False)
IsPaintedDomain = fields.Bool(missing=False, required=False)
Domains = fields.Dict(keys=fields.Integer(), values=fields.Nested(ImageSchema()), required=False, allow_none=True)
Licenses = fields.Dict(keys=fields.Integer(), values=fields.Nested(LicenseSchema()), required=False, allow_none=True)
Publications = fields.List(fields.Dict(keys=fields.String(), values=fields.Raw()), required=False)
Synonyms = fields.List(fields.Dict(keys=fields.String(), values=fields.Raw()), required=False, allow_none=True)
Technique = fields.List(fields.String(), required=False, allow_none=True)
# External DB cross-references (site label + accession link + icon), rendered
# as the panel's xrefs section.
Xrefs = fields.List(fields.Dict(keys=fields.String(), values=fields.Raw()), required=False, allow_none=True)
@post_load
def make_term_info(self, data, **kwargs):
if "Queries" in data:
data["Queries"] = [query.to_dict() for query in data["Queries"]]
return data
def __str__(self):
term_info_data = self.make_term_info(self.data)
if "Queries" in term_info_data:
term_info_data["Queries"] = [query.to_dict() for query in term_info_data["Queries"]]
return str(self.dump(term_info_data))
def encode_brackets(text):
"""
Encodes square brackets in the given text to prevent breaking markdown link syntax.
Parentheses are NOT encoded as they don't break markdown syntax.
:param text: The text to encode.
:return: The text with square brackets encoded.
"""
return (text.replace('[', '%5B')
.replace(']', '%5D'))
# Module-level pre-compiled patterns + translation tables. Defining these
# once at import time (rather than per call) is itself a measurable win on
# large frames: re.compile is cached but the lookup still adds up over
# millions of cells, and str.translate with a pre-built table is faster
# than chained .replace calls.
_BRACKET_TRANSLATE = str.maketrans({'[': '%5B', ']': '%5D'})
# Image-markdown cell: `[](ref)` OR
# `[](ref)` OR with no title slot. We only care about
# the URL slot so we can secure it; alt/title/ref pass through unchanged.
_RE_IMAGE_URL = re.compile(
r"(\[!\[[^\]]*\]\()([^'\"\s)]*)([^)]*\)\]\([^)]+\))"
)
# Regular markdown link: `[label](url)`. We secure the URL and percent-
# encode bracket characters inside the label so a label like
# "P{GMR95F02-GAL4} expression pattern[CPTI100022]" doesn't break the V2
# markdown parser.
_RE_MD_LINK = re.compile(r'\[([^\]]+)\]\(([^\)]+)\)')
# Stray backslash-before-quote artifact (e.g. y5B\'2a -> y5B'2a). The source
# label data carries a spurious backslash before apostrophes/quotes; it must be
# stripped before it reaches a display cell (and, for link cells, before it can
# leak into an HTTP request target where a backslash is illegal). Mirrors
# term_info_queries.clean_label so a term's own labels and the labels embedded
# in query preview-row markdown (name / thumbnail / label cells, built here from
# raw Neo4j labels via apoc.text.format) are cleaned identically.
_STRAY_QUOTE_ESCAPE = re.compile(r"\\(['\"])")
def _encode_image_url(match: 're.Match') -> str:
"""Repl callback for image-markdown cells — secure URL, preserve rest."""
prefix, url, suffix = match.group(1), match.group(2), match.group(3)
if url and url.startswith('http://'):
url = 'https://' + url[7:]
return f"{prefix}{url}{suffix}"
def _encode_regular_md_link(match: 're.Match') -> str:
"""Repl callback for `[label](url)` — bracket-encode label, secure URL."""
label, url = match.group(1), match.group(2)
if '[' in label or ']' in label:
label = label.translate(_BRACKET_TRANSLATE)
if url.startswith('http://'):
url = 'https://' + url[7:]
return f"[{label}]({url})"
def encode_markdown_links(df, columns):
"""
Vectorised markdown-link encoder.
For each named column:
- Image-markdown cells (`[](ref)`): secure the URL
(http→https). Alt, title, ref pass through unchanged so the V2
processor's IMAGE_MARKDOWN regex still matches both single- and
double-quoted title forms.
- Regular markdown cells (`[label](url), [label2](url2), ...`):
percent-encode `[` and `]` inside the label part and secure URLs.
- Plain text rows are left alone.
Implementation: pandas `Series.str.replace(regex=True, repl=callable)`
runs the substring scanner in C and only crosses into Python for the
actual substitution callback — roughly 10–50× faster than the
previous per-row `.apply(encode_label)` loop on the 500k-row
AllAlignedImages workload that surfaced this bottleneck. Skips empty
DataFrames and non-string columns cheaply.
Backwards-compatible: input nulls are preserved; existing data with
pre-secured URLs comes back untouched.
"""
if df is None or df.empty:
return df
for column in columns:
if column not in df.columns:
continue
s = df[column]
if s.dtype != object:
continue
# `str.replace` skips NaN automatically. We coerce to string only
# for the rows that are non-null to keep null cells as-is.
notnull_mask = s.notna()
if not notnull_mask.any():
continue
non_null = s.where(notnull_mask, '').astype(str)
# Strip stray backslash-before-quote artifacts from every cell first, so
# embedded labels (link text, image alt text, titles) are cleaned in
# both the image-markdown and label-shape branches below. PR #80 cleaned
# the term's own labels via term_info_queries.clean_label, but query
# preview rows are assembled here from raw Neo4j labels and never passed
# through that path, so the escape survived into name/thumbnail cells.
# Vectorised + guarded on a cheap literal-backslash check so it stays
# essentially free on the large frames this function was tuned for.
if non_null.str.contains('\\', regex=False, na=False).any():
non_null = non_null.str.replace(_STRAY_QUOTE_ESCAPE, r"\1", regex=True)
# Branch on shape using a vectorised prefix check — this is a single
# C-loop over the column, far cheaper than re-detecting per row.
is_image = non_null.str.startswith('[![', na=False)
if is_image.any():
# Image-markdown rows: secure URL only, preserve title quoting.
image_rows = non_null[is_image]
image_rows = image_rows.str.replace(
_RE_IMAGE_URL, _encode_image_url, regex=True
)
non_null = non_null.where(~is_image, image_rows)
non_image_mask = ~is_image
if non_image_mask.any():
# Label-shape rows: bracket-encode + secure URL via regex callback.
label_rows = non_null[non_image_mask]
label_rows = label_rows.str.replace(
_RE_MD_LINK, _encode_regular_md_link, regex=True
)
non_null = non_null.where(is_image, label_rows)
# Write back, preserving original null cells.
df.loc[notnull_mask, column] = non_null[notnull_mask]
return df
# Author-year citation linking ------------------------------------------------
# Cited publications appear in the definition/comment prose as plain author-year
# text (e.g. "Wolff et al., 2015"). We hold the id for each via the term's pubs
# (def_pubs / pub_syn / pubs), so we wrap matching mentions in markdown links the
# panel renders. Citations with no matching pub id are logged: they should also
# have appeared in the term's References, so a miss indicates a missing
# has_reference edge worth investigating.
_CITATION_RE = re.compile(
r"[A-Z][A-Za-z.'\u2019-]+"
r"(?:\s+et al\.|\s+and\s+[A-Z][A-Za-z.'\u2019-]+|\s+&\s+[A-Z][A-Za-z.'\u2019-]+)?"
r",?\s+\d{4}[a-z]?"
)
def _pub_author_year(pub):
"""Short author-year microref text for a pub, e.g. 'Wolff et al., 2015'."""
core = getattr(pub, 'core', None)
if not core:
return ""
micro = getattr(pub, 'microref', '') or ""
if micro:
return micro.strip()
label = getattr(core, 'label', '') or ""
if "," in label:
parts = label.split(",")
if len(parts) > 1:
return (parts[0] + "," + parts[1]).strip()
return label.strip()
def _collect_term_pub_map(vfbTerm):
"""{author_year_text: short_form} for every pub the term cites."""
pubs = list(getattr(vfbTerm, 'def_pubs', None) or [])
for syn in (getattr(vfbTerm, 'pub_syn', None) or []):
if getattr(syn, 'pub', None):
pubs.append(syn.pub)
pubs.extend(getattr(syn, 'pubs', None) or [])
pubs.extend(getattr(vfbTerm, 'pubs', None) or [])
mapping = {}
for p in pubs:
core = getattr(p, 'core', None)
sf = getattr(core, 'short_form', '') if core else ''
if not sf or sf == 'Unattributed':
continue
ay = _pub_author_year(p)
if ay and ay not in mapping:
mapping[ay] = sf
return mapping
def _split_author_year(author_year):
"""('Wolff et al., 2015') -> ('Wolff et al.', '2015'); handles trailing letter."""
m = re.match(r"^(.*?),?\s*\(?(\d{4})[a-z]?\)?$", author_year.strip())
return (m.group(1).strip(), m.group(2)) if m else (None, None)
def _linkify_citations(text, pub_map, term_id="", field=""):
"""Wrap known author-year citations (either 'Author, 2015' or 'Author (2015)')
in markdown links, normalising to '[Author, 2015](id)'. Logs unmatched ones."""
if not text:
return text
items = []
for ay, sf in pub_map.items():
author, year = _split_author_year(ay)
if author and year:
items.append((author, year, sf))
# Longest author first so 'Ito and Awasaki' wins over 'Ito et al.' etc.
items.sort(key=lambda x: len(x[0]), reverse=True)
linked = text
for author, year, sf in items:
# Only consume a closing ')' when the citation itself opened one — the
# "Author (2020)" form, where the parens belong to the citation. For the
# "(Author, 2020)" form the ')' belongs to the surrounding sentence and
# must be left in place (a bare `\)?` swallowed it, dropping the ')').
# `(\()` captures the citation's own '(' (group 1); `(?(1)\)|)` requires a
# ')' only when that '(' was matched.
pat = re.compile(r"(?<!\[)" + re.escape(author) + r"(?:,\s*|\s+(\()|\s+)" + year + r"(?(1)\)|)(?!\])")
linked = pat.sub("[" + author + ", " + year + "](" + sf + ")", linked)
# Flag citations in the prose we could not link -- they should also be in References.
matched_keys = {(a, y) for a, y, _ in items}
missing = []
for cite in _CITATION_RE.findall(text):
a, y = _split_author_year(cite.strip().rstrip(','))
if a and y and (a, y) not in matched_keys:
missing.append(a + ", " + y)
if missing:
logger.warning(
"term_info %s %s cites publications with no matching reference id "
"(should also appear in References -- investigate missing has_reference): %s",
term_id, field, sorted(set(missing)))
return linked
def format_edge_xrefs(dxrefs):
"""Render a relationship edge's database_cross_reference list as markdown
linkouts. Entries are 'SITE:accession' (e.g. 'FlyBase:FBrf0259490'); returns
a leading-space parenthesised group so it can be appended to a relationship.
"""
if not dxrefs:
return ""
links = []
for x in dxrefs:
if not x:
continue
if ':' in x:
site, acc = x.split(':', 1)
s = site.lower()
if s == 'flybase':
links.append("[%s](http://flybase.org/reports/%s)" % (x, acc))
elif s == 'doi':
links.append("[%s](https://doi.org/%s)" % (x, acc))
elif s in ('pmid', 'pubmed'):
links.append("[%s](https://www.ncbi.nlm.nih.gov/pubmed/%s)" % (x, acc))
else:
links.append(x)
else:
links.append(x)
if not links:
return ""
return " (" + ", ".join(links) + ")"
def term_info_parse_object(results, short_form):
termInfo = {}
termInfo["SuperTypes"] = []
termInfo["Tags"] = []
termInfo["Queries"] = []
termInfo["RelatedTools"] = []
termInfo["IsClass"] = False
termInfo["IsIndividual"] = False
termInfo["IsTemplate"] = False
termInfo["Images"] = {}
termInfo["Examples"] = {}
termInfo["Domains"] = {}
termInfo["Licenses"] = {}
termInfo["Publications"] = []
termInfo["IsPaintedDomain"] = False
termInfo["Technique"] = []
if results.hits > 0 and results.docs and len(results.docs) > 0:
termInfo["Meta"] = {}
try:
# Deserialize the term info from the first result
vfbTerm = deserialize_term_info(results.docs[0]['term_info'][0])
except KeyError:
print(f"SOLR doc missing 'term_info': {results.docs[0]}")
return None
except Exception as e:
print(f"Error deserializing term info: {e}")
return None
queries = []
# Initialize synonyms variable to avoid UnboundLocalError
synonyms = []
termInfo["Id"] = vfbTerm.term.core.short_form
termInfo["Meta"]["Name"] = "[%s](%s)"%(encode_brackets(vfbTerm.term.core.label), vfbTerm.term.core.short_form)
mainlabel = vfbTerm.term.core.label
if hasattr(vfbTerm.term.core, 'symbol') and vfbTerm.term.core.symbol and len(vfbTerm.term.core.symbol) > 0:
termInfo["Meta"]["Symbol"] = "[%s](%s)"%(encode_brackets(vfbTerm.term.core.symbol), vfbTerm.term.core.short_form)
mainlabel = vfbTerm.term.core.symbol
termInfo["Name"] = mainlabel
termInfo["SuperTypes"] = vfbTerm.term.core.types if hasattr(vfbTerm.term.core, 'types') else []
if "Class" in termInfo["SuperTypes"]:
termInfo["IsClass"] = True
elif "Individual" in termInfo["SuperTypes"]:
termInfo["IsIndividual"] = True
try:
# Retrieve tags from the term's unique_facets attribute
termInfo["Tags"] = vfbTerm.term.core.unique_facets
except (NameError, AttributeError):
# If unique_facets attribute doesn't exist, use the term's types
termInfo["Tags"] = vfbTerm.term.core.types if hasattr(vfbTerm.term.core, 'types') else []
# Map of author-year -> pub id for citation linking in description/comment.
_pub_map = _collect_term_pub_map(vfbTerm)
try:
# Retrieve description and link known author-year citations in the prose.
_desc_body = "".join(vfbTerm.term.description)
termInfo["Meta"]["Description"] = _linkify_citations(_desc_body, _pub_map, termInfo.get("Id", short_form), "description")
except (NameError, AttributeError):
pass
# Append class definition references (def_pubs) inline to the description
# as markdown microref links, matching how the panel renders them today
# (legacy VFBProcessTermInfoCachedJson definition() + "(<microrefs>)").
# Kept inline rather than as a separate Publications entry so the display
# is identical and no new panel section is introduced.
if getattr(vfbTerm, 'def_pubs', None):
def_refs = [p.get_microref() for p in vfbTerm.def_pubs
if hasattr(p, 'get_miniref') and p.get_miniref()
and hasattr(p, 'get_microref') and p.get_microref()]
if def_refs:
existing_desc = termInfo["Meta"].get("Description", "")
termInfo["Meta"]["Description"] = (existing_desc + "\n(" + ", ".join(def_refs) + ")") if existing_desc else ("(" + ", ".join(def_refs) + ")")
try:
# Retrieve comment and link known author-year citations.
_comment_body = "".join(vfbTerm.term.comment)
termInfo["Meta"]["Comment"] = _linkify_citations(_comment_body, _pub_map, termInfo.get("Id", short_form), "comment")
except (NameError, AttributeError):
pass
# External homepage link + logo (e.g. a DataSet's FlyBase/project link and
# icon). Rendered as the panel's link / logo rows
# (VFBProcessTermInfoCachedJson.java:1456 / :1449). Previously dropped.
try:
_link = vfbTerm.term.get_link() if hasattr(vfbTerm.term, 'get_link') else ""
if _link:
termInfo["Meta"]["Link"] = _link
except (AttributeError, TypeError):
pass
try:
_logo = vfbTerm.term.get_logo() if hasattr(vfbTerm.term, 'get_logo') else ""
if _logo:
termInfo["Meta"]["Logo"] = _logo
except (AttributeError, TypeError):
pass
if hasattr(vfbTerm, 'parents') and vfbTerm.parents and len(vfbTerm.parents) > 0:
parents = []
# Sort the parents alphabetically
sorted_parents = sorted(vfbTerm.parents, key=lambda parent: parent.label)
for parent in sorted_parents:
parents.append("[%s](%s)"%(encode_brackets(parent.label), parent.short_form))
termInfo["Meta"]["Types"] = "; ".join(parents)
if hasattr(vfbTerm, 'relationships') and vfbTerm.relationships and len(vfbTerm.relationships) > 0:
relationships = []
pubs_from_relationships = [] # New: Collect publication references from relationships
techniques = set() # Collect imaging techniques from relationships
# Group relationships by relation type and remove duplicates
grouped_relationships = {}
# Edge-level enriched relationships (confidence/reference) are rendered
# individually and prepended, so their per-edge data survives grouping.
enriched_relationships = []
for relationship in vfbTerm.relationships:
if hasattr(relationship.relation, 'short_form') and relationship.relation.short_form:
relation_key = (relationship.relation.label, relationship.relation.short_form)
elif hasattr(relationship.relation, 'iri') and relationship.relation.iri:
relation_key = (relationship.relation.label, relationship.relation.iri.split('/')[-1])
elif hasattr(relationship.relation, 'label') and relationship.relation.label:
relation_key = (relationship.relation.label, relationship.relation.label)
else:
# Skip relationships with no identifiable relation
continue
if not hasattr(relationship, 'object') or not hasattr(relationship.object, 'label'):
# Skip relationships with missing object information
continue
object_key = (relationship.object.label, getattr(relationship.object, 'short_form', ''))
# Collect imaging techniques from relationships
relation_id = None
if hasattr(relationship.relation, 'short_form') and relationship.relation.short_form:
relation_id = relationship.relation.short_form
elif hasattr(relationship.relation, 'iri') and relationship.relation.iri:
relation_id = relationship.relation.iri.split('/')[-1]
if relation_id == 'OBI_0000312': # is_specified_output_of
if hasattr(relationship.object, 'label') and relationship.object.label:
techniques.add(relationship.object.label)
# New: Extract publications from this relationship if they exist
if hasattr(relationship, 'pubs') and relationship.pubs:
for pub in relationship.pubs:
if hasattr(pub, 'get_miniref') and pub.get_miniref():
publication = {}
publication["title"] = pub.core.label if hasattr(pub, 'core') and hasattr(pub.core, 'label') else ""
publication["short_form"] = pub.core.short_form if hasattr(pub, 'core') and hasattr(pub.core, 'short_form') else ""
publication["microref"] = pub.get_microref() if hasattr(pub, 'get_microref') and pub.get_microref() else ""
# Add external references
refs = []
if hasattr(pub, 'PubMed') and pub.PubMed:
refs.append(f"http://www.ncbi.nlm.nih.gov/pubmed/?term={pub.PubMed}")
if hasattr(pub, 'FlyBase') and pub.FlyBase:
refs.append(f"http://flybase.org/reports/{pub.FlyBase}")
if hasattr(pub, 'DOI') and pub.DOI:
refs.append(f"https://doi.org/{pub.DOI}")
publication["refs"] = refs
pubs_from_relationships.append(publication)
# Edge-level enrichment (confidence + reference), e.g. neuro-
# transmitter predictions. Per-edge, so do NOT collapse into the
# grouped/deduped relationships -- render each individually with
# its confidence % and reference linkout, matching the pre-VFBquery
# (vfb.xmi) term-info.
cv = getattr(relationship.relation, 'confidence_value', '') or ''
dx = getattr(relationship.relation, 'database_cross_reference', None) or []
if cv or dx:
conf = ''
if cv:
try:
conf = str(int(round(float(cv) * 100))) + '% '
except (ValueError, TypeError):
conf = ''
enriched_relationships.append(
'%s[%s](%s): [%s](%s)%s' % (
conf,
encode_brackets(relation_key[0]), relation_key[1],
encode_brackets(object_key[0]), object_key[1],
format_edge_xrefs(dx),
)
)
continue
if relation_key not in grouped_relationships:
grouped_relationships[relation_key] = set()
grouped_relationships[relation_key].add(object_key)
# Sort the grouped_relationships by keys
sorted_grouped_relationships = dict(sorted(grouped_relationships.items()))
# Append the grouped relationships to termInfo
for relation_key, object_set in sorted_grouped_relationships.items():
# Sort the object_set by object_key
sorted_object_set = sorted(list(object_set))
relation_objects = []
for object_key in sorted_object_set:
relation_objects.append("[%s](%s)" % (encode_brackets(object_key[0]), object_key[1]))
relationships.append("[%s](%s): %s" % (encode_brackets(relation_key[0]), relation_key[1], ', '.join(relation_objects)))
# Enriched (confidence/reference) relationships first, then the plain
# grouped ones -- so the NT confidence line leads, as it did before.
termInfo["Meta"]["Relationships"] = "; ".join(enriched_relationships + relationships)
# New: Add relationship publications to main publications list
if pubs_from_relationships:
if "Publications" not in termInfo:
termInfo["Publications"] = pubs_from_relationships
else:
# Merge with existing publications, avoiding duplicates by short_form
existing_pub_short_forms = {pub.get("short_form", "") for pub in termInfo["Publications"]}
for pub in pubs_from_relationships:
if pub.get("short_form", "") not in existing_pub_short_forms:
termInfo["Publications"].append(pub)
existing_pub_short_forms.add(pub.get("short_form", ""))
# Add techniques from relationships to termInfo for Individuals
if termInfo["IsIndividual"] and techniques:
termInfo["Technique"].extend(techniques)
termInfo["Technique"] = sorted(list(set(termInfo["Technique"])))
# If the term has anatomy channel images, retrieve the images and associated information
if vfbTerm.anatomy_channel_image and len(vfbTerm.anatomy_channel_image) > 0:
images = {}
techniques = set()
for image in vfbTerm.anatomy_channel_image:
# Check if this is a computer graphic image (painted domain)
if hasattr(image, 'channel_image') and hasattr(image.channel_image, 'imaging_technique'):
technique = image.channel_image.imaging_technique
if hasattr(technique, 'symbol') and technique.symbol and 'computer' in technique.symbol.lower():
termInfo["IsPaintedDomain"] = True
# Collect technique for Individual terms
if hasattr(technique, 'label') and technique.label:
techniques.add(technique.label)
record = {}
record["id"] = image.anatomy.short_form
label = image.anatomy.label
if image.anatomy.symbol and len(image.anatomy.symbol) > 0:
label = image.anatomy.symbol
record["label"] = label
if not image.channel_image.image.template_anatomy.short_form in images.keys():
images[image.channel_image.image.template_anatomy.short_form]=[]
record["thumbnail"] = image.channel_image.image.image_thumbnail.replace("http://","https://").replace("thumbnailT.png","thumbnail.png")
record["thumbnail_transparent"] = image.channel_image.image.image_thumbnail.replace("http://","https://").replace("thumbnail.png","thumbnailT.png")
for key in vars(image.channel_image.image).keys():
if "image_" in key and not ("thumbnail" in key or "folder" in key) and len(vars(image.channel_image.image)[key]) > 1:
record[key.replace("image_","")] = vars(image.channel_image.image)[key].replace("http://","https://")
images[image.channel_image.image.template_anatomy.short_form].append(record)
# Sort each template's images by id in descending order (newest first)
for template_key in images:
images[template_key] = sorted(images[template_key], key=lambda x: x["id"], reverse=True)
termInfo["Examples"] = images
# Add techniques to termInfo for Individuals
if termInfo["IsIndividual"] and techniques:
termInfo["Technique"].extend(techniques)
termInfo["Technique"] = sorted(list(set(termInfo["Technique"])))
# add a query for listing all available images -- only for anatomy
# Class terms (get_instances expects a Class, per this query's own
# Class+Anatomy criteria). DataSets/Individuals that merely have
# images must not get it (they use DatasetImages etc.), otherwise a
# dataset shows a spurious "List all available images" query.
if contains_all_tags(termInfo["SuperTypes"], ["Class", "Anatomy"]):
q = ListAllAvailableImages_to_schema(termInfo["Name"], {"short_form":vfbTerm.term.core.short_form})
queries.append(q)
# If the term has channel images but not anatomy channel images, create thumbnails from channel images.
if vfbTerm.channel_image and len(vfbTerm.channel_image) > 0:
images = {}
techniques = set()
for image in vfbTerm.channel_image:
# Check if this is a computer graphic image (painted domain)
if hasattr(image, 'imaging_technique'):
technique = image.imaging_technique
if hasattr(technique, 'symbol') and technique.symbol and 'computer' in technique.symbol.lower():
termInfo["IsPaintedDomain"] = True
# Collect technique for Individual terms
if hasattr(technique, 'label') and technique.label:
techniques.add(technique.label)
record = {}
record["id"] = vfbTerm.term.core.short_form
label = vfbTerm.term.core.label
if vfbTerm.term.core.symbol and len(vfbTerm.term.core.symbol) > 0:
label = vfbTerm.term.core.symbol
record["label"] = label
if not image.image.template_anatomy.short_form in images.keys():
images[image.image.template_anatomy.short_form]=[]
record["thumbnail"] = image.image.image_thumbnail.replace("http://","https://").replace("thumbnailT.png","thumbnail.png")
record["thumbnail_transparent"] = image.image.image_thumbnail.replace("http://","https://").replace("thumbnail.png","thumbnailT.png")
for key in vars(image.image).keys():
if "image_" in key and not ("thumbnail" in key or "folder" in key) and len(vars(image.image)[key]) > 1:
record[key.replace("image_","")] = vars(image.image)[key].replace("http://","https://")
images[image.image.template_anatomy.short_form].append(record)
# Sort each template's images by id in descending order (newest first)
for template_key in images:
images[template_key] = sorted(images[template_key], key=lambda x: x["id"], reverse=True)
# Add the thumbnails to the term info
termInfo["Images"] = images
# Add techniques to termInfo for Individuals
if termInfo["IsIndividual"] and techniques:
termInfo["Technique"].extend(techniques)
termInfo["Technique"] = sorted(list(set(termInfo["Technique"])))
if vfbTerm.dataset_license and len(vfbTerm.dataset_license) > 0:
licenses = {}
for idx, dataset_license in enumerate(vfbTerm.dataset_license):
record = {}
record['iri'] = dataset_license.license.core.iri
record['short_form'] = dataset_license.license.core.short_form
record['label'] = dataset_license.license.core.label
record['icon'] = dataset_license.license.icon
record['source_iri'] = dataset_license.dataset.core.iri
record['source'] = dataset_license.dataset.core.label
licenses[idx] = record
termInfo["Licenses"] = licenses
elif vfbTerm.license and len(vfbTerm.license) > 0:
# Terms that carry a licence directly rather than inheriting one
# from the dataset they came from. DataSet term info (see
# QueryLibrary.dataset_term_info) returns has_license on the term
# itself as `license`, with no `dataset_license`, so without this
# branch every dataset page loses its License row.
# Mirrors the fallback in term_info_queries.VFBTerm.get_license()
# and the legacy Java serialiser (VFBProcessTermInfoJson.getLicense).
# Deliberately elif, not a merge: the query library populates one or
# the other per term type, and if a term ever carried both, the
# inherited dataset licence wins -- same precedence as get_license().
licenses = {}
for idx, lcns in enumerate(vfbTerm.license):
record = {}
record['iri'] = lcns.core.iri
record['short_form'] = lcns.core.short_form
record['label'] = lcns.core.label
record['icon'] = lcns.icon
# No source dataset to attribute: the term is its own source,
# and an empty source keeps the panel from rendering a Source
# row that links back to the page you are already on.
record['source_iri'] = ''
record['source'] = ''
licenses[idx] = record
termInfo["Licenses"] = licenses
if vfbTerm.template_channel and vfbTerm.template_channel.channel.short_form: