/
excel2xml.py
1896 lines (1604 loc) · 75.3 KB
/
excel2xml.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 dataclasses
import datetime
import difflib
import json
import os
import re
import uuid
import warnings
from operator import xor
from typing import Any, Iterable, Optional, Union
import pandas as pd
import regex
from lxml import etree
from lxml.builder import E
from knora.dsplib.models.helpers import BaseError, DateTimeStamp
from knora.dsplib.models.propertyelement import PropertyElement
from knora.dsplib.models.value import UriValue
from knora.dsplib.utils.shared import simplify_name, check_notna, validate_xml_against_schema
xml_namespace_map = {
None: "https://dasch.swiss/schema",
"xsi": "http://www.w3.org/2001/XMLSchema-instance"
}
def make_xsd_id_compatible(string: str) -> str:
"""
Make a string compatible with the constraints of xsd:ID, so that it can be used as "id" attribute of a <resource>
tag. An xsd:ID must not contain special characters, and it must be unique in the document.
This method replaces the illegal characters by "_" and appends a random component to the string to make it unique.
The string must contain at least one Unicode letter (matching the regex ``\\p{L}``), underscore, !, ?, or number,
but must not be "None", "<NA>", "N/A", or "-". Otherwise, a BaseError will be raised.
Args:
string: input string
Returns:
an xsd:ID based on the input string
"""
if not isinstance(string, str) or not check_notna(string):
raise BaseError(f"The input '{string}' cannot be transformed to an xsd:ID")
# if start of string is neither letter nor underscore, add an underscore
res = re.sub(r"^(?=[^A-Za-z_])", "_", string)
# add uuid
_uuid = uuid.uuid4()
res = f"{res}_{_uuid}"
# replace all illegal characters by underscore
res = re.sub(r"[^\d\w_\-.]", "_", res)
return res
def _derandomize_xsd_id(string: str, multiple_occurrences: bool = False) -> str:
"""
In some contexts, the random component of the output of make_xsd_id_compatible() is a hindrance, especially for
testing. This method removes the random part, but leaves the other modifications introduced by
make_xsd_id_compatible() in place. This method's behaviour is defined by the example in the "Examples" section.
Args:
string: the output of make_xsd_id_compatible()
multiple_occurrences: If true, string can be an entire XML document, and all occurrences will be removed
Returns:
the derandomized string
Examples:
>>> id_1 = make_xsd_id_compatible("Hello!")
>>> id_2 = make_xsd_id_compatible("Hello!")
>>> assert _derandomize_xsd_id(id_1) == _derandomize_xsd_id(id_2)
"""
if not isinstance(string, str) or not check_notna(string):
raise BaseError(f"The input '{string}' cannot be derandomized.")
uuid4_regex = r"[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}"
if multiple_occurrences:
return re.subn(uuid4_regex, "", string, flags=re.IGNORECASE)[0]
else:
return re.sub(uuid4_regex, "", string, re.IGNORECASE)
def find_date_in_string(string: str) -> Optional[str]:
"""
Checks if a string contains a date value (single date, or date range), and returns the first found date as
DSP-formatted string. Returns None if no date was found.
Notes:
- All dates are interpreted in the Christian era and the Gregorian calendar. There is no support for BC dates or
non-Gregorian calendars.
- The years 0000-2999 are supported, in 4-digit form.
- Dates written with slashes are always interpreted in a European manner: 5/11/2021 is the 5th of November.
Currently supported date formats:
- 0476-09-04 -> GREGORIAN:CE:0476-09-04:CE:0476-09-04
- 0476_09_04 -> GREGORIAN:CE:0476-09-04:CE:0476-09-04
- 30.4.2021 -> GREGORIAN:CE:2021-04-30:CE:2021-04-30
- 5/11/2021 -> GREGORIAN:CE:2021-11-05:CE:2021-11-05
- Jan 26, 1993 -> GREGORIAN:CE:1993-01-26:CE:1993-01-26
- February26,2051 -> GREGORIAN:CE:2051-02-26:CE:2051-02-26
- 28.2.-1.12.1515 --> GREGORIAN:CE:1515-02-28:CE:1515-12-01
- 25.-26.2.0800 --> GREGORIAN:CE:0800-02-25:CE:0800-02-26
- 1.9.2022-3.1.2024 --> GREGORIAN:CE:2022-09-01:CE:2024-01-03
- 1848 -> GREGORIAN:CE:1848:CE:1848
- 1849/1850 -> GREGORIAN:CE:1849:CE:1850
- 1849/50 -> GREGORIAN:CE:1849:CE:1850
- 1845-50 -> GREGORIAN:CE:1845:CE:1850
Args:
string: string to check
Returns:
DSP-formatted date string, or None
Examples:
>>> if find_date_in_string(row["Epoch"]):
>>> resource.append(make_date_prop(":hasDate", find_date_in_string(row["Epoch"]))
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#date-prop
"""
# sanitize input, just in case that the method was called on an empty or N/A cell
if not check_notna(string):
return None
string = str(string)
monthes_dict = {
"January": 1,
"Jan": 1,
"February": 2,
"Feb": 2,
"March": 3,
"Mar": 3,
"April": 4,
"Apr": 4,
"May": 5,
"June": 6,
"Jun": 6,
"July": 7,
"Jul": 7,
"August": 8,
"Aug": 8,
"September": 9,
"Sept": 9,
"October": 10,
"Oct": 10,
"November": 11,
"Nov": 11,
"December": 12,
"Dec": 12,
}
startdate: Optional[datetime.date] = None
enddate: Optional[datetime.date] = None
startyear: Optional[int] = None
endyear: Optional[int] = None
year_regex = r"([0-2][0-9][0-9][0-9])"
month_regex = r"([0-1]?[0-9])"
day_regex = r"([0-3]?[0-9])"
sep_regex = r"[\./]"
lookbehind = r"(?<![0-9A-Za-z])"
lookahead = r"(?![0-9A-Za-z])"
# template: 2021-01-01 | 2015_01_02
iso_date = re.search(fr"{lookbehind}{year_regex}[_-]([0-1][0-9])[_-]([0-3][0-9]){lookahead}", string)
# template: 6.-8.3.1948 | 6/2/1947 - 24.03.1948
eur_date_range = re.search(fr"{lookbehind}{day_regex}{sep_regex}(?:{month_regex}{sep_regex}{year_regex}?)? ?(?:-|:|to) ?"
fr"{day_regex}{sep_regex}{month_regex}{sep_regex}{year_regex}{lookahead}", string)
# template: 1.4.2021 | 5/11/2021
eur_date = re.search(fr"{lookbehind}{day_regex}{sep_regex}{month_regex}{sep_regex}{year_regex}{lookahead}", string)
# template: March 9, 1908 | March5,1908 | May 11, 1906
monthname_date = re.search(
fr"{lookbehind}(January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|July|Jul|August|Aug|September|Sept|"
fr"October|Oct|November|Nov|December|Dec) ?{day_regex}, ?{year_regex}{lookahead}", string)
# template: 1849/50 | 1849-50 | 1849/1850
year_range = re.search(lookbehind + year_regex + r"[/-](\d{2}|\d{4})" +lookahead, string)
# template: 1907
year_only = re.search(fr"{lookbehind}{year_regex}{lookahead}", string)
if iso_date:
year = int(iso_date.group(1))
month = int(iso_date.group(2))
day = int(iso_date.group(3))
try:
startdate = datetime.date(year, month, day)
enddate = startdate
except ValueError:
return None
elif eur_date_range:
startday = int(eur_date_range.group(1))
startmonth = int(eur_date_range.group(2)) if eur_date_range.group(2) else int(eur_date_range.group(5))
startyear = int(eur_date_range.group(3)) if eur_date_range.group(3) else int(eur_date_range.group(6))
endday = int(eur_date_range.group(4))
endmonth = int(eur_date_range.group(5))
endyear = int(eur_date_range.group(6))
try:
startdate = datetime.date(startyear, startmonth, startday)
enddate = datetime.date(endyear, endmonth, endday)
if enddate < startdate:
raise ValueError
except ValueError:
return None
elif eur_date:
startday = int(eur_date.group(1))
startmonth = int(eur_date.group(2))
startyear = int(eur_date.group(3))
try:
startdate = datetime.date(startyear, startmonth, startday)
enddate = startdate
except ValueError:
return None
elif monthname_date:
day = int(monthname_date.group(2))
month = monthes_dict[monthname_date.group(1)]
year = int(monthname_date.group(3))
try:
startdate = datetime.date(year, month, day)
enddate = startdate
except ValueError:
return None
elif year_range:
startyear = int(year_range.group(1))
endyear = int(year_range.group(2))
if int(endyear/100) == 0:
# endyear is only 2-digit: add the first two digits of startyear
endyear = int(startyear/100) * 100 + endyear
elif year_only:
startyear = int(year_only.group(0))
endyear = startyear
if startdate and enddate:
return f"GREGORIAN:CE:{startdate.isoformat()}:CE:{enddate.isoformat()}"
elif startyear and endyear:
return f"GREGORIAN:CE:{startyear}:CE:{endyear}"
else:
return None
def prepare_value(
value: Union[PropertyElement, str, int, float, bool, Iterable[Union[PropertyElement, str, int, float, bool]]]
) -> list[PropertyElement]:
"""
This method transforms the parameter "value" from a make_*_prop() method into a list of PropertyElements. "value" is
passed on to this method as it was received.
Args:
value: "value" as received from the caller
Returns:
a list of PropertyElements
"""
# make sure that "value" is list-like
if not isinstance(value, Iterable) or isinstance(value, str):
value = [value]
# make a PropertyElement out of its elements, if necessary.
return [x if isinstance(x, PropertyElement) else PropertyElement(x) for x in value]
def make_root(shortcode: str, default_ontology: str) -> etree._Element:
"""
Start building your XML document by creating the root element <knora>.
Args:
shortcode: The shortcode of this project as defined in the JSON project file
default ontology: one of the ontologies of the JSON project file
Returns:
The root element <knora>.
Examples:
>>> root = make_root(shortcode=shortcode, default_ontology=default_ontology)
>>> root = append_permissions(root)
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#the-root-element-knora
"""
root = etree.Element(
_tag="{%s}knora" % (xml_namespace_map[None]),
attrib={
str(etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")):
"https://dasch.swiss/schema " + \
"https://raw.githubusercontent.com/dasch-swiss/dsp-tools/main/knora/dsplib/schemas/data.xsd",
"shortcode": shortcode,
"default-ontology": default_ontology
},
nsmap=xml_namespace_map
)
return root
def append_permissions(root_element: etree.Element) -> etree._Element:
"""
After having created a root element, call this method to append the four permissions "res-default",
"res-restricted", "prop-default", and "prop-restricted" to it. These four permissions are a good basis to
start with, but remember that they can be adapted, and that other permissions can be defined instead of these.
Args:
root_element: The XML root element <knora> created by make_root()
Returns:
The root element with the four permission blocks appended
Examples:
>>> root = make_root(shortcode=shortcode, default_ontology=default_ontology)
>>> root = append_permissions(root)
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#describing-permissions-with-permissions-elements
"""
PERMISSIONS = E.permissions
ALLOW = E.allow
# lxml.builder.E is a more sophisticated element factory than etree.Element.
# E.tag is equivalent to E("tag") and results in <tag>
res_default = etree.Element("{%s}permissions" % (xml_namespace_map[None]), id="res-default")
res_default.append(ALLOW("V", group="UnknownUser"))
res_default.append(ALLOW("V", group="KnownUser"))
res_default.append(ALLOW("D", group="ProjectMember"))
res_default.append(ALLOW("CR", group="ProjectAdmin"))
res_default.append(ALLOW("CR", group="Creator"))
root_element.append(res_default)
res_restricted = PERMISSIONS(id="res-restricted")
res_restricted.append(ALLOW("M", group="ProjectMember"))
res_restricted.append(ALLOW("CR", group="ProjectAdmin"))
res_restricted.append(ALLOW("CR", group="Creator"))
root_element.append(res_restricted)
prop_default = PERMISSIONS(id="prop-default")
prop_default.append(ALLOW("V", group="UnknownUser"))
prop_default.append(ALLOW("V", group="KnownUser"))
prop_default.append(ALLOW("D", group="ProjectMember"))
prop_default.append(ALLOW("CR", group="ProjectAdmin"))
prop_default.append(ALLOW("CR", group="Creator"))
root_element.append(prop_default)
prop_restricted = PERMISSIONS(id="prop-restricted")
prop_restricted.append(ALLOW("M", group="ProjectMember"))
prop_restricted.append(ALLOW("CR", group="ProjectAdmin"))
prop_restricted.append(ALLOW("CR", group="Creator"))
root_element.append(prop_restricted)
return root_element
def make_resource(
label: str,
restype: str,
id: str,
permissions: str = "res-default",
ark: Optional[str] = None,
iri: Optional[str] = None,
creation_date: Optional[str] = None
) -> etree._Element:
"""
Creates an empty resource element, with the attributes as specified by the arguments
Args:
The arguments correspond to the attributes of the <resource> element.
Returns:
The resource element, without any children, but with the attributes
``<resource label=label restype=restype id=id permissions=permissions ark=ark iri=iri></resource>``
Examples:
>>> resource = make_resource(...)
>>> resource.append(make_text_prop(...))
>>> root.append(resource)
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#describing-resources-with-the-resource-element
"""
kwargs = {
"label": label,
"restype": restype,
"id": id,
"permissions": permissions,
"nsmap": xml_namespace_map
}
if ark:
kwargs["ark"] = ark
if iri:
kwargs["iri"] = iri
if ark and iri:
warnings.warn(f"Both ARK and IRI were provided for resource '{label}' ({id}). The ARK will override the IRI.",
stacklevel=2)
if creation_date:
try:
DateTimeStamp(creation_date)
except BaseError:
raise BaseError(f"The resource '{label}' (ID: {id}) has an invalid creation date '{creation_date}'. Did "
f"you perhaps forget the timezone?")
kwargs["creation_date"] = creation_date
resource_ = etree.Element(
"{%s}resource" % (xml_namespace_map[None]),
**kwargs
)
return resource_
def make_bitstream_prop(
path: str,
permissions: str = "prop-default",
calling_resource: str = ""
) -> etree._Element:
"""
Creates a bitstream element that points to "path". If "path" doesn't point to a valid file, a warning will be
printed to the console, but the script will continue.
Args:
path: path to a valid file that will be uploaded
permissions: permissions string
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> resource = make_resource(...)
>>> resource.append(make_bitstream_prop("data/images/tree.jpg"))
>>> root.append(resource)
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#bitstream
"""
if not os.path.isfile(path):
warnings.warn(f"Failed validation in bitstream tag of resource '{calling_resource}': The following path "
f"doesn't point to a file: {path}",
stacklevel=2)
prop_ = etree.Element("{%s}bitstream" % (xml_namespace_map[None]), permissions=permissions,
nsmap=xml_namespace_map)
prop_.text = path
return prop_
def _format_bool(unformatted: Union[bool, str, int], name: str, calling_resource: str) -> str:
if isinstance(unformatted, str):
unformatted = unformatted.lower()
if unformatted in (False, "false", "0", 0, "no"):
return "false"
elif unformatted in (True, "true", "1", 1, "yes"):
return "true"
else:
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{unformatted}' is not a valid boolean.")
def make_boolean_prop(
name: str,
value: Union[PropertyElement, str, int, bool],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <boolean-prop> from a boolean value. The value can be provided directly or inside a PropertyElement. The
following formats are supported:
- true: (True, "true", "True", "1", 1, "yes", "Yes")
- false: (False, "false", "False", "0", 0, "no", "No")
If the value is not a valid boolean, a BaseError will be raised.
Unless provided as PropertyElement, the permissions of the value default to "prop-default".
Args:
name: the name of this property as defined in the onto
value: a boolean value as str/bool/int, or as str/bool/int inside a PropertyElement
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_boolean_prop(":testproperty", "no")
<boolean-prop name=":testproperty">
<boolean permissions="prop-default">false</boolean>
</boolean-prop>
>>> make_boolean_prop(":testproperty", PropertyElement("1", permissions="prop-restricted", comment="example"))
<boolean-prop name=":testproperty">
<boolean permissions="prop-restricted" comment="example">true</boolean>
</boolean-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#boolean-prop
"""
# validate input
if isinstance(value, PropertyElement):
value_new = dataclasses.replace(value, value=_format_bool(value.value, name, calling_resource))
elif isinstance(value, str) or isinstance(value, bool) or isinstance(value, int):
value_new = PropertyElement(_format_bool(value, name, calling_resource))
else:
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{value}' is not a valid boolean.")
# make xml structure of the value
prop_ = etree.Element(
"{%s}boolean-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
kwargs = {"permissions": value_new.permissions}
if check_notna(value_new.comment):
kwargs["comment"] = value_new.comment
value_ = etree.Element(
"{%s}boolean" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = value_new.value
prop_.append(value_)
return prop_
def make_color_prop(
name: str,
value: Union[PropertyElement, str, Iterable[Union[PropertyElement, str]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <color-prop> from one or more colors. The color(s) can be provided as string or as PropertyElement with a
string inside. If provided as string, the permissions default to "prop-default".
If the value is not a valid color, a BaseError will be raised.
Args:
name: the name of this property as defined in the onto
value: one or more DSP color(s), as string/PropertyElement, or as iterable of strings/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_color_prop(":testproperty", "#00ff66")
<color-prop name=":testproperty">
<color permissions="prop-default">#00ff66</color>
</color-prop>
>>> make_color_prop(":testproperty", PropertyElement("#00ff66", permissions="prop-restricted", comment="example"))
<color-prop name=":testproperty">
<color permissions="prop-restricted" comment="example">#00ff66</color>
</color-prop>
>>> make_color_prop(":testproperty", ["#00ff66", "#000000"])
<color-prop name=":testproperty">
<color permissions="prop-default">#00ff66</color>
<color permissions="prop-default">#000000</color>
</color-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#color-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
if not re.search(r"^#[0-9a-f]{6}$", str(val.value).strip(), flags=re.IGNORECASE):
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a valid color.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}color-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}
if check_notna(val.comment):
kwargs["comment"] = val.comment
value_ = etree.Element(
"{%s}color" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = str(val.value).strip()
prop_.append(value_)
return prop_
def make_date_prop(
name: str,
value: Union[PropertyElement, str, Iterable[Union[PropertyElement, str]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <date-prop> from one or more dates/date ranges. The date(s) can be provided as string or as PropertyElement
with a string inside. If provided as string, the permissions default to "prop-default".
If the value is not a valid DSP date, a BaseError will be raised.
Args:
name: the name of this property as defined in the onto
value: one or more DSP dates, as string/PropertyElement, or as iterable of strings/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_date_prop(":testproperty", "GREGORIAN:CE:2014-01-31")
<date-prop name=":testproperty">
<date permissions="prop-default">GREGORIAN:CE:2014-01-31</date>
</date-prop>
>>> make_date_prop(":testproperty", PropertyElement("GREGORIAN:CE:2014-01-31", permissions="prop-restricted", comment="example"))
<date-prop name=":testproperty">
<date permissions="prop-restricted" comment="example">
GREGORIAN:CE:2014-01-31
</date>
</date-prop>
>>> make_date_prop(":testproperty", ["GREGORIAN:CE:1930-09-02:CE:1930-09-03", "GREGORIAN:CE:1930-09-02:CE:1930-09-03"])
<date-prop name=":testproperty">
<date permissions="prop-default">
GREGORIAN:CE:1930-09-02:CE:1930-09-03
</date>
<date permissions="prop-default">
GREGORIAN:CE:1930-09-02:CE:1930-09-03
</date>
</date-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#date-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
if not re.search(r"^(GREGORIAN:|JULIAN:)?(CE:|BCE:)?(\d{4})(-\d{1,2})?(-\d{1,2})?"
r"((:CE|:BCE)?(:\d{4})(-\d{1,2})?(-\d{1,2})?)?$", str(val.value).strip()):
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a valid DSP date.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}date-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}
if check_notna(val.comment):
kwargs["comment"] = val.comment
value_ = etree.Element(
"{%s}date" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = str(val.value).strip()
prop_.append(value_)
return prop_
def make_decimal_prop(
name: str,
value: Union[PropertyElement, str, Iterable[Union[PropertyElement, str]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <decimal-prop> from one or more decimal numbers. The decimal(s) can be provided as string, float, or as
PropertyElement with a string/float inside. If provided as string/float, the permissions default to
"prop-default".
If the value is not a valid decimal number, a BaseError will be raised.
Args:
name: the name of this property as defined in the onto
value: one or more decimal numbers, as string/float/PropertyElement, or as iterable of strings/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_decimal_prop(":testproperty", "3.14159")
<decimal-prop name=":testproperty">
<decimal permissions="prop-default">3.14159</decimal>
</decimal-prop>
>>> make_decimal_prop(":testproperty", PropertyElement("3.14159", permissions="prop-restricted", comment="example"))
<decimal-prop name=":testproperty">
<decimal permissions="prop-restricted" comment="example">3.14159</decimal>
</decimal-prop>
>>> make_decimal_prop(":testproperty", ["3.14159", "2.718"])
<decimal-prop name=":testproperty">
<decimal permissions="prop-default">3.14159</decimal>
<decimal permissions="prop-default">2.718</decimal>
</decimal-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#decimal-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
try:
float(val.value)
except ValueError:
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a valid decimal number.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}decimal-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}
if check_notna(val.comment):
kwargs["comment"] = val.comment
value_ = etree.Element(
"{%s}decimal" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = str(float(val.value))
prop_.append(value_)
return prop_
def make_geometry_prop(
name: str,
value: Union[PropertyElement, str, Iterable[Union[PropertyElement, str]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <geometry-prop> from one or more areas of an image. The area(s) can be provided as JSON-string or as
PropertyElement with the JSON-string inside. If provided as string, the permissions default to "prop-default".
If the value is not a valid JSON geometry object, a BaseError is raised.
Args:
name: the name of this property as defined in the onto
value: one or more JSON geometry objects, as string/PropertyElement, or as iterable of strings/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_geometry_prop(":testproperty", json_string)
<geometry-prop name=":testproperty">
<geometry permissions="prop-default">{JSON}</geometry>
</geometry-prop>
>>> make_geometry_prop(":testproperty", PropertyElement(json_string, permissions="prop-restricted", comment="example"))
<geometry-prop name=":testproperty">
<geometry permissions="prop-restricted" comment="example">{JSON}</geometry>
</geometry-prop>
>>> make_geometry_prop(":testproperty", [json_string1, json_string2])
<geometry-prop name=":testproperty">
<geometry permissions="prop-default">{JSON}</geometry>
<geometry permissions="prop-default">{JSON}</geometry>
</geometry-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#geometry-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
try:
value_as_dict = json.loads(val.value)
assert value_as_dict["type"] in ["rectangle", "circle", "polygon"]
assert isinstance(value_as_dict["points"], list)
except (json.JSONDecodeError, TypeError, IndexError, KeyError, AssertionError):
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a valid JSON geometry object.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}geometry-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}
if check_notna(val.comment):
kwargs["comment"] = val.comment
value_ = etree.Element(
"{%s}geometry" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = str(val.value)
prop_.append(value_)
return prop_
def make_geoname_prop(
name: str,
value: Union[PropertyElement, str, int, Iterable[Union[PropertyElement, str, int]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <geoname-prop> from one or more geonames.org IDs. The ID(s) can be provided as string, integer, or as
PropertyElement with a string/integer inside. If provided as string/integer, the permissions default to
"prop-default".
If the value is not a valid geonames.org identifier, a BaseError will be raised.
Args:
name: the name of this property as defined in the onto
value: one or more geonames.org IDs, as string/int/PropertyElement, or as iterable of strings/ints/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_geoname_prop(":testproperty", "2761369")
<geoname-prop name=":testproperty">
<geoname permissions="prop-default">2761369</geoname>
</geoname-prop>
>>> make_geoname_prop(":testproperty", PropertyElement("2761369", permissions="prop-restricted", comment="example"))
<geoname-prop name=":testproperty">
<geoname permissions="prop-restricted" comment="example">2761369</geoname>
</geoname-prop>
>>> make_geoname_prop(":testproperty", ["2761369", "1010101"])
<geoname-prop name=":testproperty">
<geoname permissions="prop-default">2761369</geoname>
<geoname permissions="prop-default">1010101</geoname>
</geoname-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#geoname-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
if not re.search(r"^[0-9]+$", str(val.value)):
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a geonames.org identifier.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}geoname-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}
if check_notna(val.comment):
kwargs["comment"] = val.comment
value_ = etree.Element(
"{%s}geoname" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = str(val.value)
prop_.append(value_)
return prop_
def make_integer_prop(
name: str,
value: Union[PropertyElement, str, int, Iterable[Union[PropertyElement, str, int]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <integer-prop> from one or more integers. The integers can be provided as string, integer, or as
PropertyElement with a string/integer inside. If provided as string/integer, the permissions default to
"prop-default".
If the value is not a valid integer, a BaseError will be raised.
Args:
name: the name of this property as defined in the onto
value: one or more integers, as string/int/PropertyElement, or as iterable of strings/ints/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_integer_prop(":testproperty", "2761369")
<integer-prop name=":testproperty">
<integer permissions="prop-default">2761369</integer>
</integer-prop>
>>> make_integer_prop(":testproperty", PropertyElement("2761369", permissions="prop-restricted", comment="example"))
<integer-prop name=":testproperty">
<integer permissions="prop-restricted" comment="example">2761369</integer>
</integer-prop>
>>> make_integer_prop(":testproperty", ["2761369", "1010101"])
<integer-prop name=":testproperty">
<integer permissions="prop-default">2761369</integer>
<integer permissions="prop-default">1010101</integer>
</integer-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#integer-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
try:
int(val.value)
except ValueError:
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a valid integer.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}integer-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}
if check_notna(val.comment):
kwargs["comment"] = val.comment
value_ = etree.Element(
"{%s}integer" % (xml_namespace_map[None]),
**kwargs,
nsmap=xml_namespace_map
)
value_.text = str(int(val.value))
prop_.append(value_)
return prop_
def make_interval_prop(
name: str,
value: Union[PropertyElement, str, Iterable[Union[PropertyElement, str]]],
calling_resource: str = ""
) -> etree._Element:
"""
Make a <interval-prop> from one or more DSP intervals. The interval(s) can be provided as string or as
PropertyElement with a string inside. If provided as string, the permissions default to "prop-default".
If the value is not a valid DSP interval, a BaseError will be raised.
Args:
name: the name of this property as defined in the onto
value: one or more DSP intervals, as string/PropertyElement, or as iterable of strings/PropertyElements
calling_resource: the name of the parent resource (for better error messages)
Returns:
an etree._Element that can be appended to the parent resource with resource.append(make_*_prop(...))
Examples:
>>> make_interval_prop(":testproperty", "61:3600")
<interval-prop name=":testproperty">
<interval permissions="prop-default">61:3600</interval>
</interval-prop>
>>> make_interval_prop(":testproperty", PropertyElement("61:3600", permissions="prop-restricted", comment="example"))
<interval-prop name=":testproperty">
<interval permissions="prop-restricted" comment="example">61:3600</interval>
</interval-prop>
>>> make_interval_prop(":testproperty", ["61:3600", "60.5:120.5"])
<interval-prop name=":testproperty">
<interval permissions="prop-default">61:3600</interval>
<interval permissions="prop-default">60.5:120.5</interval>
</interval-prop>
See https://docs.dasch.swiss/latest/DSP-TOOLS/dsp-tools-xmlupload/#interval-prop
"""
# check the input: prepare a list with valid values
values = prepare_value(value)
# check value type
for val in values:
if not re.match(r"([+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)):([+-]?([0-9]+([.][0-9]*)?|[.][0-9]+))", str(val.value)):
raise BaseError(f"Failed validation in resource '{calling_resource}', property '{name}': "
f"'{val.value}' is not a valid DSP interval.")
# make xml structure of the valid values
prop_ = etree.Element(
"{%s}interval-prop" % (xml_namespace_map[None]),
name=name,
nsmap=xml_namespace_map
)
for val in values:
kwargs = {"permissions": val.permissions}