muckrake 0.2.1__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.
Files changed (48) hide show
  1. muckrake/__init__.py +61 -0
  2. muckrake/artifacts.py +72 -0
  3. muckrake/cli.py +522 -0
  4. muckrake/crawl.py +223 -0
  5. muckrake/dataset.py +231 -0
  6. muckrake/db.py +478 -0
  7. muckrake/dedupe/README.md +52 -0
  8. muckrake/dedupe/__init__.py +37 -0
  9. muckrake/dedupe/cluster.py +534 -0
  10. muckrake/dedupe/dedupe.py +133 -0
  11. muckrake/dedupe/dedupe_edges.py +214 -0
  12. muckrake/dedupe/review.py +329 -0
  13. muckrake/entity_query.py +114 -0
  14. muckrake/entity_write.py +244 -0
  15. muckrake/env.py +52 -0
  16. muckrake/export.py +40 -0
  17. muckrake/extract/__init__.py +0 -0
  18. muckrake/extract/fetch.py +186 -0
  19. muckrake/extract/ner/README.md +210 -0
  20. muckrake/extract/ner/__init__.py +4 -0
  21. muckrake/extract/ner/engines/__init__.py +32 -0
  22. muckrake/extract/ner/engines/base.py +14 -0
  23. muckrake/extract/ner/engines/delimited.py +39 -0
  24. muckrake/extract/ner/engines/llm.py +164 -0
  25. muckrake/extract/ner/engines/llm_prompt.py +44 -0
  26. muckrake/extract/ner/materialize.py +255 -0
  27. muckrake/extract/ner/pipeline.py +151 -0
  28. muckrake/extract/ner/review.py +706 -0
  29. muckrake/extract/ner/storage.py +200 -0
  30. muckrake/id.py +3 -0
  31. muckrake/load.py +70 -0
  32. muckrake/logging.py +56 -0
  33. muckrake/py.typed +0 -0
  34. muckrake/release.py +356 -0
  35. muckrake/runs.py +228 -0
  36. muckrake/search.py +335 -0
  37. muckrake/serialize.py +119 -0
  38. muckrake/settings.py +41 -0
  39. muckrake/store.py +117 -0
  40. muckrake/util.py +27 -0
  41. muckrake/utils/__init__.py +13 -0
  42. muckrake/utils/dates.py +438 -0
  43. muckrake/utils/gb_coh.py +36 -0
  44. muckrake/view.py +58 -0
  45. muckrake-0.2.1.dist-info/METADATA +136 -0
  46. muckrake-0.2.1.dist-info/RECORD +48 -0
  47. muckrake-0.2.1.dist-info/WHEEL +4 -0
  48. muckrake-0.2.1.dist-info/entry_points.txt +3 -0
muckrake/settings.py ADDED
@@ -0,0 +1,41 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from muckrake.env import find_env_file, load_env_file
5
+
6
+ # Base directory of the project
7
+ BASE_PATH = Path(__file__).parent.parent.parent
8
+
9
+
10
+ def _normalize_database_url(url: str | None) -> str | None:
11
+ if url is None:
12
+ return None
13
+ if url.startswith("postgresql://") and "+psycopg" not in url:
14
+ return "postgresql+psycopg://" + url[len("postgresql://") :]
15
+ return url
16
+
17
+
18
+ if os.getenv("ENVIRONMENT") != "production":
19
+ env_file = find_env_file()
20
+ if env_file is not None:
21
+ load_env_file(env_file)
22
+
23
+
24
+ def _current_data_path() -> Path:
25
+ return Path(os.getenv("MUCKRAKE_DATA_PATH", "data"))
26
+
27
+
28
+ def get_working_sql_uri() -> str:
29
+ return _normalize_database_url(os.getenv("MUCKRAKE_DATABASE_URL")) or f"sqlite:///{(_current_data_path() / 'muckrake.db').as_posix()}"
30
+
31
+
32
+ def get_published_sql_uri() -> str:
33
+ return _normalize_database_url(os.getenv("MUCKRAKE_PUBLISHED_DATABASE_URL")) or get_working_sql_uri()
34
+
35
+
36
+ DATA_PATH = Path(os.getenv("MUCKRAKE_DATA_PATH", "data"))
37
+ ARTIFACT_PATH = Path(os.getenv("MUCKRAKE_ARTIFACT_PATH", DATA_PATH / "artifacts"))
38
+ SQL_URI: str = get_working_sql_uri()
39
+ PUBLISHED_SQL_URI: str = get_published_sql_uri()
40
+
41
+ LEVEL_PATH = DATA_PATH / "leveldb"
muckrake/store.py ADDED
@@ -0,0 +1,117 @@
1
+ import logging
2
+ import shutil
3
+ from typing import Iterable, Set, List, Optional
4
+
5
+ from followthemoney import DS, SE, Statement
6
+ from followthemoney.dataset import Dataset
7
+ from nomenklatura import settings as nk_settings
8
+ from nomenklatura.store import Store
9
+ from nomenklatura.store.level import LevelDBStore
10
+ from nomenklatura.store.sql import SQLStore, SQLView, SQLWriter
11
+ from nomenklatura.db import get_metadata
12
+ from nomenklatura.store.sql import make_statement_table
13
+ from sqlalchemy import MetaData, select
14
+ from sqlalchemy.engine import create_engine
15
+
16
+ from muckrake.db import get_database_dialect, get_resolver
17
+ from muckrake.settings import SQL_URI, LEVEL_PATH
18
+
19
+ log = logging.getLogger(__name__)
20
+ SQL_BATCH_STATEMENTS = 500
21
+
22
+
23
+ class CombinedDataset(Dataset):
24
+ """A virtual dataset that combines multiple leaf datasets."""
25
+
26
+ def __init__(self, name: str, datasets: Iterable[str]):
27
+ super().__init__({"name": name, "title": name})
28
+ self._leaf_names = set(datasets)
29
+
30
+ @property
31
+ def dataset_names(self) -> List[str]:
32
+ return [self.name] + list(self._leaf_names)
33
+
34
+ @property
35
+ def leaf_names(self) -> Set[str]:
36
+ return self._leaf_names
37
+
38
+
39
+ def get_level_store(dataset_names: Iterable[str], fresh: bool = False) -> LevelDBStore:
40
+ """Get a LevelDB store for processing."""
41
+ if fresh and LEVEL_PATH.exists():
42
+ shutil.rmtree(LEVEL_PATH)
43
+
44
+ LEVEL_PATH.parent.mkdir(parents=True, exist_ok=True)
45
+ dataset = CombinedDataset("all", dataset_names)
46
+ resolver = get_resolver(begin=True)
47
+ try:
48
+ linker = resolver.get_linker()
49
+ finally:
50
+ resolver.rollback()
51
+ return LevelDBStore(dataset, linker, LEVEL_PATH)
52
+
53
+
54
+ class MergedSQLView(SQLView[DS, SE]):
55
+ """Custom SQL view that properly merges entities with the same canonical_id.
56
+
57
+ When querying for an entity by its canonical ID, this view collects ALL statements
58
+ from all entities that were merged into that canonical ID and assembles them into
59
+ a single entity with the most specific schema.
60
+ """
61
+
62
+ def get_entity(self, id: str) -> Optional[SE]:
63
+ """Get entity by canonical ID, merging all statements from merged entities."""
64
+ table = self.store.table
65
+ q = select(table)
66
+ q = q.where(table.c.canonical_id == id)
67
+ q = q.where(table.c.dataset.in_(self.dataset_names))
68
+ # Order by entity_id to ensure consistent grouping if needed for debugging,
69
+ # but we'll collect ALL statements regardless
70
+ q = q.order_by(table.c.entity_id)
71
+
72
+ # Collect ALL statements with this canonical_id
73
+ all_statements: List[Statement] = []
74
+ for stmt in self.store._iterate_stmts(q, stream=False):
75
+ all_statements.append(stmt)
76
+
77
+ if not all_statements:
78
+ return None
79
+
80
+ # Assemble into a single entity - from_statements will compute the
81
+ # most specific common schema (e.g., Person over LegalEntity)
82
+ return self.store.assemble(all_statements)
83
+
84
+
85
+ class MergedSQLStore(SQLStore[DS, SE]):
86
+ """Custom SQL store that uses MergedSQLView."""
87
+
88
+ def __init__(self, dataset: DS, linker, uri: str = SQL_URI, **engine_kwargs):
89
+ Store.__init__(self, dataset, linker)
90
+ if get_database_dialect(uri) != "sqlite" and "pool_size" not in engine_kwargs:
91
+ engine_kwargs["pool_size"] = nk_settings.DB_POOL_SIZE
92
+ metadata = MetaData()
93
+ self.engine = create_engine(uri, **engine_kwargs)
94
+ self.table = make_statement_table(metadata)
95
+ metadata.create_all(self.engine, tables=[self.table], checkfirst=True)
96
+
97
+ def view(self, scope: DS, external: bool = False) -> SQLView[DS, SE]:
98
+ return MergedSQLView(self, scope, external=external)
99
+
100
+ def writer(self):
101
+ return MuckrakeSQLWriter(self)
102
+
103
+
104
+ class MuckrakeSQLWriter(SQLWriter[DS, SE]):
105
+ # Keep statement batches moderate to avoid oversized INSERT statements.
106
+ BATCH_STATEMENTS = SQL_BATCH_STATEMENTS
107
+
108
+
109
+ def get_sql_store(dataset_names: Iterable[str], uri: str = SQL_URI) -> MergedSQLStore:
110
+ """Get a SQL store for serving with proper entity merging."""
111
+ dataset = CombinedDataset("all", dataset_names)
112
+ resolver = get_resolver(uri=uri, begin=True)
113
+ try:
114
+ linker = resolver.get_linker()
115
+ finally:
116
+ resolver.rollback()
117
+ return MergedSQLStore(dataset, linker, uri=uri)
muckrake/util.py ADDED
@@ -0,0 +1,27 @@
1
+ from typing import Optional, Any
2
+
3
+ from muckrake.utils.dates import parse_date, parse_date_token
4
+
5
+
6
+ def to_string(value: Any) -> Optional[str]:
7
+ """Clean a string value, handling NaN and None."""
8
+ if value is None:
9
+ return None
10
+ text = str(value).strip()
11
+ if not text or text.lower() in ("nan", "none", "n/a"):
12
+ return None
13
+ return text
14
+
15
+
16
+ def parse_amount(text: Any) -> Optional[float]:
17
+ """Parse a currency amount string into a float."""
18
+ text = to_string(text)
19
+ if text is None:
20
+ return None
21
+
22
+ # Remove common currency symbols and commas
23
+ cleaned = text.replace("£", "").replace("$", "").replace("€", "").replace(",", "")
24
+ try:
25
+ return float(cleaned)
26
+ except ValueError:
27
+ return None
@@ -0,0 +1,13 @@
1
+ from muckrake.utils.gb_coh import is_gb_coh, normalize_gb_coh
2
+ from muckrake.utils.dates import parse_date, parse_date_token, parse_month_span, parse_month_value, parse_partial_date, parse_year_hint_date
3
+
4
+ __all__ = [
5
+ "is_gb_coh",
6
+ "normalize_gb_coh",
7
+ "parse_date",
8
+ "parse_date_token",
9
+ "parse_month_span",
10
+ "parse_month_value",
11
+ "parse_partial_date",
12
+ "parse_year_hint_date",
13
+ ]
@@ -0,0 +1,438 @@
1
+ from calendar import monthrange
2
+ from datetime import date, datetime, timedelta
3
+ import math
4
+ import re
5
+ from typing import Any, Optional
6
+
7
+
8
+ DATE_FORMATS = [
9
+ "%d/%m/%Y",
10
+ "%d/%m/%y",
11
+ "%Y-%m-%d",
12
+ "%d-%m-%Y",
13
+ "%d-%b-%Y",
14
+ "%d-%b-%y",
15
+ "%d %b %Y",
16
+ "%d %b %y",
17
+ "%d %B %Y",
18
+ "%d %B %y",
19
+ "%B %d, %Y",
20
+ "%A, %B %d, %Y",
21
+ "%A, %d %B %Y",
22
+ "%A, %d %B %y",
23
+ "%Y/%m/%d",
24
+ ]
25
+
26
+ MONTHS = {
27
+ "jan": 1,
28
+ "january": 1,
29
+ "feb": 2,
30
+ "february": 2,
31
+ "februrary": 2,
32
+ "mar": 3,
33
+ "march": 3,
34
+ "marc": 3,
35
+ "apr": 4,
36
+ "april": 4,
37
+ "may": 5,
38
+ "jun": 6,
39
+ "june": 6,
40
+ "junee": 6,
41
+ "july": 7,
42
+ "jul": 7,
43
+ "aug": 8,
44
+ "august": 8,
45
+ "sep": 9,
46
+ "sept": 9,
47
+ "september": 9,
48
+ "septeber": 9,
49
+ "oct": 10,
50
+ "october": 10,
51
+ "nov": 11,
52
+ "november": 11,
53
+ "dec": 12,
54
+ "december": 12,
55
+ }
56
+
57
+
58
+ def to_string(value: Any) -> Optional[str]:
59
+ if value is None:
60
+ return None
61
+ text = str(value).strip()
62
+ if not text or text.lower() in ("nan", "none", "n/a"):
63
+ return None
64
+ return text
65
+
66
+
67
+ def normalize_whitespace(value: str) -> str:
68
+ return re.sub(r"\s+", " ", value).strip()
69
+
70
+
71
+ def month_number(value: str) -> Optional[int]:
72
+ return MONTHS.get(value.strip().lower())
73
+
74
+
75
+ def month_last_day(year: int, month: int) -> int:
76
+ return monthrange(year, month)[1]
77
+
78
+
79
+ def safe_iso_date(year: int, month: int, day: int) -> Optional[str]:
80
+ try:
81
+ return date(year, month, day).isoformat()
82
+ except ValueError:
83
+ return None
84
+
85
+
86
+ def normalize_date_text(value: Any) -> Optional[str]:
87
+ text = to_string(value)
88
+ if text is None:
89
+ return None
90
+ text = normalize_whitespace(text)
91
+ text = text.lstrip(" ?")
92
+ text = text.rstrip("*`")
93
+ text = text.replace("–", "-").replace("—", "-").replace("Ð", "-").replace("�", "-")
94
+ text = re.sub(r"(\d)(st|nd|rd|th)\b", r"\1", text, flags=re.IGNORECASE)
95
+ text = re.sub(r"\s*-\s*", "-", text)
96
+ if re.fullmatch(r"\d{2}\.\d{2}\.\d{4}", text):
97
+ text = text.replace(".", "/")
98
+ elif re.fullmatch(r"\d{1,2}\.\d{1,2}\.\d{2,4}", text):
99
+ text = text.replace(".", "/")
100
+ elif re.fullmatch(r"\d{4}\.\d{1,2}\.\d{1,2}", text):
101
+ text = text.replace(".", "-")
102
+ elif re.fullmatch(r"\d{2}/\d{2}\d{4}", text):
103
+ text = f"{text[:2]}/{text[3:5]}/{text[5:]}"
104
+ elif re.fullmatch(r"\d{4}\s+\d{1,2}\s+\d{1,2}", text):
105
+ text = re.sub(r"\s+", "-", text)
106
+ elif re.fullmatch(r"\d{4}-\d{1,2}\s+\d{1,2}", text):
107
+ text = text.replace(" ", "-")
108
+ elif re.fullmatch(r"\d{4}\s+\d{1,2}-\d{1,2}", text):
109
+ text = text.replace(" ", "-")
110
+ return text
111
+
112
+
113
+ def infer_year(month: int, start: Optional[date], end: Optional[date]) -> Optional[int]:
114
+ if start is None or end is None:
115
+ return None
116
+ if start.year == end.year:
117
+ return start.year
118
+ if month >= start.month:
119
+ return start.year
120
+ return end.year
121
+
122
+
123
+ def parse_date(text: Any, format: Optional[str] = None) -> Optional[str]:
124
+ """Parse a date string into ISO format (YYYY-MM-DD)."""
125
+ if isinstance(text, (int, float)) and not isinstance(text, bool):
126
+ if isinstance(text, float) and math.isnan(text):
127
+ return None
128
+ serial = int(text)
129
+ if 10000 <= serial <= 100000:
130
+ return (datetime(1899, 12, 30) + timedelta(days=serial)).date().isoformat()
131
+
132
+ text = normalize_date_text(text)
133
+ if not text:
134
+ return None
135
+
136
+ if re.fullmatch(r"\d{5}", text):
137
+ serial = int(text)
138
+ return (datetime(1899, 12, 30) + timedelta(days=serial)).date().isoformat()
139
+
140
+ if len(text) >= 11 and text[4] == "-" and text[7] == "-" and text[10] == "T":
141
+ text = text.split("T")[0]
142
+
143
+ formats = list(DATE_FORMATS)
144
+ if format:
145
+ formats.insert(0, format)
146
+
147
+ for fmt in formats:
148
+ try:
149
+ parsed = datetime.strptime(text, fmt).date()
150
+ return parsed.isoformat()
151
+ except (ValueError, TypeError):
152
+ continue
153
+
154
+ return None
155
+
156
+
157
+ def parse_month_value(value: Any, start: Optional[date] = None, end: Optional[date] = None) -> Optional[tuple[str, str]]:
158
+ text = normalize_date_text(value)
159
+ if text is None:
160
+ return None
161
+ if len(text) >= 11 and text[4] == "-" and text[7] == "-" and text[10] == "T":
162
+ text = text.split("T", 1)[0]
163
+ day_match = re.fullmatch(r"(\d{4})-(\d{1,2})-(\d{1,2})", text)
164
+ if day_match is not None:
165
+ year = int(day_match.group(1))
166
+ month = int(day_match.group(2))
167
+ if 1 <= month <= 12:
168
+ return (
169
+ date(year, month, 1).isoformat(),
170
+ date(year, month, month_last_day(year, month)).isoformat(),
171
+ )
172
+ return None
173
+ iso_match = re.fullmatch(r"(\d{4})-(\d{1,2})", text)
174
+ if iso_match is not None:
175
+ year = int(iso_match.group(1))
176
+ month = int(iso_match.group(2))
177
+ if 1 <= month <= 12:
178
+ return (
179
+ date(year, month, 1).isoformat(),
180
+ date(year, month, month_last_day(year, month)).isoformat(),
181
+ )
182
+ return None
183
+ match = re.fullmatch(r"([A-Za-z]+)(?:[\s,-]+(\d{2,4}))?", text)
184
+ if match is None:
185
+ return None
186
+ month = month_number(match.group(1))
187
+ if month is None:
188
+ return None
189
+ if match.group(2) is not None:
190
+ year = int(match.group(2))
191
+ if year < 100:
192
+ year += 2000
193
+ else:
194
+ year = infer_year(month, start, end)
195
+ if year is None:
196
+ return None
197
+ return (
198
+ date(year, month, 1).isoformat(),
199
+ date(year, month, month_last_day(year, month)).isoformat(),
200
+ )
201
+
202
+
203
+ def parse_day_range(value: Any, start: Optional[date] = None, end: Optional[date] = None) -> Optional[tuple[str, str]]:
204
+ text = normalize_date_text(value)
205
+ if text is None:
206
+ return None
207
+ match = re.fullmatch(r"(\d{1,2})/(\d{1,2})/(\d{2,4})-(\d{1,2})/(\d{1,2})/(\d{2,4})", text)
208
+ if match is not None:
209
+ start_year = int(match.group(3))
210
+ end_year = int(match.group(6))
211
+ if start_year < 100:
212
+ start_year += 2000
213
+ if end_year < 100:
214
+ end_year += 2000
215
+ start_date = safe_iso_date(start_year, int(match.group(2)), int(match.group(1)))
216
+ end_date = safe_iso_date(end_year, int(match.group(5)), int(match.group(4)))
217
+ if start_date is None or end_date is None:
218
+ return None
219
+ return start_date, end_date
220
+ match = re.fullmatch(r"(\d{4})[/-](\d{1,2})-(\d{1,2})\D+(\d{4})-(\d{1,2})-(\d{1,2})", text)
221
+ if match is not None:
222
+ start_date = safe_iso_date(int(match.group(1)), int(match.group(2)), int(match.group(3)))
223
+ end_date = safe_iso_date(int(match.group(4)), int(match.group(5)), int(match.group(6)))
224
+ if start_date is None or end_date is None:
225
+ return None
226
+ return start_date, end_date
227
+ match = re.fullmatch(r"(\d{1,2})(?:-|\s+to\s+)(\d{1,2})\s+([A-Za-z]+)(?:\s+(\d{2,4}))?", text)
228
+ if match is not None:
229
+ month = month_number(match.group(3))
230
+ if month is None:
231
+ return None
232
+ year_text = match.group(4)
233
+ if year_text is None:
234
+ year = infer_year(month, start, end)
235
+ elif len(year_text) == 2:
236
+ year = 2000 + int(year_text)
237
+ else:
238
+ year = int(year_text)
239
+ if year is None:
240
+ return None
241
+ start_date = safe_iso_date(year, month, int(match.group(1)))
242
+ end_date = safe_iso_date(year, month, int(match.group(2)))
243
+ if start_date is None or end_date is None:
244
+ return None
245
+ return start_date, end_date
246
+
247
+ match = re.fullmatch(r"(\d{1,2})/(\d{1,2})\s+([A-Za-z]+)\s+(\d{2,4})", text)
248
+ if match is not None:
249
+ month = month_number(match.group(3))
250
+ if month is None:
251
+ return None
252
+ year = int(match.group(4))
253
+ if year < 100:
254
+ year += 2000
255
+ start_date = safe_iso_date(year, month, int(match.group(1)))
256
+ end_date = safe_iso_date(year, month, int(match.group(2)))
257
+ if start_date is None or end_date is None:
258
+ return None
259
+ return start_date, end_date
260
+
261
+ match = re.fullmatch(r"(\d{1,2})\s+([A-Za-z]+)\s+(\d{2,4})-(\d{1,2})\s+([A-Za-z]+)\s+(\d{2,4})", text)
262
+ if match is not None:
263
+ start_month = month_number(match.group(2))
264
+ end_month = month_number(match.group(5))
265
+ if start_month is None or end_month is None:
266
+ return None
267
+ start_year = int(match.group(3))
268
+ end_year = int(match.group(6))
269
+ if start_year < 100:
270
+ start_year += 2000
271
+ if end_year < 100:
272
+ end_year += 2000
273
+ start_date = safe_iso_date(start_year, start_month, int(match.group(1)))
274
+ end_date = safe_iso_date(end_year, end_month, int(match.group(4)))
275
+ if start_date is None or end_date is None:
276
+ return None
277
+ return start_date, end_date
278
+
279
+ match = re.fullmatch(r"(\d{1,2})\s+([A-Za-z]+)(?:-|\s+to\s+)(\d{1,2})\s+([A-Za-z]+)(?:\s+(\d{2,4}))?", text)
280
+ if match is None:
281
+ return None
282
+ start_month = month_number(match.group(2))
283
+ end_month = month_number(match.group(4))
284
+ if start_month is None or end_month is None:
285
+ return None
286
+ year_text = match.group(5)
287
+ if year_text is None:
288
+ end_year = infer_year(end_month, start, end)
289
+ elif len(year_text) == 2:
290
+ end_year = 2000 + int(year_text)
291
+ else:
292
+ end_year = int(year_text)
293
+ if end_year is None:
294
+ return None
295
+ start_year = end_year - 1 if start_month > end_month else end_year
296
+ start_date = safe_iso_date(start_year, start_month, int(match.group(1)))
297
+ end_date = safe_iso_date(end_year, end_month, int(match.group(3)))
298
+ if start_date is None or end_date is None:
299
+ return None
300
+ return start_date, end_date
301
+
302
+
303
+ def parse_day_value(
304
+ value: Any,
305
+ start: Optional[date] = None,
306
+ end: Optional[date] = None,
307
+ format: Optional[str] = None,
308
+ ) -> Optional[str | tuple[str, str]]:
309
+ parsed = parse_date(value, format)
310
+ if parsed is not None:
311
+ return parsed
312
+ parsed = parse_partial_date(value, start, end)
313
+ if parsed is not None:
314
+ return parsed
315
+ parsed = parse_year_hint_date(value, start, end)
316
+ if parsed is not None:
317
+ return parsed
318
+ return parse_day_range(value, start, end)
319
+
320
+
321
+ def parse_day_or_month_value(
322
+ value: Any,
323
+ start: Optional[date] = None,
324
+ end: Optional[date] = None,
325
+ format: Optional[str] = None,
326
+ ) -> Optional[tuple[str, str | tuple[str, str]]]:
327
+ parsed_day = parse_day_value(value, start, end, format)
328
+ if parsed_day is not None:
329
+ return "day", parsed_day
330
+ parsed_month = parse_month_value(value, start, end)
331
+ if parsed_month is not None:
332
+ return "month", parsed_month
333
+ return None
334
+
335
+
336
+ def parse_partial_date(value: Any, start: Optional[date] = None, end: Optional[date] = None) -> Optional[str]:
337
+ text = normalize_date_text(value)
338
+ if text is None:
339
+ return None
340
+ parsed = parse_date(text)
341
+ if parsed is not None:
342
+ return parsed
343
+ parsed = parse_year_hint_date(text, start, end)
344
+ if parsed is not None:
345
+ return parsed
346
+ match = re.fullmatch(r"(\d{1,2})[\s/-]+([A-Za-z]+)(?:[\s,-]+(\d{2,4}))?", text)
347
+ if match is None:
348
+ return None
349
+ month = month_number(match.group(2))
350
+ if month is None:
351
+ return None
352
+ year_text = match.group(3)
353
+ if year_text is None:
354
+ year = infer_year(month, start, end)
355
+ elif len(year_text) == 2:
356
+ year = 2000 + int(year_text)
357
+ else:
358
+ year = int(year_text)
359
+ if year is None:
360
+ return None
361
+ return safe_iso_date(year, month, int(match.group(1)))
362
+
363
+
364
+ def parse_month_span(value: Any, year_hint: Optional[int] = None) -> Optional[tuple[str, str]]:
365
+ text = normalize_date_text(value)
366
+ if text is None or year_hint is None:
367
+ return None
368
+ month_matches = [month_number(token) for token in re.findall(r"[A-Za-z]+", text)]
369
+ months = [month for month in month_matches if month is not None]
370
+ if len(months) < 2:
371
+ return None
372
+ start_month = months[0]
373
+ end_month = months[-1]
374
+ start_year = year_hint - 1 if start_month > end_month else year_hint
375
+ return (
376
+ date(start_year, start_month, 1).isoformat(),
377
+ date(year_hint, end_month, month_last_day(year_hint, end_month)).isoformat(),
378
+ )
379
+
380
+
381
+ def parse_year_hint_date(value: Any, start: Optional[date] = None, end: Optional[date] = None) -> Optional[str]:
382
+ if start is None or end is None:
383
+ return None
384
+ text = normalize_date_text(value)
385
+ if text is None:
386
+ return None
387
+
388
+ match = re.fullmatch(r"(\d{1,2})/(\d{1,2})/(\d{4})", text)
389
+ if match is not None:
390
+ raw_year = int(match.group(3))
391
+ candidates = [raw_year]
392
+ if raw_year >= 1000:
393
+ candidates.append(raw_year - 1000)
394
+ for candidate_year in candidates:
395
+ if start.year <= candidate_year <= end.year:
396
+ parsed = safe_iso_date(candidate_year, int(match.group(2)), int(match.group(1)))
397
+ if parsed is not None:
398
+ return parsed
399
+
400
+ match = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", text)
401
+ if match is not None:
402
+ year = int(match.group(1))
403
+ if 1900 <= year <= 2100:
404
+ return None
405
+ candidate_years = [int(match.group(1)[::-1])]
406
+ if year >= 1000:
407
+ candidate_years.append(year - 1000)
408
+ for candidate_year in candidate_years:
409
+ if start.year <= candidate_year <= end.year:
410
+ parsed = safe_iso_date(candidate_year, int(match.group(2)), int(match.group(3)))
411
+ if parsed is not None:
412
+ return parsed
413
+
414
+ match = re.fullmatch(r"(\d{3})-(\d{2})-(\d{2})", text)
415
+ if match is None:
416
+ return None
417
+ candidate_years: list[int] = []
418
+ if start.year == end.year:
419
+ candidate_years.append(start.year)
420
+ candidate_years.append(int(f"{start.year // 1000}{match.group(1)}"))
421
+ for candidate_year in candidate_years:
422
+ if start.year <= candidate_year <= end.year:
423
+ parsed = safe_iso_date(candidate_year, int(match.group(2)), int(match.group(3)))
424
+ if parsed is not None:
425
+ return parsed
426
+ return None
427
+
428
+
429
+ def parse_date_token(value: Optional[str], is_end: bool = False) -> Optional[date]:
430
+ if value is None:
431
+ return None
432
+ if len(value) == 7:
433
+ year, month = value.split("-")
434
+ day = monthrange(int(year), int(month))[1] if is_end else 1
435
+ return date.fromisoformat(f"{value}-{day:02d}")
436
+ if len(value) == 10:
437
+ return date.fromisoformat(value)
438
+ return None
@@ -0,0 +1,36 @@
1
+ import re
2
+ from typing import Optional
3
+
4
+ # Companies House company number regex pattern
5
+ # Source: https://gist.github.com/rob-murray/01d43581114a6b319034732bcbda29e1
6
+ GB_COH_RE = re.compile(
7
+ r"^(((AC|CE|CS|FC|FE|GE|GS|IC|LP|NC|NF|NI|NL|NO|NP|OC|OE|PC|R0|RC|SA|SC|SE|SF|SG|SI|SL|SO|SR|SZ|ZC|\d{2})\d{6})|((IP|SP|RS)[A-Z\d]{6})|(SL\d{5}[\dA])|(RS007853Z))$"
8
+ )
9
+
10
+
11
+ def is_gb_coh(company_number: str) -> bool:
12
+ """Validate a UK Companies House company number."""
13
+ if not company_number:
14
+ return False
15
+ return bool(GB_COH_RE.match(company_number))
16
+
17
+
18
+ def normalize_gb_coh(company_number: Optional[str]) -> Optional[str]:
19
+ """Normalize and validate a UK Companies House company number."""
20
+ if company_number is None:
21
+ return None
22
+
23
+ # Basic cleanup
24
+ normalized = str(company_number).strip().upper()
25
+ if not normalized:
26
+ return None
27
+
28
+ # Companies House numbers are 8 characters, often zero-padded
29
+ # e.g. '12345' -> '00012345'
30
+ if normalized.isdigit() and len(normalized) < 8:
31
+ normalized = normalized.zfill(8)
32
+
33
+ if is_gb_coh(normalized):
34
+ return normalized
35
+
36
+ return None