-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource_package.py
More file actions
1704 lines (1571 loc) · 59.1 KB
/
source_package.py
File metadata and controls
1704 lines (1571 loc) · 59.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Declarative source-package loading for Arch build suites."""
from __future__ import annotations
import hashlib
import os
from dataclasses import dataclass, replace
from importlib.resources import files
from io import BytesIO
from pathlib import Path
import re
from typing import Any
from urllib.parse import unquote, urlparse
from zipfile import ZipFile
import httpx
import yaml
from arch.core import (
Aggregation,
AggregateConstraint,
EntityDimension,
GeographyDimension,
Measure,
PeriodDimension,
SourceProvenance,
AggregateFact,
build_label,
)
from arch.sources.cells import (
SourceArtifactMetadata,
SourceCell,
source_cells_from_delimited_text,
source_cells_from_html_tables_and_text,
source_cells_from_ods,
source_cells_from_pdf_text_numbers,
source_cells_from_xls,
source_cells_from_xlsx,
)
from arch.sources.rows import (
SourceRow,
source_cells_from_source_rows,
source_rows_from_census_acs_s0101_age_json,
source_rows_from_census_acs_s2201_snap_json,
source_rows_from_census_b01001_female_age_json,
source_rows_from_cdc_vsrr_live_births_json,
source_rows_from_json_table,
source_rows_from_ees_permalink_table_html,
source_rows_from_kff_state_indicator_gdocs_html,
source_rows_from_ons_timeseries_json,
source_rows_from_delimited_text,
)
from arch.sources.specs import (
SourceRecord,
SourceRecordSetMeasure,
SourceRecordSetRangeLabelGuard,
SourceRecordSetRow,
SourceRecordSetRowGuard,
SourceRecordSetSpec,
SourceRecordSpec,
build_cells_by_sheet_address,
compile_source_record_set_specs,
resolve_source_record,
source_regions_from_record_set_spec,
)
SOURCE_PACKAGE_RESOURCE_PACKAGE = "packages"
SOURCE_PACKAGE_ALIASES = {
"soi-table-1-1": Path("irs_soi/table_1_1"),
"soi-table-1-2": Path("irs_soi/table_1_2"),
"soi-table-1-4": Path("irs_soi/table_1_4"),
"soi-table-2-1": Path("irs_soi/table_2_1"),
"soi-table-2-5": Path("irs_soi/table_2_5"),
"soi-table-4-3": Path("irs_soi/table_4_3"),
"soi-w2-statistics-2020": Path("irs_soi/w2_statistics_2020"),
"soi-ira-traditional-contributions-2022": Path(
"irs_soi/ira_traditional_contributions_2022"
),
"soi-ira-roth-contributions-2022": Path("irs_soi/ira_roth_contributions_2022"),
}
SOURCE_ARTIFACT_CACHE_ENV = "ARCH_SOURCE_ARTIFACT_CACHE_DIR"
SOURCE_ARTIFACT_FETCH_ENV = "ARCH_SOURCE_ARTIFACT_FETCH"
DEFAULT_SOURCE_ARTIFACT_CACHE_DIR = (
Path.home() / ".cache" / "policyengine-arch-data" / "source-artifacts"
)
SOURCE_PACKAGE_FILENAME = "source_package.yaml"
EXCEL_COLUMN_RE = re.compile(r"^[A-Z]+$")
@dataclass(frozen=True)
class SourceArtifactSpec:
"""Declarative source artifact lookup and provenance metadata."""
source_name: str
source_table: str
resource_package: str
resource_directory: str
manifest: str
vintage: str
extracted_at: str
extraction_method: str
parser: str = "xls_used_range"
sheet_name: str | None = None
archive_member: str | None = None
artifact_year: int | None = None
delimiter: str = ","
selected_rows: tuple[dict[str, Any], ...] = ()
def build_source_rows(self, year: int) -> list[SourceRow]:
"""Parse a delimited artifact for a year into full source-row records."""
content, filename, source_url, raw_r2 = self._artifact_content(year)
artifact = self._source_artifact_metadata(
content,
filename,
source_url,
raw_r2,
year=year,
)
if self.parser in {"delimited_text_full_rows", "zip_delimited_text_full_rows"}:
delimited_content = self._delimited_content(content, filename)
return source_rows_from_delimited_text(
delimited_content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
delimiter=self.delimiter,
)
if self.parser == "json_table_full_rows":
return source_rows_from_json_table(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
if self.parser == "census_acs_s0101_age_json_rows":
return source_rows_from_census_acs_s0101_age_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
if self.parser == "census_acs_s2201_snap_json_rows":
return source_rows_from_census_acs_s2201_snap_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
if self.parser == "census_b01001_female_age_json_rows":
return source_rows_from_census_b01001_female_age_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
if self.parser == "cdc_vsrr_live_births_json_rows":
return source_rows_from_cdc_vsrr_live_births_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
if self.parser == "ons_timeseries_json_years":
return source_rows_from_ons_timeseries_json(
content,
artifact,
sheet_name=self.sheet_name or "years",
)
if self.parser == "ees_permalink_table_html":
return source_rows_from_ees_permalink_table_html(
content,
artifact,
sheet_name=self.sheet_name or "table",
)
if self.parser == "kff_state_indicator_gdocs_html_rows":
return source_rows_from_kff_state_indicator_gdocs_html(
content,
artifact,
sheet_name=self.sheet_name or "indicator",
)
return []
def build_source_cells(
self,
year: int,
*,
source_rows: list[SourceRow] | None = None,
) -> list[SourceCell]:
"""Parse the artifact for a year into source-cell records."""
content, filename, source_url, raw_r2 = self._artifact_content(year)
artifact = self._source_artifact_metadata(
content,
filename,
source_url,
raw_r2,
year=year,
)
if self.parser == "xls_used_range":
return source_cells_from_xls(content, artifact)
if self.parser == "xlsx_used_range":
return source_cells_from_xlsx(content, artifact)
if self.parser == "zip_xlsx_used_range":
member_content, member_name = self._archive_member_content(
content,
suffixes=(".xlsx",),
)
member_sha256 = hashlib.sha256(member_content).hexdigest()
return source_cells_from_xlsx(
member_content,
replace(
artifact,
source_file=f"{filename}!{member_name}",
sha256=member_sha256,
size_bytes=len(member_content),
extraction_method=(
f"{artifact.extraction_method}; ZIP member {member_name} "
f"from outer SHA-256 {artifact.sha256}"
),
),
)
if self.parser == "zip_xls_used_range":
member_content, member_name = self._archive_member_content(
content,
suffixes=(".xls",),
)
member_sha256 = hashlib.sha256(member_content).hexdigest()
return source_cells_from_xls(
member_content,
replace(
artifact,
source_file=f"{filename}!{member_name}",
sha256=member_sha256,
size_bytes=len(member_content),
extraction_method=(
f"{artifact.extraction_method}; ZIP member {member_name} "
f"from outer SHA-256 {artifact.sha256}"
),
),
)
if self.parser == "ods_used_range":
return source_cells_from_ods(content, artifact)
if self.parser == "html_tables_and_text":
return source_cells_from_html_tables_and_text(content, artifact)
if self.parser == "pdf_text_numbers":
return source_cells_from_pdf_text_numbers(content, artifact)
if self.parser == "delimited_text_selected_rows":
return source_cells_from_delimited_text(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
delimiter=self.delimiter,
)
if self.parser in {"delimited_text_full_rows", "zip_delimited_text_full_rows"}:
delimited_content = self._delimited_content(content, filename)
rows = (
source_rows
if source_rows is not None
else source_rows_from_delimited_text(
delimited_content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
delimiter=self.delimiter,
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "json_table_full_rows":
rows = (
source_rows
if source_rows is not None
else source_rows_from_json_table(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "census_acs_s0101_age_json_rows":
rows = (
source_rows
if source_rows is not None
else source_rows_from_census_acs_s0101_age_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "census_b01001_female_age_json_rows":
rows = (
source_rows
if source_rows is not None
else source_rows_from_census_b01001_female_age_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "census_acs_s2201_snap_json_rows":
rows = (
source_rows
if source_rows is not None
else source_rows_from_census_acs_s2201_snap_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "cdc_vsrr_live_births_json_rows":
rows = (
source_rows
if source_rows is not None
else source_rows_from_cdc_vsrr_live_births_json(
content,
artifact,
sheet_name=self._sheet_name(filename, year=year),
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "ons_timeseries_json_years":
rows = (
source_rows
if source_rows is not None
else source_rows_from_ons_timeseries_json(
content,
artifact,
sheet_name=self.sheet_name or "years",
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "ees_permalink_table_html":
rows = (
source_rows
if source_rows is not None
else source_rows_from_ees_permalink_table_html(
content,
artifact,
sheet_name=self.sheet_name or "table",
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
if self.parser == "kff_state_indicator_gdocs_html_rows":
rows = (
source_rows
if source_rows is not None
else source_rows_from_kff_state_indicator_gdocs_html(
content,
artifact,
sheet_name=self.sheet_name or "indicator",
)
)
return source_cells_from_source_rows(
rows,
selected_rows=tuple(
{
key: str(_render_value(value, year=year))
for key, value in row.items()
}
for row in self.selected_rows
),
)
raise ValueError(f"Unsupported source artifact parser: {self.parser}")
def _source_artifact_metadata(
self,
content: bytes,
filename: str,
source_url: str,
raw_r2: dict[str, str],
*,
year: int,
) -> SourceArtifactMetadata:
return SourceArtifactMetadata(
source_name=self.source_name,
source_table=_render_string(self.source_table, year=year),
source_file=filename,
url=source_url,
vintage=_render_string(self.vintage, year=year),
sha256=hashlib.sha256(content).hexdigest(),
size_bytes=len(content),
extracted_at=self.extracted_at,
extraction_method=self.extraction_method,
raw_r2_bucket=raw_r2.get("bucket"),
raw_r2_key=raw_r2.get("key"),
raw_r2_uri=raw_r2.get("uri"),
)
def _artifact_content(
self,
year: int,
) -> tuple[bytes, str, str, dict[str, str]]:
manifest_path = files(self.resource_package).joinpath(
self.resource_directory,
self.manifest,
)
with manifest_path.open("r", encoding="utf-8") as file:
manifest = yaml.safe_load(file)
spec = _year_mapping(manifest["files"], self.artifact_year or year)
artifact_path = files(self.resource_package).joinpath(
self.resource_directory,
spec["filename"],
)
content = _read_source_artifact_content(artifact_path, spec)
expected_sha = spec.get("sha256")
if expected_sha:
_validate_source_artifact_sha(
content,
expected_sha=str(expected_sha),
filename=str(spec["filename"]),
)
storage = spec.get("storage") if isinstance(spec, dict) else None
raw_r2 = storage.get("r2") if isinstance(storage, dict) else {}
return content, spec["filename"], spec["source_url"], raw_r2 or {}
def _sheet_name(self, filename: str, *, year: int) -> str:
if self.sheet_name:
return _render_string(self.sheet_name, year=year)
if self.archive_member:
return self.archive_member
return Path(filename).stem
def _delimited_content(self, content: bytes, filename: str) -> bytes:
if self.parser != "zip_delimited_text_full_rows":
return content
member, _member_name = self._archive_member_content(
content,
suffixes=(".csv", ".txt", ".tsv"),
)
return member
def _archive_member_content(
self,
content: bytes,
*,
suffixes: tuple[str, ...],
) -> tuple[bytes, str]:
with ZipFile(BytesIO(content)) as archive:
member = self.archive_member or _single_archive_member(
archive,
suffixes=suffixes,
)
return archive.read(member), member
@dataclass(frozen=True)
class SourcePackageIssue:
"""One source-package authoring issue."""
code: str
message: str
record_set_id: str | None = None
row_id: str | None = None
measure_id: str | None = None
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serializable issue."""
return {
key: value
for key, value in {
"code": self.code,
"message": self.message,
"record_set_id": self.record_set_id,
"row_id": self.row_id,
"measure_id": self.measure_id,
}.items()
if value is not None
}
@dataclass(frozen=True)
class SourcePackageValidationReport:
"""Validation report for one declarative source package."""
package_id: str | None
package_path: str
year: int
counts: dict[str, int]
errors: tuple[SourcePackageIssue, ...]
warnings: tuple[SourcePackageIssue, ...] = ()
@property
def valid(self) -> bool:
"""Whether the package has no validation errors."""
return not self.errors
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serializable report."""
return {
"valid": self.valid,
"package_id": self.package_id,
"package_path": self.package_path,
"year": self.year,
"counts": self.counts,
"errors": [issue.to_dict() for issue in self.errors],
"warnings": [issue.to_dict() for issue in self.warnings],
}
@dataclass(frozen=True)
class SourcePackageScaffoldReport:
"""Report for a scaffolded source package."""
package_id: str
source_id: str
package_path: str
source_package_path: str
replaced: bool
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serializable report."""
return {
"package_id": self.package_id,
"source_id": self.source_id,
"package_path": self.package_path,
"source_package_path": self.source_package_path,
"replaced": self.replaced,
}
@dataclass(frozen=True)
class DeclarativeRecordSet:
"""One YAML record-set payload that compiles to source-record specs."""
payload: dict[str, Any]
def to_record_set_spec(self, year: int) -> SourceRecordSetSpec:
"""Compile this YAML payload into the core record-set spec."""
rows = tuple(
_row_from_mapping(row, year=year)
for row in _required(self.payload, "rows", "record_set")
)
measures = tuple(
_measure_from_mapping(measure, year=year)
for measure in _required(self.payload, "measures", "record_set")
)
return SourceRecordSetSpec(
record_set_id=_render_required_string(
self.payload,
"record_set_id",
year=year,
),
record_set_spec_id=_required(
self.payload,
"record_set_spec_id",
"record_set",
),
source_record_id_prefix=_render_required_string(
self.payload,
"source_record_id_prefix",
year=year,
),
sheet_name=_record_set_sheet_name_from_mapping(
self.payload,
year=year,
),
period_type=_required(self.payload, "period_type", "record_set"),
period=_record_set_period_from_mapping(self.payload, year=year),
geography_id=_required(self.payload, "geography_id", "record_set"),
geography_level=_required(
self.payload,
"geography_level",
"record_set",
),
geography_name=self.payload.get("geography_name"),
geography_vintage=self.payload.get("geography_vintage"),
entity=_required(self.payload, "entity", "record_set"),
entity_role=self.payload.get("entity_role"),
domain=_required(self.payload, "domain", "record_set"),
groupby_dimension=_required(
self.payload,
"groupby_dimension",
"record_set",
),
rows=rows,
measures=measures,
shared_filters={
key: _render_value(value, year=year)
for key, value in self.payload.get("shared_filters", {}).items()
},
shared_constraints=tuple(
_constraint_from_mapping(constraint, year=year)
for constraint in self.payload.get("shared_constraints", ())
),
)
@dataclass(frozen=True)
class SourcePackage:
"""A declarative Arch source package."""
package_id: str
label: str | None
artifact: SourceArtifactSpec
record_sets: tuple[DeclarativeRecordSet, ...]
package_path: Path
def build_source_rows(self, year: int) -> list[SourceRow]:
"""Build full source rows for row-oriented artifacts."""
return self.artifact.build_source_rows(year)
def build_source_cells(
self,
year: int,
*,
source_rows: list[SourceRow] | None = None,
) -> list[SourceCell]:
"""Build whole-artifact source cells for this package."""
return self.artifact.build_source_cells(year, source_rows=source_rows)
def build_source_record_set_specs(
self,
year: int,
) -> list[SourceRecordSetSpec]:
"""Build compact record-set specs for this package."""
return [record_set.to_record_set_spec(year) for record_set in self.record_sets]
def build_source_regions(self, year: int):
"""Build source-region specs implied by the package record sets."""
regions = []
for spec in self.build_source_record_set_specs(year):
regions.extend(source_regions_from_record_set_spec(spec))
return regions
def build_source_record_specs(self, year: int) -> list[SourceRecordSpec]:
"""Build atomic source-record specs for this package."""
specs: list[SourceRecordSpec] = []
for record_set in self.build_source_record_set_specs(year):
specs.extend(compile_source_record_set_specs(record_set))
return specs
def build_source_records(
self,
year: int,
*,
cells: list[SourceCell] | None = None,
source_rows: list[SourceRow] | None = None,
) -> list[SourceRecord]:
"""Resolve package source-record specs against source cells."""
if cells is None:
cells = self.build_source_cells(year, source_rows=source_rows)
cells_by_sheet_address = build_cells_by_sheet_address(cells)
return [
resolve_source_record(
cells,
spec,
cells_by_sheet_address=cells_by_sheet_address,
)
for spec in self.build_source_record_specs(year)
]
def build_facts(
self,
year: int,
*,
cells: list[SourceCell] | None = None,
source_rows: list[SourceRow] | None = None,
) -> list[AggregateFact]:
"""Build source-lineaged Arch aggregate facts."""
if cells is None:
cells = self.build_source_cells(year, source_rows=source_rows)
source = _source_provenance_from_cells(cells)
facts = []
for record in self.build_source_records(
year,
cells=cells,
source_rows=source_rows,
):
fact = _fact_from_source_record(record, source)
facts.append(replace(fact, label=build_label(fact)))
return facts
def load_source_package(source: str | Path) -> SourcePackage:
"""Load a declarative source package from an alias, directory, or YAML file."""
path = resolve_source_package_path(source)
with path.open("r", encoding="utf-8") as file:
payload = yaml.safe_load(file)
schema_version = _required(payload, "schema_version", str(path))
if schema_version != "arch.source_package.v1":
raise ValueError(f"Unsupported source package schema: {schema_version}")
package_dir = path.parent
return SourcePackage(
package_id=_required(payload, "package_id", str(path)),
label=payload.get("label"),
artifact=_artifact_from_mapping(
_required(payload, "artifact", str(path)),
),
record_sets=tuple(
DeclarativeRecordSet(record_set)
for record_set in _required(payload, "record_sets", str(path))
),
package_path=package_dir,
)
def try_load_source_package(source: str | Path) -> SourcePackage | None:
"""Return a declarative package if the source reference resolves to one."""
try:
return load_source_package(source)
except FileNotFoundError:
return None
def validate_source_package(
source: str | Path,
*,
year: int = 2023,
) -> SourcePackageValidationReport:
"""Validate declarative package structure before a full build-suite run."""
package_path = _safe_package_path(source)
errors: list[SourcePackageIssue] = []
warnings: list[SourcePackageIssue] = []
counts = {
"record_set_count": 0,
"row_count": 0,
"measure_count": 0,
"source_record_count": 0,
"source_region_count": 0,
}
try:
package = load_source_package(source)
except (FileNotFoundError, KeyError, TypeError, ValueError) as exc:
errors.append(
SourcePackageIssue(
code="source_package_load_failed",
message=str(exc),
)
)
return SourcePackageValidationReport(
package_id=None,
package_path=str(package_path),
year=year,
counts=counts,
errors=tuple(errors),
)
try:
package.artifact._artifact_content(year)
except (FileNotFoundError, KeyError, OSError, ValueError) as exc:
errors.append(
SourcePackageIssue(
code="source_artifact_unavailable",
message=str(exc),
)
)
try:
record_sets = package.build_source_record_set_specs(year)
except (KeyError, TypeError, ValueError) as exc:
errors.append(
SourcePackageIssue(
code="record_set_compile_failed",
message=str(exc),
)
)
return SourcePackageValidationReport(
package_id=package.package_id,
package_path=str(package.package_path),
year=year,
counts=counts,
errors=tuple(errors),
warnings=tuple(warnings),
)
counts["record_set_count"] = len(record_sets)
record_set_ids: dict[str, list[int]] = {}
source_record_ids: dict[str, list[int]] = {}
for record_set_index, record_set in enumerate(record_sets):
record_set_ids.setdefault(record_set.record_set_id, []).append(record_set_index)
counts["row_count"] += len(record_set.rows)
counts["measure_count"] += len(record_set.measures)
errors.extend(_validate_record_set_authoring(record_set))
try:
counts["source_region_count"] += len(
source_regions_from_record_set_spec(record_set)
)
except ValueError as exc:
errors.append(
SourcePackageIssue(
code="source_region_compile_failed",
message=str(exc),
record_set_id=record_set.record_set_id,
)
)
try:
specs = compile_source_record_set_specs(record_set)
except (KeyError, TypeError, ValueError) as exc:
errors.append(
SourcePackageIssue(
code="source_record_compile_failed",
message=str(exc),
record_set_id=record_set.record_set_id,
)
)
continue
for spec_index, spec in enumerate(specs):
source_record_ids.setdefault(spec.source_record_id, []).append(spec_index)
counts["source_record_count"] += 1
for record_set_id, indices in record_set_ids.items():
if len(indices) > 1:
errors.append(
SourcePackageIssue(
code="duplicate_record_set_id",
message=f"Duplicate record-set ID appears at indices {indices}.",
record_set_id=record_set_id,
)
)
for source_record_id, indices in source_record_ids.items():
if len(indices) > 1:
errors.append(
SourcePackageIssue(
code="duplicate_source_record_id",
message=(
"Duplicate compiled source-record ID appears at "
f"indices {indices}."
),
record_set_id=source_record_id.rsplit(".", 2)[0],
)
)
return SourcePackageValidationReport(
package_id=package.package_id,
package_path=str(package.package_path),
year=year,
counts=counts,
errors=tuple(errors),
warnings=tuple(warnings),
)
def scaffold_source_package(
output_dir: str | Path,
*,
source_id: str,
package_id: str,
source_table: str | None = None,
resource_package: str = "db",
resource_directory: str | None = None,
manifest: str = "manifest.yaml",
replace_existing: bool = False,
) -> SourcePackageScaffoldReport:
"""Write a starter declarative source package."""
package_path = Path(output_dir)
source_package_path = package_path / SOURCE_PACKAGE_FILENAME
replaced = source_package_path.exists()
if replaced and not replace_existing:
raise FileExistsError(f"Source package already exists: {source_package_path}")
package_path.mkdir(parents=True, exist_ok=True)
source_package_path.write_text(
_scaffold_template(
source_id=source_id,
package_id=package_id,
source_table=source_table or "TODO source table title",
resource_package=resource_package,
resource_directory=(resource_directory or f"data/{source_id}/TODO_table"),
manifest=manifest,
),
encoding="utf-8",
)
return SourcePackageScaffoldReport(
package_id=package_id,
source_id=source_id,
package_path=str(package_path),
source_package_path=str(source_package_path),
replaced=replaced,
)
def resolve_source_package_path(source: str | Path) -> Path:
"""Resolve a package alias, directory, or YAML file to source_package.yaml."""
source_path = Path(source)
if source_path.exists():
if source_path.is_dir():
return source_path / SOURCE_PACKAGE_FILENAME
return source_path
alias = SOURCE_PACKAGE_ALIASES.get(str(source))
if alias is None:
raise FileNotFoundError(f"Source package not found: {source}")
repo_path = _repo_root() / "packages" / alias / SOURCE_PACKAGE_FILENAME
if repo_path.exists():
return repo_path
try:
resource_path = files(SOURCE_PACKAGE_RESOURCE_PACKAGE).joinpath(
alias,
SOURCE_PACKAGE_FILENAME,
)
with resource_path.open("rb"):
pass
return Path(str(resource_path))
except (FileNotFoundError, ModuleNotFoundError):
raise FileNotFoundError(f"Source package not found: {source}") from None
def _validate_record_set_authoring(
record_set: SourceRecordSetSpec,
) -> list[SourcePackageIssue]:
errors: list[SourcePackageIssue] = []
row_ids: dict[str, list[int]] = {}
row_ordinals: dict[int, list[int]] = {}
measure_ids: dict[str, list[int]] = {}
measure_ordinals: dict[int, list[int]] = {}
for index, row in enumerate(record_set.rows):
row_ids.setdefault(row.value_id, []).append(index)
row_ordinals.setdefault(row.ordinal, []).append(index)
if _row_needs_constraints(row) and not row.constraints:
errors.append(
SourcePackageIssue(
code="missing_row_constraints",
message=(
"Detail row has semantic filters but no first-class "
"constraints."
),
record_set_id=record_set.record_set_id,
row_id=row.value_id,
)
)
errors.extend(_missing_filter_bound_constraints(record_set, row))
for index, measure in enumerate(record_set.measures):
measure_ids.setdefault(measure.measure_id, []).append(index)
measure_ordinals.setdefault(measure.ordinal, []).append(index)
if not EXCEL_COLUMN_RE.match(measure.column):
errors.append(
SourcePackageIssue(