This repository has been archived by the owner on Sep 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yso_converter.py
1668 lines (1576 loc) · 84.8 KB
/
yso_converter.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
#!/usr/bin/env python3
from rdflib import Graph, URIRef, Namespace, RDF
import pymarc
from pymarc import XmlHandler
from xml import sax
from pymarc import MARCReader, MARCWriter, XMLWriter, Record, Field, RawField, constants
from pymarc.marc8 import marc8_to_unicode
from pymarc.exceptions import (BaseAddressInvalid,
RecordLeaderInvalid,
BaseAddressNotFound,
RecordDirectoryInvalid,
NoFieldsFound,
FieldNotFound,
RecordLengthInvalid)
from xml.sax import SAXParseException
from vocabularies import Vocabularies
import urllib.request
import shutil
import argparse
import datetime
import pickle
import copy
import os
import logging
import sys
import re
import csv
def decode_marc(self, marc, to_unicode=True, force_utf8=False,
hide_utf8_warnings=False, utf8_handling='strict',encoding = 'iso8859-1'):
"""
Monkey patched function from pymarc library: https://github.com/edsu/pymarc
pymarc assumes that control fields are numeric starting with '00'.
If some library system has unconventionally tagged control fields,
this patched code will prevent pymarc from changing the control field data
"""
"""
decode_marc() accepts a MARC record in transmission format as a
a string argument, and will populate the object based on the data
found. The Record constructor actually uses decode_marc() behind
the scenes when you pass in a chunk of MARC data to it.
"""
# extract record leader
self.leader = marc[0:constants.LEADER_LEN].decode('ascii')
if len(self.leader) != constants.LEADER_LEN:
raise RecordLeaderInvalid
if self.leader[9] == 'a' or self.force_utf8:
encoding = 'utf-8'
# extract the byte offset where the record data starts
base_address = int(marc[12:17])
if base_address <= 0:
raise BaseAddressNotFound
if base_address >= len(marc):
raise BaseAddressInvalid
# extract directory, base_address-1 is used since the
# director ends with an END_OF_FIELD byte
directory = marc[constants.LEADER_LEN:base_address-1].decode('ascii')
# determine the number of fields in record
if len(directory) % constants.DIRECTORY_ENTRY_LEN != 0:
raise RecordDirectoryInvalid
field_total = len(directory) / constants.DIRECTORY_ENTRY_LEN
# add fields to our record using directory offsets
field_count = 0
while field_count < field_total:
entry_start = field_count * constants.DIRECTORY_ENTRY_LEN
entry_end = entry_start + constants.DIRECTORY_ENTRY_LEN
entry = directory[entry_start:entry_end]
entry_tag = entry[0:3]
entry_length = int(entry[3:7])
entry_offset = int(entry[7:12])
entry_data = marc[base_address + entry_offset :
base_address + entry_offset + entry_length - 1]
# assume controlfields are numeric; replicates ruby-marc behavior
if entry_tag < '010' and entry_tag.isdigit():
if to_unicode:
field = Field(tag=entry_tag, data=entry_data.decode(encoding))
else:
field = RawField(tag=entry_tag, data=entry_data)
else:
subfields = list()
subs = entry_data.split(constants.SUBFIELD_INDICATOR.encode('ascii'))
# The MARC spec requires there to be two indicators in a
# field. However experience in the wild has shown that
# indicators are sometimes missing, and sometimes there
# are too many. Rather than throwing an exception because
# we can't find what we want and rejecting the field, or
# barfing on the whole record we'll try to use what we can
# find. This means missing indicators will be recorded as
# blank spaces, and any more than 2 are dropped on the floor.
first_indicator = second_indicator = ' '
subs[0] = subs[0].decode('ascii')
if len(subs[0]) == 0:
logging.warning("missing indicators: %s", entry_data)
first_indicator = second_indicator = ' '
elif len(subs[0]) == 1:
logging.warning("only 1 indicator found: %s", entry_data)
first_indicator = subs[0][0]
second_indicator = ' '
elif len(subs[0]) > 2:
logging.warning("more than 2 indicators found: %s", entry_data)
"""
patched code: if subfield indicators are not found,
leave subfield code empty:
"""
if len(subs) == 1:
if len(subs[0]) > 2:
subfields.append("")
subfields.append(subs[0][2:])
first_indicator = subs[0][0]
second_indicator = subs[0][1]
else:
first_indicator = subs[0][0]
second_indicator = subs[0][1]
for subfield in subs[1:]:
if len(subfield) == 0:
continue
code = subfield[0:1].decode('ascii')
data = subfield[1:]
if to_unicode:
if self.leader[9] == 'a' or force_utf8:
data = data.decode('utf-8', utf8_handling)
elif encoding == 'iso8859-1':
data = marc8_to_unicode(data, hide_utf8_warnings)
else:
data = data.decode(encoding)
subfields.append(code)
subfields.append(data)
if to_unicode:
field = Field(
tag = entry_tag,
indicators = [first_indicator, second_indicator],
subfields = subfields,
)
else:
field = RawField(
tag = entry_tag,
indicators = [first_indicator, second_indicator],
subfields = subfields,
)
self.add_field(field)
field_count += 1
if field_count == 0:
raise NoFieldsFound
def as_marc(self, encoding):
"""
Monkey patched function from pymarc library: https://github.com/edsu/pymarc
pymarc assumes that control fields are numeric starting with '00'.
If some library system has unconventionally tagged control fields,
this patched code will prevent pymarc from changing the control field data
If field does not have subfields, this patch prevents pymarc from writing
subfield indicators to it.
"""
"""
used during conversion of a field to raw marc
"""
if self.is_control_field():
return (self.data + constants.END_OF_FIELD).encode(encoding)
marc = self.indicator1 + self.indicator2
for subfield in self:
if not subfield[0]:
marc += subfield[1]
else:
marc += constants.SUBFIELD_INDICATOR + subfield[0] + subfield[1]
return (marc + constants.END_OF_FIELD).encode(encoding)
# alias for backwards compatibility
as_marc21 = as_marc
class YsoConverter():
def __init__(self, input_file, input_directory, output_file, output_directory, file_format, field_links=False, all_languages=False, write_all=False):
Field.as_marc = as_marc
Record.decode_marc = decode_marc
self.log_directory = "logs"
if not os.path.isdir(self.log_directory):
os.mkdir(self.log_directory)
if input_file:
if not os.path.isfile(input_file):
logging.warning("Lähdetiedostoa ei ole olemassa.")
sys.exit(2)
if input_directory:
if not os.path.isdir(input_directory):
logging.warning("Lähdehakemistoa ei ole olemassa.")
sys.exit(2)
if input_file or output_file:
if input_file == output_file:
logging.warning("Lähdetiedoston ja kohdetiedoston nimi on sama.")
sys.exit(2)
if input_directory or output_directory:
if input_directory == output_directory:
logging.warning("Lähdetiedoston ja kohdetiedoston tiedostopolku on sama.")
sys.exit(2)
if output_file:
if os.path.exists(output_file):
while True:
answer = input("Kirjoitettava tiedosto on olemassa. Kirjoitetaanko päälle (K/E)?")
if answer.lower() == "k":
break
if answer.lower() == "e":
sys.exit(2)
if output_directory:
if not os.path.isdir(output_directory):
os.makedirs(output_directory)
elif os.path.isdir(output_directory):
while True:
answer = input("Kirjoitettava tiedostopolku on olemassa. Kirjoitetaanko päälle (K/E)?")
if answer.lower() == "k":
break
if answer.lower() == "e":
sys.exit(2)
self.input_file = input_file
self.input_directory = input_directory
self.output_file = output_file
self.output_directory = output_directory
self.vocabularies = Vocabularies()
self.file_format = file_format.lower()
self.all_languages = False
if all_languages:
self.all_languages = True
self.field_links = False
if field_links:
self.field_links = True
self.delimiter = "|"
if all_languages == "yes":
self.all_languages = True
self.write_all = False
if write_all:
self.write_all = True
self.conversion_time = datetime.datetime.now().replace(microsecond=0).isoformat()
self.marcdate = str(datetime.date.today()).replace("-","")
self.conversion_name = "yso-konversio"
#korvataan kaksoispisteet Windows-tiedostonimeä varten:
time = self.conversion_time.replace(":", "")
self.error_log = self.conversion_name + "_error-log_" + time + ".csv"
self.removed_fields_log = self.conversion_name + "_removed-fields-log_" + time + ".csv"
self.new_fields_log = self.conversion_name + "_new-fields-log_" + time + ".csv"
self.remaining_log = self.conversion_name + "_remaining-log_" + time + ".csv"
self.results_log = self.conversion_name + "_results-log_" + time + ".log"
self.missing_uris_log = self.conversion_name + "_missing-uris-log_" + time + ".log"
self.error_log = os.path.join(self.log_directory, self.error_log)
self.removed_fields_log = os.path.join(self.log_directory, self.removed_fields_log)
self.new_fields_log = os.path.join(self.log_directory, self.new_fields_log)
self.remaining_log = os.path.join(self.log_directory, self.remaining_log)
self.results_log = os.path.join(self.log_directory, self.results_log)
self.missing_uris_log = os.path.join(self.log_directory, self.missing_uris_log)
logging.basicConfig(level=logging.INFO)
self.linking_number = None #käytetään musiikkiaineiston hajotettujen ketjujen yhdistämiseen 8-osakentällä
self.statistics = {}
self.statistics.update({"konvertoituja tietueita": 0})
self.statistics.update({"käsiteltyjä tietueita": 0})
self.statistics.update({"käsiteltyjä kenttiä": 0})
self.statistics.update({"kaikki tarkistetut kentät": 0})
self.statistics.update({"poistettuja kenttiä": 0})
self.statistics.update({"uusia kenttiä": 0})
self.statistics.update({"MARC21-virheitä": 0})
self.statistics.update({"virheluokkia": {}})
#ladattavien sanastojen sijainti:
self.data_url = "http://api.finto.fi/download/"
#ladattavien sanastojen kansio- ja tiedostonimi:
def initialize_vocabularies(self):
"""
Ladataan sanastot vocabularies.pkl-väliaikaistiedostosta.
Jos tiedostoa ei löydy, sanastot ladataan Finto-rajapinnasta.
Musa-sanasto ladataan aina paikallisesta static_vocabularies-kansiosta
(Musaan tehty pari muutosta verrattuna)
"""
vocabulary_files = {
"yso": "yso-skos.ttl",
"yso-paikat": "yso-paikat-skos.ttl",
"ysa": "ysa-skos.ttl",
"allars": "allars-skos.ttl",
"slm": "slm-skos.ttl",
"seko": "seko-skos.ttl"
}
#työhakemistossa olevien varatiedostojen sijainnit, jos verkkosanastoissa on vikaa:
static_vocabulary_directory = "static_vocabularies"
static_vocabulary_files = {
"yso": "static-yso-skos.ttl",
"yso-paikat": "static-yso-paikat-skos.ttl",
"ysa": "static-ysa-skos.ttl",
"allars": "static-allars-skos.ttl",
"slm": "static-slm-skos.ttl",
"musa": "static-musa-skos.ttl",
"cilla": "static-musa-skos.ttl",
"seko": "static-seko-skos.ttl"
}
#HUOM! Cillalla ei ole omaa tiedostoa:
vocabulary_names = ['ysa', 'yso', 'yso-paikat', 'allars', 'slm', 'musa', 'cilla', 'seko']
vocabularies_dump_loaded = False
if os.path.isfile('vocabularies.pkl'):
timestamp = os.path.getmtime('vocabularies.pkl')
file_date = datetime.date.fromtimestamp(timestamp)
if file_date == datetime.date.today():
with open('vocabularies.pkl', 'rb') as input_file:
try:
self.vocabularies = pickle.load(input_file)
vocabularies_dump_loaded = True
except EOFError:
vocabularies_dump_loaded = False
for vn in vocabulary_names:
if vn not in self.vocabularies.vocabularies:
#jos kaikki sanastot eivät löydy dumpista, sanastot on käsiteltävä uudelleen:
vocabularies_dump_loaded = False
if not vocabularies_dump_loaded:
urllib_errors = False
for vf in vocabulary_files:
try:
with urllib.request.urlopen(self.data_url + "/" + vf + "/" + vocabulary_files[vf]) as turtle, \
open(vocabulary_files[vf], 'wb') as out_file:
shutil.copyfileobj(turtle, out_file)
except urllib.error.URLError as e:
logging.warning("Ei onnistuttu lataamaan sanastoa %s"%vf)
urllib_errors = True
if urllib_errors:
while True:
answer = input("Kaikkia sanastoja ei onnistuttu lataamaan. Haluatko käyttää mahdollisesti vanhentuneita sanastoja paikalliselta levyltä (K/E)?")
if answer.lower() == "k":
break
if answer.lower() == "e":
sys.exit(2)
graphs = {}
#lisätään tässä vaiheessa Musa paikallisesta kansiosta:
musa_path = os.path.join(static_vocabulary_directory, static_vocabulary_files['musa'])
vocabulary_files['musa'] = musa_path
for vf in vocabulary_files:
g = Graph()
graphs.update({vf: g})
try:
logging.info("parsitaan sanastoa %s"%vf)
g.parse(vocabulary_files[vf], format='ttl')
except FileNotFoundError:
logging.error("Tiedostoa %s ei löytynyt levyltä. "
"Tiedoston automaattinen lataaminen ei ole onnistunut tai tiedosto on poistettu. "
"Siirrä sanastotiedosto ohjelman kansioon tai"
"käy hakemassa kaikki tarvittavat sanastot 'ysa', 'yso', 'yso-paikat', 'allars', 'slm', 'musa', 'cilla', 'seko' "
"ja tallenna ne ohjelman kansioon"
"osoitteesta finto.fi ttl-tiedostomuodossa"%vocabulary_files[vf])
sys.exit(2)
logging.info("valmistellaan sanastot konversiokäyttöä varten")
for vocabulary_name in vocabulary_names:
self.vocabularies.parse_vocabulary(vocabulary_name, graphs)
missing_relations = self.vocabularies.get_missing_relations(['ysa', 'allars', 'musa', 'cilla'], ['yso', 'yso-paikat'])
if any(len(mr) > 0 for mr in missing_relations):
faulty_vocabularies = []
for voc in missing_relations[0]:
fault_number = len(missing_relations[0][voc]) / len(self.vocabularies.vocabularies[voc].labels)
if fault_number > 0.05:
logging.warning('Sanaston %s käsitteistä puuttuu vastineita YSOsta: '%voc + '{:.1%}'.format(fault_number))
faulty_vocabularies.append(voc)
if any(len(voc) > 0 for voc in missing_relations[1]):
faulty_vocabularies.extend(['yso', 'yso-paikat'])
logging.warning("YSO- tai YSO-paikoista ei löydy vastinetta kaikille konvertoitaville käsitteille")
logging.warning("Viallisten YSO-käsitteiden lista on luettavissa tiedostossa %s"%self.missing_uris_log)
with open(self.missing_uris_log, 'w', encoding='utf-8') as output:
for voc in missing_relations[1]:
if len( missing_relations[1][voc]) > 0:
output.write("Näillä sanaston %s linkeillä ei ole vastinetta YSOssa:\n"%voc)
for label in missing_relations[1][voc]:
output.write(label + " " + missing_relations[1][voc][label] + "\n")
output.close()
if faulty_vocabularies:
logging.warning("Korvataan puutteelliset sanastot vuoden 2019 static-alkuisilla sanastoilla" )
while True:
answer = input("1. Jatka ohjelman suoritusta tämän päivän sanastoilla vai 2. Suorita konversio työhakemiston vanhoilla static-alkuisilla sanastoilla (1/2)?")
if answer.lower() == "1":
break
if answer.lower() == "2":
for fv in faulty_vocabularies:
g = Graph()
graphs.update({fv: g})
try:
logging.info("parsitaan uudestaan sanastoa %s"%fv)
path = os.path.join(static_vocabulary_directory, static_vocabulary_files[fv])
g.parse(path, format='ttl')
except FileNotFoundError:
logging.error("Tiedostoa %s ei löytynyt levyltä. "
"Korvaavan tiedoston lataaminen ei ole onnistunut tai tiedosto on poistettu. "
"Hae static-alkuinen tiedosto projektin GitHub-repositoriosta "
"ja tallenna ne ohjelman kansioon")
sys.exit(2)
for fv in faulty_vocabularies:
self.vocabularies.parse_vocabulary(fv, graphs)
break
with open('vocabularies.pkl', 'wb') as output: # Overwrites any existing file.
pickle.dump(self.vocabularies, output, pickle.HIGHEST_PROTOCOL)
logging.info("sanastot tallennettu muistiin ja tiedostoon vocabularies.pkl")
output.close()
def read_records(self):
with open(self.removed_fields_log, 'w', newline='', encoding = 'utf-8-sig') as rf_handler, \
open(self.new_fields_log, 'w', newline='', encoding = 'utf-8-sig') as nf_handler, \
open(self.error_log, 'w', newline='', encoding='utf-8-sig') as error_handler, \
open(self.remaining_log , 'w', newline='', encoding='utf-8-sig') as r_handler:
self.rf_writer = csv.writer(rf_handler, delimiter=self.delimiter, quotechar='"', quoting=csv.QUOTE_MINIMAL)
self.nf_writer = csv.writer(nf_handler, delimiter=self.delimiter, quotechar='"', quoting=csv.QUOTE_MINIMAL)
self.error_writer = csv.writer(error_handler, delimiter=self.delimiter, quotechar='"', quoting=csv.QUOTE_MINIMAL)
self.remaining_writer = csv.writer(r_handler, delimiter=self.delimiter, quotechar='"', quoting=csv.QUOTE_MINIMAL)
input_files = []
o_directory = ""
i_directory = ""
if self.input_directory:
input_files = os.listdir(self.input_directory)
elif self.input_file:
input_files.append(self.input_file)
if self.file_format == "marcxml":
if self.output_file:
self.open_writer(XMLWriter, self.output_file)
for i_file in input_files:
if self.output_directory:
self.output_file = i_file
self.output_path = os.path.join(self.output_directory, self.output_file)
else:
self.output_path = self.output_file
if self.input_directory:
input_path = os.path.join(self.input_directory, i_file)
else:
input_path = i_file
try:
pymarc.map_xml(self.read_and_write_record, input_path)
except SAXParseException as e:
logging.warning("XML-rakenne viallinen")
logging.warning(e)
if not self.output_directory and self.input_directory:
continue
if not self.output_directory:
self.writer.close()
if self.file_format == "marc21":
if not self.output_directory and self.input_directory:
self.open_writer(MARCWriter, self.output_file)
for i_file in input_files:
if self.output_directory:
self.output_file = i_file
self.output_path = os.path.join(self.output_directory, self.output_file)
else:
self.output_path = self.output_file
if self.input_directory:
input_path = os.path.join(self.input_directory, i_file)
else:
input_path = i_file
if not self.output_directory and self.input_directory:
pass
else:
self.open_writer(MARCWriter, self.output_path)
try:
reader = MARCReader(open(input_path, 'rb'), to_unicode=True)
except TypeError as e:
logging.error("Tiedosto %s ei ole MARC21-muodossa"%input_path)
sys.exit(2)
record = Record()
while record:
try:
record = next(reader, None)
if record:
self.read_and_write_record(record)
except (BaseAddressInvalid,
RecordLeaderInvalid,
BaseAddressNotFound,
RecordDirectoryInvalid,
NoFieldsFound,
UnicodeDecodeError,
ValueError,
RecordLengthInvalid) as e:
if e.__class__.__name__ in self.statistics["virheluokkia"]:
self.statistics["virheluokkia"][e.__class__.__name__] += 1
else:
self.statistics["virheluokkia"].update({e.__class__.__name__: 1})
self.statistics['MARC21-virheitä'] += 1
reader.close()
if not self.output_directory and self.input_directory:
continue
self.writer.close()
if not self.output_directory and self.input_directory:
self.writer.close()
rf_handler.close()
nf_handler.close()
error_handler.close()
r_handler.close()
with open(self.results_log, 'w', encoding = 'utf-8-sig') as result_handler:
self.statistics["käsiteltyjä kenttiä"] = \
self.statistics["poistettuja kenttiä"] + \
self.statistics["uusia kenttiä"]
for stat in self.statistics:
if stat == "virheluokkia":
result_handler.write("Virhetilastot: \n")
for e in self.statistics[stat]:
result_handler.write("Virhetyyppi: %s, määrä: %s \n"%(e, self.statistics[stat][e]))
else:
result_handler.write("%s: %s \n"%(stat, self.statistics[stat]))
result_handler.close()
logging.info("konversio tehty")
def read_and_write_record(self, record):
#tarkistetaan, löytääkö pymarc XML-muotoisesta tietueesta MARC21-virheitä:
if self.file_format == "marcxml":
new_record = None
try:
raw = record.as_marc()
new_record = Record(data=raw)
except (ValueError, IndexError) as e:
self.statistics['MARC21-virheitä'] += 1
new_record = self.process_record(record)
self.statistics['käsiteltyjä tietueita'] += 1
if new_record or self.write_all:
if self.file_format == "marcxml" and self.output_directory:
self.open_writer(XMLWriter, self.output_path)
if new_record:
try:
self.writer.write(new_record)
self.statistics['konvertoituja tietueita'] += 1
except (ValueError, IndexError) as e:
record_id = "tuntematon"
if record['001']:
record_id = record['001'].data
logging.error("Viallinen tietue id:%s"%record_id)
elif self.write_all:
try:
self.writer.write(record)
except (ValueError, IndexError) as e:
record_id = "tuntematon"
if record['001']:
record_id = record['001'].data
logging.error("Viallinen tietue id:%s"%record_id)
if self.file_format == "marcxml" and self.output_directory:
self.writer.close()
def open_writer(self, writer, path):
"""
apufunktio, joka avaa tiedostokirjoittimen ja luo hakemiston, jos sitä ei vielä ole olemassa
writer: MARCWriter- tai XMLWriter-luokka
path: tiedostopolku
"""
try:
self.writer = writer(open(path,'wb'))
except FileNotFoundError:
os.makedirs(os.path.dirname(path))
self.writer = writer(open(path,'wb'))
def subfields_to_dict(self, subfields):
"""
muuntaa pymarc-kirjaston käyttämän osakenttälistan, jossa joka toinen alkio on osakenttäkoodi ja joka toinen osakenttä,
konversio-ohjelmalle helpommin käsiteltävään muotoon listaksi, jossa on avainarvopareja {osakenttäkoodi, osakenttä}
"""
subfields_list = []
#Testattava, jos subfields-listassa pariton määrä alkioita!
for idx in range(0, len(subfields), 2):
if idx + 1 < len(subfields):
subfields_list.append({"code": subfields[idx], "value": subfields[idx+1]})
return subfields_list
def remove_subfields(self, codes, subfields):
#apufunktio identtisten rivien poistamiseen, kun konvertoidut kentät ovat valmiina
trimmed_subfields = []
for subfield in self.subfields_to_dict(subfields):
if subfield['code'] not in codes:
trimmed_subfields.append({"code": subfield['code'], "value": subfield['value']})
return trimmed_subfields
def is_equal_field(self, first_subfields, second_subfields):
#apufunktio identtisten rivien poistamiseen, kun konvertoidut kentät ovat valmiina
first_subfields = self.sort_subfields(self.subfields_to_dict(first_subfields))
second_subfields = self.sort_subfields(self.subfields_to_dict(second_subfields))
return first_subfields == second_subfields
def similar_fields(self, ignored_codes, *fields):
"""
apufunktio, joka vertailee parametreinä annettuja MARC21-kenttiä ja testaa, ovatko ne kaikki identtisiä
ignored_codes: osakenttäkoodit, joita ei huomioida vertailussa
fields: vertailtavat MARC21-kentät
"""
field_subfields = []
for field in fields:
trimmed_subfields = []
for subfield in self.subfields_to_dict(field.subfields):
if subfield['code'] not in ignored_codes:
trimmed_subfields.append({"code": subfield['code'], "value": subfield['value']})
field_subfields.append(trimmed_subfields)
for m in range(len(field_subfields) - 1):
for n in range(m + 1, len(field_subfields)):
if field_subfields[m] != field_subfields[n]:
return False
return True
def get_record_code(self, non_fiction, record_type):
if record_type == "movie":
record_code = "e"
elif record_type == "music":
record_code = "m"
elif non_fiction:
record_code = "t"
elif not non_fiction:
record_code = "f"
return record_code
def process_record(self, record):
tags_of_fields_to_convert = ['385', '567', '648', '650', '651', '655']
tags_of_fields_to_process = ['257', '370', '382', '385', '386', '388', '567', '648', '650', '651', '653', '655']
original_fields = {}
new_fields = {}
altered_fields = set()
record_status = record.leader[5]
if record['001']:
record_id = record['001'].data
else:
record_id = "001 kenttä puuttuu"
#laitetaan lokitiedostoon konvertoinnin ulkopuolisista kentistä löytyneet konvertoitavat kentät:
for field in record.get_fields():
if field.tag not in tags_of_fields_to_convert and field.tag.isdigit():
if any (sf in ['musa', 'cilla', 'ysa', 'allars'] for sf in field.get_subfields("2")):
self.remaining_writer.writerow([record_id, field])
self.linking_number = None #käytetään musiikkiaineiston hajotettujen ketjujen yhdistämiseen 8-osakentällä
linking_numbers = [] #merkitään 8-osakenttien numerot, joita tietueessa on jo ennestään
if record_status == "d":
return
"""
KAUNOKIRJALLISUUS
leader/06 on a tai t JA leader/07 ei ole b, i eikä s ->
008/33 - Kirjallisuuslaji ei ole 0 eikä u (painetut ja e-kirjat)
leader/06 on i ->
008/30-31 - Kirjallisuuslaji on d, f tai p (äänikirjat)
"""
leader_type = record.leader[6]
record_type = None
non_fiction = True
control_field_genres = []
convertible_record = False
#moniviestin:
if leader_type == "o":
if record['006']:
if len(record['006'].data) > 16:
if record['006'].data[0] in ['a', 't']:
if record['006'].data[16] not in ['0', 'u', '|', 'e', 's', 'i']:
non_fiction = False
elif record['006'].data[0] == "i":
for char in ['d', 'f', 'p']:
if char in record['006'].data[13:15]:
non_fiction = False
if leader_type in ['a', 't']:
record_type = "text"
if record.leader[7] not in ['b', 'i', 's']:
"""
008 (BK) merkkipaikka 34 arvo on erittäin oleellinen ja paljon käytetty
a, niin 655 $a kenttään voidaan tallettaa muistelmat http://urn.fi/URN:NBN:fi:au:slm:s286
b tai c niin 655 $a kenttään elämäkerrat http://urn.fi/URN:NBN:fi:au:slm:s1006
008 (BK) merkkipaikka 33 samaten
d - näytelmät http://urn.fi/URN:NBN:fi:au:slm:s929
f - romaanit http://urn.fi/URN:NBN:fi:au:slm:s518
h - huumori http://urn.fi/URN:NBN:fi:au:slm:s1128
j - novellit http://urn.fi/URN:NBN:fi:au:slm:s27
p - runot http://urn.fi/URN:NBN:fi:au:slm:s1150
s - puheet http://urn.fi/URN:NBN:fi:au:slm:s775 tai esitelmät http://urn.fi/URN:NBN:fi:au:slm:s313
"""
if record['008']:
if len(record['008'].data) > 34:
if record['008'].data[33] not in ['0', 'u', '|', 'e', 's', 'i']:
non_fiction = False
elif leader_type == "i":
record_type = "text"
if record['008']:
if len(record['008'].data) > 31:
for char in ['d', 'f', 'p']:
if char in record['008'].data[30:32]:
non_fiction = False
elif leader_type == "m":
#Konsolipelien tunnistaminen
#Leader/06 on m JA kenttä 008/26 on g (eli peli)
if record['008']:
if len(record['008'].data) > 33:
if record['008'].data[26] == "g":
non_fiction = False
elif leader_type == "r":
#Lautapelien tunnistaminen
#leader/06 on r JA 008/33 on g
if record['008']:
if len(record['008'].data) > 33:
if record['008'].data[33] == "g":
non_fiction = False
elif leader_type in ['c', 'd', 'j']:
record_type = "music"
non_fiction = False
elif leader_type == "g":
if record['007']:
if len(record['007'].data) > 0:
if record['007'].data[0] == "v":
record_type = "movie"
non_fiction = False
for field in record.get_fields('084'):
for subfield in field.get_subfields('a'):
if subfield.startswith("78"):
record_type = "music"
if not record_type:
record_type = "text"
if record['567']:
convertible_record = True
for tag in tags_of_fields_to_convert:
for field in record.get_fields(tag):
self.statistics["kaikki tarkistetut kentät"] += 1
if any (sf in ['musa', 'cilla', 'ysa', 'allars'] for sf in field.get_subfields("2")):
convertible_record = True
if convertible_record:
"""
Jos käynnistysparametri field_links annetu,
tarkistetaan elokuva- ja musiikkitietueessa aiemmin esiintyvät 8-osakentät
mahdollisten uusien $8-osakenttien 1. numeroksi valitaan alkuperäisten 8-osakenttien viimeistä seuraava numero:
"""
if self.field_links:
if record_type in ['music', 'movie']:
for field in record.get_fields():
if hasattr(field, 'subfields'):
for subfield in self.subfields_to_dict(field.subfields):
if subfield['code'] == "8":
value = subfield['value']
if "\\" in value:
value = value.split("\\")[0]
if "." in value:
value = value.split(".")[0]
if value.isdigit():
linking_numbers.append(int(value))
linking_numbers = sorted(linking_numbers)
if linking_numbers:
self.linking_number = linking_numbers[len(linking_numbers) - 1]
else:
self.linking_number = 0
subfields = []
for tag in tags_of_fields_to_process:
for field in record.get_fields(tag):
converted_fields = []
vocabulary_code = None
if tag in tags_of_fields_to_convert:
for sf in field.get_subfields('2'):
#valitaan ensimmäinen vastaantuleva sanastokoodi:
if not vocabulary_code:
if sf == "ysa" or sf == "allars" or sf == "musa" or sf == "cilla":
vocabulary_code = sf
#567-kentistä käsitellään myös sanastokoodittomat:
if vocabulary_code or tag == "567":
converted_fields = self.process_field(record_id, field, vocabulary_code, non_fiction, record_type)
self.rf_writer.writerow([record_id, field])
self.statistics['poistettuja kenttiä'] += 1
"""
HUOM! Jos samannumeroiset kentät sisältävät vain poistettavia asiasanoja,
kentät pitää tulkita muuttuneeksi lisäämällä kenttänumero tässä
"""
altered_fields.add(tag)
if converted_fields:
for cf in converted_fields:
if len(cf.subfields) == 0:
self.error_writer.writerow(["8", record_id, self.get_record_code(non_fiction, record_type), "", field])
else:
altered_fields.add(cf.tag)
if cf.tag in new_fields:
new_fields[cf.tag].append(cf)
else:
new_fields.update({cf.tag: [cf]})
#jos kentällä on sanastokoodi, mutta mitään osakenttää ei konvertoitu, kenttä pudotetaan tässä pois:
if not converted_fields and not vocabulary_code:
if tag in original_fields:
original_fields[tag].append(field)
else:
original_fields.update({tag: [field]})
#järjestetään uudet ja alkuperäiset rivit:
for tag in altered_fields:
record.remove_fields(tag)
for tag in altered_fields:
original_fields_with_tag = []
new_fields_with_tag = []
if tag in original_fields:
original_fields_with_tag = original_fields[tag]
if tag in new_fields:
new_fields_with_tag = new_fields[tag]
sorted_fields = self.sort_fields(tag, original_fields_with_tag, new_fields_with_tag)
#poistetaan identtiset rivit:
removable_fields = set()
for m in range(len(sorted_fields)):
for n in range(m + 1, len(sorted_fields)):
if m not in removable_fields and n not in removable_fields:
if self.is_equal_field(sorted_fields[m].subfields, sorted_fields[n].subfields):
if sorted_fields[m].indicators == sorted_fields[n].indicators:
removable_fields.add(n)
if sorted_fields[m].indicators[1] == " " and not sorted_fields[n].indicators[1] == " ":
removable_fields.add(m)
if sorted_fields[n].indicators[1] == " " and not sorted_fields[m].indicators[1] == " ":
removable_fields.add(n)
elif self.sort_subfields(self.remove_subfields(['0'], sorted_fields[m].subfields)) == \
self.sort_subfields(self.remove_subfields(['0'], sorted_fields[n].subfields)):
if sorted_fields[m]['2'] and sorted_fields[m]['0']:
removable_fields.add(n)
elif sorted_fields[n]['2'] and sorted_fields[n]['0']:
removable_fields.add(m)
elif self.sort_subfields(self.remove_subfields(['9'], sorted_fields[m].subfields)) == \
self.sort_subfields(self.remove_subfields(['9'], sorted_fields[n].subfields)):
if sorted_fields[m]['9'] and not sorted_fields[n]['9']:
removable_fields.add(n)
if sorted_fields[n]['9'] and not sorted_fields[m]['9']:
removable_fields.add(m)
#poistetaan identtiset $8-osakentät ja yhdistellään $8-osakentät samaan kenttään:
for m in range(len(sorted_fields)):
linking_numbers_list = [] #tallentaan erilaiset $8-osakentät, jos on useampia muuten identtisiä kenttiä
if sorted_fields[m]['2']:
if sorted_fields[m]['2'] in ['yso/fin', 'yso/swe', 'slm/fin', 'slm/swe', 'seko'] and m not in removable_fields:
for n in range(m + 1, len(sorted_fields)):
if m not in removable_fields and n not in removable_fields:
m_subfields = self.subfields_to_dict(sorted_fields[m].subfields)
n_subfields = self.subfields_to_dict(sorted_fields[n].subfields)
if self.similar_fields(['8'], sorted_fields[m], sorted_fields[n]):
for subfield in m_subfields:
if subfield['code'] == "8":
if subfield['value'] not in linking_numbers_list:
linking_numbers_list.append(subfield['value'])
for subfield in n_subfields:
if subfield['code'] == "8":
if subfield['value'] not in linking_numbers_list:
linking_numbers_list.append(subfield['value'])
removable_fields.add(n)
if linking_numbers_list:
while (sorted_fields[m]['8']):
sorted_fields[m].delete_subfield('8')
for ln in linking_numbers_list:
sorted_fields[m].add_subfield('8', ln)
new_subfields = self.subfields_to_dict(sorted_fields[m].subfields)
#lajitellaan 8-osakentät kentän ensimmäisiksi osakentiksi:
if '8' in sorted_fields[m]:
temp_subfields = []
for ns in new_subfields:
if ns['code'] == "8":
temp_subfields.append(ns)
for ns in new_subfields:
if not ns['code'] == "8":
temp_subfields.append(ns)
new_subfields = temp_subfields
subfield_list = []
for ns in new_subfields:
subfield_list.extend([ns['code'], ns['value']])
new_field = Field(
tag = tag,
indicators = sorted_fields[m].indicators,
subfields = subfield_list
)
sorted_fields[m] = new_field
for idx in range(len(sorted_fields)):
if idx not in removable_fields:
is_new_field = False
if tag in original_fields:
if not any(str(sorted_fields[idx]) == str(field) for field in original_fields[tag]):
is_new_field = True
else:
is_new_field = True
if is_new_field:
self.nf_writer.writerow([record_id, \
self.get_record_code(non_fiction, record_type), \
str(sorted_fields[idx])])
self.statistics['uusia kenttiä'] += 1
record.add_ordered_field(sorted_fields[idx])
else:
return
return record
def process_field(self, record_id, field, vocabulary_code, non_fiction=True, record_type=None):
"""
record_id -- 001-kentästä poimittu tietue-id
field -- käsiteltävä kenttä MARC21-muodossa
vocabulary_code -- alkuperäisen tietueen 2-osakentästä otettu sanastokoodi
non_fiction -- määrittelee, onko tietueen aineisto tietokirjallisuutta
record_type -- aineistotyyppi joidenkin kenttien erikoiskäsittelyä varten, käyvät arvot: "text", "music", "movie"
"""
new_fields = []
tag = field.tag
subfields = self.subfields_to_dict(field.subfields)
#jos ei-numeerisia arvoja on enemmän kuin yksi, kyseessä on asiasanaketju:
non_digit_codes = []
#$6-osakentälliset kentät jätetään käsittelemättä, mutta poistetaan $2- ja $0-osakentät:
for subfield in field.get_subfields('6'):
new_field = self.strip_vocabulary_codes(field)
new_field.indicators[1] = "4"
self.error_writer.writerow(["9", record_id, self.get_record_code(non_fiction, record_type), subfield, field, new_field])
return [new_field]
for subfield in subfields:
if not subfield['code'].isdigit():
non_digit_codes.append(subfield['code'])
if len(non_digit_codes) > 1 and self.linking_number is not None and not field['8']:
#musiikin asiasanaketjuihin liitetään 8-osakenttä ja linkkinumero ellei sellaista ole ennestään:
self.linking_number += 1
#tallennetaan numeroilla koodatut osakentät, jotka liitetään jokaiseen uuteen kenttään, paitsi $0 ja $2:
control_subfield_codes = ['1', '3', '4', '5', '6', '7', '8', '9']
if tag == "567":
for sf in field.get_subfields('2'):
if sf not in ['ysa', 'allars']:
return
if field['b']:
control_subfield_codes.append('a')
elif field['a']:
if not any(subfield['code'] == "b" for subfield in subfields):
for subfield in subfields:
if subfield['code'] == "a":
subfield['code'] = "b"
control_subfields = {}
for csc in control_subfield_codes:
"""
HUOM! sanastokoodeja voi olla useampia, jos yksikin niistä ysa/allars,
tulee valituksi niistä ensimmäiseksi kentässä esiintyvä sanastokoodi
"""
if field[csc]:
for sf in field.get_subfields(csc):
if "<DROP>" in sf and csc == "9":
#jos kyseessä on ketju, <DROP>-merkityt jätetään pois:
if len(non_digit_codes) > 1:
continue
if csc in control_subfields:
try:
control_subfields[csc].append(sf)
except TypeError:
logging.info("type error "+str(sf))
else:
control_subfields.update({csc: [sf]})
#etsitään paikkaketjut ja muodostetaan niistä yksiosainen käsite:
#TODO: katsotaan mahdollisesti myös muita kuin maantieteellisiä termejä
if len(non_digit_codes) > 1:
if tag == "650" or tag == "651":
combined_subfields = []
while len(subfields) > 0:
if len(subfields) > 1:
if subfields[0]['code'] in ['a', 'b', 'c', 'd', 'v', 'x', 'y', 'z']:
first = subfields[0]['value']
if subfields[1]['code'] == "z":
second = subfields[1]['value']
combined_concept = first + " -- " + second
if combined_concept in \
self.vocabularies.vocabularies['ysa'].geographical_chained_labels | \
self.vocabularies.vocabularies['allars'].geographical_chained_labels:
combined_subfields.append({'code': subfields[0]['code'], 'value': combined_concept})
del subfields[0]
del subfields[0]
continue
combined_subfields.append({'code': subfields[0]['code'], 'value': subfields[0]['value']})
del subfields[0]
subfields = combined_subfields
#jos kaikki osakenttäkoodit ovat numeroita, tulostetaan kenttä sellaisenaan ilman 0- ja 2-osakenttiä:
if all(subfield['code'].isdigit() for subfield in subfields):
original_field = copy.deepcopy(field)
field = self.strip_vocabulary_codes(field)
field.indicators[1] = "4"
self.error_writer.writerow(["8", record_id, self.get_record_code(non_fiction, record_type), "", original_field, field])
return [field]
if tag in ['650', '655'] and record_type == "movie":
if len(non_digit_codes) > 1 and not field['8']:
linked = True
else:
linked = False
has_topics = True #alkuoletuksena on, että elokuvatietueen kentät tulkitaan aiheiksi
has_genre_terms = False #kentän loput termeistä tulkitaan tämän perusteella luomiseen liittyviksi
for subfield in subfields:
if subfield['code'] in ['a', 'x']:
if subfield['code'] == "a" and "elokuvat" in subfield['value']:
has_genre_terms = True
has_topics = False
if tag == "650" and subfield['value'] == "aiheet":
has_topics = True
self.error_writer.writerow(["6", record_id, self.get_record_code(non_fiction, record_type), subfield['value'], field])
else:
converted_fields = self.process_subfield(record_id, field, subfield, vocabulary_code, non_fiction, record_type, has_topics)
if converted_fields: