"""Untrusted date rendering over source-bound metadata; no historical truth proof. Legacy timestamps are not precision declarations. A versioned sidecar binds an entity/property/literal to same-revision Wikidata JSON and RDF statements. Missing, invalid or conflicting metadata is exposed, never guessed from day/month digits. Maintainer amendment (10.1): a pair the sidecar does not cover is rendered from its digits only as far as the digits can carry. Wikidata serialises a coarser precision with day 01 (month) or 01-01 (year), so a day other than the 1st can only come from a day-precision statement, while a 1st may be a placeholder. From 1583 on, the stored value is a Gregorian date: a day other than the 1st is given whole, a 1st gives the month and year, and 1 January gives the year. Earlier and BCE values decline, because their calendar and precision cannot be read from the digits. A pair the sidecar does cover but whose literal it cannot bind still declines. """ import json import os from pathlib import Path import re TIME = re.compile(r'^([+-]?)(\d{1,16})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}Z$') CALENDARS = {'http://www.wikidata.org/entity/Q1985727': 'Gregorian', 'http://www.wikidata.org/entity/Q1985786': 'Julian'} MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') QUALIFIER_NAMES = {'P1480': 'sourcing circumstances', 'P4241': 'date refinement', 'P1319': 'earliest date', 'P1326': 'latest date', 'P7452': 'preferred-rank reason', 'P580': 'start time', 'P582': 'end time', 'P1013': 'criterion', 'P2241': 'deprecation reason'} ITEM_NAMES = {'Q5727902': 'circa', 'Q18122778': 'presumably', 'Q18912752': 'disputed', 'Q18195782': 'unspecified calendar', 'Q40719727': 'beginning of', 'Q40719748': 'middle of', 'Q40719766': 'end of', 'Q40719687': 'first half', 'Q40719707': 'second half', 'Q115018754': 'original value', 'Q111606173': 'most inclusive value'} _CACHE = None def is_time(value): return isinstance(value, str) and TIME.fullmatch(value) is not None def _load(): global _CACHE if _CACHE is not None: return _CACHE _CACHE = {} path = Path(os.environ.get('ORACLE7_DATE_PRECISION', str(Path(os.environ.get('ORACLE7_ROOT', '/opt/oracle-clm'))/'relstore/date_precision_v1.json'))) try: if path.stat().st_size > 16*1024*1024: return _CACHE document = json.loads(path.read_text()) if not isinstance(document, dict): return _CACHE if document.get('schema') != 'oracle7-date-precision-v1' or document.get('version') != 1: return _CACHE records = document['records'] if not isinstance(records, list) or len(records) > 2048: return _CACHE for record in records: if not isinstance(record, dict): raise ValueError('record must be an object') if not isinstance(record.get('statements'), list) or not isinstance(record.get('bindings'), list): raise ValueError('statements/bindings must be arrays') if any(not isinstance(s, dict) for s in record['statements']+record['bindings']): raise ValueError('statements/bindings must contain objects') key = (record['subject'], record['property']) if key in _CACHE: _CACHE = {} return _CACHE if not re.fullmatch(r'Q[1-9][0-9]*', key[0]) or not re.fullmatch(r'P[1-9][0-9]*', key[1]): raise ValueError('invalid record identity') if len(record['statements']) > 100 or len(record['bindings']) > 100: raise ValueError('record too large') _CACHE[key] = record except (OSError, ValueError, KeyError, TypeError, AttributeError): _CACHE = {} return _CACHE def _qid(value, prefix): return prefix+str(value) if type(value) is int else value def selected(value, subject=None, property=None, calendar=None): """Return matching best-rank source statements; no match is not a false fact.""" if subject is None or property is None: return [] record = _load().get((_qid(subject, 'Q'), _qid(property, 'P'))) if not record: return [] try: statements = record['statements'] if calendar is not None: statements = [s for s in statements if s.get('mainsnak', {}).get('datavalue', {}).get('value', {}).get('calendarmodel') == calendar] rank = 'preferred' if any(s.get('rank') == 'preferred' for s in statements) else 'normal' ids = {b['statement_id'].lower() for b in record['bindings'] if b['legacy_literal'] == value} out = [] for statement in statements: if statement.get('rank') != rank or statement.get('id', '').lower() not in ids: continue time = statement['mainsnak']['datavalue']['value'] rdf = statement['rdf_time'] if (rdf['timeValue'] != value or int(rdf['timePrecision']) != time['precision'] or rdf['timeCalendarModel'] != time['calendarmodel'] or int(rdf['timeTimezone']) != time['timezone']): return [] if statement['mainsnak']['property'] != record['property'] or not statement['id'].lower().startswith(record['subject'].lower()+'$'): return [] # Rendering validates precision and calendar before using digits. _format_time(time, '') out.append(statement) return out except (ValueError, KeyError, TypeError, IndexError, AttributeError): return [] def _ordinal(n): return str(n)+('th' if 10 <= n % 100 <= 20 else {1:'st', 2:'nd', 3:'rd'}.get(n % 10, 'th')) def _parts(time): match = TIME.fullmatch(time['time']) precision = time['precision'] if not match or type(precision) is not int or not 0 <= precision <= 11: raise ValueError('unsupported time or precision') if time['calendarmodel'] not in CALENDARS: raise ValueError('unsupported calendar') year, month, day = int(match[2]), int(match[3]), int(match[4]) if year == 0: raise ValueError('Wikibase JSON year zero has no historical interpretation') if match[1] == '-': year = -year if not 0 <= month <= 12 or not 0 <= day <= 31: raise ValueError('invalid date fields') if precision >= 10 and month == 0 or precision >= 11 and day == 0: raise ValueError('precision requires unavailable date fields') if precision == 11: astro = year if year > 0 else year + 1 leap = astro % 4 == 0 and (time['calendarmodel'].endswith('Q1985786') or astro % 100 != 0 or astro % 400 == 0) days = (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) if day > days[month-1]: raise ValueError('invalid day for source calendar') for field in ('before', 'after', 'timezone'): if type(time.get(field)) is not int: raise ValueError('missing uncertainty/timezone metadata') if time['before'] < 0 or time['after'] < 0: raise ValueError('negative uncertainty') return year, month, day, precision def _format_time(time, question): year, month, day, precision = _parts(time) y = str(abs(year))+(' BCE' if year < 0 else '') wants_year = bool(re.search(r'\b(?:what|which) year\b|\bin what year\b|\byear (?:was|did|of)\b', question, re.I)) wants_month = bool(re.search(r'\b(?:what|which) month\b', question, re.I)) if precision >= 9 and wants_year: body = y elif precision == 11 and not wants_month: body = f'{day} {MONTHS[month-1]} {y}' elif precision >= 10: body = f'{MONTHS[month-1]} {y}' elif precision == 9: body = y elif precision == 8: start = (abs(year)//10)*10 body = f'{start}s'+(' BCE' if year < 0 else '') elif precision in (6, 7): unit = 100 if precision == 7 else 1000 body = _ordinal((abs(year)-1)//unit+1)+(' century' if precision == 7 else ' millennium')+(' BCE' if year < 0 else '') else: body = f'around {y} (source resolution: {10**(9-precision):,} years)' notes = [CALENDARS[time['calendarmodel']]+' calendar'] if precision == 10 and not wants_year: notes.append('day unspecified') elif precision == 9 and not wants_year: notes.append('month and day unspecified') if time['before'] or time['after']: notes.append(f"source uncertainty before={time['before']}, after={time['after']}, precision={precision}") if time['timezone']: notes.append(f"source timezone offset={time['timezone']}; not converted") return body+' ('+'; '.join(notes)+')' def _qualifiers(statement): out = [] for prop, snaks in sorted(statement.get('qualifiers', {}).items()): values = [] for snak in snaks: if snak.get('snaktype') != 'value': values.append(snak.get('snaktype', 'unknown')) continue value = snak.get('datavalue', {}).get('value') if isinstance(value, dict) and 'time' in value: values.append(_format_time(value, '')) elif isinstance(value, dict) and 'id' in value: values.append(ITEM_NAMES.get(value['id'], value['id'])) else: values.append(str(value)) out.append(QUALIFIER_NAMES.get(prop, prop)+': '+', '.join(values)) return out def requested_calendar(question): named = [uri for uri, label in CALENDARS.items() if re.search(r'\b'+label+r'\b', question, re.I)] return named[0] if len(named) == 1 else None def evidence(value, subject=None, property=None, question=''): records = selected(value, subject, property, requested_calendar(question)) record = _load().get((_qid(subject,'Q'), _qid(property,'P')), {}) return {'status': 'source_metadata' if records else 'precision_unavailable', 'legacy_literal': value, 'source': record.get('source'), 'statements': [{'id': s['id'], 'rank': s['rank'], 'time': s['mainsnak']['datavalue']['value'], 'qualifiers': s.get('qualifiers', {}), 'references': s.get('references', [])} for s in records]} def _render(value, question='', subject=None, property=None): if not is_time(value): return value statements = selected(value, subject, property, requested_calendar(question)) if not statements: if (_qid(subject, 'Q'), _qid(property, 'P')) in _load(): return None return _from_digits(value, question) try: rendered = [] for statement in statements: time = statement['mainsnak']['datavalue']['value'] text = _format_time(time, question) qualifiers = _qualifiers(statement) if qualifiers: text += '; '+ '; '.join(qualifiers) if text not in rendered: rendered.append(text) if len(rendered) > 1: return 'source records differ: '+' / '.join(rendered) return rendered[0] except (ValueError, KeyError, TypeError, IndexError, AttributeError): return None NOT_CONFIRMED = 'stored date; precision and calendar not source-confirmed' # 10.2: a date read from its digits says so (ember arlynx, issue #4) def _from_digits(value, question=''): """Maintainer amendment (10.1): an uncovered pair, read only as far as its digits can carry.""" match = TIME.fullmatch(value) if not match or match[1] == '-' or requested_calendar(question) not in (None, 'http://www.wikidata.org/entity/Q1985727'): return None year, month, day = int(match[2]), int(match[3]), int(match[4]) if year < 1583 or not 1 <= month <= 12 or not 1 <= day <= 31: return None wants_year = bool(re.search(r'\b(?:what|which) year\b|\bin what year\b|\byear (?:was|did|of)\b', question, re.I)) wants_month = bool(re.search(r'\b(?:what|which) month\b', question, re.I)) if wants_year: return f'{year} ({NOT_CONFIRMED})' if month == 1 and day == 1: return f'{year} ({NOT_CONFIRMED}; month and day not recorded in this store)' if day == 1: return f'{MONTHS[month-1]} {year} ({NOT_CONFIRMED}; day not recorded in this store)' if wants_month: return f'{MONTHS[month-1]} {year} ({NOT_CONFIRMED})' return f'{day} {MONTHS[month-1]} {year} ({NOT_CONFIRMED})' def render(value, question='', subject=None, property=None): result = _render(value, question, subject, property) return result if result is not None else f'date precision and calendar unavailable (stored timestamp: {value})' def available(value, question='', subject=None, property=None): """A route may assert a date only when its metadata can actually be rendered.""" return _render(value, question, subject, property) is not None def _time_interval(time): """Inclusive calendar-local bounds; never converts between calendars.""" year, month, day, precision = _parts(time) if precision < 6 or time['before'] or time['after'] or time['timezone']: return None astro = lambda y: y if y > 0 else y + 1 def last_day(y, m): a = astro(y) leap = a % 4 == 0 and (time['calendarmodel'].endswith('Q1985786') or a % 100 != 0 or a % 400 == 0) return (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[m-1] if precision == 11: low = high = (astro(year), month, day) elif precision == 10: low, high = (astro(year), month, 1), (astro(year), month, last_day(year, month)) elif precision == 9: low, high = (astro(year), 1, 1), (astro(year), 12, 31) elif precision == 8: a = abs(year)//10*10 ys = (a, a+9) if year > 0 else (-a-9, -a) if 0 in ys: return None low, high = (astro(ys[0]), 1, 1), (astro(ys[1]), 12, 31) else: unit = 100 if precision == 7 else 1000 n = (abs(year)-1)//unit+1 ys = ((n-1)*unit+1, n*unit) if year > 0 else (-n*unit, -(n-1)*unit-1) low, high = (astro(ys[0]), 1, 1), (astro(ys[1]), 12, 31) return time['calendarmodel'], low, high def _interval_from_digits(value): """Maintainer amendment (10.1): bounds for an uncovered stored date, as wide as its digits leave open.""" match = TIME.fullmatch(value) if isinstance(value, str) else None if not match or match[1] == '-': return None year, month, day = int(match[2]), int(match[3]), int(match[4]) if year < 1583 or not 1 <= month <= 12 or not 1 <= day <= 31: return None # 10.2: the digits are not a source, so the bounds are a year either side of the middle of the stored year; two such # dates order only when their years differ by at least two return 'http://www.wikidata.org/entity/Q1985727', (year - 1, 7, 1), (year + 1, 6, 30) def interval(value, subject, property): """Conservative bounds for ordering; uncertain/unknown qualifiers never prove order. Refinement can only narrow the coarse source period, so retaining that wider period is safe. Explicit earliest/latest bounds narrow only in the same calendar. Circa/disputed and unrecognized qualifiers remain unknown. """ records = selected(value, subject, property) if not records: if subject is None or property is None or (_qid(subject, 'Q'), _qid(property, 'P')) in _load(): return None return _interval_from_digits(value) intervals = [] try: for record in records: qualifiers = record.get('qualifiers', {}) if set(qualifiers) - {'P4241', 'P7452', 'P1319', 'P1326'}: return None bounds = _time_interval(record['mainsnak']['datavalue']['value']) if bounds is None: return None calendar, low, high = bounds for prop in ('P1319', 'P1326'): for snak in qualifiers.get(prop, []): if snak.get('snaktype') != 'value' or snak.get('datavalue', {}).get('type') != 'time': return None bound = _time_interval(snak['datavalue']['value']) if bound is None or bound[0] != calendar: return None if prop == 'P1319': low = max(low, bound[1]) else: high = min(high, bound[2]) if low > high: return None intervals.append((calendar, low, high)) if len({b[0] for b in intervals}) != 1: return None return intervals[0][0], min(b[1] for b in intervals), max(b[2] for b in intervals) except (ValueError, KeyError, TypeError, IndexError, AttributeError): return None