-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2000 lines (1723 loc) · 62.8 KB
/
utils.py
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 apsw
import copy
import json
import os
import urllib.parse
import rdflib
import sqlite3
import sys
from rdflib.plugins.sparql import prepareQuery
import regex as re
apsw.config(apsw.SQLITE_CONFIG_MULTITHREAD)
def regularize_string(_):
"""Regularize a string for browses by trimming excess whitespace,
converting all whitespace to a single space, etc.
Parameters: _(str) - a string to regularize.
Returns:
str:
"""
return ' '.join(_.split())
class GlottologLookup:
def __init__(self, config):
self.config = config
if os.path.exists(self.config['GLOTTO_LOOKUP']):
with open(self.config['GLOTTO_LOOKUP']) as f:
self._lookup = json.load(f)
else:
self._lookup = {
'altLabel': {},
'prefLabel': {}
}
def build_lookup(self):
g = rdflib.Graph()
g.parse(self.config['GLOTTO_TRIPLES'], format='turtle')
lookup = {
'altLabel': {},
'prefLabel': {}
}
# load altLabel.
for row in g.query('''
PREFIX lexvo: <https://www.iso.org/standard/39534.html>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?code ?label
WHERE {
?identifier lexvo:iso639P3PCode ?code .
?identifier skos:altLabel ?label
}
'''):
code = str(row[0]).strip()
label = str(row[1]).strip()
if not code in lookup['altLabel']:
lookup['altLabel'][code] = []
if not label in lookup['altLabel'][code]:
lookup['altLabel'][code].append(label)
# load prefLabel.
for row in g.query('''
PREFIX lexvo: <https://www.iso.org/standard/39534.html>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?code ?label
WHERE {
?identifier lexvo:iso639P3PCode ?code .
?identifier skos:prefLabel ?label
}
'''):
code = str(row[0]).strip()
label = str(row[1]).strip()
if not code in lookup['prefLabel']:
lookup['prefLabel'][code] = []
if not label in lookup['prefLabel'][code]:
lookup['prefLabel'][code].append(label)
del g
with open(self.config['GLOTTO_LOOKUP'], 'w') as f:
f.write(json.dumps(lookup))
def get_glottolog_codes(self):
"""Get all ISO639P3P Codes from the Glottolog graph.
Parameters:
(none)
Returns:
list: all identifiers.
"""
return set(self._lookup['altLabel'].keys()) | \
set(self._lookup['prefLabel'].keys())
def get_glottolog_language_names(self, c):
"""Get all language names from Glottolog for a given identifier.
Parameters:
c (str): ISO 639P3P code, e.g., "eng"
Returns:
list: a list of language names as unicode strings.
"""
result = set()
try:
result = set(self._lookup['altLabel'][c])
except KeyError:
sys.stderr.write('GlottologLookup key error, ' + c + ' not found\n')
pass
try:
result |= set(self._lookup['prefLabel'][c])
except KeyError:
sys.stderr.write('GlottologLookup key error, ' + c + ' not found\n')
pass
return result
def get_glottolog_language_names_preferred(self, c):
"""Get preferred language names from Glottolog.
Parameters:
c (str): ISO 639P3P code, e.g., "eng"
Returns:
list: a list of language names, e.g., "English"
"""
try:
return self._lookup['prefLabel'][c]
except KeyError:
sys.stderr.write('GlottologLookup key error, ' + c + ' not found\n')
return ''
class MLCGraph:
def __init__(self, config, graph):
"""
Parameters:
g (rdflib.Graph): a graph containing triples for the project.
"""
self.config = config
self.graph = graph
self.glottolog_lookup = GlottologLookup(self.config)
def get_browse_terms(self, browse_type):
"""
Get a dictionary of browse terms, along with the items for each term.
It's currently not documented whether a browse should return series
nodes, item nodes, or both - so this includes both.
Paramters:
browse_type (str): e.g., 'contributor', 'creator', 'date',
'decade', 'language', 'location'
Returns:
dict: a Python dictionary, where the key is the browse term and the
value is a list of identifiers.
Notes:
The date browse converts all dates into decades and is range-aware-
so an item with the date "1933/1955" will appear in "1930s",
"1940s", and "1950s".
When I try to match our dc:language to Glottolog's
lexvo:iso639P3PCode, I run into trouble in Python's rdflib because
Glottolog's data has an explicit datatype of xsd:string() and ours
doesn't have an explicit datatype. Making both match manually
solves the problem. We may be able to solve this in MarkLogic by
casting the variable.
Here I solved the problem by manually editing the glottolog triples
so they match ours.
I would like to get TGN data as triples.
Go to http://vocab.getty.edu/sparql.
"""
browse_types = {
'contributor': 'http://purl.org/dc/terms/contributor',
'creator': 'http://purl.org/dc/terms/creator',
'date': 'http://purl.org/dc/terms/date',
'decade': 'http://purl.org/dc/terms/date',
'language': 'http://purl.org/dc/elements/1.1/language',
'location': 'http://purl.org/dc/terms/spatial'
}
assert browse_type in browse_types
browse_dict = {}
if browse_type == 'decade':
qres = self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?date_str ?identifier
WHERE {{
?identifier ?browse_type ?date_str .
?identifier dcterms:hasPart ?_
}}
'''),
initBindings={
'browse_type': rdflib.URIRef(browse_types[browse_type])
}
)
for date_str, identifier in qres:
if str(date_str) == '(:unav)':
continue
match = re.search('([0-9]{4})', date_str)
if match:
decade = str(match.group(0))[:3] + '0s'
if decade not in browse_dict:
browse_dict[decade] = set()
browse_dict[decade].add(str(identifier))
elif browse_type == 'language':
qres = self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?browse_term ?identifier
WHERE {
?identifier ?browse_type ?browse_term .
?identifier dcterms:hasPart ?_
}
'''),
initBindings={
'browse_type': rdflib.URIRef(browse_types[browse_type])
}
)
for browse_term, identifier in qres:
browse_term = regularize_string(str(browse_term))
for label in self.glottolog_lookup.get_glottolog_language_names_preferred(
browse_term
):
label = regularize_string(label)
if not label:
continue
if label not in browse_dict:
browse_dict[label] = set()
browse_dict[label].add(regularize_string(str(identifier)))
elif browse_type == 'location':
qres = self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?browse_term ?identifier
WHERE {
?identifier ?browse_type ?browse_term .
?identifier dcterms:hasPart ?_
}
'''),
initBindings={
'browse_type': rdflib.URIRef(browse_types[browse_type])
}
)
for browse_terms, identifier in qres:
for browse_term in browse_terms.split():
browse_term = regularize_string(browse_term)
for label in self.get_tgn_place_names_preferred(
browse_term
):
label = regularize_string(label)
if not label:
continue
if label not in browse_dict:
browse_dict[label] = set()
browse_dict[label].add(
regularize_string(str(identifier)))
else:
qres = self.graph.query(
prepareQuery('''
SELECT ?browse_term ?identifier
WHERE {
?identifier ?browse_type ?browse_term .
?identifier <http://purl.org/dc/terms/hasPart> ?_
}
'''),
initBindings={
'browse_type': rdflib.URIRef(browse_types[browse_type])
}
)
for labels, identifier in qres:
for label in labels.split('\n'):
label = regularize_string(label)
if not label:
continue
if label not in browse_dict:
browse_dict[label] = set()
browse_dict[label].add(regularize_string(str(identifier)))
# convert identifiers set to a list.
for k in browse_dict.keys():
browse_dict[k] = sorted(list(browse_dict[k]))
return browse_dict
def get_item_dbid(self, item_id):
"""
Get the database identifier for a given item.
Parameters:
item_id (str): a series identifier.
Returns:
str: item identifier.
"""
dbid = ''
for row in self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?dbid
WHERE {
?item_id dc:identifier ?dbid
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
dbid = row[0]
return dbid
def get_item_has_panopto_link(self, item_id):
"""
Return whether an item has a Panopto link or not.
Parameters:
item_id (str): a series identifier.
Returns:
bool
"""
has_panopto_link = '0'
for row in self.graph.query(
prepareQuery('''
PREFIX edm: <http://www.europeana.eu/schemas/edm/>
SELECT ?url
WHERE {
?aggregation edm:aggregatedCHO ?item_id .
?aggregation edm:isShownBy ?url
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
has_panopto_link = '1'
return has_panopto_link
def get_item_info(self, item_id):
"""
Get info for search snippets and page views of a given item.
Parameters:
item_id (str): a series identifier.
Returns:
dict: item information.
"""
data = {}
for label, p in {
'content_type': 'http://id.loc.gov/ontologies/bibframe/content',
'linguistic_data_type':
'http://lib.uchicago.edu/dma/olacLinguisticDataType',
'creator': 'http://purl.org/dc/terms/creator',
'description': 'http://purl.org/dc/elements/1.1/description',
'identifier': 'http://purl.org/dc/elements/1.1/identifier',
'medium': 'http://purl.org/dc/terms/medium',
'titles': 'http://purl.org/dc/elements/1.1/title',
'alternative_title': 'http://purl.org/dc/terms/alternative',
'contributor': 'http://purl.org/dc/terms/contributor',
'date': 'http://purl.org/dc/terms/date',
'is_part_of': 'http://purl.org/dc/terms/isPartOf',
'location': 'http://purl.org/dc/terms/spatial',
'discourse_type':
'http://www.language−archives.org/OLAC/metadata.html' +
'discourseType'
}.items():
values = set()
for row in self.graph.query(
prepareQuery('''
SELECT ?value
WHERE {
?item_id ?p ?value
}
'''),
initBindings={
'p': rdflib.URIRef(p),
'item_id': rdflib.URIRef(item_id)
}
):
values.add(' '.join(row[0].split()))
data[label] = sorted(list(values))
# convert TGN identifiers to preferred names.
tgn_identifiers = set()
for i in data['location']:
for j in i.split():
tgn_identifiers.add(j)
data['location'] = []
for i in tgn_identifiers:
for preferred_name in self.get_tgn_place_names_preferred(
i
):
data['location'].append(preferred_name)
# primary_language
codes = set()
for row in self.graph.query(
prepareQuery('''
PREFIX icu: <http://lib.uchicago.edu/icu/>
PREFIX lexvo: <https://www.iso.org/standard/39534.html>
PREFIX uchicago: <http://lib.uchicago.edu/>
SELECT ?code
WHERE {
?item_id uchicago:language ?l .
?l icu:languageRole ?role .
?l lexvo:iso639P3PCode ?code .
FILTER (?role IN ('Both', 'Primary'))
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
codes.add(str(row[0]))
preferred_names = set()
for c in codes:
for preferred_name in self.glottolog_lookup.get_glottolog_language_names_preferred(
c
):
preferred_names.add(preferred_name)
data['primary_language'] = []
for preferred_name in preferred_names:
data['primary_language'].append(preferred_name)
# subject_language
codes = set()
for row in self.graph.query(
prepareQuery('''
PREFIX icu: <http://lib.uchicago.edu/icu/>
PREFIX lexvo: <https://www.iso.org/standard/39534.html>
PREFIX uchicago: <http://lib.uchicago.edu/>
SELECT ?code
WHERE {
?item_id uchicago:language ?l .
?l icu:languageRole ?role .
?l lexvo:iso639P3PCode ?code .
FILTER (?role IN ('Both', 'Subject'))
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
codes.add(str(row[0]))
preferred_names = set()
for c in codes:
for preferred_name in self.glottolog_lookup.get_glottolog_language_names_preferred(
c
):
preferred_names.add(preferred_name)
data['subject_language'] = []
for preferred_name in preferred_names:
data['subject_language'].append(preferred_name)
# has_format
data['has_format'] = {}
for row in self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX edm: <http://www.europeana.eu/schemas/edm/>
SELECT ?format_item_id ?format_medium
WHERE {
?item_id dcterms:hasFormat ?format_item_id .
?format_item_id dcterms:medium ?format_medium .
?format_item_id dc:identifier ?format_dbid .
?format_agg edm:aggregatedCHO ?format_item_id .
BIND( EXISTS {
?format_agg edm:isShownBy ?_ .
}
AS ?has_panopto
)
}
ORDER BY DESC(?has_panopto) ?format_dbid
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
format_id = str(row[0])
medium = str(row[1])
if medium not in data['has_format']:
data['has_format'][medium] = []
data['has_format'][medium].append(row[0])
# is_format_of
data['is_format_of'] = {}
for row in self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX edm: <http://www.europeana.eu/schemas/edm/>
SELECT ?format_item_id ?format_medium
WHERE {
?item_id dcterms:isFormatOf ?format_item_id .
?format_item_id dcterms:medium ?format_medium .
?format_item_id dc:identifier ?format_dbid .
?format_agg edm:aggregatedCHO ?format_item_id .
BIND( EXISTS {
?format_agg edm:isShownBy ?_ .
}
AS
?has_panopto
)
}
ORDER BY DESC(?has_panopto) ?format_dbid
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
format_id = str(row[0])
medium = str(row[1])
if medium not in data['is_format_of']:
data['is_format_of'][medium] = []
data['is_format_of'][medium].append(row[0])
# panopto links
panopto_links = set()
for row in self.graph.query(
prepareQuery('''
PREFIX edm: <http://www.europeana.eu/schemas/edm/>
SELECT ?panopto_link
WHERE {
?aggregation edm:aggregatedCHO ?item_id .
?aggregation edm:isShownBy ?panopto_link
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
panopto_links.add(str(row[0]))
data['panopto_links'] = list(panopto_links)
# panopto identifiers
panopto_identifiers = set()
panopto_prefix = 'https://uchicago.hosted.panopto.com/Panopto/Pages/Embed.aspx?id='
for row in self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?identifier
WHERE {
?web_resource dcterms:identifier ?identifier
}
'''),
initBindings={
'web_resource': rdflib.URIRef(item_id + '/file.wav')
}
):
if str(row[0]).startswith(panopto_prefix):
panopto_identifiers.add(str(row[0]).replace(panopto_prefix, ''))
data['panopto_identifiers'] = list(panopto_identifiers)
# access rights
access_rights = set()
for row in self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?access_rights
WHERE {
?item_id dcterms:isPartOf ?series_id .
?series_id dcterms:accessRights ?access_rights
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
access_rights.add(str(row[0]))
data['access_rights'] = list(access_rights)
data['ark'] = item_id
return data
def get_item_identifiers(self):
"""
Get all item identifiers from the graph.
Parameters:
None
Returns:
list: item identifiers.
"""
qres = self.graph.query('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?item_id
WHERE {
?_ dcterms:hasPart ?item_id
}
''')
results = set()
for row in qres:
results.add(str(row[0]))
return sorted(list(results))
def get_item_identifiers_for_series(self, i):
"""
Get the item identifiers for a given series.
Parameters:
i (str): a series identifier.
Returns:
list: a list of item identifiers.
"""
r = self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?item_id
WHERE {
?series_id dcterms:hasPart ?item_id
}
'''),
initBindings={
'series_id': rdflib.URIRef(i)
}
)
results = set()
for row in r:
results.add(str(row[0]))
return sorted(list(results))
def get_item_medium(self, item_id):
"""
Get the medium for a given item.
Parameters:
item_id (str): a series identifier.
Returns:
str: medium
"""
medium = ''
for row in self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?medium
WHERE {
?item_id dcterms:medium ?medium
}
'''),
initBindings={
'item_id': rdflib.URIRef(item_id)
}
):
medium = str(row[0])
return medium
def get_search_tokens_for_identifier(self, i):
"""
Get the search tokens for a given series or item identifier from the
graph.
Parameters:
i (str): a series identifier
Returns:
str: a string that can be searched via SQLite.
"""
search_tokens = []
# non-blank triples with no special processing
for p in (
'http://purl.org/dc/elements/1.1/description',
'http://purl.org/dc/elements/1.1/title',
'http://purl.org/dc/terms/alternative',
'http://purl.org/dc/terms/creator',
'http://purl.org/dc/terms/contributor',
'http://www.language−archives.org/OLAC/metadata.htmldiscourseType',
'http://lib.uchicago.edu/dma/contentType'
):
r = self.graph.query(
prepareQuery('''
SELECT ?o
WHERE {
?series_id ?p ?o
}
'''),
initBindings={
'p': rdflib.URIRef(p),
'series_id': rdflib.URIRef(i)
}
)
for row in r:
search_tokens.append(str(row[0]))
# fn:collection
r = self.graph.query(
prepareQuery('''
PREFIX fn: <http://www.w3.org/2005/xpath-functions>
SELECT ?o
WHERE {
?series_aggregation_id fn:collection ?o .
}
'''),
initBindings={
'p': rdflib.URIRef(p),
'series_aggregation_id': rdflib.URIRef(i + '/aggregation')
}
)
lookup = {
'dma': 'Digital Media Archive'
}
for row in r:
if str(row[0]) in lookup:
search_tokens.append(lookup[str(row[0])])
# dc:language
r = self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?o
WHERE {
?series_id dc:language ?o
}
'''),
initBindings={
'series_id': rdflib.URIRef(i)
}
)
for row in r:
for label in self.glottolog_lookup.get_glottolog_language_names(str(row[0])):
search_tokens.append(label)
# dcterms:spatial
r = self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?o
WHERE {
?series_id dcterms:spatial ?o
}
'''),
initBindings={
'series_id': rdflib.URIRef(i)
}
)
for row in r:
for tgn_identifier in str(row[0]).split():
for label in self.get_tgn_place_names(tgn_identifier):
search_tokens.append(label)
# series-level dc:date
years = set()
r = self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?o
WHERE {
?series_id dcterms:date ?o
}
'''),
initBindings={
'series_id': rdflib.URIRef(i)
}
)
for row in r:
date_str = str(row[0])
year_strs = []
for year_str in date_str.split('/'):
if year_str.isnumeric() and len(year_str) == 4:
year_strs.append(int(year_str))
if len(year_strs) == 1:
years.add(str(year_strs[0]))
elif len(year_strs) > 1:
year_strs.sort()
y = year_strs[0]
while y <= year_strs[-1]:
years.add(str(y))
y += 1
for y in sorted(list(years)):
search_tokens.append(y)
# replace all whitespace with single spaces and return all search
# tokens in a single string.
return ' '.join([' '.join(s.split()) for s in search_tokens])
def get_search_tokens_for_series_identifier(self, i):
"""
Get the search tokens for a given series identifier from the graph.
Parameters:
i (str): a series identifier
Returns:
str: a string that can be searched via SQLite.
"""
search_tokens = []
# item-level description
for iid in self.get_item_identifiers_for_series(i):
r = self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?o
WHERE {
?item_id dc:description ?o
}
'''),
initBindings={
'item_id': rdflib.URIRef(iid)
}
)
for row in r:
search_tokens.append(row[0])
token_str = self.get_search_tokens_for_identifier(i)
if token_str and search_tokens:
token_str = token_str + \
' ' + \
' '.join([' '.join(s.split()) for s in search_tokens])
return token_str
def get_search_tokens_for_item_identifier(self, i):
"""
Get the search tokens for a given item identifier from the graph.
Parameters:
i (str): a series identifier
Returns:
str: a string that can be searched via SQLite.
"""
search_tokens = []
# item-level description
r = self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?o
WHERE {
?item_id dc:description ?o
}
'''),
initBindings={
'item_id': rdflib.URIRef(i)
}
)
for row in r:
search_tokens.append(row[0])
token_str = self.get_search_tokens_for_identifier(i)
if token_str and search_tokens:
token_str = token_str + \
' ' + \
' '.join([' '.join(s.split()) for s in search_tokens])
return token_str
def get_series_date(self, i):
"""
Get a single date for a given series identifier from the graph.
Parameters:
i (str): a series identifier
Returns:
str: a four-digit year (YYYY) or a year range (YYYY/YYYY)
"""
years = []
for row in self.graph.query(
prepareQuery('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?date
WHERE {
?identifier dcterms:date ?date
}
'''
),
initBindings={
'identifier': rdflib.URIRef(i)
}
):
for year in row[0].split('/'):
years.append(year)
if len(years) == 0:
return ''
if len(years) == 1:
return years[0]
years = sorted(years)
return '/'.join([years[0], years[-1]])
def get_series_dbid(self, i):
"""
Get a single database identifier for a given series identifier.
Parameters:
i (str): a series identifier
Returns:
str: a database identifier.
"""
dbids = []
for row in self.graph.query(
prepareQuery('''
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?dbid
WHERE {
?identifier dc:identifier ?dbid
}
'''
),
initBindings={
'identifier': rdflib.URIRef(i)
}
):
dbids.append(str(row[0]))
if len(dbids) == 0:
return ''
return dbids[0]
def get_series_identifiers(self):
"""
Get all series identifiers from the graph.
Parameters:
None
Returns:
list: series identifiers.
"""
qres = self.graph.query('''
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?series_id
WHERE {
?series_id dcterms:hasPart ?_
}
''')
results = set()
for row in qres:
results.add(str(row[0]))
return sorted(list(results))
def get_series_identifiers_for_item(self, i):
"""
Get the series identifiers for a given item.
Parameters:
i (str): an item identifier.
Returns:
list: a list of series identifiers.