tripverify 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tripverify/__init__.py +12 -0
- tripverify/adapters/__init__.py +35 -0
- tripverify/adapters/chinatravel.py +257 -0
- tripverify/adapters/travelplanner.py +290 -0
- tripverify/aggregate.py +120 -0
- tripverify/cli.py +524 -0
- tripverify/constraints/__init__.py +25 -0
- tripverify/constraints/base.py +303 -0
- tripverify/constraints/budget.py +288 -0
- tripverify/constraints/structural.py +290 -0
- tripverify/constraints/temporal.py +331 -0
- tripverify/constraints/transit.py +403 -0
- tripverify/hashing.py +159 -0
- tripverify/models.py +111 -0
- tripverify/providers/__init__.py +11 -0
- tripverify/providers/base.py +132 -0
- tripverify/providers/null.py +22 -0
- tripverify/verdict.py +121 -0
- tripverify-0.1.0.dist-info/METADATA +174 -0
- tripverify-0.1.0.dist-info/RECORD +24 -0
- tripverify-0.1.0.dist-info/WHEEL +5 -0
- tripverify-0.1.0.dist-info/entry_points.txt +12 -0
- tripverify-0.1.0.dist-info/licenses/LICENSE +202 -0
- tripverify-0.1.0.dist-info/top_level.txt +1 -0
tripverify/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""tripverify - verdict semantics for travel itinerary constraint checking.
|
|
2
|
+
|
|
3
|
+
The judgment kernel is deterministic and calls no language model and no
|
|
4
|
+
network: the same plan under the same ruleset version always yields the same
|
|
5
|
+
verdicts. Data that is absent is reported as ``UNDECIDABLE`` rather than
|
|
6
|
+
being folded into pass or fail, so a plan cannot score well by omitting
|
|
7
|
+
information.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Format adapters: foreign plan formats -> canonical :class:`Plan`.
|
|
2
|
+
|
|
3
|
+
Every adapter exposes the same entry point::
|
|
4
|
+
|
|
5
|
+
to_canonical(raw: dict) -> tuple[Plan, list[str]]
|
|
6
|
+
|
|
7
|
+
The second element is the **lost-field list**: the dotted paths of source keys
|
|
8
|
+
that the canonical model has no slot for. A lossy conversion must never be
|
|
9
|
+
silent, so the list is empty *only* when the conversion was lossless. Paths are
|
|
10
|
+
index free, de-duplicated and sorted (``"accommodation.room_type"``, not
|
|
11
|
+
``"plan[2].accommodation.room_type"``).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from types import ModuleType
|
|
17
|
+
|
|
18
|
+
from . import chinatravel, travelplanner
|
|
19
|
+
|
|
20
|
+
__all__ = ["chinatravel", "travelplanner", "ADAPTERS", "get_adapter"]
|
|
21
|
+
|
|
22
|
+
#: Registry of adapter modules by format name.
|
|
23
|
+
ADAPTERS: dict[str, ModuleType] = {
|
|
24
|
+
"chinatravel": chinatravel,
|
|
25
|
+
"travelplanner": travelplanner,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def get_adapter(name: str) -> ModuleType:
|
|
30
|
+
"""Return the adapter module for ``name``; raise ``KeyError`` if unknown."""
|
|
31
|
+
try:
|
|
32
|
+
return ADAPTERS[name]
|
|
33
|
+
except KeyError:
|
|
34
|
+
known = ", ".join(sorted(ADAPTERS))
|
|
35
|
+
raise KeyError(f"unknown plan format {name!r}; known formats: {known}") from None
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""ChinaTravel plan format -> canonical :class:`~tripverify.models.Plan`.
|
|
2
|
+
|
|
3
|
+
The canonical representation is *modelled on* ChinaTravel, but it is a strict
|
|
4
|
+
subset: ChinaTravel carries per-leg transport detail, ticket counts, intercity
|
|
5
|
+
vehicle identifiers and run-level telemetry that the canonical model has no
|
|
6
|
+
slot for. Every such key is reported in the ``lost`` list returned alongside
|
|
7
|
+
the plan -- a lossy conversion must never be silent.
|
|
8
|
+
|
|
9
|
+
Lost-field paths are **index free and de-duplicated**, e.g.
|
|
10
|
+
``itinerary.activities.transports.distance`` rather than one entry per
|
|
11
|
+
occurrence; the list answers "which fields were dropped", not "how often".
|
|
12
|
+
|
|
13
|
+
Source format reference: ``tests/fixtures/ct_sample.json`` (real sample, see
|
|
14
|
+
``tests/fixtures/SOURCES.md``).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from datetime import time
|
|
20
|
+
from decimal import Decimal, InvalidOperation
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ..models import Activity, Money, Plan
|
|
24
|
+
|
|
25
|
+
__all__ = ["to_canonical"]
|
|
26
|
+
|
|
27
|
+
#: Top-level keys that map onto the canonical model.
|
|
28
|
+
_PLAN_CONSUMED = frozenset({"itinerary", "budget"})
|
|
29
|
+
|
|
30
|
+
#: Per-day keys that map onto the canonical model.
|
|
31
|
+
_DAY_CONSUMED = frozenset({"day", "activities"})
|
|
32
|
+
|
|
33
|
+
#: Activity keys that map onto the canonical model.
|
|
34
|
+
_ACTIVITY_CONSUMED = frozenset(
|
|
35
|
+
{"position", "start_time", "end_time", "cost", "price", "transports"}
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
#: Transport-leg keys consumed while deriving ``transport_mode`` / minutes.
|
|
39
|
+
_TRANSPORT_CONSUMED = frozenset({"mode", "start_time", "end_time"})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _parse_time(raw: Any) -> time | None:
|
|
43
|
+
"""Parse ``"HH:MM"`` / ``"HH:MM:SS"``; return ``None`` if unparsable.
|
|
44
|
+
|
|
45
|
+
ChinaTravel writes end-of-day as ``"24:00"`` (seen on `accommodation`
|
|
46
|
+
activities). ``datetime.time`` cannot hold hour 24, but midnight is the
|
|
47
|
+
same instant, so it maps to ``00:00`` -- no information is lost, and the
|
|
48
|
+
temporal checker's cross-midnight rule reconstructs the duration.
|
|
49
|
+
"""
|
|
50
|
+
if not isinstance(raw, str):
|
|
51
|
+
return None
|
|
52
|
+
parts = raw.strip().split(":")
|
|
53
|
+
if len(parts) not in (2, 3):
|
|
54
|
+
return None
|
|
55
|
+
try:
|
|
56
|
+
nums = [int(p) for p in parts]
|
|
57
|
+
except ValueError:
|
|
58
|
+
return None
|
|
59
|
+
hh, mm = nums[0], nums[1]
|
|
60
|
+
ss = nums[2] if len(nums) == 3 else 0
|
|
61
|
+
if hh == 24 and mm == 0 and ss == 0:
|
|
62
|
+
return time(0, 0)
|
|
63
|
+
if not (0 <= hh < 24 and 0 <= mm < 60 and 0 <= ss < 60):
|
|
64
|
+
return None
|
|
65
|
+
return time(hh, mm, ss)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _to_decimal(raw: Any) -> Decimal | None:
|
|
69
|
+
"""Coerce a JSON number / numeric string to ``Decimal``; else ``None``."""
|
|
70
|
+
if raw is None or isinstance(raw, bool):
|
|
71
|
+
return None
|
|
72
|
+
if isinstance(raw, (int, float)):
|
|
73
|
+
return Decimal(str(raw))
|
|
74
|
+
if isinstance(raw, str):
|
|
75
|
+
try:
|
|
76
|
+
return Decimal(raw.strip())
|
|
77
|
+
except (InvalidOperation, ValueError):
|
|
78
|
+
return None
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _minutes_between(start: time | None, end: time | None) -> int | None:
|
|
83
|
+
if start is None or end is None:
|
|
84
|
+
return None
|
|
85
|
+
s = start.hour * 60 + start.minute
|
|
86
|
+
e = end.hour * 60 + end.minute
|
|
87
|
+
if e < s: # crossed midnight
|
|
88
|
+
e += 24 * 60
|
|
89
|
+
return e - s
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _activity_cost(src: dict[str, Any], lost: set[str], prefix: str) -> Money | None:
|
|
93
|
+
"""Fold ChinaTravel's ``cost`` / ``price`` pair into one canonical slot.
|
|
94
|
+
|
|
95
|
+
They are aliases in practice (identical in the reference sample). When both
|
|
96
|
+
are present *and disagree*, the unused one is genuine information loss and
|
|
97
|
+
is reported.
|
|
98
|
+
"""
|
|
99
|
+
cost = _to_decimal(src.get("cost")) if "cost" in src else None
|
|
100
|
+
price = _to_decimal(src.get("price")) if "price" in src else None
|
|
101
|
+
if "cost" in src and cost is None:
|
|
102
|
+
lost.add(f"{prefix}.cost")
|
|
103
|
+
if "price" in src and price is None and "cost" not in src:
|
|
104
|
+
lost.add(f"{prefix}.price")
|
|
105
|
+
chosen = cost if cost is not None else price
|
|
106
|
+
if cost is not None and price is not None and cost != price:
|
|
107
|
+
lost.add(f"{prefix}.price")
|
|
108
|
+
if chosen is None:
|
|
109
|
+
return None
|
|
110
|
+
return Money(amount=chosen)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _transports(
|
|
114
|
+
legs: Any, lost: set[str], prefix: str
|
|
115
|
+
) -> tuple[str | None, int | None]:
|
|
116
|
+
"""Collapse a leg list into ``(transport_mode, transport_minutes)``.
|
|
117
|
+
|
|
118
|
+
Minutes are the sum over legs; the mode is that of the longest leg (first
|
|
119
|
+
one wins a tie). Anything that does not survive the collapse is reported.
|
|
120
|
+
"""
|
|
121
|
+
if not isinstance(legs, list) or not legs:
|
|
122
|
+
return None, None
|
|
123
|
+
|
|
124
|
+
total = 0
|
|
125
|
+
have_minutes = False
|
|
126
|
+
best_mode: str | None = None
|
|
127
|
+
best_len = -1
|
|
128
|
+
modes: set[str] = set()
|
|
129
|
+
|
|
130
|
+
for leg in legs:
|
|
131
|
+
if not isinstance(leg, dict):
|
|
132
|
+
lost.add(f"{prefix}.transports")
|
|
133
|
+
continue
|
|
134
|
+
for key in leg:
|
|
135
|
+
if key not in _TRANSPORT_CONSUMED:
|
|
136
|
+
lost.add(f"{prefix}.transports.{key}")
|
|
137
|
+
mins = _minutes_between(
|
|
138
|
+
_parse_time(leg.get("start_time")), _parse_time(leg.get("end_time"))
|
|
139
|
+
)
|
|
140
|
+
if mins is not None:
|
|
141
|
+
total += mins
|
|
142
|
+
have_minutes = True
|
|
143
|
+
mode = leg.get("mode")
|
|
144
|
+
if isinstance(mode, str) and mode.strip():
|
|
145
|
+
modes.add(mode.strip())
|
|
146
|
+
weight = mins if mins is not None else 0
|
|
147
|
+
if weight > best_len:
|
|
148
|
+
best_len, best_mode = weight, mode.strip()
|
|
149
|
+
|
|
150
|
+
if len(modes) > 1:
|
|
151
|
+
# Only one mode fits the canonical slot; the others are dropped.
|
|
152
|
+
lost.add(f"{prefix}.transports.mode")
|
|
153
|
+
return best_mode, (total if have_minutes else None)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def to_canonical(raw: dict[str, Any]) -> tuple[Plan, list[str]]:
|
|
157
|
+
"""Convert a ChinaTravel plan dict to ``(Plan, lost_fields)``.
|
|
158
|
+
|
|
159
|
+
``lost_fields`` is sorted and empty exactly when the conversion was
|
|
160
|
+
lossless.
|
|
161
|
+
"""
|
|
162
|
+
if not isinstance(raw, dict):
|
|
163
|
+
raise TypeError(f"ChinaTravel plan must be a dict, got {type(raw).__name__}")
|
|
164
|
+
|
|
165
|
+
lost: set[str] = set()
|
|
166
|
+
for key in raw:
|
|
167
|
+
if key not in _PLAN_CONSUMED:
|
|
168
|
+
lost.add(key)
|
|
169
|
+
|
|
170
|
+
budget: Money | None = None
|
|
171
|
+
if "budget" in raw:
|
|
172
|
+
amount = _to_decimal(raw.get("budget"))
|
|
173
|
+
if amount is None:
|
|
174
|
+
lost.add("budget")
|
|
175
|
+
else:
|
|
176
|
+
budget = Money(amount=amount)
|
|
177
|
+
|
|
178
|
+
itinerary = raw.get("itinerary")
|
|
179
|
+
if itinerary is None:
|
|
180
|
+
itinerary = []
|
|
181
|
+
elif not isinstance(itinerary, list):
|
|
182
|
+
raise TypeError("ChinaTravel 'itinerary' must be a list")
|
|
183
|
+
|
|
184
|
+
activities: list[Activity] = []
|
|
185
|
+
max_day = 0
|
|
186
|
+
|
|
187
|
+
for day_index, day_entry in enumerate(itinerary, start=1):
|
|
188
|
+
if not isinstance(day_entry, dict):
|
|
189
|
+
lost.add("itinerary")
|
|
190
|
+
continue
|
|
191
|
+
for key in day_entry:
|
|
192
|
+
if key not in _DAY_CONSUMED:
|
|
193
|
+
lost.add(f"itinerary.{key}")
|
|
194
|
+
|
|
195
|
+
day_no = day_entry.get("day")
|
|
196
|
+
if not isinstance(day_no, int) or isinstance(day_no, bool) or day_no < 1:
|
|
197
|
+
day_no = day_index
|
|
198
|
+
max_day = max(max_day, day_no)
|
|
199
|
+
|
|
200
|
+
raw_activities = day_entry.get("activities") or []
|
|
201
|
+
if not isinstance(raw_activities, list):
|
|
202
|
+
lost.add("itinerary.activities")
|
|
203
|
+
continue
|
|
204
|
+
|
|
205
|
+
for item in raw_activities:
|
|
206
|
+
if not isinstance(item, dict):
|
|
207
|
+
lost.add("itinerary.activities")
|
|
208
|
+
continue
|
|
209
|
+
prefix = "itinerary.activities"
|
|
210
|
+
|
|
211
|
+
name = item.get("position")
|
|
212
|
+
if not (isinstance(name, str) and name.strip()):
|
|
213
|
+
# Intercity legs (train / airplane) carry no `position`; the
|
|
214
|
+
# arrival endpoint is the closest canonical POI.
|
|
215
|
+
name = item.get("end")
|
|
216
|
+
if isinstance(name, str) and name.strip():
|
|
217
|
+
# `end` was consumed as the POI name, `start` is dropped.
|
|
218
|
+
if "start" in item:
|
|
219
|
+
lost.add(f"{prefix}.start")
|
|
220
|
+
else:
|
|
221
|
+
name = None
|
|
222
|
+
|
|
223
|
+
for key in item:
|
|
224
|
+
if key in _ACTIVITY_CONSUMED:
|
|
225
|
+
continue
|
|
226
|
+
if key == "end" and name is not None and "position" not in item:
|
|
227
|
+
continue # consumed as poi_name above
|
|
228
|
+
lost.add(f"{prefix}.{key}")
|
|
229
|
+
|
|
230
|
+
if name is None:
|
|
231
|
+
# No usable POI name at all: the whole entry cannot be carried.
|
|
232
|
+
lost.add(f"{prefix}.position")
|
|
233
|
+
continue
|
|
234
|
+
|
|
235
|
+
start = _parse_time(item.get("start_time"))
|
|
236
|
+
end = _parse_time(item.get("end_time"))
|
|
237
|
+
if item.get("start_time") is not None and start is None:
|
|
238
|
+
lost.add(f"{prefix}.start_time")
|
|
239
|
+
if item.get("end_time") is not None and end is None:
|
|
240
|
+
lost.add(f"{prefix}.end_time")
|
|
241
|
+
|
|
242
|
+
mode, minutes = _transports(item.get("transports"), lost, prefix)
|
|
243
|
+
|
|
244
|
+
activities.append(
|
|
245
|
+
Activity(
|
|
246
|
+
poi_name=name,
|
|
247
|
+
day=day_no,
|
|
248
|
+
start=start,
|
|
249
|
+
end=end,
|
|
250
|
+
cost=_activity_cost(item, lost, prefix),
|
|
251
|
+
transport_mode=mode,
|
|
252
|
+
transport_minutes=minutes,
|
|
253
|
+
)
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
plan = Plan(activities=activities, days=max(max_day, 1), budget=budget)
|
|
257
|
+
return plan, sorted(lost)
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""TravelPlanner plan format -> canonical :class:`~tripverify.models.Plan`.
|
|
2
|
+
|
|
3
|
+
TravelPlanner emits one dict per day whose values are free-form English
|
|
4
|
+
sentences (``"Catfish Charlie's, Myrtle Beach; Cost: 14"``). Converting that
|
|
5
|
+
into the structured canonical model is inherently lossy: city annotations,
|
|
6
|
+
flight numbers, nightly-rate notes, room types and the plan-level budget
|
|
7
|
+
bookkeeping have no canonical slot. Every dropped key is reported in the
|
|
8
|
+
``lost`` list; paths are index free, de-duplicated and sorted.
|
|
9
|
+
|
|
10
|
+
Only the *structured* part of a value is parsed. No free-text semantic
|
|
11
|
+
matching is attempted (spec SS5.2) -- an unrecognised fragment is reported as
|
|
12
|
+
lost rather than guessed at.
|
|
13
|
+
|
|
14
|
+
Source format reference: ``tests/fixtures/tp_sample.json`` (real sample, see
|
|
15
|
+
``tests/fixtures/SOURCES.md``).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from datetime import time
|
|
22
|
+
from decimal import Decimal, InvalidOperation
|
|
23
|
+
from typing import Any, TypeGuard
|
|
24
|
+
|
|
25
|
+
from ..models import Activity, Money, Plan
|
|
26
|
+
|
|
27
|
+
__all__ = ["to_canonical"]
|
|
28
|
+
|
|
29
|
+
#: Top-level keys of an evaluation record that map onto the canonical model.
|
|
30
|
+
_RECORD_CONSUMED = frozenset({"plan", "budget"})
|
|
31
|
+
|
|
32
|
+
#: Per-day keys that map onto the canonical model.
|
|
33
|
+
_DAY_CONSUMED = frozenset(
|
|
34
|
+
{
|
|
35
|
+
"day",
|
|
36
|
+
"days",
|
|
37
|
+
"attraction",
|
|
38
|
+
"breakfast",
|
|
39
|
+
"lunch",
|
|
40
|
+
"dinner",
|
|
41
|
+
"accommodation",
|
|
42
|
+
"transportation",
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
#: Deterministic within-day ordering (TravelPlanner supplies no clock times).
|
|
47
|
+
_POI_FIELDS = ("breakfast", "attraction", "lunch", "dinner", "accommodation")
|
|
48
|
+
|
|
49
|
+
#: Accommodation keys consumed when the value is given as a nested object.
|
|
50
|
+
_ACCOMMODATION_CONSUMED = frozenset({"name", "cost", "price"})
|
|
51
|
+
|
|
52
|
+
#: Placeholder values meaning "nothing happened here" -- not a loss.
|
|
53
|
+
_EMPTY_VALUES = frozenset({"", "-", "--", "n/a", "na", "none", "null"})
|
|
54
|
+
|
|
55
|
+
_COST_RE = re.compile(r"^\s*cost\s*:\s*(?P<num>[-+]?[\d,]*\.?\d+)(?P<rest>.*)$", re.I)
|
|
56
|
+
_LABELLED_RE = re.compile(r"^\s*(?P<label>[A-Za-z][A-Za-z ./-]*?)\s*:\s*(?P<value>.*)$")
|
|
57
|
+
_TIME_RE = re.compile(r"(?P<h>\d{1,2}):(?P<m>\d{2})")
|
|
58
|
+
|
|
59
|
+
_MODE_KEYWORDS: tuple[tuple[str, str], ...] = (
|
|
60
|
+
("self-driving", "drive"),
|
|
61
|
+
("self driving", "drive"),
|
|
62
|
+
("rental car", "drive"),
|
|
63
|
+
("rental van", "drive"),
|
|
64
|
+
("driving", "drive"),
|
|
65
|
+
("drive", "drive"),
|
|
66
|
+
("flight", "flight"),
|
|
67
|
+
("airplane", "flight"),
|
|
68
|
+
("taxi", "taxi"),
|
|
69
|
+
("subway", "metro"),
|
|
70
|
+
("metro", "metro"),
|
|
71
|
+
("train", "train"),
|
|
72
|
+
("bus", "bus"),
|
|
73
|
+
("walk", "walk"),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _is_nonempty_str(value: Any) -> TypeGuard[str]:
|
|
78
|
+
"""Narrowing counterpart of :func:`_is_empty`.
|
|
79
|
+
|
|
80
|
+
Carries the same rule, but as a ``TypeGuard`` so that call sites which
|
|
81
|
+
skip empty values are statically known to hold a ``str`` afterwards.
|
|
82
|
+
"""
|
|
83
|
+
return isinstance(value, str) and value.strip().lower() not in _EMPTY_VALUES
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _is_empty(value: Any) -> bool:
|
|
87
|
+
return not _is_nonempty_str(value)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _to_decimal(raw: Any) -> Decimal | None:
|
|
91
|
+
if raw is None or isinstance(raw, bool):
|
|
92
|
+
return None
|
|
93
|
+
if isinstance(raw, (int, float)):
|
|
94
|
+
return Decimal(str(raw))
|
|
95
|
+
if isinstance(raw, str):
|
|
96
|
+
try:
|
|
97
|
+
return Decimal(raw.replace(",", "").strip())
|
|
98
|
+
except (InvalidOperation, ValueError):
|
|
99
|
+
return None
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _slug(label: str) -> str:
|
|
104
|
+
return re.sub(r"[^a-z0-9]+", "_", label.strip().lower()).strip("_")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _parse_time(text: str) -> time | None:
|
|
108
|
+
m = _TIME_RE.search(text)
|
|
109
|
+
if not m:
|
|
110
|
+
return None
|
|
111
|
+
hh, mm = int(m.group("h")), int(m.group("m"))
|
|
112
|
+
if "pm" in text.lower() and hh < 12:
|
|
113
|
+
hh += 12
|
|
114
|
+
elif "am" in text.lower() and hh == 12:
|
|
115
|
+
hh = 0
|
|
116
|
+
if not (0 <= hh < 24 and 0 <= mm < 60):
|
|
117
|
+
return None
|
|
118
|
+
return time(hh, mm)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _split_entities(value: str) -> list[tuple[str, Money | None, str | None]]:
|
|
122
|
+
"""Split ``"A, City; Cost: 14;B, City"`` into ``(name, cost, note)`` tuples.
|
|
123
|
+
|
|
124
|
+
A ``Cost:`` segment attaches to the entity that precedes it. ``note`` holds
|
|
125
|
+
trailing text that the ``Money`` model cannot carry (e.g. ``"for 3
|
|
126
|
+
nights"``) so the caller can report it as lost.
|
|
127
|
+
"""
|
|
128
|
+
entities: list[tuple[str, Money | None, str | None]] = []
|
|
129
|
+
for segment in value.split(";"):
|
|
130
|
+
chunk = segment.strip()
|
|
131
|
+
if not chunk or chunk.lower() in _EMPTY_VALUES:
|
|
132
|
+
continue
|
|
133
|
+
cost_match = _COST_RE.match(chunk)
|
|
134
|
+
if cost_match and entities:
|
|
135
|
+
amount = _to_decimal(cost_match.group("num"))
|
|
136
|
+
note = cost_match.group("rest").strip() or None
|
|
137
|
+
name, _, prev_note = entities[-1]
|
|
138
|
+
money = Money(amount=amount) if amount is not None else None
|
|
139
|
+
entities[-1] = (name, money, note or prev_note)
|
|
140
|
+
else:
|
|
141
|
+
entities.append((chunk, None, None))
|
|
142
|
+
return entities
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _parse_transportation(
|
|
146
|
+
value: str, lost: set[str]
|
|
147
|
+
) -> tuple[str | None, int | None]:
|
|
148
|
+
"""Extract ``(mode, minutes)``; report every fragment that does not fit."""
|
|
149
|
+
lowered = value.lower()
|
|
150
|
+
mode: str | None = None
|
|
151
|
+
for keyword, canonical in _MODE_KEYWORDS:
|
|
152
|
+
if keyword in lowered:
|
|
153
|
+
mode = canonical
|
|
154
|
+
break
|
|
155
|
+
if mode is None:
|
|
156
|
+
lost.add("transportation.mode")
|
|
157
|
+
|
|
158
|
+
departure: time | None = None
|
|
159
|
+
arrival: time | None = None
|
|
160
|
+
for segment in re.split(r"[;,]", value):
|
|
161
|
+
chunk = segment.strip()
|
|
162
|
+
if not chunk:
|
|
163
|
+
continue
|
|
164
|
+
labelled = _LABELLED_RE.match(chunk)
|
|
165
|
+
if labelled:
|
|
166
|
+
label = _slug(labelled.group("label"))
|
|
167
|
+
if label in ("departure_time", "departure"):
|
|
168
|
+
departure = _parse_time(labelled.group("value"))
|
|
169
|
+
continue
|
|
170
|
+
if label in ("arrival_time", "arrival"):
|
|
171
|
+
arrival = _parse_time(labelled.group("value"))
|
|
172
|
+
continue
|
|
173
|
+
lost.add(f"transportation.{label}")
|
|
174
|
+
continue
|
|
175
|
+
if mode is not None and any(k in chunk.lower() for k, _ in _MODE_KEYWORDS):
|
|
176
|
+
continue # this fragment is the mode phrase itself
|
|
177
|
+
lost.add("transportation.detail")
|
|
178
|
+
|
|
179
|
+
minutes: int | None = None
|
|
180
|
+
if departure is not None and arrival is not None:
|
|
181
|
+
start = departure.hour * 60 + departure.minute
|
|
182
|
+
end = arrival.hour * 60 + arrival.minute
|
|
183
|
+
if end < start:
|
|
184
|
+
end += 24 * 60
|
|
185
|
+
minutes = end - start
|
|
186
|
+
elif departure is not None or arrival is not None:
|
|
187
|
+
lost.add("transportation.detail")
|
|
188
|
+
return mode, minutes
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _accommodation_object(
|
|
192
|
+
value: dict[str, Any], lost: set[str]
|
|
193
|
+
) -> tuple[str, Money | None] | None:
|
|
194
|
+
"""Handle the object form ``{"name": ..., "room_type": ..., "cost": ...}``."""
|
|
195
|
+
for key in value:
|
|
196
|
+
if key not in _ACCOMMODATION_CONSUMED:
|
|
197
|
+
lost.add(f"accommodation.{key}")
|
|
198
|
+
name = value.get("name")
|
|
199
|
+
if not (isinstance(name, str) and name.strip()):
|
|
200
|
+
lost.add("accommodation.name")
|
|
201
|
+
return None
|
|
202
|
+
amount = _to_decimal(value.get("cost"))
|
|
203
|
+
if amount is None:
|
|
204
|
+
amount = _to_decimal(value.get("price"))
|
|
205
|
+
elif _to_decimal(value.get("price")) not in (None, amount):
|
|
206
|
+
lost.add("accommodation.price")
|
|
207
|
+
return name.strip(), (Money(amount=amount) if amount is not None else None)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def to_canonical(raw: dict[str, Any]) -> tuple[Plan, list[str]]:
|
|
211
|
+
"""Convert a TravelPlanner record to ``(Plan, lost_fields)``.
|
|
212
|
+
|
|
213
|
+
``raw`` may be a full evaluation record (``{"idx", "query", "plan"}``) or
|
|
214
|
+
any dict carrying a ``"plan"`` list. ``lost_fields`` is sorted and empty
|
|
215
|
+
exactly when the conversion was lossless.
|
|
216
|
+
"""
|
|
217
|
+
if not isinstance(raw, dict):
|
|
218
|
+
raise TypeError(f"TravelPlanner record must be a dict, got {type(raw).__name__}")
|
|
219
|
+
if "plan" not in raw:
|
|
220
|
+
raise ValueError("TravelPlanner record has no 'plan' key")
|
|
221
|
+
|
|
222
|
+
lost: set[str] = set()
|
|
223
|
+
for key in raw:
|
|
224
|
+
if key not in _RECORD_CONSUMED:
|
|
225
|
+
lost.add(key)
|
|
226
|
+
|
|
227
|
+
budget: Money | None = None
|
|
228
|
+
if "budget" in raw:
|
|
229
|
+
amount = _to_decimal(raw.get("budget"))
|
|
230
|
+
if amount is None:
|
|
231
|
+
lost.add("budget")
|
|
232
|
+
else:
|
|
233
|
+
budget = Money(amount=amount)
|
|
234
|
+
|
|
235
|
+
steps = raw.get("plan") or []
|
|
236
|
+
if not isinstance(steps, list):
|
|
237
|
+
raise TypeError("TravelPlanner 'plan' must be a list")
|
|
238
|
+
|
|
239
|
+
activities: list[Activity] = []
|
|
240
|
+
max_day = 0
|
|
241
|
+
|
|
242
|
+
for step_index, step in enumerate(steps, start=1):
|
|
243
|
+
if not isinstance(step, dict):
|
|
244
|
+
lost.add("plan")
|
|
245
|
+
continue
|
|
246
|
+
for key in step:
|
|
247
|
+
if key not in _DAY_CONSUMED:
|
|
248
|
+
lost.add(key)
|
|
249
|
+
|
|
250
|
+
day_no = step.get("days", step.get("day"))
|
|
251
|
+
if isinstance(day_no, str):
|
|
252
|
+
day_no = _to_decimal(day_no)
|
|
253
|
+
day_no = int(day_no) if day_no is not None else None
|
|
254
|
+
if not isinstance(day_no, int) or isinstance(day_no, bool) or day_no < 1:
|
|
255
|
+
day_no = step_index
|
|
256
|
+
max_day = max(max_day, day_no)
|
|
257
|
+
|
|
258
|
+
day_start = len(activities)
|
|
259
|
+
for field in _POI_FIELDS:
|
|
260
|
+
value = step.get(field)
|
|
261
|
+
if isinstance(value, dict) and field == "accommodation":
|
|
262
|
+
parsed = _accommodation_object(value, lost)
|
|
263
|
+
if parsed is not None:
|
|
264
|
+
name, money = parsed
|
|
265
|
+
activities.append(
|
|
266
|
+
Activity(poi_name=name, day=day_no, cost=money)
|
|
267
|
+
)
|
|
268
|
+
continue
|
|
269
|
+
if not _is_nonempty_str(value):
|
|
270
|
+
if value is not None and not isinstance(value, str):
|
|
271
|
+
lost.add(field)
|
|
272
|
+
continue
|
|
273
|
+
for name, money, note in _split_entities(value):
|
|
274
|
+
if note:
|
|
275
|
+
lost.add(f"{field}.cost_note")
|
|
276
|
+
activities.append(Activity(poi_name=name, day=day_no, cost=money))
|
|
277
|
+
|
|
278
|
+
transportation = step.get("transportation")
|
|
279
|
+
if _is_nonempty_str(transportation):
|
|
280
|
+
if len(activities) > day_start:
|
|
281
|
+
mode, minutes = _parse_transportation(transportation, lost)
|
|
282
|
+
first = activities[day_start]
|
|
283
|
+
first.transport_mode = mode
|
|
284
|
+
first.transport_minutes = minutes
|
|
285
|
+
else:
|
|
286
|
+
# No activity on this day to hang the transport leg on.
|
|
287
|
+
lost.add("transportation")
|
|
288
|
+
|
|
289
|
+
plan = Plan(activities=activities, days=max(max_day, 1), budget=budget)
|
|
290
|
+
return plan, sorted(lost)
|