Beemer Claude Opus 4.7 commited on
Commit
8c9bc18
·
1 Parent(s): ef6e3dc

Ingest Customs Tariff Schedule Chapters 98 and 99

Browse files

The CBSA special-classification provisions: Chapter 98 (non-commercial -- traveller
exemptions, settler's effects, returning Canadians, conveyances temporarily imported,
charitable donations, prohibited firearms) and Chapter 99 (commercial -- end-use
programs, temporary importations for industry). 96 chunks, one per 4-digit heading
plus a notes chunk per chapter. Source: CBSA's 2026 HTML edition of the Customs
Tariff (the Schedule is not in Justice Laws XML), bump the SOURCES year to refresh.

Tagged doc_type='legislation', act_code='C-54.011'. Five new tariff-schedule gold
eval questions added (settler's effects, alcohol/tobacco allowance, non-resident
conveyance, prohibited firearms, foreign-country representatives).

134-question eval: Hit@1 0.75 / Hit@3 0.89 / Hit@5 0.93 / Hit@10 0.96 / MRR 0.83
(vs pre-add 129-Q baseline 0.74 / 0.88 / 0.92 / 0.96 / 0.82 -- flat or up everywhere).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

canlex/tariff_schedule.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ingest Chapters 98 and 99 of the Customs Tariff Schedule.
2
+
3
+ The Customs Tariff's Schedule is the Harmonized System classification of goods
4
+ -- chapters 1-97 categorise every imported good for duty purposes. Those 97
5
+ chapters are huge and outside CanLex's scope, but **chapters 98 and 99 are
6
+ different**: they carry Canada's "special classification" provisions, which
7
+ matter for almost every CBSA border interaction:
8
+
9
+ - Chapter 98 (non-commercial): traveller exemptions, settler's effects,
10
+ Canadian goods returned, ancestral household effects, conveyances
11
+ temporarily imported by a resident, etc.
12
+ - Chapter 99 (commercial): temporary importations, end-use programs,
13
+ government imports, reduced-rate goods for specific industries.
14
+
15
+ Source: the CBSA's HTML edition of the current Customs Tariff. The Justice
16
+ Laws XML for the Act (C-54.011) does NOT include the Schedule.
17
+
18
+ Chunking is one chunk per 4-digit HEADING (98.01, 98.02, ...) plus one chunk
19
+ per chapter for its Notes and Subheading Notes -- a heading is the natural
20
+ unit of legal classification (the eight- and ten-digit items below it are the
21
+ same rule with finer rate granularity).
22
+
23
+ py -m canlex.tariff_schedule
24
+ """
25
+ import json
26
+ import re
27
+ import time
28
+ import urllib.request
29
+ from collections import defaultdict
30
+
31
+ from bs4 import BeautifulSoup
32
+
33
+ from .config import PROCESSED_DIR, RAW_DIR
34
+
35
+ RAW = RAW_DIR / "tariff_schedule"
36
+ OUT = PROCESSED_DIR / "tariff_schedule.json"
37
+
38
+ _UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
39
+ "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
40
+
41
+ # The 2026 edition is the current Customs Tariff at the time of writing. To
42
+ # refresh: bump the year in the URL and `edition` once CBSA publishes the next.
43
+ SOURCES = {
44
+ "ch98": {
45
+ "code": "ch98",
46
+ "chapter": "98",
47
+ "title": "Special classification provisions — non-commercial",
48
+ "url": ("https://www.cbsa-asfc.gc.ca/trade-commerce/tariff-tarif/"
49
+ "2026/html/00/ch98-eng.html"),
50
+ "edition": "2026",
51
+ },
52
+ "ch99": {
53
+ "code": "ch99",
54
+ "chapter": "99",
55
+ "title": "Special classification provisions — commercial",
56
+ "url": ("https://www.cbsa-asfc.gc.ca/trade-commerce/tariff-tarif/"
57
+ "2026/html/00/ch99-eng.html"),
58
+ "edition": "2026",
59
+ },
60
+ }
61
+
62
+
63
+ def _norm(text):
64
+ return re.sub(r"\s+", " ", (text or "").replace("\xa0", " ")).strip()
65
+
66
+
67
+ def _fetch(url, dest):
68
+ if dest.exists():
69
+ return dest.read_bytes()
70
+ dest.parent.mkdir(parents=True, exist_ok=True)
71
+ req = urllib.request.Request(url, headers={"User-Agent": _UA})
72
+ with urllib.request.urlopen(req, timeout=60) as resp:
73
+ dest.write_bytes(resp.read())
74
+ time.sleep(0.5)
75
+ return dest.read_bytes()
76
+
77
+
78
+ def _heading_of(item):
79
+ """Map a tariff-item code to its 4-digit heading. The schedule uses three
80
+ levels:
81
+ - '98.01' (4 digits) -- heading
82
+ - '9801.10' (6 digits) -- subheading
83
+ - '9801.10.10' (8 digits) -- tariff item
84
+ All three roll up to heading '98.01'."""
85
+ digits = re.sub(r"\D", "", item)
86
+ if len(digits) < 4:
87
+ return None
88
+ return f"{digits[:2]}.{digits[2:4]}"
89
+
90
+
91
+ def _collect_notes(main):
92
+ """Return the chapter's Notes + Subheading Notes as a single text block."""
93
+ out = []
94
+ for label in ("Notes", "Subheading Notes"):
95
+ h2 = main.find(
96
+ "h2",
97
+ string=lambda s, lbl=label: s and lbl in s and (
98
+ lbl != "Notes" or "Subheading" not in s))
99
+ if not h2:
100
+ continue
101
+ parts = []
102
+ sib = h2.find_next_sibling()
103
+ while sib and sib.name != "h2":
104
+ t = _norm(sib.get_text(" ", strip=True))
105
+ if t:
106
+ parts.append(t)
107
+ sib = sib.find_next_sibling()
108
+ if parts:
109
+ out.append(f"{label}:\n" + "\n".join(parts))
110
+ return "\n\n".join(out)
111
+
112
+
113
+ def parse_chapter(html, src):
114
+ """Parse one Customs Tariff Schedule chapter into chunks."""
115
+ soup = BeautifulSoup(html, "html.parser")
116
+ main = soup.find("main")
117
+ if main is None:
118
+ return []
119
+ for sup in main.find_all("sup"):
120
+ sup.decompose()
121
+
122
+ chunks = []
123
+ chapter = src["chapter"]
124
+ citation_root = f"Customs Tariff, Sched., Ch. {chapter}"
125
+
126
+ # Chapter Notes + Subheading Notes -- one chunk per chapter.
127
+ notes_body = _collect_notes(main)
128
+ if notes_body:
129
+ chunks.append({
130
+ "id": f"tariff-sched-ch{chapter}-notes",
131
+ "doc_type": "legislation",
132
+ "act_code": "C-54.011",
133
+ "act_short": "Customs Tariff",
134
+ "act_name": "Customs Tariff",
135
+ "section": f"Sch-Ch{chapter}-Notes",
136
+ "marginal_note": (f"Chapter {chapter} Notes — "
137
+ f"{src['title']}"),
138
+ "part": f"Schedule, Chapter {chapter}",
139
+ "division": "",
140
+ "heading": src["title"],
141
+ "text": notes_body,
142
+ "history": "",
143
+ "last_amended": "",
144
+ "current_to": src["edition"],
145
+ "citation": f"{citation_root}, Notes",
146
+ "source_url": src["url"],
147
+ })
148
+
149
+ # Walk every row in the schedule table, grouping by 4-digit heading.
150
+ table = main.find("table")
151
+ if table is None:
152
+ return chunks
153
+
154
+ rows_by_heading = defaultdict(list) # heading -> list of (item, ss, desc, unit, mfn, pref)
155
+ heading_desc = {} # heading -> the 4-digit row's description
156
+
157
+ for tr in table.find_all("tr"):
158
+ cells = tr.find_all(["td", "th"], recursive=False)
159
+ if not cells:
160
+ continue
161
+ first = _norm(cells[0].get_text(" ", strip=True))
162
+ if not first or first == "Tariff Item":
163
+ continue # header row or blank
164
+ heading = _heading_of(first)
165
+ if heading is None:
166
+ continue
167
+
168
+ def col(i):
169
+ return _norm(cells[i].get_text(" ", strip=True)) if i < len(cells) else ""
170
+
171
+ ss, desc, unit, mfn, pref = col(1), col(2), col(3), col(4), col(5)
172
+
173
+ # A 4-digit row carries only the heading number and description -- store
174
+ # it once. Otherwise it's a subheading/item row; remember its rate cells.
175
+ digits = re.sub(r"\D", "", first)
176
+ if len(digits) == 4 and desc and heading not in heading_desc:
177
+ heading_desc[heading] = desc
178
+ rows_by_heading[heading].append((first, ss, desc, unit, mfn, pref))
179
+
180
+ for heading in sorted(rows_by_heading):
181
+ desc = heading_desc.get(heading, "")
182
+ rows = rows_by_heading[heading]
183
+ if not desc:
184
+ # No bare 4-digit row -- fall back to the first row's description.
185
+ desc = next((r[2] for r in rows if r[2]), "")
186
+
187
+ # Format the chunk: heading description first, then the items as a
188
+ # readable list. Suppress description on item/subheading rows that just
189
+ # repeat the heading desc verbatim (very common in this Schedule).
190
+ lines = []
191
+ for item, ss, item_desc, unit, mfn, pref in rows:
192
+ d = re.sub(r"\D", "", item)
193
+ if len(d) == 4:
194
+ continue # the heading row, already in desc
195
+ label = f" {item}"
196
+ if ss:
197
+ label += f" (SS {ss})"
198
+ extras = []
199
+ if item_desc and item_desc != desc:
200
+ extras.append(item_desc)
201
+ rate = []
202
+ if mfn:
203
+ rate.append(f"MFN {mfn}")
204
+ if pref:
205
+ rate.append(f"Pref: {pref}")
206
+ if unit and unit != "-":
207
+ rate.append(f"Unit {unit}")
208
+ if rate:
209
+ extras.append(" | ".join(rate))
210
+ tail = " — " + "; ".join(extras) if extras else ""
211
+ lines.append(label + tail)
212
+
213
+ body = f"Heading {heading} — {desc}"
214
+ if lines:
215
+ body += "\n\nTariff items:\n" + "\n".join(lines)
216
+
217
+ chunks.append({
218
+ "id": f"tariff-sched-{heading.replace('.', '-')}",
219
+ "doc_type": "legislation",
220
+ "act_code": "C-54.011",
221
+ "act_short": "Customs Tariff",
222
+ "act_name": "Customs Tariff",
223
+ "section": f"Sch-{heading}",
224
+ "marginal_note": desc[:200],
225
+ "part": f"Schedule, Chapter {chapter}",
226
+ "division": "",
227
+ "heading": src["title"],
228
+ "text": body,
229
+ "history": "",
230
+ "last_amended": "",
231
+ "current_to": src["edition"],
232
+ "citation": f"Customs Tariff, Sched., heading {heading}",
233
+ "source_url": src["url"],
234
+ })
235
+
236
+ return chunks
237
+
238
+
239
+ def build():
240
+ all_chunks = []
241
+ for src in SOURCES.values():
242
+ print(f"Ingesting Customs Tariff Schedule {src['code']} ...")
243
+ try:
244
+ html = _fetch(src["url"], RAW / f"{src['code']}.html")
245
+ chunks = parse_chapter(html, src)
246
+ except Exception as exc:
247
+ print(f" !! {src['code']}: {type(exc).__name__}: {exc}")
248
+ continue
249
+ all_chunks.extend(chunks)
250
+ print(f" {len(chunks)} chunks")
251
+ PROCESSED_DIR.mkdir(parents=True, exist_ok=True)
252
+ OUT.write_text(json.dumps(all_chunks, ensure_ascii=False, indent=1),
253
+ encoding="utf-8")
254
+ print(f"\n{len(all_chunks)} tariff-schedule chunks from {len(SOURCES)} "
255
+ f"chapter(s) -> {OUT}")
256
+
257
+
258
+ if __name__ == "__main__":
259
+ build()
data/eval/questions.json CHANGED
@@ -30,6 +30,11 @@
30
  {"query": "Advance information about commercial goods before they arrive in Canada", "answers": [["Customs Act", "12.1"]]},
31
  {"query": "How is the value for duty of imported goods determined?", "answers": [["Customs Act", "46"], ["Customs Act", "47"], ["Customs Act", "48"]]},
32
  {"query": "How are imported goods classified under the Customs Tariff?", "answers": [["Customs Tariff", "10"]]},
 
 
 
 
 
33
  {"query": "Must travellers report large amounts of currency when crossing the border?", "answers": [["PCMLTFA", "12"]]},
34
  {"query": "Can an officer seize currency that was not reported at the border?", "answers": [["PCMLTFA", "18"]]},
35
  {"query": "How does someone appeal the forfeiture of seized currency to the Federal Court?", "answers": [["PCMLTFA", "30"]]},
 
30
  {"query": "Advance information about commercial goods before they arrive in Canada", "answers": [["Customs Act", "12.1"]]},
31
  {"query": "How is the value for duty of imported goods determined?", "answers": [["Customs Act", "46"], ["Customs Act", "47"], ["Customs Act", "48"]]},
32
  {"query": "How are imported goods classified under the Customs Tariff?", "answers": [["Customs Tariff", "10"]]},
33
+ {"query": "Which tariff heading in the Customs Tariff Schedule covers a settler's effects on first arrival?", "answers": [["Customs Tariff", "Sch-98.07"]]},
34
+ {"query": "What allowance of alcohol and tobacco may a traveller bring back to Canada duty free?", "answers": [["Customs Tariff", "Sch-98.27"]]},
35
+ {"query": "Conveyance temporarily imported by a non-resident visiting Canada -- customs tariff treatment", "answers": [["Customs Tariff", "Sch-98.03"]]},
36
+ {"query": "Tariff classification of prohibited firearms and weapons under the Customs Tariff", "answers": [["Customs Tariff", "Sch-98.98"]]},
37
+ {"query": "Tariff treatment of articles imported for personal use of representatives of foreign countries", "answers": [["Customs Tariff", "Sch-98.08"]]},
38
  {"query": "Must travellers report large amounts of currency when crossing the border?", "answers": [["PCMLTFA", "12"]]},
39
  {"query": "Can an officer seize currency that was not reported at the border?", "answers": [["PCMLTFA", "18"]]},
40
  {"query": "How does someone appeal the forfeiture of seized currency to the Federal Court?", "answers": [["PCMLTFA", "30"]]},
data/processed/tariff_schedule.json ADDED
The diff for this file is too large to render. See raw diff