-
Notifications
You must be signed in to change notification settings - Fork 2
/
dodo.py
614 lines (528 loc) · 21.8 KB
/
dodo.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
# vi:autoindent:sw=4:ts=4:et
# encoding=utf8
import logging
import logging.config
import yaml
import re
import paramiko
with open('logging.yml') as cfg:
logging.config.dictConfig(yaml.safe_load(cfg))
logger = logging.getLogger()
from doit import get_var
from roald import Roald
from rdflib.graph import Graph, URIRef
import csv
import time
import json
import os
import data_ub_tasks
from dotenv import load_dotenv
load_dotenv()
FUSEKI_HOST = os.environ.get('FUSEKI_HOST', 'localhost')
config = {
'dumps_dir': get_var('dumps_dir', '/opt/data.ub/www/default/dumps'),
'dumps_dir_url': get_var('dumps_dir_url', 'http://data.ub.uio.no/dumps'),
'graph': 'http://data.ub.uio.no/realfagstermer',
'fuseki': 'http://%s:3031/ds' % FUSEKI_HOST,
'basename': 'realfagstermer',
'git_user': 'ubo-bot',
'git_email': 'danmichaelo+ubobot@gmail.com',
'es_index': 'authority'
}
DOIT_CONFIG = {
'default_tasks': [
'fetch_core:src/sonja_todo.json',
'git-push',
#'build-solr-json',
'publish-dumps',
'fuseki',
'stats',
]
}
def task_fetch_from_bibsys_sftp():
def uptodate(task, values):
host,port = "sftp.bibsys.no",22
transport = paramiko.Transport((host,port))
username,password = os.getenv("SFTP_USER"), os.getenv("SFTP_PASSWORD")
transport.connect(None,username,password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.chdir('/home')
files = sorted(sftp.listdir())
real_files = [f for f in files if f.startswith('REAL')]
latest_file = real_files.pop()
def save_latest_file():
return {'latest_file': latest_file}
task.value_savers.append(save_latest_file)
return values.get('latest_file') == latest_file
def fetch(task):
host,port = "sftp.bibsys.no",22
transport = paramiko.Transport((host,port))
username,password = os.getenv("SFTP_USER"), os.getenv("SFTP_PASSWORD")
transport.connect(None,username,password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.chdir('/home')
files = sorted(sftp.listdir())
real_files = [f for f in files if f.startswith('REAL')]
latest_file = real_files.pop()
# Cleanup old files
for other_file in real_files:
sftp.remove(other_file)
# Fetch latest file
sftp.get(latest_file, 'src/realfagstermer.marc21.tar.gz')
return {
'doc': 'Fetch data from Bibsys SFTP',
'basename': 'fetch-sftp',
'actions': [
fetch,
'tar -xOzf src/realfagstermer.marc21.tar.gz | xmllint -format - > src/realfagstermer.marc21.xml',
],
'uptodate': [uptodate],
'targets': [
'src/realfagstermer.marc21.xml',
],
}
def task_fetch_core():
yield {
'doc': 'Fetch remote core files that have changed',
'basename': 'fetch-core',
'name': None
}
yield data_ub_tasks.git_pull_task_gen(config)
for file in [
{'remote': 'https://raw.githubusercontent.com/scriptotek/data_ub_ontology/master/ub-onto.ttl',
'local': 'src/ub-onto.ttl'},
{'remote': 'https://raw.githubusercontent.com/realfagstermer/prosjekt-kinderegg/master/sonja_todo.json',
'local': 'src/sonja_todo.json'},
{'remote': 'https://raw.githubusercontent.com/realfagstermer/prosjekt-kinderegg/master/categories_and_mappings.ttl',
'local': 'src/categories_and_mappings.ttl'},
]:
yield data_ub_tasks.fetch_remote_gen(file['remote'], file['local'], ['fetch_core:git-pull'])
def task_fetch_extras():
yield {
'doc': 'Fetch remote extra files that have changed',
'basename': 'fetch-extras',
'name': None
}
for file in [
#{'remote': 'https://mapper.biblionaut.net/export/real_tekord_mappings.ttl',
# 'local': 'src/real_tekord_mappings.ttl'},
#{'remote': 'https://mapper.biblionaut.net/export/real_agrovoc_mappings.ttl',
# 'local': 'src/real_agrovoc_mappings.ttl'},
#{'remote': 'https://lambda.biblionaut.net/export/real_hume_mappings.ttl',
# 'local': 'src/real_hume_mappings.ttl'},
#{'remote': 'https://lambda.biblionaut.net/export/ccmapper_mappings.ttl',
# 'local': 'src/ccmapper_mappings.ttl'},
{'remote': 'https://data.ub.uio.no/dumps/msc-ubo.mappings.nt',
'local': 'src/msc-ubo.mappings.nt'}, # {'remote': 'https://rawgit.com/realfagstermer/prosjekt-kinderegg/master/categories_and_mappings.ttl',
# 'local': 'src/categories_and_mappings.ttl'},
]:
yield data_ub_tasks.fetch_remote_gen(file['remote'], file['local'], [])
def task_build_core():
def build(task):
logger.info('Building new core dist')
roald = Roald(mail_config={
'domain': os.getenv('MAIL_DOMAIN'),
'apikey': os.getenv('MAIL_APIKEY'),
'sender': os.getenv('MAIL_SENDER'),
'reply': os.getenv('MAIL_REPLY'),
'recipients': os.getenv('MAIL_RECIPIENTS').split(','),
})
# The following line must be commented out.
#roald.load('src/realfagstermer.marc21.xml', format='roald2', language='nb', vocabulary_code='noubomn', id_validator=re.compile('REAL\d{5,}'))
# The following line is the correct version of the line above.
roald.load('src/realfagstermer.marc21.xml', format='marc21', language='nb', vocabulary_code='noubomn', id_validator=re.compile('REAL\d{5,}'))
roald.set_uri_format('http://data.ub.uio.no/%s/c{id}' % config['basename'], 'REAL')
roald.save('%s.json' % config['basename'])
logger.info('Wrote %s.json', config['basename'])
includes = [
'%s.scheme.ttl' % config['basename'],
'src/ub-onto.ttl',
# 'src/nynorsk.ttl'
]
roald.export('dist/%s.ttl' % config['basename'],
format='rdfskos',
include=includes
)
logger.info('Wrote dist/%s.core.ttl', config['basename'])
return {
'doc': 'Build core distribution files (JSON + TTL)',
'basename': 'build-core',
'actions': [
'mkdir -p dist',
build,
],
'file_dep': [
'src/realfagstermer.marc21.xml',
'src/ub-onto.ttl',
'%s.scheme.ttl' % config['basename']
],
'targets': [
'%s.json' % config['basename'],
#'dist/%s.marc21.xml' % config['basename'],
'dist/%s.ttl' % config['basename'],
]
}
def task_build_extras():
def build(task):
logger.info('Building extras')
#roald = Roald()
roald = Roald(mail_config={
'domain': os.getenv('MAIL_DOMAIN'),
'apikey': os.getenv('MAIL_APIKEY'),
'sender': os.getenv('MAIL_SENDER'),
'reply': os.getenv('MAIL_REPLY'),
'recipients': "loke.sjolie@ub.uio.no",
})
# This code is used to force updates.
# roald.load('src/realfagstermer.marc21.xml', format='roald2', language='nb', vocabulary_code='noubomn', id_validator=re.compile('REAL\d{5,}'))
# This is the code that we actually want.
roald.load('src/realfagstermer.marc21.xml', format='marc21', language='nb', vocabulary_code='noubomn', id_validator=re.compile('REAL\d{5,}'))
roald.set_uri_format('http://data.ub.uio.no/%s/c{id}' % config['basename'], 'REAL')
roald.load('src/categories_and_mappings.ttl', format='skos') # From soksed
roald.load('src/real_hume_mappings.ttl', format='skos') # mappings from mymapper
# 0) MARC21 for general use, reintroduced
marc21options = {
'vocabulary_code': 'noubomn',
'created_by': 'NO-TrBIB',
'include_d9': 'simple',
'include_memberships': False,
}
roald.export('dist/%s.marc21.xml' %
config['basename'], format='marc21', **marc21options)
logger.info('Wrote dist/%s.marc21.xml', config['basename'])
# 1) MARC21 with $9 fields for CCMapper
marc21options = {
'vocabulary_code': 'noubomn',
'created_by': 'NO-TrBIB',
'include_d9': 'complex',
'include_memberships': True,
}
roald.export('dist/%s.ccmapper.marc21.xml' %
config['basename'], format='marc21',
**marc21options)
logger.info('Wrote dist/%s.ccmapper.marc21.xml', config['basename'])
roald.load('src/real_tekord_mappings.ttl', format='skos') # Tekord mappings
roald.load('src/real_agrovoc_mappings.ttl', format='skos') # Agrovoc mappings
roald.load('src/ccmapper_mappings.ttl', format='skos') # Mappings from CCMapper
roald.load('src/msc-ubo.mappings.nt', format='skos') # MSC mappings
# 2) RDF (core + mappings)
prepared = roald.prepare_export(format='rdfskos',
include=[
'%s.scheme.ttl' % config['basename'],
'src/ub-onto.ttl',
'src/categories_and_mappings.ttl',
],
with_ccmapper_candidates=True,
infer=True
)
prepared.write('dist/%s.complete.ttl' % config['basename'], format='turtle')
logger.info('Wrote dist/%s.complete.ttl', config['basename'])
prepared.write('dist/%s.complete.nt' % config['basename'], format='nt')
logger.info('Wrote dist/%s.complete.nt', config['basename'])
return {
'doc': 'Build extra distribution files (RDF/SKOS with mappings + MARC21XML)',
'basename': 'build-extras',
'actions': [
'mkdir -p dist',
build,
],
'file_dep': [
'src/real_tekord_mappings.ttl',
'src/real_agrovoc_mappings.ttl',
'src/real_hume_mappings.ttl',
'src/ccmapper_mappings.ttl',
'src/categories_and_mappings.ttl',
'src/msc-ubo.mappings.nt',
'src/ub-onto.ttl',
'%s.scheme.ttl' % config['basename']
],
'targets': [
'dist/%s.marc21.xml' % config['basename'],
'dist/%s.ccmapper.marc21.xml' % config['basename'],
'dist/%s.complete.ttl' % config['basename'],
'dist/%s.complete.nt' % config['basename'],
]
}
def task_build_mappings():
src_uri = 'http://data.ub.uio.no/realfagstermer/'
mapping_sets = [
{
'source_files': ['src/categories_and_mappings.ttl'],
'target': 'wikidata',
},
{
'source_files': ['src/real_hume_mappings.ttl'],
'target': 'humord',
},
{
'source_files': ['src/real_tekord_mappings.ttl'],
'target': 'tekord',
},
{
'source_files': ['src/ccmapper_mappings.ttl'],
'target': 'ddc23no',
},
{
'source_files': ['src/msc-ubo.mappings.nt'],
'target': 'msc-ubo',
},
]
yield {
'doc': 'Build mapping distributions',
'basename': 'build-mappings',
'name': None
}
for mapping_set in mapping_sets:
yield data_ub_tasks.build_mappings_gen(
mapping_set['source_files'],
'dist/%s-%s.mappings.nt' % (config['basename'], mapping_set['target']),
src_uri
)
def task_build_json():
return data_ub_tasks.gen_solr_json(config, 'realfagstermer')
def task_elasticsearch():
return data_ub_tasks.gen_elasticsearch(config, 'realfagstermer')
def task_git_push():
return data_ub_tasks.git_push_task_gen(config)
def task_publish_dumps():
return data_ub_tasks.publish_dumps_task_gen(config['dumps_dir'], [
'%s.marc21.xml' % config['basename'],
'%s.ccmapper.marc21.xml' % config['basename'],
'%s.ttl' % config['basename'],
'%s.complete.ttl' % config['basename'],
'%s.complete.nt' % config['basename'],
'%s-wikidata.mappings.nt' % config['basename'],
'%s-humord.mappings.nt' % config['basename'],
'%s-tekord.mappings.nt' % config['basename'],
'%s-ddc23no.mappings.nt' % config['basename'],
'%s-msc-ubo.mappings.nt' % config['basename'],
])
def task_fuseki():
return data_ub_tasks.fuseki_task_gen(config, ['dist/%(basename)s.complete.ttl'])
# def task_nynorsk_liste():
# def build_table(task):
# graph = Graph()
# graph.load('dist/realfagstermer.ttl', format='turtle')
# concepts = {}
# for tr in graph.triples_choices((None, [SKOS.prefLabel, SKOS.altLabel], None)):
# uri = str(tr[0])
# term = tr[2].value
# lang = tr[2].language
# if uri not in concepts:
# concepts[uri] = {'pref': {}, 'alt': {}}
# if tr[1] == SKOS.prefLabel:
# concepts[uri]['pref'][lang] = term
# else:
# concepts[uri]['alt'][lang] = concepts[uri]['alt'].get(lang, []) + [term]
# with open('dist/realfagstermer_bm-nn.csv', 'wb') as f:
# writer = csv.writer(f, delimiter =',', quotechar ='"',quoting=csv.QUOTE_MINIMAL)
# writer.writerow([
# 'URI for begrepet',
# 'Foretrukket term (bokmål)',
# 'Foretrukken term (nynorsk)',
# 'Alternative termer (bokmål)',
# 'Alternative termar (nynorsk)'
# ])
# for k, v in concepts.items():
# pbm = v['pref'].get('nb')
# pnn = v['pref'].get('nn')
# if pbm is not None and pnn is not None:
# abm = '|'.join(v['alt'].get('nb', []))
# ann = '|'.join(v['alt'].get('nn', []))
# writer.writerow([
# k.encode('utf-8'),
# pbm.encode('utf-8'),
# pnn.encode('utf-8'),
# abm.encode('utf-8'),
# ann.encode('utf-8')
# ])
# else:
# pass # for now..
# return {
# 'doc': 'Build bokmaal-nynorsk list',
# 'actions': [build_table],
# 'file_dep': [
# 'src/nynorsk.ttl',
# 'dist/realfagstermer.ttl'
# ],
# 'targets': [
# 'dist/realfagstermer_bm-nn.csv'
# ]
# }
def task_stats():
# Note: We cannot import rdflib namespaces globally because doit
# think they are task creator classes because
# hasattr(Namespace, 'create_doit_tasks') evaluates to True, since
# a namespace can include *any* value.
from rdflib.namespace import SKOS
def stats_from_graph(g):
facets = {
'Topic': {
'concepts': 0,
'terms': 0,
'prefLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0},
'altLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0}
},
'Temporal': {
'concepts': 0,
'terms': 0,
'prefLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0},
'altLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0}
},
'Geographic': {
'concepts': 0,
'terms': 0,
'prefLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0},
'altLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0}
},
'GenreForm': {
'concepts': 0,
'terms': 0,
'prefLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0},
'altLabels': {'nb': 0, 'nn': 0, 'en': 0, 'la': 0}
},
'ComplexConcept': {
'concepts': 0,
'terms': 0,
'prefLabels': {}
},
'VirtualComplexConcept': {
'concepts': 0,
'terms': 0,
'prefLabels': {}
}
}
features = {
'definition': 0,
'editorialNote': 0,
'related': 0,
'exactMatch': 0,
'closeMatch': 0,
'relatedMatch': 0,
'broadMatch': 0,
'narrowMatch': 0,
}
mappingUris = {
'agrovoc': 'http://aims.fao.org/aos/agrovoc/',
'ddc': 'http://dewey.info/',
'tekord': 'http://data.ub.uio.no/tekord/',
'wikidata': 'http://www.wikidata.org/',
'humord': 'http://data.ub.uio.no/humord',
}
mappings = {
'agrovoc': 0,
'ddc': 0,
'tekord': 0,
'humord': 0,
'wikidata': 0,
}
for x in g.triples_choices((None, [SKOS.mappingRelation], None)):
if type(x[2]) == URIRef:
uri = str(x[2])
for k, v in mappingUris.items():
if uri.startswith(v):
mappings[k] += 1
for featureName in features.keys():
vals = g.query(u"""PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX mads: <http://www.loc.gov/mads/rdf/v1#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT (COUNT(DISTINCT ?o) AS ?c)
WHERE {
?s skos:%s ?o
FILTER NOT EXISTS { ?s owl:deprecated true }
}""" % featureName).bindings[0].values()
features[featureName] = int(list(vals)[0].value)
terms = {}
for triple in g.triples_choices((None, [SKOS.prefLabel, SKOS.altLabel], None)):
lang = triple[2].language
if lang not in terms:
terms[lang] = 0
terms[lang] += 1
terms['_sum'] = sum([v for x, v in terms.items()])
sumConcepts = 0
sumConceptsWithStrings = 0
vals = g.query(u"""PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX ubo: <http://data.ub.uio.no/onto#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT (COUNT(DISTINCT ?s) AS ?c)
WHERE {
?s owl:deprecated true .
}""").bindings[0].values()
deprecatedConcepts = int(list(vals)[0].value)
for facetName, facet in facets.items():
vals = g.query(u"""PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX ubo: <http://data.ub.uio.no/onto#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT (COUNT(DISTINCT ?s) AS ?c)
WHERE {
?s a ubo:%s .
FILTER NOT EXISTS { ?s owl:deprecated true } .
}""" % (facetName)).bindings[0].values()
facets[facetName]['concepts'] = int(list(vals)[0].value)
sumConceptsWithStrings += facets[facetName]['concepts']
if facetName != 'ComplexConcept' and facetName != 'VirtualComplexConcept':
sumConcepts += facets[facetName]['concepts']
facets[facetName]['terms'] = 0
for langName in facet['prefLabels'].keys():
vals = g.query(u"""PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX ubo: <http://data.ub.uio.no/onto#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT (COUNT(DISTINCT ?o) AS ?c)
WHERE {
?s a ubo:%s .
?s skos:prefLabel ?o .
FILTER(langMatches(lang(?o), "%s"))
FILTER NOT EXISTS { ?s owl:deprecated true } .
}""" % (facetName, langName)).bindings[0].values()
facets[facetName]['prefLabels'][langName] = int(list(vals)[0].value)
vals = g.query(u"""PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX ubo: <http://data.ub.uio.no/onto#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT (COUNT(DISTINCT ?o) AS ?c)
WHERE {
?s a ubo:%s .
?s skos:altLabel ?o .
FILTER(langMatches(lang(?o), "%s"))
FILTER NOT EXISTS { ?s owl:deprecated true } .
}""" % (facetName, langName)).bindings[0].values()
facets[facetName]['altLabels'][langName] = int(list(vals)[0].value)
facets[facetName]['terms'] += facets[facetName]['prefLabels'][langName] + facets[facetName]['altLabels'][langName]
return {
'deprecatedConcepts': deprecatedConcepts,
'concepts': sumConceptsWithStrings,
'conceptsWithoutStrings': sumConcepts,
'terms': terms,
'facets': facets,
'features': features,
'mappings': mappings
}
def stats(task):
t0 = time.time()
g = Graph()
g.parse('dist/realfagstermer.complete.ttl', format='turtle')
s = json.load(open('realfagstermer.github.io/_data/stats.json', 'r'))
current = stats_from_graph(g)
current['ts'] = now = int(time.time())
s.append(current)
json.dump(current, open('realfagstermer.github.io/_data/stats_current.json', 'w'), indent=2, sort_keys=True)
json.dump(s, open('realfagstermer.github.io/_data/stats.json', 'w'), indent=2, sort_keys=True)
dt = time.time() - t0
logger.info('Generated stats in %.1f seconds', dt)
return {
'doc': 'Generate stats',
'actions': [
'test -d realfagstermer.github.io || git clone git@github.com:realfagstermer/realfagstermer.github.io.git',
'cd realfagstermer.github.io && git pull && cd ..',
stats,
'cd realfagstermer.github.io && git add _data/stats_current.json _data/stats.json',
'cd realfagstermer.github.io && git commit -m "Update stats"',
'cd realfagstermer.github.io && git push origin',
],
'file_dep': [
'dist/realfagstermer.complete.ttl'
],
'targets': [
'realfagstermer.github.io/_data/stats.json',
'realfagstermer.github.io/_data/stats_current.json'
]
}