diff --git a/PERFORMANCE.md b/PERFORMANCE.md index 33e21db..0ec7212 100644 --- a/PERFORMANCE.md +++ b/PERFORMANCE.md @@ -4,21 +4,12 @@ Status as of April 2, 2026. ## Results -- Runtime path: deterministic whole-string parse, extraction-first for noisy text, LALR fallback only on misses. Earley is not used at runtime. -- Test suite: `127 passed in 0.22s` -- Tight loop: `19.52 us/input` at `10000` rounds -- Internal path benchmark: - - `fast exact`: `6.5 us` - - `fast collection`: `19.5 us` - - `extract hit`: `46.1 us` - - `extract miss`: `13.6 us` -- Cross-library snapshot from `benchmarks/benchmark_baselines.py`: - - `timefhuman`: `56.1 us/input`, `37/37 ok`, `10/10 exact` - - `parsedatetime`: `45.0 us/input`, `36/37 ok`, `6/10 exact` - - `datefinder`: `42.9 us/input`, `23/37 ok`, `5/10 exact` - - `recurrent`: `195.2 us/input`, `36/37 ok`, `6/10 exact` - - `ctparse`: `12808.2 us/input`, `37/37 ok`, `3/10 exact` - - `dateparser`: `49105.3 us/input`, `20/37 ok`, `6/10 exact` +- Runtime path: deterministic whole-string parse first, bounded extraction for noisy text, LALR fallback only on misses. Earley is not used at runtime. +- Correctness: public `timefhuman(...)` now completes on the `datefinder` `core_corpus` and `seattle_html_76k` datasets without raising conversion errors. +- Test suite: `137 passed in 0.55s` +- Warm whole-document median on this machine: + - `core_corpus`: `timefhuman 0.00199s` for `10` matches, `datefinder.extract 0.00045s` for `14` matches + - `seattle_html_76k`: `timefhuman 0.09717s` for `48` matches, `datefinder.extract 0.07821s` for `57` matches ## Reproduce @@ -28,36 +19,43 @@ Run tests: /tmp/timefhuman-bench-venv/bin/python -m pytest -q ``` -Run the cross-library benchmark: - -```bash -/tmp/timefhuman-bench-venv/bin/python benchmarks/benchmark_baselines.py -``` - -Run the internal path benchmark: - -```bash -/tmp/timefhuman-bench-venv/bin/python benchmarks/benchmark_paths.py -``` - -Run the local tight loop: +Run the warmed whole-document benchmark used above. +This expects a local clone of `datefinder` at `/tmp/datefinder`. ```bash /tmp/timefhuman-bench-venv/bin/python - <<'PY' +from datetime import datetime, timezone +import statistics import time -from datetime import datetime -from benchmarks.benchmark_baselines import INPUTS -from timefhuman import timefhuman -from timefhuman.main import tfhConfig +from pathlib import Path -cfg = tfhConfig(now=datetime(2018, 8, 4, 14, 0)) -for rounds in [1000, 5000, 10000]: - start = time.perf_counter() - for _ in range(rounds): - for text in INPUTS: - timefhuman(text, config=cfg) - us = (time.perf_counter() - start) / (rounds * len(INPUTS)) * 1e6 - print(rounds, f"{us:.2f} us/input") +import datefinder +from timefhuman import timefhuman, tfhConfig + +ref = datetime(2026, 3, 18, 12, 0, tzinfo=timezone.utc) +cfg = tfhConfig(now=ref) +docs = [ + ("core_corpus", "\n".join( + x.strip() + for x in Path("/tmp/datefinder/bench/corpus_core.txt").read_text(encoding="utf-8").splitlines() + if x.strip() + ), 10), + ("seattle_html_76k", Path("/tmp/datefinder/tests/seattle_weekly.html").read_text(errors="ignore"), 7), +] + +def bench(fn, iterations): + times = [] + count = 0 + for _ in range(iterations): + start = time.perf_counter() + count = fn() + times.append(time.perf_counter() - start) + return statistics.median(times), count + +for name, text, iterations in docs: + tfh = bench(lambda: len(timefhuman(text, cfg)), iterations) + df = bench(lambda: len(datefinder.extract(text, reference_dt=ref)), iterations) + print(name, "timefhuman", tfh, "datefinder", df) PY ``` diff --git a/timefhuman/fastpath.py b/timefhuman/fastpath.py index 56de861..c2a152a 100644 --- a/timefhuman/fastpath.py +++ b/timefhuman/fastpath.py @@ -1,5 +1,5 @@ import re -from datetime import timedelta +from datetime import timedelta, timezone as dt_timezone from dateutil.relativedelta import relativedelta, weekdays import pytz @@ -11,6 +11,9 @@ from timefhuman.semantics import ( DATE_TIME_NAME_TO_TEMPLATE, MODIFIER_TO_OFFSET, NUMBER_WORDS, + build_date, + build_numeric_date, + build_time, POSITION_TO_DELTA, TIME_NAME_TO_TEMPLATE, UNIT_ALIASES, @@ -78,6 +81,7 @@ NUMBER_UNIT_PATTERN = re.compile( r"\s*" r"(?Pseconds?|secs?|sec|minutes?|mins?|min|hours?|hour|hrs?|hr|days?|day|weeks?|week|wks?|wk|months?|month|mos|years?|year|yrs?|yr|mo|[smhdwy])" ) +NUMERIC_TIMEZONE_OFFSET_PATTERN = re.compile(r"^(?P.*\S)\s+(?P[+-])(?P\d{2})(?::?(?P\d{2}))$") def parse_fast(text: str, config: tfhConfig, timezone_mapping, start_pos: int = 0): @@ -253,18 +257,22 @@ def _parse_atomic_datetime(text: str, config: tfhConfig, tzinfo): lower_body = text.lower() iso_match = ISO_PATTERN.fullmatch(text) if iso_match: + date = build_date( + year=int(iso_match.group("year")), + month=int(iso_match.group("month")), + day=int(iso_match.group("day")), + ) + time = build_time( + hour=int(iso_match.group("hour")), + minute=int(iso_match.group("minute")), + second=int(iso_match.group("second") or 0), + millisecond=int(iso_match.group("millisecond") or 0), + ) + if date is None or time is None: + return None return tfhDatetime( - date=tfhDate( - year=int(iso_match.group("year")), - month=int(iso_match.group("month")), - day=int(iso_match.group("day")), - ), - time=tfhTime( - hour=int(iso_match.group("hour")), - minute=int(iso_match.group("minute")), - second=int(iso_match.group("second") or 0), - millisecond=int(iso_match.group("millisecond") or 0), - ), + date=date, + time=time, tz=tzinfo, ) @@ -336,7 +344,7 @@ def _parse_date(text: str, config: tfhConfig): day_suffix = DAY_SUFFIX_PATTERN.fullmatch(lower) if day_suffix: - return tfhDate(day=int(day_suffix.group("day"))) + return build_date(day=int(day_suffix.group("day"))) weekday = _parse_weekday_name(lower) if weekday is not None: @@ -354,15 +362,7 @@ def _parse_numeric_date(text: str): first = int(match.group("a")) second = int(match.group("b")) third = match.group("c") - - if third is None: - if second > 31: - return tfhDate(month=first, year=normalize_year(second)) - return tfhDate(month=first, day=second) - - if len(match.group("a")) == 4: - return tfhDate(year=first, month=second, day=int(third)) - return tfhDate(month=first, day=second, year=normalize_year(int(third))) + return build_numeric_date(first, second, int(third) if third is not None else None) def _parse_monthname_date(text: str): @@ -379,10 +379,10 @@ def _parse_monthname_date(text: str): year = match.group("year") if year is not None: - return tfhDate(month=month, day=first, year=normalize_year(int(year))) + return build_date(month=month, day=first, year=normalize_year(int(year))) if suffix or first <= 31: - return tfhDate(month=month, day=first) - return tfhDate(month=month, year=normalize_year(first)) + return build_date(month=month, day=first) + return build_date(month=month, year=normalize_year(first)) def _parse_day_month_or_year(text: str): @@ -393,12 +393,12 @@ def _parse_day_month_or_year(text: str): return None year = match.group("year") if year is not None: - return tfhDate(day=int(match.group("day")), month=month, year=normalize_year(int(year))) - return tfhDate(day=int(match.group("day")), month=month) + return build_date(day=int(match.group("day")), month=month, year=normalize_year(int(year))) + return build_date(day=int(match.group("day")), month=month) match = DAY_YEAR_PATTERN.fullmatch(text) if match: - return tfhDate(day=int(match.group("day")), year=normalize_year(int(match.group("year")))) + return build_date(day=int(match.group("day")), year=normalize_year(int(match.group("year")))) return None @@ -423,7 +423,7 @@ def _parse_time_component(text: str, allow_houronly: bool): if meridiem is None and match.group("minute") is None and not allow_houronly: return None - return tfhTime( + return build_time( hour=int(match.group("hour")), minute=int(match.group("minute") or 0), second=int(match.group("second") or 0), @@ -503,6 +503,15 @@ def _consume_word_duration(segment: str): def _strip_trailing_timezone(text: str, timezone_mapping): + offset_match = NUMERIC_TIMEZONE_OFFSET_PATTERN.fullmatch(text) + if offset_match: + hours = int(offset_match.group("hour")) + minutes = int(offset_match.group("minute")) + if hours <= 23 and minutes <= 59: + sign = -1 if offset_match.group("sign") == "-" else 1 + offset = sign * timedelta(hours=hours, minutes=minutes) + return offset_match.group("body").strip(), dt_timezone(offset) + if not text or not text[-1].isalpha(): return text, None @@ -534,7 +543,7 @@ def _parse_modifier_prefix(tokens): def _strip_leading_weekday(text: str): parts = text.split(maxsplit=1) - if len(parts) == 2 and weekday_index(parts[0]) is not None: + if len(parts) == 2 and weekday_index(parts[0].rstrip(",")) is not None: return parts[1] return text diff --git a/timefhuman/grammar.lark b/timefhuman/grammar.lark index e46bc8d..b55c24f 100644 --- a/timefhuman/grammar.lark +++ b/timefhuman/grammar.lark @@ -24,6 +24,7 @@ FLOAT_NUMBER: /((\d+\.\d*|\.\d+)(e[-+]?\d+)?|\d+(e[-+]?\d+))/ NUMERIC_DATE.2: /\d{1,4}\/\d{1,4}(?:\/\d{1,4})?|\d{1,4}\-\d{1,4}\-\d{1,4}/ ISO_DATETIME.3: /\d{4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?/ TIMEZONE: /(? 31: - return {'date': tfhDate(month=first, year=normalize_year(second))} - return {'date': tfhDate(month=first, day=second)} - - third = parts[2] - if first >= 1000: - return {'date': tfhDate(year=first, month=second, day=third)} - return {'date': tfhDate(month=first, day=second, year=normalize_year(third))} + result = build_numeric_date(first, second, parts[2] if len(parts) == 3 else None) + if result is None: + raise ValueError(f"Invalid numeric date: {value}") + return {'date': result} def day(self, children): return {'day': int(children[0].value)} @@ -219,16 +222,28 @@ class tfhTransformer(Transformer): year = match.group('year') if year is not None: - return {'date': tfhDate(month=month, day=first, year=normalize_year(int(year)))} + result = build_date(month=month, day=first, year=normalize_year(int(year))) + if result is None: + raise ValueError(f"Invalid monthname date: {children[0].value}") + return {'date': result} if match.group('suffix') or first <= 31: - return {'date': tfhDate(month=month, day=first)} - return {'date': tfhDate(month=month, year=normalize_year(first))} + result = build_date(month=month, day=first) + if result is None: + raise ValueError(f"Invalid monthname date: {children[0].value}") + return {'date': result} + result = build_date(month=month, year=normalize_year(first)) + if result is None: + raise ValueError(f"Invalid monthname date: {children[0].value}") + return {'date': result} def day_ordinal(self, children): match = DAY_ORDINAL_PATTERN.fullmatch(children[0].value) if match is None: raise NotImplementedError(f"Unknown day ordinal: {children[0].value}") - return {'date': tfhDate(day=int(match.group('day')))} + result = build_date(day=int(match.group('day'))) + if result is None: + raise ValueError(f"Invalid day ordinal: {children[0].value}") + return {'date': result} def modified_month(self, children): offset = sum(child['offset'] for child in children[:-1]) @@ -274,13 +289,16 @@ class tfhTransformer(Transformer): if 'time' in data: return {'time': data['time']} - return {'time': tfhTime( + result = build_time( hour=int(data.get("hour", 0)), minute=int(data.get("minute", 0)), second=int(data.get("second", 0)), millisecond=int(data.get("millisecond", 0)), - meridiem=data.get("meridiem", None) - )} + meridiem=data.get("meridiem", None), + ) + if result is None: + raise ValueError(f"Invalid time: {data}") + return {'time': result} def meridiem(self, children): meridiem = children[0].value.lower() @@ -292,6 +310,14 @@ class tfhTransformer(Transformer): def timezone(self, children): timezone = children[0].value.lower() + if timezone.startswith(("+", "-")): + sign = -1 if timezone[0] == "-" else 1 + body = timezone[1:].replace(":", "") + hours = int(body[:2]) + minutes = int(body[2:]) + if hours > 23 or minutes > 59: + raise ValueError(f"Invalid timezone offset: {timezone}") + return {'timezone': dt_timezone(sign * timedelta(hours=hours, minutes=minutes))} return {'timezone': pytz.timezone(timezone_mapping[timezone])} def timename(self, children): @@ -301,7 +327,10 @@ class tfhTransformer(Transformer): return {'time': clone_time(TIME_NAME_TO_TEMPLATE[timename])} def houronly(self, children): - return {'time': tfhTime(hour=int(children[0].value))} + result = build_time(hour=int(children[0].value)) + if result is None: + raise ValueError(f"Invalid hour: {children[0].value}") + return {'time': result} def datetimename(self, children): datetimename = children[0].value.lower() @@ -326,7 +355,11 @@ class tfhTransformer(Transformer): if len(time_parts) > 2: second = time_parts[2] + date = build_date(year=year, month=month, day=day) + time = build_time(hour=hour, minute=minute, second=second, millisecond=millisecond) + if date is None or time is None: + raise ValueError(f"Invalid ISO datetime: {value}") return {'datetime': tfhDatetime( - date=tfhDate(year=year, month=month, day=day), - time=tfhTime(hour=hour, minute=minute, second=second, millisecond=millisecond), + date=date, + time=time, )} diff --git a/timefhuman/main.py b/timefhuman/main.py index 784f72e..d285e2f 100644 --- a/timefhuman/main.py +++ b/timefhuman/main.py @@ -57,10 +57,25 @@ def _parse_renderers(string: str, config: tfhConfig): def _matched_results(string: str, renderers, config: tfhConfig): - positions = [(renderer.matched_text_pos[0], renderer.matched_text_pos[1]) for renderer in renderers] - matched_texts = [string[start:end] for start, end in positions] - datetimes = [renderer.to_object(config) for renderer in renderers] - return list(zip(matched_texts, positions, datetimes)) + results = [] + for renderer in renderers: + try: + value = renderer.to_object(config) + except ValueError: + continue + start, end = renderer.matched_text_pos + results.append((string[start:end], (start, end), value)) + return results + + +def _valid_objects(renderers, config: tfhConfig): + results = [] + for renderer in renderers: + try: + results.append(renderer.to_object(config)) + except ValueError: + continue + return results def build_raw_tree(string: str, config: tfhConfig): @@ -97,4 +112,4 @@ def timefhuman(string, config: tfhConfig = DEFAULT_CONFIG, raw: bool=False, now: if config.return_matched_text: return _matched_results(string, renderers, config) - return [renderer.to_object(config) for renderer in renderers] + return _valid_objects(renderers, config) diff --git a/timefhuman/semantics.py b/timefhuman/semantics.py index bfc6317..cbb5d9e 100644 --- a/timefhuman/semantics.py +++ b/timefhuman/semantics.py @@ -1,8 +1,8 @@ -from datetime import timedelta +from datetime import date, timedelta from dateutil.relativedelta import relativedelta -from timefhuman.renderers import tfhDatetime, tfhTime +from timefhuman.renderers import tfhDate, tfhDatetime, tfhTime from timefhuman.utils import get_month_mapping @@ -103,6 +103,69 @@ def normalize_year(value: int): return value +def build_date(year: int | None = None, month: int | None = None, day: int | None = None): + if year is not None and not 1 <= year <= 9999: + return None + if month is not None and not 1 <= month <= 12: + return None + if day is not None and not 1 <= day <= 31: + return None + if month is not None and day is not None: + validation_year = year if year is not None else 2000 + try: + date(validation_year, month, day) + except ValueError: + return None + return tfhDate(year=year, month=month, day=day) + + +def build_numeric_date(first: int, second: int, third: int | None = None): + if third is None: + if first >= 1000: + return build_date(year=first, month=second) + if second > 31: + return build_date(month=first, year=normalize_year(second)) + if 1 <= first <= 12: + return build_date(month=first, day=second) + if 1 <= second <= 12: + return build_date(month=second, day=first) + return None + + if first >= 1000: + return build_date(year=first, month=second, day=third) + + year = normalize_year(third) + if 1 <= first <= 12: + return build_date(month=first, day=second, year=year) + if 1 <= second <= 12: + return build_date(year=year, month=second, day=first) + return None + + +def build_time( + hour: int, + minute: int = 0, + second: int = 0, + millisecond: int = 0, + meridiem=None, +): + if not 0 <= minute <= 59 or not 0 <= second <= 59 or not 0 <= millisecond <= 999999: + return None + if meridiem is None: + if not 0 <= hour <= 23: + return None + elif not 1 <= hour <= 12: + return None + + return tfhTime( + hour=hour, + minute=minute, + second=second, + millisecond=millisecond, + meridiem=meridiem, + ) + + def clone_time(template: tfhTime): return tfhTime( hour=template.hour,