-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathparser_classes.py
1118 lines (937 loc) · 35.2 KB
/
parser_classes.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 calendar
import math
import re
from datetime import date, datetime
from operator import add, sub
from time import struct_time
from dateutil.relativedelta import relativedelta
from edtf import appsettings
from edtf.convert import (
TIME_EMPTY_EXTRAS,
TIME_EMPTY_TIME,
dt_to_struct_time,
trim_struct_time,
)
EARLIEST = "earliest"
LATEST = "latest"
PRECISION_MILLENIUM = "millenium"
PRECISION_CENTURY = "century"
PRECISION_DECADE = "decade"
PRECISION_YEAR = "year"
PRECISION_MONTH = "month"
PRECISION_SEASON = "season"
PRECISION_DAY = "day"
def days_in_month(year, month):
"""
Return the number of days in the given year and month, where month is
1=January to 12=December, and respecting leap years as identified by
`calendar.isleap()`
"""
return {
1: 31,
2: 29 if calendar.isleap(year) else 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}[month]
def apply_delta(op, time_struct, delta):
"""
Apply a `relativedelta` to a `struct_time` data structure.
`op` is an operator function, probably always `add` or `sub`tract to
correspond to `a_date + a_delta` and `a_date - a_delta`.
This function is required because we cannot use standard `datetime` module
objects for conversion when the date/time is, or will become, outside the
boundary years 1 AD to 9999 AD.
"""
if not delta:
return time_struct # No work to do
try:
dt_result = op(datetime(*time_struct[:6]), delta)
return dt_to_struct_time(dt_result)
except (OverflowError, ValueError):
# Year is not within supported 1 to 9999 AD range
pass
# Here we fake the year to one in the acceptable range to avoid having to
# write our own date rolling logic
# Adjust the year to be close to the 2000 millenium in 1,000 year
# increments to try and retain accurate relative leap years
actual_year = time_struct.tm_year
millenium = int(float(actual_year) / 1000)
millenium_diff = (2 - millenium) * 1000
adjusted_year = actual_year + millenium_diff
# Apply delta to the date/time with adjusted year
dt = datetime(*(adjusted_year,) + time_struct[1:6])
dt_result = op(dt, delta)
# Convert result year back to its original millenium
final_year = dt_result.year - millenium_diff
return struct_time(
(final_year,) + dt_result.timetuple()[1:6] + tuple(TIME_EMPTY_EXTRAS)
)
class EDTFObject:
"""
Object to attach to a parser to become instantiated when the parser
completes.
"""
parser = None
@classmethod
def set_parser(cls, p):
cls.parser = p
p.addParseAction(cls.parse_action)
@classmethod
def parse_action(cls, toks):
kwargs = toks.asDict()
try:
return cls(**kwargs) # replace the token list with the class
except Exception as e:
print(f"trying to {cls.__name__}.__init__(**{kwargs})")
raise e
@classmethod
def parse(cls, s):
return cls.parser.parseString(s)[0]
def __repr__(self):
return f"{type(self).__name__}: '{str(self)}'"
def __init__(self, *args, **kwargs):
str = f"{type(self).__name__}.__init__(*{args}, **{kwargs})"
raise NotImplementedError(f"{str} is not implemented.")
def __str__(self):
raise NotImplementedError
def _strict_date(self, lean):
raise NotImplementedError
def lower_strict(self):
return self._strict_date(lean=EARLIEST)
def upper_strict(self):
return self._strict_date(lean=LATEST)
def _get_fuzzy_padding(self, lean):
"""
Subclasses should override this to pad based on how precise they are.
"""
return relativedelta(0)
def get_is_approximate(self):
return getattr(self, "_is_approximate", False)
def set_is_approximate(self, val):
self._is_approximate = val
is_approximate = property(get_is_approximate, set_is_approximate)
def get_is_uncertain(self):
return getattr(self, "_is_uncertain", False)
def set_is_uncertain(self, val):
self._is_uncertain = val
is_uncertain = property(get_is_uncertain, set_is_uncertain)
def get_is_uncertain_and_approximate(self):
return getattr(self, "_uncertain_and_approximate", False)
def set_is_uncertain_and_approximate(self, val):
self._uncertain_and_approximate = val
is_uncertain_and_approximate = property(
get_is_uncertain_and_approximate, set_is_uncertain_and_approximate
)
def lower_fuzzy(self):
strict_val = self.lower_strict()
return apply_delta(sub, strict_val, self._get_fuzzy_padding(EARLIEST))
def upper_fuzzy(self):
strict_val = self.upper_strict()
return apply_delta(add, strict_val, self._get_fuzzy_padding(LATEST))
def __eq__(self, other):
if isinstance(other, EDTFObject):
return str(self) == str(other)
elif isinstance(other, date):
return str(self) == other.isoformat()
elif isinstance(other, struct_time):
return self._strict_date() == trim_struct_time(other)
return False
def __ne__(self, other):
if isinstance(other, EDTFObject):
return str(self) != str(other)
elif isinstance(other, date):
return str(self) != other.isoformat()
elif isinstance(other, struct_time):
return self._strict_date() != trim_struct_time(other)
return True
def __gt__(self, other):
if isinstance(other, EDTFObject):
return self.lower_strict() > other.lower_strict()
elif isinstance(other, date):
return self.lower_strict() > dt_to_struct_time(other)
elif isinstance(other, struct_time):
return self.lower_strict() > trim_struct_time(other)
raise TypeError(
f"can't compare {type(self).__name__} with {type(other).__name__}"
)
def __ge__(self, other):
if isinstance(other, EDTFObject):
return self.lower_strict() >= other.lower_strict()
elif isinstance(other, date):
return self.lower_strict() >= dt_to_struct_time(other)
elif isinstance(other, struct_time):
return self.lower_strict() >= trim_struct_time(other)
raise TypeError(
f"can't compare {type(self).__name__} with {type(other).__name__}"
)
def __lt__(self, other):
if isinstance(other, EDTFObject):
return self.lower_strict() < other.lower_strict()
elif isinstance(other, date):
return self.lower_strict() < dt_to_struct_time(other)
elif isinstance(other, struct_time):
return self.lower_strict() < trim_struct_time(other)
raise TypeError(
f"can't compare {type(self).__name__} with {type(other).__name__}"
)
def __le__(self, other):
if isinstance(other, EDTFObject):
return self.lower_strict() <= other.lower_strict()
elif isinstance(other, date):
return self.lower_strict() <= dt_to_struct_time(other)
elif isinstance(other, struct_time):
return self.lower_strict() <= trim_struct_time(other)
raise TypeError(
f"can't compare {type(self).__name__} with {type(other).__name__}"
)
# (* ************************** Level 0 *************************** *)
class Date(EDTFObject):
def set_year(self, y):
if y is None:
raise AttributeError("Year must not be None")
self._year = y
def get_year(self):
return self._year
year = property(get_year, set_year)
def set_month(self, m):
self._month = m
if m is None:
self.day = None
def get_month(self):
return self._month
month = property(get_month, set_month)
def __init__(
self, year=None, month=None, day=None, significant_digits=None, **kwargs
):
for param in ("date", "lower", "upper"):
if param in kwargs:
self.__init__(**kwargs[param])
return
self.year = year # Year is required, but sometimes passed in as a 'date' dict.
self.month = month
self.day = day
self.significant_digits = (
int(significant_digits) if significant_digits else None
)
def __str__(self):
r = self.year
if self.month:
r += f"-{self.month}"
if self.day:
r += f"-{self.day}"
if self.significant_digits:
r += f"S{self.significant_digits}"
return r
def isoformat(self, default=date.max):
return "%s-%02d-%02d" % (
self.year,
int(self.month or default.month),
int(self.day or default.day),
)
def lower_fuzzy(self):
if not hasattr(self, "significant_digits") or not self.significant_digits:
return apply_delta(
sub, self.lower_strict(), self._get_fuzzy_padding(EARLIEST)
)
else:
total_digits = len(self.year)
insignificant_digits = total_digits - self.significant_digits
lower_year = (
int(self.year)
// (10**insignificant_digits)
* (10**insignificant_digits)
)
return struct_time([lower_year, 1, 1] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS)
def upper_fuzzy(self):
if not hasattr(self, "significant_digits") or not self.significant_digits:
return apply_delta(
add, self.upper_strict(), self._get_fuzzy_padding(LATEST)
)
else:
total_digits = len(self.year)
insignificant_digits = total_digits - self.significant_digits
upper_year = (int(self.year) // (10**insignificant_digits) + 1) * (
10**insignificant_digits
) - 1
return struct_time(
[upper_year, 12, 31] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS
)
def _precise_year(self, lean):
# Replace any ambiguous characters in the year string with 0s or 9s
if lean == EARLIEST:
return int(re.sub(r"X", r"0", self.year))
else:
return int(re.sub(r"X", r"9", self.year))
def _precise_month(self, lean):
if self.month and self.month != "XX":
try:
return int(self.month)
except ValueError as err:
raise ValueError(
f"Couldn't convert {self.month} to int (in {self})"
) from err
else:
return 1 if lean == EARLIEST else 12
def _precise_day(self, lean):
if not self.day or self.day == "XX":
if lean == EARLIEST:
return 1
else:
return days_in_month(
self._precise_year(LATEST), self._precise_month(LATEST)
)
else:
return int(self.day)
def _strict_date(self, lean):
"""
Return a `time.struct_time` representation of the date.
"""
return struct_time(
(
self._precise_year(lean),
self._precise_month(lean),
self._precise_day(lean),
)
+ tuple(TIME_EMPTY_TIME)
+ tuple(TIME_EMPTY_EXTRAS)
)
@property
def precision(self):
if self.day:
return PRECISION_DAY
if self.month:
return PRECISION_MONTH
return PRECISION_YEAR
def estimated(self):
return self._precise_year(EARLIEST)
class DateAndTime(EDTFObject):
def __init__(self, date, time):
self.date = date
self.time = time
def __str__(self):
return self.isoformat()
def isoformat(self):
return self.date.isoformat() + "T" + self.time
def _strict_date(self, lean):
return self.date._strict_date(lean)
def __eq__(self, other):
if isinstance(other, datetime):
return self.isoformat() == other.isoformat()
elif isinstance(other, struct_time):
return self._strict_date() == trim_struct_time(other)
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, datetime):
return self.isoformat() != other.isoformat()
elif isinstance(other, struct_time):
return self._strict_date() != trim_struct_time(other)
return super().__ne__(other)
class Interval(EDTFObject):
def __init__(self, lower, upper):
self.lower = lower
self.upper = upper
def __str__(self):
return f"{self.lower}/{self.upper}"
def _strict_date(self, lean):
if lean == EARLIEST:
r = self.lower._strict_date(lean)
else:
r = self.upper._strict_date(lean)
return r
@property
def precision(self):
if self.lower.precision == self.upper.precision:
return self.lower.precision
return None
# (* ************************** Level 1 *************************** *)
class UA(EDTFObject):
@classmethod
def parse_action(cls, toks):
args = toks.asList()
return cls(*args)
def __init__(self, *args):
if len(args) != 1:
raise AssertionError("UA must have exactly one argument")
ua = args[0]
self.is_uncertain = "?" in ua
self.is_approximate = "~" in ua
self.is_uncertain_and_approximate = "%" in ua
def __str__(self):
d = ""
if self.is_uncertain:
d += "?"
if self.is_approximate:
d += "~"
if self.is_uncertain_and_approximate:
d += "%"
return d
def _get_multiplier(self):
if self.is_uncertain_and_approximate:
return appsettings.MULTIPLIER_IF_BOTH
elif self.is_uncertain:
return appsettings.MULTIPLIER_IF_UNCERTAIN
elif self.is_approximate:
return appsettings.MULTIPLIER_IF_APPROXIMATE
class UncertainOrApproximate(EDTFObject):
def __init__(self, date, ua):
self.date = date
self.ua = ua
self.is_uncertain = ua.is_uncertain if ua else False
self.is_approximate = ua.is_approximate if ua else False
self.is_uncertain_and_approximate = (
ua.is_uncertain_and_approximate if ua else False
)
def __str__(self):
if self.ua:
return f"{self.date}{self.ua}"
else:
return str(self.date)
def _strict_date(self, lean):
return self.date._strict_date(lean)
def _get_fuzzy_padding(self, lean):
if not self.ua:
return relativedelta()
multiplier = self.ua._get_multiplier()
padding = relativedelta()
# Check the presence of uncertainty on each component
# self.precision not helpful here:
# L1 qualified EDTF dates apply qualification across all parts of the date
if self.date.year:
padding += relativedelta(
years=int(multiplier * appsettings.PADDING_YEAR_PRECISION.years)
)
if self.date.month:
padding += relativedelta(
months=int(multiplier * appsettings.PADDING_MONTH_PRECISION.months)
)
if self.date.day:
padding += relativedelta(
days=int(multiplier * appsettings.PADDING_DAY_PRECISION.days)
)
return padding
class UnspecifiedIntervalSection(EDTFObject):
def __init__(self, sectionOpen=False, other_section_element=None):
if sectionOpen:
self.is_open = True
self.is_unknown = False
else:
self.is_open = False
self.is_unknown = True
self.other = other_section_element
def __str__(self):
if self.is_unknown:
return ""
else:
return ".."
def _strict_date(self, lean):
if lean == EARLIEST:
if self.is_unknown:
upper = self.other._strict_date(LATEST)
return apply_delta(sub, upper, appsettings.DELTA_IF_UNKNOWN)
else:
return -math.inf
else:
if self.is_unknown:
lower = self.other._strict_date(EARLIEST)
return apply_delta(add, lower, appsettings.DELTA_IF_UNKNOWN)
else:
return math.inf
@property
def precision(self):
return self.other.date.precision or PRECISION_YEAR
class Unspecified(Date):
def __init__(
self,
year=None,
month=None,
day=None,
significant_digits=None,
ua=None,
**kwargs,
):
super().__init__(
year=year,
month=month,
day=day,
significant_digits=significant_digits,
**kwargs,
)
self.ua = ua
self.is_uncertain = ua.is_uncertain if ua else False
self.is_approximate = ua.is_approximate if ua else False
self.is_uncertain_and_approximate = (
ua.is_uncertain_and_approximate if ua else False
)
self.negative = self.year.startswith("-")
def __str__(self):
base = super().__str__()
if self.ua:
base += str(self.ua)
return base
def _get_fuzzy_padding(self, lean):
if not self.ua:
return relativedelta()
multiplier = self.ua._get_multiplier()
padding = relativedelta()
if self.year:
years_padding = self._years_padding(multiplier)
padding += years_padding
if self.month:
padding += relativedelta(
months=int(multiplier * appsettings.PADDING_MONTH_PRECISION.months)
)
if self.day:
padding += relativedelta(
days=int(multiplier * appsettings.PADDING_DAY_PRECISION.days)
)
return padding
def _years_padding(self, multiplier):
"""Calculate year padding based on the precision."""
precision_settings = {
PRECISION_MILLENIUM: appsettings.PADDING_MILLENNIUM_PRECISION.years,
PRECISION_CENTURY: appsettings.PADDING_CENTURY_PRECISION.years,
PRECISION_DECADE: appsettings.PADDING_DECADE_PRECISION.years,
PRECISION_YEAR: appsettings.PADDING_YEAR_PRECISION.years,
}
years = precision_settings.get(self.precision, 0)
return relativedelta(years=int(multiplier * years))
def lower_fuzzy(self):
strict_val = (
self.lower_strict()
) # negative handled in the lower_strict() override
adjusted = apply_delta(sub, strict_val, self._get_fuzzy_padding(EARLIEST))
return adjusted
def upper_fuzzy(self):
strict_val = (
self.upper_strict()
) # negative handled in the upper_strict() override
adjusted = apply_delta(add, strict_val, self._get_fuzzy_padding(LATEST))
return adjusted
def lower_strict(self):
if self.negative:
strict_val = self._strict_date(
lean=LATEST
) # gets the year right, but need to adjust day and month
if self.precision in (
PRECISION_YEAR,
PRECISION_DECADE,
PRECISION_CENTURY,
PRECISION_MILLENIUM,
):
return struct_time(
(strict_val.tm_year, 1, 1)
+ tuple(TIME_EMPTY_TIME)
+ tuple(TIME_EMPTY_EXTRAS)
)
elif self.precision == PRECISION_MONTH:
return struct_time(
(strict_val.tm_year, strict_val.tm_mon, 1)
+ tuple(TIME_EMPTY_TIME)
+ tuple(TIME_EMPTY_EXTRAS)
)
else:
return strict_val
else:
return self._strict_date(lean=EARLIEST)
def upper_strict(self):
if self.negative:
strict_val = self._strict_date(lean=EARLIEST)
if self.precision in (
PRECISION_YEAR,
PRECISION_DECADE,
PRECISION_CENTURY,
PRECISION_MILLENIUM,
):
return struct_time(
(strict_val.tm_year, 12, 31)
+ tuple(TIME_EMPTY_TIME)
+ tuple(TIME_EMPTY_EXTRAS)
)
elif self.precision == PRECISION_MONTH:
days_in_month = calendar.monthrange(
strict_val.tm_year, strict_val.tm_mon
)[1]
return struct_time(
(strict_val.tm_year, strict_val.tm_mon, days_in_month)
+ tuple(TIME_EMPTY_TIME)
+ tuple(TIME_EMPTY_EXTRAS)
)
else:
return strict_val
else:
return self._strict_date(lean=LATEST)
@property
def precision(self):
if self.day:
return PRECISION_DAY
if self.month:
return PRECISION_MONTH
if self.year:
year_no_symbol = self.year.lstrip("-")
if year_no_symbol.isdigit():
return PRECISION_YEAR
if len(year_no_symbol) == 4 and year_no_symbol.endswith("XXX"):
return PRECISION_MILLENIUM
if len(year_no_symbol) == 4 and year_no_symbol.endswith("XX"):
return PRECISION_CENTURY
if len(year_no_symbol) == 4 and year_no_symbol.endswith("X"):
return PRECISION_DECADE
raise ValueError(f"Unspecified date {self} has no precision")
class Level1Interval(Interval):
def __init__(self, lower=None, upper=None):
if lower:
if lower["date"] == "..":
self.lower = UnspecifiedIntervalSection(
True, UncertainOrApproximate(**upper)
)
else:
self.lower = UncertainOrApproximate(**lower)
else:
self.lower = UnspecifiedIntervalSection(
False, UncertainOrApproximate(**upper)
)
if upper:
if upper["date"] == "..":
self.upper = UnspecifiedIntervalSection(
True, UncertainOrApproximate(**lower)
)
else:
self.upper = UncertainOrApproximate(**upper)
else:
self.upper = UnspecifiedIntervalSection(
False, UncertainOrApproximate(**lower)
)
self.is_approximate = self.lower.is_approximate or self.upper.is_approximate
self.is_uncertain = self.lower.is_uncertain or self.upper.is_uncertain
self.is_uncertain_and_approximate = (
self.lower.is_uncertain_and_approximate
or self.upper.is_uncertain_and_approximate
)
def _get_fuzzy_padding(self, lean):
if lean == EARLIEST:
return self.lower._get_fuzzy_padding(lean)
elif lean == LATEST:
return self.upper._get_fuzzy_padding(lean)
class LongYear(EDTFObject):
def __init__(self, year, significant_digits=None):
self.year = year
self.significant_digits = (
int(significant_digits) if significant_digits else None
)
def __str__(self):
if self.significant_digits:
return f"Y{self.year}S{self.significant_digits}"
else:
return f"Y{self.year}"
def _precise_year(self):
return int(self.year)
def _strict_date(self, lean):
py = self._precise_year()
if lean == EARLIEST:
return struct_time([py, 1, 1] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS)
else:
return struct_time([py, 12, 31] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS)
def estimated(self):
return self._precise_year()
def lower_fuzzy(self):
full_year = self._precise_year()
strict_val = self.lower_strict()
if not self.significant_digits:
return apply_delta(sub, strict_val, self._get_fuzzy_padding(EARLIEST))
else:
insignificant_digits = len(str(full_year)) - int(self.significant_digits)
if insignificant_digits <= 0:
return apply_delta(sub, strict_val, self._get_fuzzy_padding(EARLIEST))
padding_value = 10**insignificant_digits
sig_digits = full_year // padding_value
lower_year = sig_digits * padding_value
return apply_delta(
sub,
struct_time([lower_year, 1, 1] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS),
self._get_fuzzy_padding(EARLIEST),
)
def upper_fuzzy(self):
full_year = self._precise_year()
strict_val = self.upper_strict()
if not self.significant_digits:
return apply_delta(add, strict_val, self._get_fuzzy_padding(LATEST))
else:
insignificant_digits = len(str(full_year)) - self.significant_digits
if insignificant_digits <= 0:
return apply_delta(add, strict_val, self._get_fuzzy_padding(LATEST))
padding_value = 10**insignificant_digits
sig_digits = full_year // padding_value
upper_year = (sig_digits + 1) * padding_value - 1
return apply_delta(
add,
struct_time([upper_year, 12, 31] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS),
self._get_fuzzy_padding(LATEST),
)
class Season(Date):
def __init__(self, year, season, **kwargs):
self.year = year
self.season = season # use season to look up month
# day isn't part of the 'season' spec, but it helps the inherited
# `Date` methods do their thing.
self.day = None
def __str__(self):
return f"{self.year}-{self.season}"
def _precise_month(self, lean):
rng = appsettings.SEASON_L2_MONTHS_RANGE[int(self.season)]
if lean == EARLIEST:
return rng[0]
else:
return rng[1]
# (* ************************** Level 2 *************************** *)
class PartialUncertainOrApproximate(Date):
def set_year(self, y): # Year can be None.
self._year = y
year = property(Date.get_year, set_year)
def __init__(
self,
year=None,
month=None,
day=None,
year_ua=False,
month_ua=False,
day_ua=False,
year_month_ua=False,
month_day_ua=False,
ssn=None,
season_ua=False,
all_ua=False,
year_ua_b=False,
):
self.year = year
self.month = month
self.day = day
self.year_ua = year_ua
self.year_ua_b = year_ua_b
self.month_ua = month_ua
self.day_ua = day_ua
self.year_month_ua = year_month_ua
self.month_day_ua = month_day_ua
self.season = ssn
self.season_ua = season_ua
self.all_ua = all_ua
uas = [
year_ua,
month_ua,
day_ua,
year_month_ua,
month_day_ua,
season_ua,
all_ua,
]
self.is_uncertain = any(
item.is_uncertain for item in uas if hasattr(item, "is_uncertain")
)
self.is_approximate = any(
item.is_approximate for item in uas if hasattr(item, "is_approximate")
)
self.is_uncertain_and_approximate = any(
item.is_uncertain_and_approximate
for item in uas
if hasattr(item, "is_uncertain_and_approximate")
)
def __str__(self):
if self.season_ua:
return f"{self.season}{self.season_ua}"
if self.year_ua:
y = f"{self.year}{self.year_ua}"
else:
y = f"{self.year_ua_b}{self.year}" if self.year_ua_b else str(self.year)
m = f"{self.month_ua}{self.month}" if self.month_ua else str(self.month)
if self.day:
d = f"{self.day_ua}{self.day}" if self.day_ua else str(self.day)
else:
d = None
if self.year_month_ua: # year/month approximate. No brackets needed.
ym = f"{y}-{m}{self.year_month_ua}"
result = f"{ym}-{d}" if d else ym
elif self.month_day_ua:
if self.year_ua: # we don't need the brackets round month and day
result = f"{y}-{m}-{d}{self.month_day_ua}"
else:
result = f"{y}-({m}-{d}){self.month_day_ua}"
else:
result = f"{y}-{m}-{d}" if d else f"{y}-{m}"
if self.all_ua:
result = f"({result}){self.all_ua}"
return result
def _precise_year(self, lean):
if self.season:
return self.season._precise_year(lean)
return super()._precise_year(lean)
def _precise_month(self, lean):
if self.season:
return self.season._precise_month(lean)
return super()._precise_month(lean)
def _precise_day(self, lean):
if self.season:
return self.season._precise_day(lean)
return super()._precise_day(lean)
def _get_fuzzy_padding(self, lean):
"""
This is not a perfect interpretation as fuzziness is introduced for
redundant uncertainly modifiers e.g. (2006~)~ will get two sets of
fuzziness.
"""
result = relativedelta(0)
if self.year_ua:
result += (
appsettings.PADDING_YEAR_PRECISION * self.year_ua._get_multiplier()
)
if self.year_ua_b:
result += (
appsettings.PADDING_YEAR_PRECISION * self.year_ua_b._get_multiplier()
)
if self.month_ua:
result += (
appsettings.PADDING_MONTH_PRECISION * self.month_ua._get_multiplier()
)
if self.day_ua:
result += appsettings.PADDING_DAY_PRECISION * self.day_ua._get_multiplier()
if self.year_month_ua:
result += (
appsettings.PADDING_YEAR_PRECISION
* self.year_month_ua._get_multiplier()
)
result += (
appsettings.PADDING_MONTH_PRECISION
* self.year_month_ua._get_multiplier()
)
if self.month_day_ua:
result += (
appsettings.PADDING_DAY_PRECISION * self.month_day_ua._get_multiplier()
)
result += (
appsettings.PADDING_MONTH_PRECISION
* self.month_day_ua._get_multiplier()
)
if self.season_ua:
result += (
appsettings.PADDING_SEASON_PRECISION * self.season_ua._get_multiplier()
)
if self.all_ua:
multiplier = self.all_ua._get_multiplier()
if self.precision == PRECISION_DAY:
result += multiplier * appsettings.PADDING_DAY_PRECISION
result += multiplier * appsettings.PADDING_MONTH_PRECISION
result += multiplier * appsettings.PADDING_YEAR_PRECISION
elif self.precision == PRECISION_MONTH:
result += multiplier * appsettings.PADDING_MONTH_PRECISION
result += multiplier * appsettings.PADDING_YEAR_PRECISION
elif self.precision == PRECISION_YEAR:
result += multiplier * appsettings.PADDING_YEAR_PRECISION
return result
class PartialUnspecified(Unspecified):
pass
class Consecutives(Interval):
# Treating Consecutive ranges as intervals where one bound is optional
def __init__(self, lower=None, upper=None):
if lower and not isinstance(lower, EDTFObject):
self.lower = Date.parse(lower)
else:
self.lower = lower