studia_bas: Studia BAS policy articles (scoped from #19)

#44
by PiotrSty - opened
artifacts/source_findings.md CHANGED
@@ -911,3 +911,63 @@ quoted citizens' statements remain), near-dedup vs `dziennik_ustaw`/`eurlex`
911
  turns well (98.9% of the ASW pilot's audited corrected characters), but it is
912
  the pilot comparison that makes the reconstruction auditable — keep that step
913
  for future spoken sources.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911
  turns well (98.9% of the ASW pilot's audited corrected characters), but it is
912
  the pilot comparison that makes the reconstruction auditable — keep that step
913
  for future spoken sources.
914
+
915
+ ---
916
+
917
+ ## Studia BAS — Kancelaria Sejmu research & public-policy journal (2021–2025)
918
+
919
+ **Investigated:** 2026-08-29
920
+ **Verdict:** `ready` — official open-access transition under **CC BY 3.0 PL** starting with issue **2(66)/2021**; verified per-article license statements and clean born-digital PDF text layer.
921
+
922
+ Quarterly peer-reviewed journal published by the **Biuro Analiz Sejmowych (BAS)** of the Chancellery of the Sejm (Kancelaria Sejmu). Focuses on public policy, socio-economic research, constitutional and EU law, public finance, and legislative commentary. Provides contemporary, formal academic/policy analysis prose — a critical register bridging official administrative/legal texts and general expository literature without being raw statutory legalese or web crawl.
923
+
924
+ ### Archive enumeration & fetch route — verified
925
+
926
+ - **Archive URL:** `https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL`
927
+ - **Enumeration:** The Lotus Domino / XPages archive portal uses dynamic AJAX updates. Querying issues by year (2021–2025) requires parsing the initial `xspForm` state (`$$viewid`, `$$ajaxid`, `cbYear`) and submitting multipart POST requests.
928
+ - **PDF Resolution:** Issue records point to download endpoints on `orka.sejm.gov.pl` (either direct issue PDF paths or the download-counting agent `LiczOpen?OpenAgent&<UNID>`).
929
+ - **WAF / Network:** `studiabas.sejm.gov.pl` is fronted by Imperva WAF, requiring browser-like TLS handshakes (`curl_cffi` impersonating Chrome) for reliable programmatic querying and retrieval.
930
+
931
+ ### License evidence — verified cutoff from issue 2(66)/2021
932
+
933
+ - **Historical cutoff:** Issues 1–65 (prior to 2/2021) were published under traditional all-rights-reserved copyright.
934
+ - **Open-access grant:** Starting with issue **2(66)/2021** (issue 66), the journal officially transitioned to open access under **Creative Commons Attribution 3.0 Poland (CC BY 3.0 PL / `CC-BY-3.0-PL`)**.
935
+ - **Dual-gate verification:** Ingestion enforces a hard issue boundary (`issue >= 66`) and additionally validates the presence of the explicit CC BY 3.0 PL statement inside every article PDF (*"Artykuł został udostępniony na licencji Creative Commons – Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL)"*). Issues or articles lacking this statement fail closed.
936
+
937
+ ### PDF characteristics, text extraction & non-OCR status
938
+
939
+ - **Born-digital PDFs (`is_ocr: False`):** Whole-issue PDFs feature high-fidelity digital text layers, not scanned or OCR-derived text.
940
+ - **Article segmentation:** Multi-article issue PDFs are sliced at article title pages identified via title font size (`max_size >= 12`), registered DOI (`10.31268/StudiaBAS.YYYY.NN`), and the in-PDF CC BY license block.
941
+ - **Layout normalization:**
942
+ - Running headers (page numbering, journal title, ISSN `2082-0658`, `studiabas.sejm.gov.pl`) and author affiliation footnote blocks are stripped from the main body.
943
+ - PDF line-break hyphenation is reconstructed for Polish compounds (e.g. `przedsię-\nbiorców`, `rolno-\n-spożywczy`).
944
+ - Paragraph breaks are preserved and reconstructed using vertical spacing, indentation, and heading font shifts.
945
+ - **Polish scope:** Ingestion extracts the Polish title, Polish abstract (*Streszczenie*), Polish keywords (*Słowa kluczowe*), and full Polish article body. Incidental English titles/abstracts (*Abstract*, *Keywords*) in dual-language front matter are excluded from the main text.
946
+
947
+ ### Observed yield (2021–2025)
948
+
949
+ - **Extracted articles:** **115 articles** across issues 66 to 81 (2021–2025).
950
+ - **Retained articles:** **112 articles** after dropping 3 entirely English-language articles.
951
+ - **Token volume:** ~112 long-form scholarly articles yielding ~0.8–1.2M tokens of dense, high-register Polish analytical prose.
952
+
953
+ ### Author, affiliation & PII handling
954
+
955
+ - **Scholarly attribution:** Lead and contributing author names and DOIs are preserved in document metadata (`author`, `doi`, `source_url`) as official academic attribution.
956
+ - **PII scrubbing:** Author email addresses, ORCID identifiers (`orcid.org/0000-...`), phone numbers, and national identifiers (PESEL, NIP, REGON) appearing in contact blocks or bios are systematically scrubbed and replaced with stable `[PII]` tokens, preserving sentence syntax.
957
+
958
+ ### Inclusion rationale & quality/bias caveats
959
+
960
+ - **Inclusion rationale:** High-quality, editorially reviewed policy research and academic discourse with unambiguous CC BY 3.0 PL licensing, permanent DOI provenance, and zero OCR noise. Fills a major gap in formal analytical Polish.
961
+ - **Quality & bias caveats:**
962
+ - Institutional focus: Content is oriented toward state policy, parliamentary advisory topics, economics, and legal regulation.
963
+ - Complex formatting: Rare multi-column tables, statistical charts, or boxed exhibits in PDFs may yield minor layout artifacts or omitted figure captions.
964
+
965
+ ### Cross-source exact dedup — verified 2026-08-31
966
+
967
+ - All 112 released `studia_bas` texts are internally unique.
968
+ - Full byte-for-byte text comparison against 4,366,651 documents in all 20
969
+ other local Parquets found **0 exact-text matches**.
970
+ - No `studia_bas` record required removal. A future rebuild of
971
+ `biblioteka_nauki` still needs cross-source dedup because its current upstream
972
+ catalogue exposes 105 of these articles even though the released local shard
973
+ does not contain them.
data/studia_bas/NOTICE.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Attribution and licensing notice
2
+
3
+ The `studia_bas` source contains peer-reviewed articles from *Studia BAS*, the
4
+ socioeconomic and public-policy journal published by the Bureau of Research
5
+ (Biuro Analiz Sejmowych) at the Chancellery of the Sejm, taken from the
6
+ [official journal archive](https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL).
7
+
8
+ Articles are published under the [Creative Commons Attribution 3.0
9
+ Poland](https://creativecommons.org/licenses/by/3.0/pl/) license
10
+ (`CC-BY-3.0-PL`). That license applies from issue 2(66)/2021 onward; issues
11
+ 1(1) through 1(65) are marked "Wszelkie prawa zastrzeżone" and are excluded
12
+ from this source entirely. The evidence for the cutoff, together with the
13
+ SHA-256 hash of every eligible issue PDF, is recorded in
14
+ `studia_bas.license-evidence.json`.
15
+
16
+ For every released DynaWord document:
17
+
18
+ - the `author` column carries the article's author list, read from the PDF
19
+ title page;
20
+ - `studia_bas.attribution.jsonl` preserves the article DOI, the recommended
21
+ attribution URL, the journal archive URL, the issue number, the filename and
22
+ SHA-256 of the issue PDF the text came from, the publisher, the license URL
23
+ and the modification notice — one row per Parquet row, in the same order;
24
+ - the text was extracted from the text layer of the official issue PDF. Running
25
+ headers, page numbers, author affiliation/contact blocks, and terminal
26
+ bibliographies were removed, residual personal data was replaced with `[PII]`,
27
+ and PDF line wrapping was normalized.
28
+
29
+ CC BY 3.0 PL requires attribution and an indication that changes were made.
30
+ When redistributing or adapting these texts, name the author and the publisher
31
+ (Kancelaria Sejmu, Biuro Analiz Sejmowych), link the license, and retain the
32
+ modification notice above.
33
+
34
+ Figures, tables, photographs and any third-party material reproduced inside the
35
+ source PDFs may carry separate rights and are not covered by this notice. Only
36
+ the extracted article text is redistributed here; the issue PDFs themselves are
37
+ not.
data/studia_bas/studia_bas.attribution.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c9f024da591ecea96aec4ee340570dc6177b4c551ad376a42ee09cef65f80ee
3
+ size 98122
data/studia_bas/studia_bas.license-evidence.json ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "studia_bas",
3
+ "checked_at": "2026-08-29T16:18:15Z",
4
+ "license_spdx": "CC-BY-3.0-PL",
5
+ "license_name": "Creative Commons Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL)",
6
+ "license_legal_code_url": "https://creativecommons.org/licenses/by/3.0/pl/legalcode",
7
+ "scope_and_cutoff": {
8
+ "rule": "CC BY 3.0 PL applies starting at issue 2(66)/2021 and does not automatically cover earlier issues.",
9
+ "cutoff_issue": 66,
10
+ "cutoff_issue_string": "2(66)/2021",
11
+ "cutoff_year": 2021,
12
+ "earlier_issues_status": "Issues 1(1)/2009 through 1(65)/2021 were published under All rights reserved (Wszelkie prawa zastrzeżone by Kancelaria Sejmu) and are not licensed under Creative Commons; they are strictly excluded.",
13
+ "eligible_issues_count": 17,
14
+ "eligible_issue_numbers": [
15
+ 66,
16
+ 67,
17
+ 68,
18
+ 69,
19
+ 70,
20
+ 71,
21
+ 72,
22
+ 73,
23
+ 74,
24
+ 75,
25
+ 76,
26
+ 77,
27
+ 78,
28
+ 79,
29
+ 80,
30
+ 81,
31
+ 82
32
+ ]
33
+ },
34
+ "direct_official_evidence": {
35
+ "publisher": "Kancelaria Sejmu RP",
36
+ "journal": "Studia BAS (e-ISSN: 2082-0658, p-ISSN: 2080-2404)",
37
+ "evidence_urls": {
38
+ "journal_home_pl": "https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=1&seria=4&lang=PL",
39
+ "journal_home_en": "https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=1&seria=4&lang=EN",
40
+ "author_instructions_pl": "https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=5&seria=4&lang=PL",
41
+ "author_instructions_en": "https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=5&seria=4&lang=EN",
42
+ "archive_url": "https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL",
43
+ "license_legal_code": "https://creativecommons.org/licenses/by/3.0/pl/legalcode"
44
+ },
45
+ "observed_wording": {
46
+ "website_open_access_statement_pl": "Od numeru 2(66)2021 zawartość kwartalnika jest udostępniana na licencji Creative Commons – Uznanie Autorstwa 3.0 Polska (CC-BY 3.0 PL). Pozwala ona na natychmiastowy bezpłatny dostęp do wszystkich opublikowanych artykułów i umożliwia wszystkim użytkownikom czytanie, pobieranie, kopiowanie, rozpowszechnianie, drukowanie, przeszukiwanie, wykorzystywanie linków do pełnej treści artykułów, ich indeksowanie, używanie jako danych w oprogramowaniu oraz wykorzystywanie w każdym innym celu zgodnym z warunkami licencji i przepisami prawa.",
47
+ "website_open_access_statement_en": "Starting from No. 2(66)2021, “Studia BAS” is licensed under the Creative Commons Attribution 3.0 Poland License (CC-BY 3.0 PL). It allows for immediate free access to the work and permitting any user to read, download, copy, distribute, print, search, or link to the full texts of articles, crawl them for indexing, pass them as data to software, or use them for any other lawful purpose.",
48
+ "website_author_contract_terms_pl": "Po przyjęciu artykułu do publikacji autor podpisuje z Kancelarią Sejmu (KS) umowę o dzieło z przeniesieniem majątkowych praw autorskich oraz Oświadczenie o występowaniu albo o niewystępowaniu konfliktu interesów (odrębny dokument wymagany przez KS). W umowie autor m.in. wyraża zgodę, aby Kancelaria Sejmu udostępniała dzieło na licencji Creative Commons-Uznanie autorstwa 3.0 PL (CC-BY 3.0 PL).",
49
+ "website_author_contract_terms_en": "After acceptance of the article for publication the author signs a contract for specific work and the transfer of proprietary copyrights with the Chancellery of the Sejm, and submits Conflict of interest disclosure statement (separate document required by the Chancellery). The author consents that the Chancellery of Sejm makes the work available under the Creative Commons-Attribution 3.0 PL license (CC-BY 3.0 PL).",
50
+ "website_open_access_notice_en": "Studia BAS is an open access journal. Starting from No. 2(66)2021 it is is licensed under the CC BY 3.0 PL license.",
51
+ "pdf_issue_editorial_notice": "Zawartość czasopisma została udostępniona na licencji Creative Commons – Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL).",
52
+ "pdf_article_license_notice": "Artykuł został udostępniony na licencji Creative Commons – Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL).",
53
+ "pdf_pre_cutoff_copyright_notice": "Wszelkie prawa zastrzeżone. Żadna część ani całość opracowania nie może być bez zgody wydawcy – Kancelarii Sejmu – reprodukowana, użyta do innej publikacji oraz przechowywana w jakiejkolwiek bazie danych."
54
+ }
55
+ },
56
+ "corroborating_evidence": {
57
+ "doaj": {
58
+ "indexed": true,
59
+ "journal_url": "https://doaj.org/toc/2082-0658",
60
+ "api_search_url": "https://doaj.org/api/v2/search/journals/issn:2082-0658",
61
+ "oa_start_year": 2021,
62
+ "publisher": "Kancelaria Sejmu",
63
+ "author_retains_copyright": false,
64
+ "finding": "DOAJ independently confirms the 2021 open access start date and copyright transfer to publisher Kancelaria Sejmu which grants the open license."
65
+ }
66
+ },
67
+ "eligible_pdfs": [
68
+ {
69
+ "issue": 66,
70
+ "filename": "Studia_BAS_66.pdf",
71
+ "bytes": 4741995,
72
+ "sha256": "f318ff61f5f7ce4a6df408a73439884d11a185d50811c16c09a6254eeabf1185"
73
+ },
74
+ {
75
+ "issue": 67,
76
+ "filename": "Studia_BAS_67.pdf",
77
+ "bytes": 2932063,
78
+ "sha256": "6a65b4abc1abe005bcf6d83a010361648061bd15f90f2593a58afcb49912a6b0"
79
+ },
80
+ {
81
+ "issue": 68,
82
+ "filename": "Studia_BAS_68.pdf",
83
+ "bytes": 3138686,
84
+ "sha256": "dad27e0f21ae93c9a9218d8b8e529b90e5e33aebbcd7ed651ad214d293e19bc9"
85
+ },
86
+ {
87
+ "issue": 69,
88
+ "filename": "Studia_BAS_69.pdf",
89
+ "bytes": 2376821,
90
+ "sha256": "4f574d44fd97496975345dcc0fbc86903cfe57d446655b2c42bbe80402cb8e8d"
91
+ },
92
+ {
93
+ "issue": 70,
94
+ "filename": "Studia_BAS_70.pdf",
95
+ "bytes": 3267508,
96
+ "sha256": "4ba093eb43594c929cc62ba86f46ac0a285430b27022b1f434454835e19a048b"
97
+ },
98
+ {
99
+ "issue": 71,
100
+ "filename": "Studia_BAS_71.pdf",
101
+ "bytes": 2776345,
102
+ "sha256": "356f7305608d52b851805b330a7e6d24c3320171a9c70ed967989bcd384442f7"
103
+ },
104
+ {
105
+ "issue": 72,
106
+ "filename": "Studia_BAS_72.pdf",
107
+ "bytes": 2277688,
108
+ "sha256": "59bf48a26429c127b148922c264a93ecca6c4e53f1b0f29d5df67eec3021046f"
109
+ },
110
+ {
111
+ "issue": 73,
112
+ "filename": "Studia_BAS_73.pdf",
113
+ "bytes": 6191724,
114
+ "sha256": "38f278d82fd7a48a985633481cd9c10e023a07179d05a358874ae9f0c934b1f9"
115
+ },
116
+ {
117
+ "issue": 74,
118
+ "filename": "Studia_BAS_74.pdf",
119
+ "bytes": 4428291,
120
+ "sha256": "3af2bad701f679d844adc0d7a6cda5d0fe0ec94ec379f73d79e615d703c82aa8"
121
+ },
122
+ {
123
+ "issue": 75,
124
+ "filename": "Studia_BAS_75.pdf",
125
+ "bytes": 2481583,
126
+ "sha256": "ef60fc12a1821db384ec7ba4bdfc42db25f14b705d2f9dc4d547a242ee4f16a2"
127
+ },
128
+ {
129
+ "issue": 76,
130
+ "filename": "Studia_BAS_76.pdf",
131
+ "bytes": 5269351,
132
+ "sha256": "69b739b58bfab8de967aba9b02babede9f59dc319d6e84bdd17c57f30b17e627"
133
+ },
134
+ {
135
+ "issue": 77,
136
+ "filename": "Studia_BAS_77.pdf",
137
+ "bytes": 1795087,
138
+ "sha256": "320eb7df6b03b90d53095c9d08c56cfd9c3cfceb5e84ba0d919a53c8d4655027"
139
+ },
140
+ {
141
+ "issue": 78,
142
+ "filename": "Studia_BAS_78.pdf",
143
+ "bytes": 2027451,
144
+ "sha256": "16fbd7b70a1fb9f244669923ec2d0260c09d17a6000aa7bee7192d1f9d368910"
145
+ },
146
+ {
147
+ "issue": 79,
148
+ "filename": "Studia_BAS_79.pdf",
149
+ "bytes": 2272573,
150
+ "sha256": "aa1a3100f2ed46941c442bca6bc2ada828c3d90dc5017eae560cebc4c122443e"
151
+ },
152
+ {
153
+ "issue": 80,
154
+ "filename": "Studia_BAS_80.pdf",
155
+ "bytes": 1347696,
156
+ "sha256": "b7e0a95ea4ab0ae97aa8297d3ecf103f3a68b5e2ba777718e91d608ef7b38765"
157
+ },
158
+ {
159
+ "issue": 81,
160
+ "filename": "Studia_BAS_81.pdf",
161
+ "bytes": 2017390,
162
+ "sha256": "ef24bab005c1ab17f381d6c7e5c8a12a3dd77ca2daa0ce0dbd411206569d9d36"
163
+ },
164
+ {
165
+ "issue": 82,
166
+ "filename": "Studia_BAS_82.pdf",
167
+ "bytes": 2359571,
168
+ "sha256": "40426dad520e291370a8172b4da4275789f3fc91587fc306fe6580c9bd6fcf3e"
169
+ }
170
+ ]
171
+ }
data/studia_bas/studia_bas.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # studia_bas
2
+
3
+ Peer-reviewed Polish articles from *Studia BAS*, the socioeconomic and
4
+ public-policy journal of the Bureau of Research (Biuro Analiz Sejmowych) at the
5
+ Chancellery of the Sejm. Each record is one article, extracted from the text
6
+ layer of the official issue PDF.
7
+
8
+ ## Dataset description
9
+
10
+ - **Original platform:** https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL
11
+ - **Publisher:** Kancelaria Sejmu, Biuro Analiz Sejmowych
12
+ - **Domain:** academic, economics, social policy and public policy
13
+ - **Language:** Polish (`pl`)
14
+ - **License:** `CC-BY-3.0-PL` — https://creativecommons.org/licenses/by/3.0/pl/
15
+ - **Created:** 2021-2025 (per article in the `created` column)
16
+ - **Added:** 2026-07-19 (inherited from the global `ADDED` constant in
17
+ `src/sources.py`, which is what `build_dynaword.py` stamps; the shard is left
18
+ as the committed pipeline produces it rather than hand-restamped)
19
+
20
+ ## Statistics
21
+
22
+ | read | kept | characters | tokens (`cl100k_base` proxy) | issues |
23
+ |---:|---:|---:|---:|---:|
24
+ | 115 | 112 | 6,089,085 | 2,256,009 | 17 |
25
+
26
+ The released Parquet uses the canonical DynaWord schema:
27
+
28
+ `id, text, source, added, created, token_count, license, author`
29
+
30
+ Every retained article carries its author list in `author`, read from the PDF
31
+ title page. Because the canonical schema has no column for it, the per-article
32
+ DOI, attribution URL and source-PDF hash that CC BY attribution requires live in
33
+ `studia_bas.attribution.jsonl`, one row per Parquet row, in the same order.
34
+
35
+ ## Provenance and Licensing
36
+ - **Origin**: Official journal archive at https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL
37
+ - **License**: Creative Commons Attribution 3.0 Poland (CC BY 3.0 PL).
38
+ - **License Evidence**: CC BY 3.0 PL applies from issue 2(66)/2021 onward. Issues 1(1) through 1(65) are "Wszelkie prawa zastrzeżone" and are strictly excluded. This is corroborated by the journal's own statement and by pl.wikipedia.org/wiki/Studia_BAS. Eligible range is issues 66-82 = 17 issues. All 17 source PDFs are present locally and their SHA-256 hashes and byte sizes were independently recomputed and matched 17/17 against `data/studia_bas/studia_bas.license-evidence.json`.
39
+ - **Genre/Register**: Peer-reviewed socioeconomic and public-policy articles, academic register.
40
+ - **Coverage**: COMPLETE for the eligible range. Cross-checked against Crossref (journal ISSN 2082-0658, 246 works). Crossref lists 132 DOIs for issues 66-82; the corpus has 115. The 17-record difference is fully explained: every one of those 17 DOIs has type 'journal-issue' (issue-level front matter, no title, no authors, no pages), not 'journal-article'. Zero journal-article records are missing, and zero corpus DOIs are absent from Crossref.
41
+ - **Coverage Cutoff**: `2(82)/2025`. Crossref holds nothing above DOI 10.31268/StudiaBAS.2025.10; the whole 2025.11-2025.25 and 2026.x ranges return HTTP 404. Newest Crossref deposit is 2026-03-06, i.e. roughly a 9-month deposit lag, so later issues may exist without DOIs yet.
42
+
43
+ ## Collection and Filtering
44
+ - Articles are extracted from the text layer of the official issue PDFs. They are split by DOI title pages.
45
+ - **Normalization/Modification**:
46
+ - Running headers, page numbers, author affiliation/contact blocks, terminal
47
+ bibliographies, and ORCID values are excluded.
48
+ - Common PII (emails, national identifiers) is replaced with `[PII]` to retain sentence structure.
49
+ - PDF line wrapping is normalized without flattening paragraph breaks.
50
+ - **Drops (Language Gate)**: 115 read -> 112 kept. The three language-gate drops are genuine English-language articles, correctly dropped because they contain insufficient Polish:
51
+ - DOI 10.31268/StudiaBAS.2021.26 ("The EU Fiscal Risk Matrix")
52
+ - DOI 10.31268/StudiaBAS.2022.08 ("Cultural and creative sectors in the COVID-19 pandemic crisis")
53
+ - DOI 10.31268/StudiaBAS.2025.08 ("Integration of electricity markets throughout the European Economic Area")
54
+
55
+ ## Argument for Inclusion
56
+ This source adds high-quality, professional, and peer-reviewed academic texts in the domain of economics, social policy, and public policy, enriching the corpus with formal legal and socioeconomic Polish terminology.
57
+
58
+ ## Metadata Quality
59
+ - **Record ids** are derived from the article DOI (`studia_bas_<year>_<ordinal>`) and are stable across rebuilds (`preserve_id`).
60
+ - **Authors** are read from the PDF title page, not from any metadata service. All 112 released author lists were cross-checked against Crossref: 108 match exactly, and none of the 4 differences is an extraction error. Three are errors in Crossref itself, where the PDF is correct ("Dorora"/"Dorota" Wyszkowska in 10.31268/StudiaBAS.2021.36, "Maciej N."/"Maciej J." Nowak in 10.31268/StudiaBAS.2023.02, and a dropped middle initial in 10.31268/StudiaBAS.2024.02); the fourth, 10.31268/StudiaBAS.2021.23, is a Crossref record that carries no author field at all. Co-authors are delimited by the affiliation markers the journal prints on the title page rather than by line spacing, because the journal sets a wrapped name and a following co-author at the same pitch; `src/test_studia_bas_contract.py` pins both that rule and the case of an author list running past the ordinary title-page band.
61
+ - **PII audit**: `src/audit_studia_bas.py` finds zero emails, ORCIDs, PESEL,
62
+ NIP or REGON values across all 115 extracted records. Run
63
+ `src/report_studia_bas_audit.py --corpus <intermediate.jsonl>` to reproduce
64
+ it. The report also lists advisory extraction-quality heuristics; those
65
+ matchers are deliberately broad and fire on ordinary inline references, so
66
+ they do not fail the audit.
67
+
68
+ ## PII scrubber and NERGAL gate
69
+
70
+ Scrubber that ran: `scrub_pii()` in `src/fetch_studia_bas.py` — regex pass over
71
+ the extracted text (e-mail, ORCID, labelled PESEL/NIP/REGON, labelled phone ->
72
+ `[PII]`), plus structural exclusion of author-affiliation/contact blocks and
73
+ ORCID values at extraction time. This is **not**
74
+ [SlayerLab/NERGAL](https://huggingface.co/SlayerLab/NERGAL); per AGENTS.md the
75
+ shard must be re-run through NERGAL before it is admitted to a release (quoted
76
+ case material and third-party names can survive any regex pass). Merge with
77
+ `release: None` is fine meanwhile. The independent audit above (0 structured
78
+ residuals over all 115 records) is evidence for the current build, not a
79
+ substitute for the model-based pass.
data/studia_bas/studia_bas.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdcafd5bbda9c053abd4a4286181ca44dd8c16b556ba33232a18f81d218be1c7
3
+ size 2362278
data/studia_bas/studia_bas.stats.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "read": 115,
3
+ "kept": 112,
4
+ "drop_short": 0,
5
+ "drop_lang": 3,
6
+ "drop_dup": 0,
7
+ "drop_ocr": 0,
8
+ "chars": 6089085,
9
+ "tokens": 2256009,
10
+ "licenses": {
11
+ "CC-BY-3.0-PL": 112
12
+ },
13
+ "authors_with_value": 112,
14
+ "secs": 3.1,
15
+ "license": "CC-BY-3.0-PL"
16
+ }
src/audit_studia_bas.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from pathlib import Path
4
+ from typing import Dict, Any, List
5
+
6
+ EMAIL_RE = re.compile(r"(?i)[a-z0-9._%+-]+\s*@\s*[a-z0-9.-]+\s*\.\s*[a-z]{2,}")
7
+ ORCID_RE = re.compile(r"(?i)\b(?:0\s*0\s*0\s*[0-3])\s*-\s*(?:\d\s*){4}\s*-\s*(?:\d\s*){4}\s*-\s*(?:\d\s*){3}[\dX]\b")
8
+ PHONE_RE = re.compile(r"(?i)\btel\.?\s*:?\s*(?:\d\s*){9,}")
9
+ PESEL_RE = re.compile(r"(?i)\bpesel\b\s*:?\s*(?:\d[\s-]*){11}\b")
10
+ NIP_RE = re.compile(r"(?i)\bnip\b\s*:?\s*(?:\d[\s-]*){10}\b")
11
+ REGON_RE = re.compile(r"(?i)\bregon\b\s*:?\s*(?:(?:\d[\s-]*){9}|(?:\d[\s-]*){14})\b")
12
+ AFFILIATION_RE = re.compile(r"(?i)\b(uniwersytet|wydział|instytut|katedra|mgr inż|dr hab|prof\.)\b")
13
+ NAV_HEADER_RE = re.compile(r"(?i)\bstudia bas\b|\bnr \d+\(\d+\)")
14
+ HYPHEN_RE = re.compile(r"\b\w+-\s+[a-ząćęłńóśźż]\w+\b")
15
+
16
+ REQUIRED_KEYS = {"id", "text", "source", "created", "license", "author", "doi", "source_url", "issue_url", "issue", "license_url"}
17
+
18
+ def get_context(text, match):
19
+ if not match: return ""
20
+ s = max(0, match.start() - 40)
21
+ e = min(len(text), match.end() + 40)
22
+ snippet = text[s:e]
23
+ redacted = snippet[:match.start()-s] + "[REDACTED]" + snippet[match.end()-s:]
24
+ return redacted.replace('\n', ' ')
25
+
26
+ def audit_record(record: Dict[str, Any], seen_ids: set, seen_texts: set) -> Dict[str, List[str]]:
27
+ issues = {}
28
+ text = record.get("text", "")
29
+ author = record.get("author", "")
30
+ doc_id = record.get("id", "")
31
+
32
+ # Missing metadata
33
+ if not all(k in record for k in REQUIRED_KEYS):
34
+ issues["malformed_metadata"] = ["Missing keys"]
35
+
36
+ if not author.strip():
37
+ issues["empty_author"] = ["Empty author field"]
38
+
39
+ if doc_id in seen_ids:
40
+ issues["duplicate_id"] = [f"ID: {doc_id}"]
41
+ seen_ids.add(doc_id)
42
+
43
+ if text in seen_texts:
44
+ issues["duplicate_text"] = ["Duplicate text block"]
45
+ seen_texts.add(text)
46
+
47
+ for issue_name, regex in [
48
+ ("residual_email", EMAIL_RE),
49
+ ("orcid_found", ORCID_RE),
50
+ ("phone_number", PHONE_RE),
51
+ ("pesel", PESEL_RE),
52
+ ("nip", NIP_RE),
53
+ ("regon", REGON_RE),
54
+ ("affiliation_block", AFFILIATION_RE),
55
+ ("navigation_header", NAV_HEADER_RE),
56
+ ("suspicious_hyphenation", HYPHEN_RE),
57
+ ]:
58
+ matches = list(regex.finditer(text))
59
+ if matches:
60
+ issues[issue_name] = [get_context(text, m) for m in matches[:2]]
61
+
62
+ return issues
63
+
64
+ def audit_corpus(path: Path) -> Dict[str, Dict[str, List[str]]]:
65
+ results = {}
66
+ seen_ids = set()
67
+ seen_texts = set()
68
+
69
+ with open(path, 'r', encoding='utf-8') as f:
70
+ for line in f:
71
+ if not line.strip():
72
+ continue
73
+ record = json.loads(line)
74
+ doc_id = record.get("id", "UNKNOWN")
75
+ issues = audit_record(record, seen_ids, seen_texts)
76
+ if issues:
77
+ results[doc_id] = issues
78
+
79
+ return results
src/fetch_studia_bas.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract CC-BY Studia BAS articles from official issue PDFs.
3
+
4
+ The official archive publishes whole issues as text-layer PDFs. This source
5
+ extractor splits each issue at article title pages, removes running headers and
6
+ author-affiliation blocks, normalizes PDF line wrapping, scrubs common PII and
7
+ writes one JSONL record per article. ``build_dynaword.py`` performs the
8
+ canonical token count and Parquet build afterwards.
9
+
10
+ PoC using an existing, reproducibly downloaded issue cache::
11
+
12
+ python3 src/fetch_studia_bas.py \
13
+ --pdf-dir D:/projects/open-charts/out/studiabas/pdf \
14
+ --issues 77 --sample 5 --out artifacts/studia_bas_sample.jsonl
15
+
16
+ Only issue 66 (2/2021) and later are accepted because the journal's CC BY 3.0
17
+ Poland grant starts there. The license line is also verified inside every PDF;
18
+ the issue number alone is never treated as sufficient evidence.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import functools
24
+ import html as html_module
25
+ import json
26
+ import re
27
+ import shutil
28
+ import subprocess
29
+ import tempfile
30
+ import time
31
+ import unicodedata
32
+ import urllib.parse
33
+ import uuid
34
+ from dataclasses import dataclass
35
+ from pathlib import Path
36
+ from typing import Iterable, Sequence
37
+
38
+ SOURCE = "studia_bas"
39
+ LICENSE = "CC-BY-3.0-PL"
40
+ CC_BY_URL = "https://creativecommons.org/licenses/by/3.0/pl/"
41
+ MIN_LICENSED_ISSUE = 66
42
+ BASE = "https://studiabas.sejm.gov.pl"
43
+ ARCHIVE_URL = BASE + "/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL"
44
+ ORKA = "https://orka.sejm.gov.pl"
45
+
46
+ _DOI_RE = re.compile(r"(?:https?://(?:dx\.)?doi\.org/)?(10\.31268/StudiaBAS\.(\d{4})\.([0-9]+(?:\.[0-9]+)*))", re.I)
47
+ _ISSUE_RE = re.compile(r"(?:Studia[_\s-]*BAS[_\s-]*|sb)(\d{1,3})", re.I)
48
+ _ISSUE_YEAR_RE = re.compile(r"\b\d\((\d{2,3})\)\s*((?:19|20)\d{2})\b")
49
+ _LICENSE_RE = re.compile(
50
+ r"Creative\s+Commons.{0,100}(?:Uznanie\s+Autorstwa|CC\s*BY).{0,40}3\.0.{0,20}(?:Polska|PL)",
51
+ re.I | re.S,
52
+ )
53
+ _MARKER_RE = re.compile(r"[*†‡]+")
54
+ _MARKER_END_RE = re.compile(r"[*†‡]+\s*$")
55
+ _EMAIL_RE = re.compile(r"(?<![\w.+-])[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}(?![\w.-])")
56
+ _ORCID_RE = re.compile(
57
+ r"(?i)(?:(?:https?\s*:\s*/\s*/\s*)?orcid\s*\.\s*org\s*/\s*|ORCID\s*:?\s*)?"
58
+ r"\b\d{4}-\d{4}-\d{4}-[\dX]{4}\b"
59
+ )
60
+ _PHONE_RE = re.compile(
61
+ r"(?i)(?<!\w)(?:tel(?:efon)?\.?\s*:?\s*|\+48[\s.-]*)(?:\d[\s.-]*){9}(?!\d)"
62
+ )
63
+ _PESEL_RE = re.compile(r"(?i)PESEL\s*:?\s*\d{11}\b")
64
+ _NIP_RE = re.compile(r"(?i)NIP\s*:?\s*\d{3}[- ]?\d{3}[- ]?\d{2}[- ]?\d{2}\b")
65
+ _REGON_RE = re.compile(r"(?i)REGON\s*:?\s*(?:\d{9}|\d{14})\b")
66
+ _CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
67
+ _ROW_RE = re.compile(r"<tr\b[^>]*>(.*?)</tr>", re.I | re.S)
68
+ _CELL_RE = re.compile(r"<t[dh]\b[^>]*>(.*?)</t[dh]>", re.I | re.S)
69
+ _TAG_RE = re.compile(r"<[^>]+>")
70
+ _DOCID_RE = re.compile(r"documentId=([0-9A-Fa-f]{32})")
71
+ _PDF_RE = re.compile(r'href=["\']([^"\']*?\.pdf)["\']', re.I)
72
+ _AGENT_RE = re.compile(
73
+ r'href=["\']([^"\']*LiczOpen\?OpenAgent&amp;([0-9A-Fa-f]{32})[^"\']*)["\']', re.I
74
+ )
75
+ _VIEWID_RE = re.compile(r'name="\$\$viewid"[^>]*value="([^"]+)"')
76
+ _PANEL_RE = re.compile(r'id="([^"]*:rok)"')
77
+ _COMBO_RE = re.compile(r'name="([^"]*cbYear)"')
78
+ _FORM_RE = re.compile(r'<form[^>]*id="([^"]+)"[^>]*class="xspForm"', re.I)
79
+ _BIBLIOGRAPHY_HEADING_RE = re.compile(r"Bibliografia|References|Bibiliografia", re.I)
80
+ _APPENDIX_HEADING_RE = re.compile(r"^(Załącznik|Aneks|Appendix)\b", re.I)
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class ArchiveIssue:
85
+ year: int
86
+ number: str
87
+ title: str
88
+ editor: str
89
+ document_id: str
90
+
91
+ @property
92
+ def url(self) -> str:
93
+ return f"{BASE}/journal.nsf/pubBAS.xsp?documentId={self.document_id}&lang=PL"
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Block:
98
+ """Text block reduced to the layout signals needed by the extractor."""
99
+
100
+ text: str
101
+ x0: float
102
+ y0: float
103
+ x1: float
104
+ y1: float
105
+ min_size: float
106
+ max_size: float
107
+ lines: tuple[str, ...] = ()
108
+ title_text: str = ""
109
+ author_text: str = ""
110
+ abstract_text: str = ""
111
+
112
+
113
+ def _html_text(fragment: str) -> str:
114
+ return " ".join(html_module.unescape(_TAG_RE.sub(" ", fragment)).replace("\xa0", " ").split())
115
+
116
+
117
+ def parse_archive_rows(fragment: str, year: int) -> list[ArchiveIssue]:
118
+ """Parse the HTML fragment returned by the XPages year refresh."""
119
+
120
+ issues: list[ArchiveIssue] = []
121
+ seen: set[str] = set()
122
+ for row in _ROW_RE.findall(fragment):
123
+ found = _DOCID_RE.search(row)
124
+ if not found:
125
+ continue
126
+ document_id = found.group(1).upper()
127
+ if document_id in seen:
128
+ continue
129
+ seen.add(document_id)
130
+ cells = [_html_text(cell) for cell in _CELL_RE.findall(row)]
131
+ cells += [""] * (3 - len(cells))
132
+ parenthesized = re.search(r"\((\d{1,3})\)", cells[0])
133
+ plain = re.search(r"\d{1,3}", cells[0])
134
+ number = parenthesized.group(1) if parenthesized else (plain.group(0) if plain else "")
135
+ issues.append(ArchiveIssue(year, number, cells[2], cells[1], document_id))
136
+ return issues
137
+
138
+
139
+ def find_issue_pdf_link(page: str, document_id: str) -> str | None:
140
+ """Resolve a direct PDF or the issue-specific download-counting agent."""
141
+
142
+ for href in _PDF_RE.findall(page):
143
+ url = html_module.unescape(href)
144
+ if "/xPDF/" in url:
145
+ continue
146
+ return ORKA + url if url.startswith("/") else url
147
+ for href, unid in _AGENT_RE.findall(page):
148
+ if unid.upper() != document_id.upper():
149
+ continue
150
+ url = html_module.unescape(href)
151
+ return ORKA + url if url.startswith("/") else url
152
+ return None
153
+
154
+
155
+ def normalize_pdf_text(value: str) -> str:
156
+ """Normalize Unicode and whitespace without flattening paragraph breaks."""
157
+
158
+ value = unicodedata.normalize("NFKC", value)
159
+ value = value.replace("\u00ad", "").replace("\u200b", "")
160
+ value = re.sub(r"[\u00a0\u2000-\u200a\u202f\u205f\u3000]", " ", value)
161
+ value = _CONTROL_RE.sub("", value)
162
+ value = value.replace("…", "...")
163
+ value = value.replace("„", '"').replace("”", '"').replace("“", '"')
164
+ value = value.replace("–", "-").replace("—", "-")
165
+ # PDF line wrapping: hard hyphens repeat ("rolno-\n-spożywczy"), soft hyphens don't ("przedsię-\nbiorców").
166
+ value = re.sub(r"(?<=\w)-\s*\n\s*-(?=\w)", "-", value)
167
+ value = re.sub(r"(?<=\w)-\s*\n\s*(?=[a-ząćęłńóśźż])", "", value)
168
+ value = re.sub(r"[ \t]+", " ", value)
169
+ value = re.sub(r" *\n *", "\n", value)
170
+ value = re.sub(r"\n{3,}", "\n\n", value)
171
+ return value.strip()
172
+
173
+
174
+ def scrub_pii(value: str) -> str:
175
+ """Replace contact and national identifiers while retaining sentence shape."""
176
+
177
+ for pattern in (_EMAIL_RE, _ORCID_RE, _PESEL_RE, _NIP_RE, _REGON_RE, _PHONE_RE):
178
+ value = pattern.sub("[PII]", value)
179
+ return normalize_pdf_text(value)
180
+
181
+
182
+ def _from_pymupdf(raw: dict) -> Block | None:
183
+ lines = raw.get("lines")
184
+ if not lines:
185
+ return None
186
+ line_texts: list[str] = []
187
+ title_lines: list[str] = []
188
+ author_lines: list[str] = []
189
+ abstract_lines: list[str] = []
190
+ sizes: list[float] = []
191
+ for line in lines:
192
+ spans = line.get("spans", [])
193
+ text = "".join(str(span.get("text", "")) for span in spans)
194
+ if text.strip():
195
+ line_texts.append(text.strip())
196
+ title = "".join(str(span.get("text", "")) for span in spans if float(span.get("size", 0.0)) >= 12)
197
+ author = "".join(
198
+ str(span.get("text", ""))
199
+ for span in spans
200
+ if 8.8 <= float(span.get("size", 0.0)) <= 10.5
201
+ )
202
+ if title.strip():
203
+ title_lines.append(title.strip())
204
+ if author.strip():
205
+ author_lines.append(author.strip())
206
+ if text.strip() and spans and not any(int(span.get("flags", 0)) & 16 for span in spans):
207
+ abstract_lines.append(text.strip())
208
+ sizes.extend(float(span.get("size", 0.0)) for span in spans)
209
+ text = "\n".join(line_texts).strip()
210
+ if not text or not sizes:
211
+ return None
212
+ x0, y0, x1, y1 = map(float, raw["bbox"])
213
+ return Block(
214
+ text,
215
+ x0,
216
+ y0,
217
+ x1,
218
+ y1,
219
+ min(sizes),
220
+ max(sizes),
221
+ tuple(line_texts),
222
+ "\n".join(title_lines),
223
+ "\n".join(author_lines),
224
+ "\n".join(abstract_lines),
225
+ )
226
+
227
+
228
+ def pdf_pages(path: Path) -> list[list[Block]]:
229
+ """Read the text layer; scanned/image-only issues fail closed."""
230
+
231
+ try:
232
+ import pymupdf
233
+ except ImportError as exc: # pragma: no cover - environment-specific
234
+ raise RuntimeError("Studia BAS extraction requires pymupdf: pip install pymupdf") from exc
235
+
236
+ document = pymupdf.open(path)
237
+ pages: list[list[Block]] = []
238
+ for page in document:
239
+ blocks = [block for raw in page.get_text("dict")["blocks"] if (block := _from_pymupdf(raw))]
240
+ pages.append(sorted(blocks, key=lambda item: (item.y0, item.x0)))
241
+ if not pages or sum(bool(page) for page in pages) < len(pages) * 0.8:
242
+ raise ValueError(f"{path} has too many pages without a usable text layer")
243
+ return pages
244
+
245
+
246
+ def _page_text(page: Sequence[Block]) -> str:
247
+ return "\n".join(block.text for block in page)
248
+
249
+
250
+ def article_start_indexes(pages: Sequence[Sequence[Block]]) -> list[int]:
251
+ """Find article title pages, rejecting incidental DOI citations."""
252
+
253
+ starts: list[int] = []
254
+ for index, page in enumerate(pages):
255
+ text = _page_text(page)
256
+ has_title = any(block.max_size >= 12 and 70 <= block.y0 <= 250 for block in page)
257
+ if has_title and _DOI_RE.search(text) and _LICENSE_RE.search(text):
258
+ starts.append(index)
259
+ return starts
260
+
261
+
262
+ def _author_lines(value: str) -> list[tuple[str, bool]]:
263
+ """Author lines, each flagged with the affiliation marker that closes a name.
264
+
265
+ Studia BAS prints one asterisk run per co-author, so a marked line ends an
266
+ author and an unmarked line below it is the wrapped remainder of that name.
267
+ Markers are stripped from the name itself; only their position is a signal.
268
+ """
269
+
270
+ value = re.sub(r"^\s*\d+\s*", "", value, flags=re.MULTILINE)
271
+ lines: list[tuple[str, bool]] = []
272
+ for line in normalize_pdf_text(value).splitlines():
273
+ marked = bool(_MARKER_END_RE.search(line))
274
+ line = " ".join(_MARKER_RE.sub("", line).split())
275
+ if line:
276
+ lines.append((line, marked))
277
+ return lines
278
+
279
+
280
+ def _join_author(previous: str, line: str) -> str:
281
+ """Append a wrapped continuation line, healing the hyphen the wrap repeated."""
282
+
283
+ if previous.endswith("-"):
284
+ return previous + line.lstrip("-")
285
+ return previous + " " + line
286
+
287
+
288
+ def _front_matter(page: Sequence[Block]) -> dict[str, object]:
289
+ title_candidates = [
290
+ block
291
+ for block in page
292
+ if (block.title_text or block.max_size >= 12) and 70 <= block.y0 <= 250
293
+ ]
294
+ if not title_candidates:
295
+ raise ValueError("article page has no large Polish title block")
296
+ title_candidates.sort(key=lambda block: (block.y0, block.x0))
297
+ title = normalize_pdf_text(
298
+ "\n".join(block.title_text or block.text for block in title_candidates)
299
+ ).replace("\n", " ")
300
+ title_block = title_candidates[0]
301
+
302
+ # The author band ends at 155 in every ordinary layout, but a long author
303
+ # list simply keeps running down the page, so follow it while the blocks stay
304
+ # contiguous and keep the same author typography.
305
+ author_values: list[str] = []
306
+ author_blocks: list[Block] = []
307
+ for block in page:
308
+ if block.y0 < 55:
309
+ continue
310
+ geometric = 8.8 <= block.max_size <= 10.5 and block.x0 < title_block.x0 - 5
311
+ if block.y0 > 155:
312
+ previous = author_blocks[-1] if author_blocks else None
313
+ if previous is None or not geometric or not 0 <= block.y0 - previous.y1 <= 4:
314
+ continue
315
+ if not (8.8 <= previous.max_size <= 10.5 and previous.x0 < title_block.x0 - 5):
316
+ continue
317
+ value = block.author_text or (block.text if geometric else "")
318
+ if value:
319
+ author_values.append(value)
320
+ author_blocks.append(block)
321
+
322
+ # Line pitch cannot tell a wrapped name from the next co-author: the journal
323
+ # sets some title pages at 12pt leading and others at 14.9pt, so both look
324
+ # alike. The affiliation marker can, and it is present whenever there is
325
+ # more than one author to tell apart.
326
+ lines = [pair for value in author_values for pair in _author_lines(value)]
327
+ authors: list[str] = []
328
+ if any(marked for _, marked in lines):
329
+ closed = True
330
+ for line, marked in lines:
331
+ if authors and not closed:
332
+ authors[-1] = _join_author(authors[-1], line)
333
+ else:
334
+ authors.append(line)
335
+ closed = marked
336
+ else:
337
+ # No marker means nothing delimits the names, which is what a sole author
338
+ # looks like: a name wrapped over one or two lines ("Agnieszka Paulina" /
339
+ # "Smolenska"). Only fall back to guessing per line if the join is too
340
+ # long to be one person's name.
341
+ joined = functools.reduce(_join_author, [line for line, _ in lines], "").strip()
342
+ if len(joined.split()) <= 4:
343
+ authors = [joined] if joined else []
344
+ else:
345
+ for line, _ in lines:
346
+ if authors and authors[-1].endswith("-"):
347
+ authors[-1] = _join_author(authors[-1], line)
348
+ elif authors and len(line.split()) == 1 and len(authors[-1].split()) == 1:
349
+ authors[-1] = _join_author(authors[-1], line)
350
+ else:
351
+ authors.append(line)
352
+ authors = [author for author in authors if author and len(author.split()) <= 8]
353
+
354
+ doi_match = _DOI_RE.search(_page_text(page))
355
+ if not doi_match:
356
+ raise ValueError("article page has no Studia BAS DOI")
357
+ doi = doi_match.group(1)
358
+
359
+ # DOI suffix format mapping: 2024.03 -> 03, 2024.1.1 -> 01_01.
360
+ # We zero-pad each part to 2 digits to ensure deterministic sorting
361
+ # and prevent collisions across issues that reset article numbering.
362
+ ordinal_raw = doi_match.group(3)
363
+ ordinal = "_".join(f"{int(p):02d}" for p in ordinal_raw.split("."))
364
+
365
+ doi_blocks = [block for block in page if _DOI_RE.search(block.text)]
366
+ doi_top = min(block.y0 for block in doi_blocks)
367
+ title_bottom = max(block.y1 for block in title_candidates)
368
+ abstract_parts: list[str] = []
369
+ for block in page:
370
+ if block.y0 < title_bottom - 1 or block.y0 >= doi_top or block.max_size > 8.5:
371
+ continue
372
+ value = block.abstract_text
373
+ if not value:
374
+ lines = list(block.lines) if block.lines else block.text.splitlines()
375
+ value = "\n".join(lines[1:]) if len(lines) >= 2 else ""
376
+ if value and not value.lstrip().startswith(("DOI", "Słowa", "Keywords")):
377
+ abstract_parts.append(value)
378
+ abstract = normalize_pdf_text("\n".join(abstract_parts)).replace("\n", " ")
379
+
380
+ keywords = ""
381
+ for block in page:
382
+ compact = normalize_pdf_text(block.text).replace("\n", " ")
383
+ if compact.lower().startswith("słowa kluczowe"):
384
+ keywords = re.sub(r"(?i)^słowa kluczowe\s*", "", compact).strip()
385
+ break
386
+
387
+ license_blocks = [block for block in page if _LICENSE_RE.search(block.text)]
388
+ if not license_blocks:
389
+ raise ValueError("article page lacks its CC BY 3.0 PL statement")
390
+ license_bottom = max(block.y1 for block in license_blocks)
391
+ return {
392
+ "title": title,
393
+ "authors": authors,
394
+ "doi": doi,
395
+ "year": int(doi_match.group(2)),
396
+ "ordinal": ordinal,
397
+ "abstract": abstract,
398
+ "keywords": keywords,
399
+ "license_bottom": license_bottom,
400
+ }
401
+
402
+
403
+ def _content_blocks(pages: Sequence[Sequence[Block]], license_bottom: float) -> list[Block]:
404
+ content: list[Block] = []
405
+ for page_index, page in enumerate(pages):
406
+ for block in page:
407
+ if block.y0 < 50: # running header/page number
408
+ continue
409
+ if page_index == 0 and block.y0 <= license_bottom:
410
+ continue
411
+ content.append(block)
412
+ return content
413
+
414
+
415
+ def _blocks_to_text(blocks: Sequence[Block]) -> str:
416
+ paragraphs: list[str] = []
417
+ current = ""
418
+ previous: Block | None = None
419
+ for block in blocks:
420
+ value = normalize_pdf_text(block.text)
421
+ if not value:
422
+ continue
423
+ heading = block.max_size >= 10.3 and len(value) < 180
424
+ gap = block.y0 - previous.y1 if previous is not None else 99.0
425
+ indented = block.x0 >= 65 and previous is not None
426
+ font_change = previous is not None and abs(block.max_size - previous.max_size) >= 1.0
427
+ new_paragraph = heading or previous is None or gap > 4.5 or indented or font_change
428
+ if new_paragraph and current:
429
+ paragraphs.append(normalize_pdf_text(current))
430
+ current = ""
431
+ if heading:
432
+ paragraphs.append(value.replace("\n", " "))
433
+ else:
434
+ piece = value.replace("\n", " ")
435
+ if current.endswith("-") and re.match(r"^-?[a-ząćęłńóśźż]", piece):
436
+ current = current[:-1] + piece.lstrip("-")
437
+ else:
438
+ current = f"{current} {piece}".strip()
439
+ previous = block
440
+ if current:
441
+ paragraphs.append(normalize_pdf_text(current))
442
+ return "\n\n".join(paragraph for paragraph in paragraphs if paragraph)
443
+
444
+
445
+ def remove_terminal_bibliography(text: str) -> str:
446
+ """Remove terminal bibliography section while restoring any substantive appendix."""
447
+ body_parts = text.split("\n\n")
448
+ bib_idx = -1
449
+ for i in reversed(range(len(body_parts))):
450
+ if _BIBLIOGRAPHY_HEADING_RE.fullmatch(body_parts[i].strip()):
451
+ bib_idx = i
452
+ break
453
+
454
+ if bib_idx != -1:
455
+ end_idx = len(body_parts)
456
+ for i in range(bib_idx + 1, len(body_parts)):
457
+ if _APPENDIX_HEADING_RE.match(body_parts[i].strip()) and len(body_parts[i]) < 150:
458
+ end_idx = i
459
+ break
460
+ body_parts = body_parts[:bib_idx] + body_parts[end_idx:]
461
+ return "\n\n".join(body_parts)
462
+ return text
463
+
464
+
465
+ def extract_article(
466
+ pages: Sequence[Sequence[Block]],
467
+ *,
468
+ issue_number: str,
469
+ year: int,
470
+ issue_url: str = "",
471
+ ) -> dict[str, object]:
472
+ """Convert one already-sliced article to a provenance-rich JSONL record."""
473
+
474
+ if not pages:
475
+ raise ValueError("article has no pages")
476
+ meta = _front_matter(pages[0])
477
+ if int(meta["year"]) != int(year):
478
+ raise ValueError(f"issue year {year} disagrees with DOI year {meta['year']}")
479
+ body = _blocks_to_text(_content_blocks(pages, float(meta["license_bottom"])))
480
+ body = remove_terminal_bibliography(body)
481
+
482
+ parts = [str(meta["title"])]
483
+ if meta["abstract"]:
484
+ parts.extend(["Streszczenie", str(meta["abstract"])])
485
+ if meta["keywords"]:
486
+ parts.extend(["Słowa kluczowe", str(meta["keywords"])])
487
+ parts.append(body)
488
+ text = scrub_pii("\n\n".join(part for part in parts if part).strip())
489
+ doi = str(meta["doi"])
490
+ ordinal = str(meta["ordinal"])
491
+ return {
492
+ "id": f"{SOURCE}_{year}_{ordinal}",
493
+ "text": text,
494
+ "source": SOURCE,
495
+ "created": str(year),
496
+ "license": LICENSE,
497
+ "author": "; ".join(str(author) for author in meta["authors"]),
498
+ "doi": doi,
499
+ "source_url": f"https://doi.org/{doi}",
500
+ "issue_url": issue_url,
501
+ "issue": str(issue_number),
502
+ "license_url": CC_BY_URL,
503
+ }
504
+
505
+
506
+ def issue_metadata(path: Path, pages: Sequence[Sequence[Block]]) -> tuple[str, int]:
507
+ number_match = _ISSUE_RE.search(path.stem)
508
+ front = "\n".join(_page_text(page) for page in pages[:8])
509
+ issue_year = _ISSUE_YEAR_RE.search(front)
510
+ number = number_match.group(1) if number_match else (issue_year.group(1) if issue_year else "")
511
+ year = int(issue_year.group(2)) if issue_year else 0
512
+ if not number or not year:
513
+ raise ValueError(f"cannot infer issue/year from {path}")
514
+ if int(number) < MIN_LICENSED_ISSUE:
515
+ raise ValueError(f"issue {number} predates the CC BY corpus boundary (66)")
516
+ if not _LICENSE_RE.search(front):
517
+ raise ValueError(f"issue {number} does not expose the expected CC BY 3.0 PL statement")
518
+ return number, year
519
+
520
+
521
+ def extract_issue(path: Path, issue_url: str = "") -> list[dict[str, object]]:
522
+ pages = pdf_pages(path)
523
+ issue_number, year = issue_metadata(path, pages)
524
+ starts = article_start_indexes(pages)
525
+ if not starts:
526
+ raise ValueError(f"no article title pages found in {path}")
527
+ records: list[dict[str, object]] = []
528
+ for position, start in enumerate(starts):
529
+ end = starts[position + 1] if position + 1 < len(starts) else len(pages)
530
+ records.append(
531
+ extract_article(
532
+ pages[start:end],
533
+ issue_number=issue_number,
534
+ year=year,
535
+ issue_url=issue_url,
536
+ )
537
+ )
538
+ ids = [str(record["id"]) for record in records]
539
+ if len(ids) != len(set(ids)):
540
+ raise ValueError(f"duplicate DOI-derived IDs in {path}")
541
+ return records
542
+
543
+
544
+ def _archive_form_state(page: str) -> dict[str, str]:
545
+ values = {
546
+ "viewid": _VIEWID_RE.search(page),
547
+ "panel": _PANEL_RE.search(page),
548
+ "combo": _COMBO_RE.search(page),
549
+ "form": _FORM_RE.search(page),
550
+ }
551
+ if not all(values.values()):
552
+ raise ValueError("archive page does not expose the expected XPages form state")
553
+ return {key: match.group(1) for key, match in values.items()} # type: ignore[union-attr]
554
+
555
+
556
+ def _multipart(fields: dict[str, str]) -> tuple[bytes, str]:
557
+ boundary = "----WebKitFormBoundary" + uuid.uuid4().hex[:16]
558
+ body = "".join(
559
+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'
560
+ for name, value in fields.items()
561
+ ) + f"--{boundary}--\r\n"
562
+ return body.encode("utf-8"), f"multipart/form-data; boundary={boundary}"
563
+
564
+
565
+ class ArchiveClient:
566
+ """Browser-TLS client for the Imperva-fronted official archive."""
567
+
568
+ def __init__(self, tries: int = 8, timeout: float = 45.0, pause: float = 2.0):
569
+ try:
570
+ from curl_cffi import requests
571
+ except ImportError as exc: # pragma: no cover - environment-specific
572
+ raise RuntimeError(
573
+ "Studia BAS archive requires browser TLS: pip install curl_cffi"
574
+ ) from exc
575
+ self._requests = requests
576
+ self.tries = tries
577
+ self.timeout = timeout
578
+ self.pause = pause
579
+ self.session = self._new_session()
580
+ self.state: dict[str, str] | None = None
581
+
582
+ def _new_session(self):
583
+ return self._requests.Session(impersonate="chrome")
584
+
585
+ def request(self, method: str, url: str, **kwargs):
586
+ last: BaseException | None = None
587
+ for attempt in range(self.tries):
588
+ try:
589
+ response = getattr(self.session, method)(url, timeout=self.timeout, **kwargs)
590
+ if int(response.status_code) >= 400:
591
+ raise OSError(f"HTTP {response.status_code}")
592
+ return response
593
+ except BaseException as exc:
594
+ if isinstance(exc, (KeyboardInterrupt, SystemExit)):
595
+ raise
596
+ last = exc
597
+ if attempt == self.tries - 1:
598
+ break
599
+ time.sleep(1.5 * (attempt + 1))
600
+ self.session = self._new_session()
601
+ self.state = None
602
+ raise ConnectionError(f"{method.upper()} {url} failed after {self.tries} attempts") from last
603
+
604
+ def open(self) -> dict[str, str]:
605
+ if self.state is None:
606
+ self.state = _archive_form_state(self.request("get", ARCHIVE_URL).text)
607
+ return self.state
608
+
609
+ def issues_for_year(self, year: int) -> list[ArchiveIssue]:
610
+ state = self.open()
611
+ body, content_type = _multipart(
612
+ {
613
+ "$$viewid": state["viewid"],
614
+ state["form"]: state["form"],
615
+ state["combo"]: str(year),
616
+ }
617
+ )
618
+ url = ARCHIVE_URL + "&$$ajaxid=" + urllib.parse.quote(state["panel"], safe="")
619
+ response = self.request(
620
+ "post",
621
+ url,
622
+ data=body,
623
+ headers={
624
+ "X-Requested-With": "XMLHttpRequest",
625
+ "Referer": ARCHIVE_URL,
626
+ "Origin": BASE,
627
+ "Content-Type": content_type,
628
+ },
629
+ )
630
+ return parse_archive_rows(response.text, year)
631
+
632
+ def download_issue(self, issue: ArchiveIssue, directory: Path) -> Path:
633
+ directory.mkdir(parents=True, exist_ok=True)
634
+ path = directory / f"Studia_BAS_{issue.number}.pdf"
635
+ if path.is_file() and path.stat().st_size and path.read_bytes()[:4] == b"%PDF":
636
+ return path
637
+ page = self.request("get", issue.url).text
638
+ pdf_url = find_issue_pdf_link(page, issue.document_id)
639
+ if not pdf_url:
640
+ raise ValueError(f"issue {issue.number} page contains no matching PDF link")
641
+ content = self.request("get", pdf_url, headers={"Referer": issue.url}).content
642
+ if not content.startswith(b"%PDF"):
643
+ raise ValueError(f"issue {issue.number} download did not return a PDF")
644
+ path.write_bytes(content)
645
+ time.sleep(self.pause)
646
+ return path
647
+
648
+
649
+ def download_archive_years(
650
+ years: Sequence[int], directory: Path, issues: set[int] | None = None
651
+ ) -> list[Path]:
652
+ """Reproducibly enumerate and cache official issue PDFs."""
653
+
654
+ client = ArchiveClient()
655
+ paths: list[Path] = []
656
+ for year in years:
657
+ for issue in client.issues_for_year(year):
658
+ if not issue.number or int(issue.number) < MIN_LICENSED_ISSUE:
659
+ continue
660
+ if issues is not None and int(issue.number) not in issues:
661
+ continue
662
+ paths.append(client.download_issue(issue, directory))
663
+ return paths
664
+
665
+
666
+ def _selected_pdfs(directory: Path, issues: set[int] | None) -> list[Path]:
667
+ paths: list[tuple[int, Path]] = []
668
+ for path in directory.glob("*.pdf"):
669
+ match = _ISSUE_RE.search(path.stem)
670
+ if not match:
671
+ continue
672
+ number = int(match.group(1))
673
+ if number < MIN_LICENSED_ISSUE or (issues is not None and number not in issues):
674
+ continue
675
+ paths.append((number, path))
676
+ return [path for _, path in sorted(paths)]
677
+
678
+
679
+ PUBLISHER = "Kancelaria Sejmu, Biuro Analiz Sejmowych"
680
+ MODIFICATION_NOTICE = (
681
+ "Article text was extracted from the text layer of the official issue PDF. "
682
+ "Running headers, page numbers, author affiliation/contact blocks, and "
683
+ "terminal bibliographies were removed, residual personal data was replaced "
684
+ "with [PII], and PDF line wrapping was normalized."
685
+ )
686
+
687
+
688
+ def read_jsonl(path: Path) -> list[dict[str, object]]:
689
+ """Read a .jsonl or .jsonl.zst file written by write_jsonl."""
690
+ if path.suffix == ".zst":
691
+ import zstandard
692
+
693
+ payload = zstandard.ZstdDecompressor().decompress(
694
+ path.read_bytes(), max_output_size=1 << 30
695
+ )
696
+ text = payload.decode("utf-8")
697
+ else:
698
+ text = path.read_text(encoding="utf-8")
699
+ return [json.loads(line) for line in text.splitlines() if line.strip()]
700
+
701
+
702
+ def build_attribution_rows(
703
+ records: Iterable[dict[str, object]],
704
+ ids: Sequence[str],
705
+ issue_pdfs: dict[str, dict[str, object]] | None = None,
706
+ ) -> list[dict[str, object]]:
707
+ """One attribution row per Parquet id, in Parquet order.
708
+
709
+ The canonical Parquet keeps only eight columns, so the per-article DOI and
710
+ the issue PDF an article came from live here instead, which is what CC BY
711
+ attribution needs. Building from the Parquet id order is what keeps the two
712
+ files aligned: an id the source cannot explain raises rather than shifting
713
+ every later row onto the wrong article.
714
+ """
715
+ issue_pdfs = issue_pdfs or {}
716
+ by_id = {str(record["id"]): record for record in records}
717
+ rows = []
718
+ for record_id in ids:
719
+ record = by_id.get(record_id)
720
+ if record is None:
721
+ raise ValueError(f"Parquet id {record_id!r} is absent from the source records")
722
+ issue = str(record["issue"])
723
+ pdf = issue_pdfs.get(issue, {})
724
+ rows.append(
725
+ {
726
+ "id": record_id,
727
+ "doi": record["doi"],
728
+ "attribution_url": record["source_url"],
729
+ "archive_url": ARCHIVE_URL,
730
+ "issue": issue,
731
+ "issue_pdf_filename": pdf.get("filename", ""),
732
+ "issue_pdf_sha256": pdf.get("sha256", ""),
733
+ "author": record["author"],
734
+ "publisher": PUBLISHER,
735
+ "license": LICENSE,
736
+ "license_url": record.get("license_url", CC_BY_URL),
737
+ "modified": True,
738
+ "modification_notice": MODIFICATION_NOTICE,
739
+ }
740
+ )
741
+ return rows
742
+
743
+
744
+ def load_issue_pdfs(evidence: Path) -> dict[str, dict[str, object]]:
745
+ """Map issue number to the hashed source PDF recorded in the licence evidence."""
746
+ if not evidence.exists():
747
+ return {}
748
+ payload = json.loads(evidence.read_text(encoding="utf-8"))
749
+ return {str(entry["issue"]): entry for entry in payload.get("eligible_pdfs", [])}
750
+
751
+
752
+
753
+ def write_attribution_sidecar(source: Path, parquet: Path, output: Path, evidence: Path) -> int:
754
+ """Write the attribution sidecar for an already-built canonical Parquet."""
755
+ import pyarrow.parquet as pq
756
+
757
+ ids = [str(value) for value in pq.read_table(parquet, columns=["id"])["id"].to_pylist()]
758
+ rows = build_attribution_rows(read_jsonl(source), ids, load_issue_pdfs(evidence))
759
+ output.parent.mkdir(parents=True, exist_ok=True)
760
+ with output.open("w", encoding="utf-8", newline="") as handle:
761
+ for row in rows:
762
+ print(json.dumps(row, ensure_ascii=False, sort_keys=True), file=handle)
763
+ return len(rows)
764
+
765
+
766
+
767
+ def write_jsonl(records: Iterable[dict[str, object]], output: Path) -> int:
768
+ rows = sorted(records, key=lambda row: str(row["id"]))
769
+ output.parent.mkdir(parents=True, exist_ok=True)
770
+ if output.suffix == ".zst":
771
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".jsonl", delete=False) as handle:
772
+ temporary = Path(handle.name)
773
+ for row in rows:
774
+ handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
775
+ try:
776
+ executable = shutil.which("zstd")
777
+ if executable:
778
+ subprocess.run([executable, "-19", "-f", str(temporary), "-o", str(output)], check=True)
779
+ else:
780
+ try:
781
+ import zstandard
782
+ except ImportError as exc: # pragma: no cover - environment-specific
783
+ raise RuntimeError(
784
+ "writing .zst requires zstd or Python zstandard: pip install zstandard"
785
+ ) from exc
786
+ compressor = zstandard.ZstdCompressor(level=19)
787
+ with temporary.open("rb") as source, output.open("wb") as target:
788
+ compressor.copy_stream(source, target)
789
+ finally:
790
+ temporary.unlink(missing_ok=True)
791
+ else:
792
+ output.write_text(
793
+ "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows),
794
+ encoding="utf-8",
795
+ )
796
+ return len(rows)
797
+
798
+
799
+ def main() -> None:
800
+ parser = argparse.ArgumentParser()
801
+ parser.add_argument(
802
+ "--pdf-dir",
803
+ type=Path,
804
+ default=Path("studia_bas_pdfs"),
805
+ help="cache directory of official Studia BAS issue PDFs",
806
+ )
807
+ parser.add_argument(
808
+ "--download-years",
809
+ type=int,
810
+ nargs="*",
811
+ help="enumerate these archive years and download missing official PDFs",
812
+ )
813
+ parser.add_argument("--issues", type=int, nargs="*", help="continuous issue numbers, e.g. 77")
814
+ parser.add_argument("--sample", type=int, default=None, help="keep only the first N articles after sorting")
815
+ parser.add_argument("--out", type=Path, default=Path("studia_bas.jsonl.zst"))
816
+ parser.add_argument(
817
+ "--sidecar-parquet",
818
+ type=Path,
819
+ help="write the attribution sidecar for this already-built canonical Parquet "
820
+ "instead of extracting PDFs; --pdf-dir is then unused",
821
+ )
822
+ parser.add_argument(
823
+ "--sidecar-source",
824
+ type=Path,
825
+ default=Path("studia_bas.jsonl.zst"),
826
+ help="source records the Parquet was built from, as written by --out; "
827
+ "this intermediate is a build input and is not part of the released shard",
828
+ )
829
+ parser.add_argument(
830
+ "--sidecar-out",
831
+ type=Path,
832
+ default=Path("data/studia_bas/studia_bas.attribution.jsonl"),
833
+ )
834
+ parser.add_argument(
835
+ "--sidecar-evidence",
836
+ type=Path,
837
+ default=Path("data/studia_bas/studia_bas.license-evidence.json"),
838
+ )
839
+
840
+ args = parser.parse_args()
841
+
842
+ if args.sidecar_parquet:
843
+ count = write_attribution_sidecar(
844
+ args.sidecar_source, args.sidecar_parquet, args.sidecar_out, args.sidecar_evidence
845
+ )
846
+ print(f"wrote {count} attribution rows to {args.sidecar_out}")
847
+ return
848
+
849
+
850
+ wanted_issues = set(args.issues) if args.issues else None
851
+ if args.download_years:
852
+ download_archive_years(args.download_years, args.pdf_dir, wanted_issues)
853
+ paths = _selected_pdfs(args.pdf_dir, wanted_issues)
854
+ if not paths:
855
+ raise SystemExit("no licensed Studia BAS PDFs matched the selection")
856
+ records: list[dict[str, object]] = []
857
+ for path in paths:
858
+ extracted = extract_issue(path)
859
+ records.extend(extracted)
860
+ print(f"{path.name}: {len(extracted)} articles", flush=True)
861
+ records.sort(key=lambda row: str(row["id"]))
862
+ if args.sample is not None:
863
+ records = records[: args.sample]
864
+ count = write_jsonl(records, args.out)
865
+ print(f"wrote {count} records to {args.out}")
866
+
867
+
868
+ if __name__ == "__main__":
869
+ main()
src/report_studia_bas_audit.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render src/audit_studia_bas.py findings as a Markdown report.
2
+
3
+ Input is the intermediate JSONL src/fetch_studia_bas.py writes, not the released
4
+ Parquet: the audit reads provenance fields (``source_url``, ``issue_url``) that
5
+ only exist upstream of the canonical eight-column schema.
6
+ """
7
+
8
+ from pathlib import Path
9
+ import sys
10
+ from collections import defaultdict
11
+ from audit_studia_bas import audit_corpus
12
+
13
+ import argparse
14
+
15
+ EXTRACTION_ISSUES = {"affiliation_block", "navigation_header", "suspicious_hyphenation", "empty_author", "malformed_metadata", "duplicate_id", "duplicate_text"}
16
+
17
+ def main():
18
+ parser = argparse.ArgumentParser()
19
+ # No default: the intermediate is a build artifact and is not committed, so a
20
+ # default path would only ever be a stale guess.
21
+ parser.add_argument("--corpus", type=Path, required=True,
22
+ help="intermediate JSONL from src/fetch_studia_bas.py")
23
+ parser.add_argument("--out", type=Path, default=Path("artifacts/studia_bas_pii_audit.md"))
24
+ args = parser.parse_args()
25
+
26
+ path = args.corpus
27
+ if not path.exists():
28
+ print(f"File not found: {path}")
29
+ sys.exit(1)
30
+
31
+ results = audit_corpus(path)
32
+
33
+ total_records_checked = 0
34
+ with open(path, 'r', encoding='utf-8') as f:
35
+ total_records_checked = sum(1 for line in f if line.strip())
36
+
37
+ report = ["# Studia BAS PII Audit Report\n"]
38
+ report.append(f"**Total records checked:** {total_records_checked}\n")
39
+
40
+ extraction_by_type = defaultdict(list)
41
+ pii_by_type = defaultdict(list)
42
+
43
+ for doc_id, issues in results.items():
44
+ for issue_type, contexts in issues.items():
45
+ if issue_type in EXTRACTION_ISSUES:
46
+ extraction_by_type[issue_type].append((doc_id, contexts))
47
+ else:
48
+ pii_by_type[issue_type].append((doc_id, contexts))
49
+
50
+ # The verdict is decided by PII only. The extraction-quality matchers are
51
+ # deliberately broad and fire on ordinary inline references or citations (institution
52
+ # names inside texts, "nr 4(12)" issue references, suspended hyphens),
53
+ # so they are reported as advisory findings and never fail the audit.
54
+ pii_records = sorted({doc_id for rows in pii_by_type.values() for doc_id, _ in rows})
55
+ if not pii_records:
56
+ report.append("## Conclusion: PASS")
57
+ report.append("No PII detected in any record.")
58
+ else:
59
+ report.append("## Conclusion: FAIL")
60
+ report.append(f"PII detected in {len(pii_records)} records.")
61
+ report.append("")
62
+ if extraction_by_type:
63
+ advisory = sorted({doc_id for rows in extraction_by_type.values() for doc_id, _ in rows})
64
+ report.append(
65
+ f"Advisory: {len(advisory)} records matched an extraction-quality "
66
+ "heuristic. These are not audit failures; review them by hand."
67
+ )
68
+ report.append("")
69
+ if results:
70
+ if pii_by_type:
71
+ report.append("## PII Leaks\n")
72
+ for issue_type, instances in sorted(pii_by_type.items()):
73
+ report.append(f"### {issue_type} ({len(instances)} affected IDs)")
74
+ for doc_id, contexts in instances:
75
+ report.append(f"- **{doc_id}**")
76
+ for ctx in contexts:
77
+ if ctx:
78
+ report.append(f" - Context: `{ctx}`")
79
+ report.append("")
80
+
81
+ if extraction_by_type:
82
+ report.append("## Extraction Quality Issues\n")
83
+ for issue_type, instances in sorted(extraction_by_type.items()):
84
+ report.append(f"### {issue_type} ({len(instances)} affected IDs)")
85
+ for doc_id, contexts in instances:
86
+ report.append(f"- **{doc_id}**")
87
+ for ctx in contexts:
88
+ if ctx:
89
+ report.append(f" - Context: `{ctx}`")
90
+ report.append("")
91
+
92
+ report_path = args.out
93
+ report_path.parent.mkdir(parents=True, exist_ok=True)
94
+ report_path.write_text("\n".join(report), encoding="utf-8")
95
+ print(f"Report written to {report_path}")
96
+
97
+ if __name__ == "__main__":
98
+ main()
src/sources.py CHANGED
@@ -510,6 +510,35 @@ SOURCES = {
510
  "is_ocr": False,
511
  "custom_datasheet": True,
512
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  "biblioteka_nauki": {
514
  "added": "2026-06-27",
515
  "custom_datasheet": True,
 
510
  "is_ocr": False,
511
  "custom_datasheet": True,
512
  },
513
+ "studia_bas": {
514
+ "file_key": "studia_bas",
515
+ "preserve_id": True,
516
+ "preserve_created": True,
517
+ "added": "2026-07-19",
518
+ "release": None,
519
+ "pretty": "Studia BAS — peer-reviewed socioeconomic and public-policy articles",
520
+ "license": "CC-BY-3.0-PL",
521
+ "license_spdx": "CC-BY-3.0-PL",
522
+ "traceable": "Starting with issue 2(66)/2021, Studia BAS publishes its "
523
+ "content under Creative Commons Attribution 3.0 Poland. "
524
+ "The grant is stated both on the journal open-access page "
525
+ "and inside every retained official issue PDF.",
526
+ "upstream": "https://studiabas.sejm.gov.pl/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL",
527
+ "provenance": "Official issue PDFs are enumerated through the journal's XPages "
528
+ "archive and downloaded with browser-TLS transport by "
529
+ "src/fetch_studia_bas.py. Text-layer articles are split by DOI "
530
+ "title pages; running headers, author affiliation/contact blocks "
531
+ "and ORCID values are excluded, common PII is replaced with [PII], "
532
+ "terminal bibliographies are removed, and PDF line wrapping is "
533
+ "normalized before the canonical build. The preserve_id / "
534
+ "preserve_created entry flags require the separate build_dynaword.py "
535
+ "change (split out for its own review). Pattern scrubbing only - "
536
+ "re-run through SlayerLab/NERGAL before release.",
537
+ "domain": "academic, economics, social policy and public policy",
538
+ "created": "2021-2025 (per article in the created column)",
539
+ "is_ocr": False,
540
+ "custom_datasheet": True,
541
+ },
542
  "biblioteka_nauki": {
543
  "added": "2026-06-27",
544
  "custom_datasheet": True,
src/test_audit_studia_bas.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from audit_studia_bas import audit_record
3
+
4
+ def get_base_record(text="", author="Jan Kowalski", doc_id="1"):
5
+ return {
6
+ "id": doc_id,
7
+ "text": text,
8
+ "author": author,
9
+ "created": "2021",
10
+ "issue": "66",
11
+ "license": "CC-BY-3.0-PL",
12
+ "doi": "10.1",
13
+ "source": "studia_bas",
14
+ "source_url": "",
15
+ "issue_url": "",
16
+ "license_url": ""
17
+ }
18
+
19
+ def test_empty_author():
20
+ record = get_base_record(author=" ")
21
+ issues = audit_record(record, set(), set())
22
+ assert "empty_author" in issues
23
+
24
+ def test_duplicate_id():
25
+ record = get_base_record(doc_id="id123")
26
+ seen_ids = {"id123"}
27
+ issues = audit_record(record, seen_ids, set())
28
+ assert "duplicate_id" in issues
29
+
30
+ def test_duplicate_text():
31
+ record = get_base_record(text="Some unique text")
32
+ seen_texts = {"Some unique text"}
33
+ issues = audit_record(record, set(), seen_texts)
34
+ assert "duplicate_text" in issues
35
+
36
+ def test_email():
37
+ record = get_base_record(text="Contact me at test@example.com for info.")
38
+ issues = audit_record(record, set(), set())
39
+ assert "residual_email" in issues
40
+
41
+ def test_orcid():
42
+ record = get_base_record(text="My ORCID is 0000-0002-1825-0097")
43
+ issues = audit_record(record, set(), set())
44
+ assert "orcid_found" in issues
45
+
46
+ def test_orcid_corrupted():
47
+ record = get_base_record(text="O R C I D : 0 0 0 0 - 0 0 0 2 - 1 8 2 5 - 0 0 9 7")
48
+ issues = audit_record(record, set(), set())
49
+ assert "orcid_found" in issues
50
+
51
+ def test_phone_number():
52
+ record = get_base_record(text="Zadzwoń: tel. 123 456 789")
53
+ issues = audit_record(record, set(), set())
54
+ assert "phone_number" in issues
55
+
56
+ def test_pesel():
57
+ record = get_base_record(text="PESEL 12345678901")
58
+ issues = audit_record(record, set(), set())
59
+ assert "pesel" in issues
60
+
61
+ def test_nip():
62
+ record = get_base_record(text="NIP: 123-456-32-18")
63
+ issues = audit_record(record, set(), set())
64
+ assert "nip" in issues
65
+
66
+ def test_regon():
67
+ record = get_base_record(text="REGON 123456789")
68
+ issues = audit_record(record, set(), set())
69
+ assert "regon" in issues
70
+
71
+ def test_author_affiliation():
72
+ record = get_base_record(text="Mgr inż. Jan Kowalski, Uniwersytet Warszawski")
73
+ issues = audit_record(record, set(), set())
74
+ assert "affiliation_block" in issues
75
+
76
+ def test_navigation_header():
77
+ record = get_base_record(text="Studia BAS Nr 4(68) 2021")
78
+ issues = audit_record(record, set(), set())
79
+ assert "navigation_header" in issues
80
+
81
+ def test_suspicious_hyphenation():
82
+ record = get_base_record(text="To jest testowe przedsię- biorstwo.")
83
+ issues = audit_record(record, set(), set())
84
+ assert "suspicious_hyphenation" in issues
85
+
86
+ def test_malformed_metadata():
87
+ record = get_base_record()
88
+ del record["created"]
89
+ issues = audit_record(record, set(), set())
90
+ assert "malformed_metadata" in issues
src/test_studia_bas_contract.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contract tests for the Studia BAS direct-source contribution."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
12
+
13
+ from fetch_studia_bas import (
14
+ ArchiveIssue,
15
+ Block,
16
+ CC_BY_URL,
17
+ LICENSE,
18
+ SOURCE,
19
+ article_start_indexes,
20
+ extract_article,
21
+ find_issue_pdf_link,
22
+ normalize_pdf_text,
23
+ parse_archive_rows,
24
+ scrub_pii,
25
+ )
26
+
27
+
28
+ def block(text, y0, y1=None, *, x0=57.0, size=9.0, lines=()):
29
+ return Block(
30
+ text=text,
31
+ x0=x0,
32
+ y0=float(y0),
33
+ x1=413.0,
34
+ y1=float(y1 if y1 is not None else y0 + 13),
35
+ min_size=float(size),
36
+ max_size=float(size),
37
+ lines=tuple(lines),
38
+ )
39
+
40
+
41
+ def article_fixture():
42
+ page_one = [
43
+ block("Magdalena Janiszewska*", 96, x0=64, size=9.5),
44
+ block("Jan M. Janiszewski**", 111, x0=82, size=9.5),
45
+ block(
46
+ "Ulgi podatkowe jako narzędzie wspierania konkurencyjności polskich przedsiębiorstw",
47
+ 93,
48
+ x0=176,
49
+ size=13,
50
+ ),
51
+ block(
52
+ "Tax reliefs as a tool to support the competitiveness of Polish enterprises "
53
+ "The level of innovation and technological advancement is important.",
54
+ 151,
55
+ size=8,
56
+ lines=(
57
+ "Tax reliefs as a tool to support the competitiveness of Polish enterprises",
58
+ "The level of innovation and technological advancement is important.",
59
+ ),
60
+ ),
61
+ block("DOI https://doi.org/10.31268/StudiaBAS.2024.03", 259, size=8),
62
+ block(
63
+ "Słowa kluczowe ulgi podatkowe w Polsce, polityka innowacyjna, konkurencyjność",
64
+ 276,
65
+ size=8,
66
+ ),
67
+ block("Keywords tax reliefs, innovation policy", 303, size=8),
68
+ block(
69
+ "O autorach adiunkt, SGH, magdalena.janiszewska@sgh.waw.pl "
70
+ "https://orcid.org/0000-0001-9442-4426",
71
+ 330,
72
+ size=8,
73
+ ),
74
+ block(
75
+ "Artykuł został udostępniony na licencji Creative Commons – "
76
+ "Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL).",
77
+ 428,
78
+ size=6,
79
+ ),
80
+ block("Wstęp", 463, size=11),
81
+ block("Zapoczątkowane starania polskiego ustawodawcy na rzecz przedsię-", 488),
82
+ block("biorców do podejmowania działalności innowacyjnej.", 502),
83
+ block("1(77) 2024 ISSN 2082-0658 studiabas.sejm.gov.pl 29", 25, size=8),
84
+ ]
85
+ page_two = [
86
+ block("30 studiabas.sejm.gov.pl 1(77) 2024", 25, size=8),
87
+ block("Kolejny akapit omawia narzędzia fiskalne.", 68, x0=68),
88
+ block("Bibliografia", 500, size=11),
89
+ block("Przykładowa pozycja bibliograficzna.", 525),
90
+ ]
91
+ return [page_one, page_two]
92
+
93
+
94
+ def test_normalize_pdf_text_repairs_unicode_whitespace_and_line_hyphenation():
95
+ raw = " przedsiębior-\n ców\u00a0\u2009oraz\u200b inne\u00ad słowa… "
96
+ assert normalize_pdf_text(raw) == "przedsiębiorców oraz inne słowa..."
97
+
98
+
99
+ def test_scrub_pii_replaces_email_orcid_phone_and_polish_identifiers():
100
+ raw = (
101
+ "Kontakt: anna@example.org, ORCID 0000-0002-1825-0097, "
102
+ "https://orcid. org/0000-0003-1111-2222, tel. +48 22 694 17 50, "
103
+ "PESEL 44051401458, NIP 5260250274, REGON 000261197."
104
+ )
105
+ cleaned = scrub_pii(raw)
106
+ assert "anna@example.org" not in cleaned
107
+ assert "0000-0002-1825-0097" not in cleaned
108
+ assert "0000-0003-1111-2222" not in cleaned
109
+ assert "orcid" not in cleaned.lower()
110
+ assert "+48 22 694 17 50" not in cleaned
111
+ assert "44051401458" not in cleaned
112
+ assert "5260250274" not in cleaned
113
+ assert "000261197" not in cleaned
114
+ assert cleaned.count("[PII]") >= 6
115
+
116
+
117
+ def test_article_start_requires_doi_license_and_large_polish_title():
118
+ pages = article_fixture()
119
+ pages.append([block("Cytowanie DOI https://doi.org/10.1/example", 100)])
120
+ assert article_start_indexes(pages) == [0]
121
+
122
+
123
+ def test_extract_article_keeps_content_and_metadata_but_drops_author_affiliation_pii():
124
+ record = extract_article(
125
+ article_fixture(),
126
+ issue_number="77",
127
+ year=2024,
128
+ issue_url="https://studiabas.sejm.gov.pl/example",
129
+ )
130
+
131
+ assert record["text"].startswith(
132
+ "Ulgi podatkowe jako narzędzie wspierania konkurencyjności polskich przedsiębiorstw"
133
+ )
134
+ assert "Streszczenie\n\nThe level of innovation" in record["text"]
135
+ assert "Słowa kluczowe\n\nulgi podatkowe" in record["text"]
136
+ assert "Wstęp" in record["text"]
137
+ assert "przedsiębiorców" in record["text"]
138
+ assert "Bibliografia" not in record["text"]
139
+ assert "Przykładowa pozycja bibliograficzna." not in record["text"]
140
+ assert "magdalena.janiszewska@sgh.waw.pl" not in record["text"]
141
+ assert "orcid" not in record["text"].lower()
142
+ assert "studiabas.sejm.gov.pl 1(77)" not in record["text"]
143
+
144
+ assert record["author"] == "Magdalena Janiszewska; Jan M. Janiszewski"
145
+ assert record["created"] == "2024"
146
+ assert record["license"] == LICENSE
147
+ assert record["source"] == SOURCE
148
+ assert record["doi"] == "10.31268/StudiaBAS.2024.03"
149
+ assert record["id"] == "studia_bas_2024_03"
150
+ assert record["source_url"] == "https://doi.org/10.31268/StudiaBAS.2024.03"
151
+ assert record["issue_url"] == "https://studiabas.sejm.gov.pl/example"
152
+ assert record["license_url"] == CC_BY_URL
153
+
154
+
155
+ def test_jsonl_record_exposes_metadata_to_the_canonical_builder():
156
+ record = extract_article(article_fixture(), issue_number="77", year=2024)
157
+ encoded = json.dumps(record, ensure_ascii=False)
158
+ decoded = json.loads(encoded)
159
+ assert decoded["author"]
160
+ assert decoded["created"] == "2024"
161
+ assert decoded["license"] == "CC-BY-3.0-PL"
162
+ assert re.fullmatch(r"studia_bas_\d{4}_\d{2}", decoded["id"])
163
+
164
+
165
+ class _TokenStub:
166
+ def encode_ordinary_batch(self, texts, num_threads=1):
167
+ return [[1] * len(text.split()) for text in texts]
168
+
169
+
170
+ def test_canonical_builder_preserves_per_record_created_metadata(monkeypatch):
171
+ import build_dynaword
172
+
173
+ monkeypatch.setattr(build_dynaword, "_ENC", _TokenStub())
174
+ record = extract_article(article_fixture(), issue_number="77", year=2024)
175
+ kept, stats = build_dynaword._process_chunk(
176
+ (False, "2021-2025", LICENSE, True, [json.dumps(record, ensure_ascii=False)])
177
+ )
178
+ assert stats[0] == 1
179
+ assert kept[0][1] == "2024"
180
+
181
+
182
+ def test_pii_scrub_leaves_public_author_name_available_for_attribution():
183
+ record = extract_article(article_fixture(), issue_number="77", year=2024)
184
+ assert "Magdalena Janiszewska" in record["author"]
185
+ assert "Magdalena Janiszewska" not in record["text"]
186
+
187
+
188
+ def test_archive_rows_preserve_issue_metadata_and_document_id():
189
+ fragment = """
190
+ <table><tr><th>Nr</th><th>Redakcja</th><th>Tytuł</th></tr>
191
+ <tr><td><a href="pubBAS.xsp?documentId=3624167FFF2C8EFAC1258B25002FE5CA">1(77) 2024</a></td>
192
+ <td>Adrian Grycuk, Piotr Russel</td><td>Konkurencyjność przedsiębiorstw w Polsce</td></tr></table>
193
+ """
194
+ assert parse_archive_rows(fragment, 2024) == [
195
+ ArchiveIssue(
196
+ year=2024,
197
+ number="77",
198
+ title="Konkurencyjność przedsiębiorstw w Polsce",
199
+ editor="Adrian Grycuk, Piotr Russel",
200
+ document_id="3624167FFF2C8EFAC1258B25002FE5CA",
201
+ )
202
+ ]
203
+
204
+
205
+ def test_issue_pdf_link_prefers_the_issue_agent_over_article_agents():
206
+ issue_id = "3624167FFF2C8EFAC1258B25002FE5CA"
207
+ article_id = "E93BE3D25D621D1CC1258B25003263B7"
208
+ page = (
209
+ f'<a href="/wydbas.nsf/LiczOpen?OpenAgent&amp;{article_id}&amp;lang=PL">article</a>'
210
+ f'<a href="/wydbas.nsf/LiczOpen?OpenAgent&amp;{issue_id}&amp;lang=PL">issue</a>'
211
+ )
212
+ assert issue_id in find_issue_pdf_link(page, issue_id)
213
+
214
+ def test_author_line_wrap_fixed():
215
+ page = [
216
+ block('Tytuł artykułu', 80, size=13, lines=['Tytuł artykułu']),
217
+ block('Kamilla Marchewka-', 110, size=9.5, lines=['Kamilla Marchewka-']),
218
+ block('-Bartkowiak', 125, size=9.5, lines=['-Bartkowiak']),
219
+ block('10.31268/StudiaBAS.2024.03', 259, size=8),
220
+ block('Creative Commons Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL)', 428, size=6)
221
+ ]
222
+ # In block helper, title_text/author_text is not set, so we need to set them
223
+
224
+ import dataclasses
225
+ new_page = []
226
+ for b in page:
227
+ if b.y0 == 80: b = dataclasses.replace(b, title_text=b.text)
228
+ if b.y0 in (110, 125): b = dataclasses.replace(b, author_text=b.text)
229
+ new_page.append(b)
230
+ page = new_page
231
+
232
+
233
+ from fetch_studia_bas import _front_matter
234
+ meta = _front_matter(page)
235
+ assert meta['authors'] == ['Kamilla Marchewka-Bartkowiak']
236
+
237
+
238
+ def test_doi_ordinal_derivation():
239
+ from fetch_studia_bas import _front_matter
240
+ page = [
241
+ block('Tytuł artykułu', 80, size=13, lines=['Tytuł artykułu']),
242
+ block('Jan Kowalski', 110, size=9.5, lines=['Jan Kowalski']),
243
+ block('10.31268/StudiaBAS.2024.1.2', 259, size=8),
244
+ block('Creative Commons Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL)', 428, size=6)
245
+ ]
246
+ import dataclasses
247
+ new_page = []
248
+ for b in page:
249
+ if b.y0 == 80: b = dataclasses.replace(b, title_text=b.text)
250
+ if b.y0 == 110: b = dataclasses.replace(b, author_text=b.text)
251
+ new_page.append(b)
252
+ page = new_page
253
+ meta = _front_matter(page)
254
+ assert meta['ordinal'] == '01_02'
255
+
256
+
257
+
258
+ def test_canonical_builder_falls_back_to_source_created_when_record_metadata_is_absent(monkeypatch):
259
+ import build_dynaword
260
+ import json
261
+ monkeypatch.setattr(build_dynaword, '_ENC', _TokenStub())
262
+
263
+ # Missing 'created' in the record
264
+ record = {'text': 'To jest testowy polski tekst z polskimi znakami diakrytycznymi ąćęłńóśźż.' * 10}
265
+ kept, stats = build_dynaword._process_chunk(
266
+ (False, '2010-2020', 'CC0', True, [json.dumps(record)])
267
+ )
268
+ assert kept[0][1] == '2010-2020'
269
+
270
+
271
+
272
+
273
+ def test_canonical_builder_backward_compatibility(monkeypatch, tmp_path):
274
+ import build_dynaword
275
+ import json
276
+
277
+ monkeypatch.setattr(build_dynaword, '_ENC', _TokenStub())
278
+
279
+ # Missing 'created' falls back to source config
280
+ record = {'text': 'To jest testowy polski tekst z polskimi znakami diakrytycznymi ąćęłńóśźż.' * 10, 'id': 'custom_123'}
281
+ kept, _ = build_dynaword._process_chunk(
282
+ (False, 'fallback_created', 'fallback_license', True, [json.dumps(record)])
283
+ )
284
+ assert kept[0][1] == 'fallback_created'
285
+ assert kept[0][6] == 'custom_123'
286
+
287
+
288
+ def test_front_matter_cleans_footnote_digits_from_multiple_authors():
289
+ from fetch_studia_bas import _front_matter
290
+ page = [
291
+ block('Tytuł artykułu', 80, size=13, lines=['Tytuł artykułu']),
292
+ block('1 Jan Kowalski', 110, size=9.5, lines=['1 Jan Kowalski']),
293
+ block('2 Anna Nowak', 125, size=9.5, lines=['2 Anna Nowak']),
294
+ block('3 Piotr Zielinski', 140, size=9.5, lines=['3 Piotr Zielinski']),
295
+ block('10.31268/StudiaBAS.2024.1.2', 259, size=8),
296
+ block('Creative Commons Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL)', 428, size=6)
297
+ ]
298
+ import dataclasses
299
+ new_page = []
300
+ for b in page:
301
+ if b.y0 == 80: b = dataclasses.replace(b, title_text=b.text)
302
+ if b.y0 in (110, 125, 140): b = dataclasses.replace(b, author_text=b.text)
303
+ new_page.append(b)
304
+ meta = _front_matter(new_page)
305
+ assert meta['authors'] == ['Jan Kowalski', 'Anna Nowak', 'Piotr Zielinski']
306
+ def test_studia_bas_artifacts():
307
+ import pyarrow.parquet as pq
308
+ import json
309
+
310
+ parquet_path = Path("data/studia_bas/studia_bas.parquet")
311
+ stats_path = Path("data/studia_bas/studia_bas.stats.json")
312
+ md_path = Path("data/studia_bas/studia_bas.md")
313
+
314
+ assert parquet_path.exists(), "Parquet artifact missing"
315
+ assert stats_path.exists(), "Stats artifact missing"
316
+ assert md_path.exists(), "Datasheet missing"
317
+
318
+ table = pq.read_table(parquet_path)
319
+
320
+ # Exact schema
321
+ import pyarrow as pa
322
+ expected_schema = pa.schema([
323
+ ("id", pa.string()), ("text", pa.string()), ("source", pa.string()),
324
+ ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()),
325
+ ("license", pa.string()), ("author", pa.string()),
326
+ ])
327
+ assert table.schema.equals(expected_schema), "Schema mismatch"
328
+
329
+ ids = table["id"].to_pylist()
330
+ texts = table["text"].to_pylist()
331
+ sources = table["source"].to_pylist()
332
+ licenses = table["license"].to_pylist()
333
+ tokens = table["token_count"].to_pylist()
334
+ created = table["created"].to_pylist()
335
+
336
+ # Unique IDs/texts
337
+ assert len(ids) == len(set(ids)), "Duplicate IDs"
338
+ assert len(texts) == len(set(texts)), "Duplicate texts"
339
+
340
+ # Positive token_count
341
+ assert all(t > 0 for t in tokens), "Non-positive token count"
342
+
343
+ # Uniform source/license
344
+ assert all(s == SOURCE for s in sources), "Non-uniform source"
345
+ assert all(l == LICENSE for l in licenses), "Non-uniform license"
346
+
347
+ # Created range
348
+ for c in created:
349
+ year = int(c)
350
+ assert 2021 <= year <= 2025, f"Created year {year} out of range"
351
+
352
+ # Stats totals
353
+ stats = json.loads(stats_path.read_text(encoding="utf-8"))
354
+ assert stats["kept"] == len(ids)
355
+ assert stats["tokens"] == sum(tokens)
356
+ assert stats["chars"] == sum(len(t) for t in texts)
357
+
358
+ # Sidecar-Parquet alignment
359
+ md_content = md_path.read_text(encoding="utf-8")
360
+ assert str(stats["kept"]) in md_content
361
+ assert "10.31268/StudiaBAS.2021.26" in md_content
362
+ assert "10.31268/StudiaBAS.2022.08" in md_content
363
+ assert "10.31268/StudiaBAS.2025.08" in md_content
364
+
365
+ # Bibliography and Annex checks
366
+ bib_pattern = re.compile(r"Bibliografia|References|Bibiliografia", re.I)
367
+ annex_pattern = re.compile(r"^(Aneks|Załącznik)\b", re.I)
368
+ expected_annex_ids = {
369
+ "studia_bas_2021_23", "studia_bas_2022_04", "studia_bas_2023_13",
370
+ "studia_bas_2023_20", "studia_bas_2023_26", "studia_bas_2023_33",
371
+ "studia_bas_2024_09"
372
+ }
373
+
374
+ id_to_text = dict(zip(ids, texts))
375
+
376
+ for record_id, t in id_to_text.items():
377
+ paras = [p.strip() for p in t.split("\n\n")]
378
+ for p in paras:
379
+ assert not bib_pattern.fullmatch(p), (
380
+ f"Found bibliography heading in {record_id}"
381
+ )
382
+
383
+ for expected_id in expected_annex_ids:
384
+ assert expected_id in id_to_text, f"Expected annex ID missing: {expected_id}"
385
+ t = id_to_text[expected_id]
386
+ paras = [p.strip() for p in t.split("\n\n")]
387
+ assert any(annex_pattern.match(p) for p in paras), (
388
+ f"Missing annex in {expected_id}"
389
+ )
390
+
391
+
392
+ def _front_matter_authors(author_blocks, *, title_x0=57.0, author_x0=57.0, extra=()):
393
+ """Run _front_matter over a minimal title page with the given author blocks."""
394
+ import dataclasses
395
+
396
+ from fetch_studia_bas import _front_matter
397
+
398
+ page = [dataclasses.replace(
399
+ block('Tytul artykulu', 80, size=13, x0=title_x0, lines=['Tytul artykulu']),
400
+ title_text='Tytul artykulu',
401
+ )]
402
+ y = 105
403
+ for text in author_blocks:
404
+ b = block(text, y, size=9.5, x0=author_x0, lines=text.splitlines())
405
+ page.append(dataclasses.replace(b, author_text=text))
406
+ y += 15
407
+ page.extend(extra)
408
+ page.append(block('10.31268/StudiaBAS.2024.03', 259, size=8))
409
+ page.append(block(
410
+ 'Creative Commons Uznanie Autorstwa 3.0 Polska (CC BY 3.0 PL)', 428, size=6
411
+ ))
412
+ return _front_matter(page)['authors']
413
+
414
+
415
+ def test_wrapped_given_name_and_surname_form_one_author():
416
+ # PDF wraps a single long name across two lines with no hyphen.
417
+ assert _front_matter_authors(['Elzbieta\nMalinowska-Misiag']) == [
418
+ 'Elzbieta Malinowska-Misiag'
419
+ ]
420
+
421
+
422
+ def test_one_complete_name_per_line_stays_separate():
423
+ # Several full names inside one block must not be glued together.
424
+ assert _front_matter_authors(['Maciej J. Nowak\nBarbara Szulczewska']) == [
425
+ 'Maciej J. Nowak',
426
+ 'Barbara Szulczewska',
427
+ ]
428
+
429
+
430
+ def test_wrapped_name_between_two_complete_names():
431
+ assert _front_matter_authors([
432
+ 'Grzegorz Humenny\nMalgorzata\nKlobuszewska\nTomasz Plachecki'
433
+ ]) == ['Grzegorz Humenny', 'Malgorzata Klobuszewska', 'Tomasz Plachecki']
434
+
435
+
436
+ def test_attribution_sidecar_matches_parquet_order():
437
+ """The sidecar carries the DOI the 8-column Parquet cannot, so it must stay
438
+ row-for-row aligned with it: same count, same ids, same order."""
439
+ import json
440
+ from pathlib import Path
441
+
442
+ import pyarrow.parquet as pq
443
+
444
+ root = Path(__file__).resolve().parent.parent / "data" / SOURCE
445
+ parquet = root / f"{SOURCE}.parquet"
446
+ sidecar = root / f"{SOURCE}.attribution.jsonl"
447
+ if not parquet.exists() or not sidecar.exists():
448
+ pytest.skip("canonical artifacts are not built in this checkout")
449
+
450
+ ids = [str(v) for v in pq.read_table(parquet, columns=["id"])["id"].to_pylist()]
451
+ rows = [
452
+ json.loads(line)
453
+ for line in sidecar.read_text(encoding="utf-8").splitlines()
454
+ if line.strip()
455
+ ]
456
+ stats = json.loads((root / f"{SOURCE}.stats.json").read_text(encoding="utf-8"))
457
+
458
+ assert len(rows) == len(ids) == stats["kept"]
459
+ assert [row["id"] for row in rows] == ids
460
+ for row in rows:
461
+ assert row["license"] == LICENSE
462
+ assert row["license_url"] == CC_BY_URL
463
+ assert row["doi"] and row["attribution_url"].endswith(row["doi"])
464
+ assert row["issue_pdf_sha256"]
465
+ assert row["modified"] is True
466
+ notice = row.get("modification_notice", "").lower()
467
+ assert "bibliograph" in notice or "reference" in notice, (
468
+ "Notice must disclose bibliography removal"
469
+ )
470
+
471
+
472
+ def test_build_attribution_rows_rejects_unknown_parquet_id():
473
+ # A missing source record must raise, not silently shift later rows onto
474
+ # the wrong article.
475
+ from fetch_studia_bas import build_attribution_rows
476
+
477
+ with pytest.raises(ValueError):
478
+ build_attribution_rows([], ["studia_bas_2021_15"])
479
+
480
+
481
+ def test_three_token_name_wrapped_across_blocks_is_one_author():
482
+ # 10.31268/StudiaBAS.2023.12 sets one author over two blocks and prints no
483
+ # affiliation marker, because there is no second author to tell apart.
484
+ assert _front_matter_authors(['Agnieszka Paulina', 'Smolenska']) == [
485
+ 'Agnieszka Paulina Smolenska'
486
+ ]
487
+
488
+
489
+ def test_footnote_marker_closes_an_author_at_wrapped_line_pitch():
490
+ # 10.31268/StudiaBAS.2023.17 stacks three co-authors at the same 12pt pitch a
491
+ # wrapped name uses, so only the marker separates them.
492
+ assert _front_matter_authors(
493
+ ['Zbigniew M. Karaczun*', 'Piotr Swacha**\nTomasz Herudzinski***']
494
+ ) == ['Zbigniew M. Karaczun', 'Piotr Swacha', 'Tomasz Herudzinski']
495
+
496
+
497
+ def test_unmarked_line_continues_the_marked_name_above_it():
498
+ # 10.31268/StudiaBAS.2022.17: the marker sits on the wrap, not on the line
499
+ # that starts the name.
500
+ assert _front_matter_authors(
501
+ ['Grzegorz Humenny*', 'Malgorzata\nKlobuszewska**', 'Tomasz Plachecki***']
502
+ ) == ['Grzegorz Humenny', 'Malgorzata Klobuszewska', 'Tomasz Plachecki']
503
+
504
+
505
+ def test_author_list_running_below_the_title_band_is_not_truncated():
506
+ # 10.31268/StudiaBAS.2023.35 has six authors; the last two sit below the y=155
507
+ # the ordinary title page never reaches.
508
+ assert _front_matter_authors(
509
+ [
510
+ 'Pawel Felis*',
511
+ 'Michal Bernardelli**',
512
+ 'Agnieszka Bem***',
513
+ 'Anita Makowska****',
514
+ 'Milena Kowalska*****',
515
+ 'Grzegorz Otczyk******',
516
+ ],
517
+ title_x0=175.9,
518
+ author_x0=80.0,
519
+ ) == [
520
+ 'Pawel Felis',
521
+ 'Michal Bernardelli',
522
+ 'Agnieszka Bem',
523
+ 'Anita Makowska',
524
+ 'Milena Kowalska',
525
+ 'Grzegorz Otczyk',
526
+ ]
527
+ def test_hyphen_wrapped_surname_needs_the_marker_to_close_the_author():
528
+ # 10.31268/StudiaBAS.2021.33: two authors whose four name tokens are indis-
529
+ # tinguishable from one wrapped name unless the markers are read.
530
+ assert _front_matter_authors(
531
+ ['Elzbieta\nMalinowska-Misiag*', 'Wojciech Misiag**']
532
+ ) == ['Elzbieta Malinowska-Misiag', 'Wojciech Misiag']
533
+
534
+
535
+ def test_text_below_the_author_band_is_not_taken_for_an_author():
536
+ # The band only extends for blocks that continue the author list without a
537
+ # gap; the abstract further down the page must stay out.
538
+ assert _front_matter_authors(
539
+ ['Anna Szelagowska'],
540
+ title_x0=175.9,
541
+ author_x0=80.0,
542
+ extra=[block('Streszczenie artykulu o mieszkalnictwie', 200, size=9.5, x0=80.0)],
543
+ ) == ['Anna Szelagowska']
544
+
545
+ def test_extract_article_removes_bibliography_variants():
546
+ pages_bib = article_fixture()
547
+ pages_bib[1].extend([
548
+ block("Bibiliografia", 600, size=11),
549
+ block("Item 1", 620)
550
+ ])
551
+ record = extract_article(pages_bib, issue_number="77", year=2024, issue_url="")
552
+ assert "Bibiliografia" not in record["text"]
553
+ assert "Item 1" not in record["text"]
554
+
555
+ pages_ref = article_fixture()
556
+ pages_ref[1].extend([
557
+ block("References", 600, size=11),
558
+ block("Item 2", 620)
559
+ ])
560
+ record = extract_article(pages_ref, issue_number="77", year=2024, issue_url="")
561
+ assert "References" not in record["text"]
562
+ assert "Item 2" not in record["text"]
563
+
564
+
565
+ def test_extract_article_keeps_appendix_after_bibliography():
566
+ pages = article_fixture()
567
+ pages[1].extend([
568
+ block("Załącznik 1", 600, size=11),
569
+ block("Ważne dane", 620),
570
+ block("Aneks 2", 640, size=11),
571
+ block("Inne dane", 660)
572
+ ])
573
+ record = extract_article(pages, issue_number="77", year=2024, issue_url="")
574
+ assert "Bibliografia" not in record["text"]
575
+ assert "Przykładowa pozycja bibliograficzna" not in record["text"]
576
+ assert "Załącznik 1\n\nWażne dane\n\nAneks 2\n\nInne dane" in record["text"]
577
+
578
+
579
+ def test_extract_article_does_not_remove_inline_bibliography_mention():
580
+ pages = article_fixture()
581
+ pages[1].insert(1,
582
+ block("To jest akapit, w którym jest słowo bibliografia na końcu", 400)
583
+ )
584
+ record = extract_article(pages, issue_number="77", year=2024, issue_url="")
585
+ assert "bibliografia" in record["text"]
586
+
587
+
588
+ def test_remove_terminal_bibliography_variants():
589
+ from fetch_studia_bas import remove_terminal_bibliography
590
+ # Variants
591
+ assert remove_terminal_bibliography("wstęp\n\nBibliografia\n\npoz 1") == "wstęp"
592
+ assert remove_terminal_bibliography("wstęp\n\nBibiliografia\n\npoz 1") == "wstęp"
593
+ assert remove_terminal_bibliography("wstęp\n\nReferences\n\npoz 1") == "wstęp"
594
+
595
+ # Bibliography subheadings should be removed
596
+ assert (
597
+ remove_terminal_bibliography("wstęp\n\nBibliografia\n\nAkty prawne\n\npoz 1")
598
+ == "wstęp"
599
+ )
600
+
601
+ # Inline mentions should NOT be removed
602
+ text = "W tym zdaniu słowo bibliografia jest użyte."
603
+ assert remove_terminal_bibliography(text) == text
604
+ text_multiline = (
605
+ "Rozdział\n\nW tym rozdziale znajduje się bibliografia, która coś opisuje."
606
+ )
607
+ assert remove_terminal_bibliography(text_multiline) == text_multiline
608
+
609
+ # Missing marker (no bibliography heading)
610
+ assert (
611
+ remove_terminal_bibliography("wstęp\n\nRozdział\n\nKoniec")
612
+ == "wstęp\n\nRozdział\n\nKoniec"
613
+ )
614
+
615
+ # All relevant Aneks/Załącznik heading shapes
616
+ text_appendix = "wstęp\n\nBibliografia\n\npoz 1\n\nZałącznik 1\n\nTreść"
617
+ assert (
618
+ remove_terminal_bibliography(text_appendix)
619
+ == "wstęp\n\nZałącznik 1\n\nTreść"
620
+ )
621
+
622
+ text_appendix2 = "wstęp\n\nBibliografia\n\npoz 1\n\nAneks\n\nTreść"
623
+ assert (
624
+ remove_terminal_bibliography(text_appendix2)
625
+ == "wstęp\n\nAneks\n\nTreść"
626
+ )
627
+
628
+ text_appendix3 = "wstęp\n\nBibliografia\n\npoz 1\n\nAppendix\n\nTreść"
629
+ assert (
630
+ remove_terminal_bibliography(text_appendix3)
631
+ == "wstęp\n\nAppendix\n\nTreść"
632
+ )
633
+
634
+ text_appendix4 = "wstęp\n\nBibliografia\n\npoz 1\n\nZałącznik 1. Transpozycja\n\nTreść"
635
+ assert (
636
+ remove_terminal_bibliography(text_appendix4)
637
+ == "wstęp\n\nZałącznik 1. Transpozycja\n\nTreść"
638
+ )