polish-dynaword / src /fetch_studia_bas.py
ppuzio's picture
studia_bas: Studia BAS policy articles (scoped from #19) (#44)
9b0d67f
Raw History Blame Contribute Delete
34.1 kB
#!/usr/bin/env python3
"""Extract CC-BY Studia BAS articles from official issue PDFs.
The official archive publishes whole issues as text-layer PDFs. This source
extractor splits each issue at article title pages, removes running headers and
author-affiliation blocks, normalizes PDF line wrapping, scrubs common PII and
writes one JSONL record per article. ``build_dynaword.py`` performs the
canonical token count and Parquet build afterwards.
PoC using an existing, reproducibly downloaded issue cache::
python3 src/fetch_studia_bas.py \
--pdf-dir D:/projects/open-charts/out/studiabas/pdf \
--issues 77 --sample 5 --out artifacts/studia_bas_sample.jsonl
Only issue 66 (2/2021) and later are accepted because the journal's CC BY 3.0
Poland grant starts there. The license line is also verified inside every PDF;
the issue number alone is never treated as sufficient evidence.
"""
from __future__ import annotations
import argparse
import functools
import html as html_module
import json
import re
import shutil
import subprocess
import tempfile
import time
import unicodedata
import urllib.parse
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Sequence
SOURCE = "studia_bas"
LICENSE = "CC-BY-3.0-PL"
CC_BY_URL = "https://creativecommons.org/licenses/by/3.0/pl/"
MIN_LICENSED_ISSUE = 66
BASE = "https://studiabas.sejm.gov.pl"
ARCHIVE_URL = BASE + "/journal.nsf/pubBAS.xsp?view=12&seria=4&lang=PL"
ORKA = "https://orka.sejm.gov.pl"
_DOI_RE = re.compile(r"(?:https?://(?:dx\.)?doi\.org/)?(10\.31268/StudiaBAS\.(\d{4})\.([0-9]+(?:\.[0-9]+)*))", re.I)
_ISSUE_RE = re.compile(r"(?:Studia[_\s-]*BAS[_\s-]*|sb)(\d{1,3})", re.I)
_ISSUE_YEAR_RE = re.compile(r"\b\d\((\d{2,3})\)\s*((?:19|20)\d{2})\b")
_LICENSE_RE = re.compile(
r"Creative\s+Commons.{0,100}(?:Uznanie\s+Autorstwa|CC\s*BY).{0,40}3\.0.{0,20}(?:Polska|PL)",
re.I | re.S,
)
_MARKER_RE = re.compile(r"[*†‡]+")
_MARKER_END_RE = re.compile(r"[*†‡]+\s*$")
_EMAIL_RE = re.compile(r"(?<![\w.+-])[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}(?![\w.-])")
_ORCID_RE = re.compile(
r"(?i)(?:(?:https?\s*:\s*/\s*/\s*)?orcid\s*\.\s*org\s*/\s*|ORCID\s*:?\s*)?"
r"\b\d{4}-\d{4}-\d{4}-[\dX]{4}\b"
)
_PHONE_RE = re.compile(
r"(?i)(?<!\w)(?:tel(?:efon)?\.?\s*:?\s*|\+48[\s.-]*)(?:\d[\s.-]*){9}(?!\d)"
)
_PESEL_RE = re.compile(r"(?i)PESEL\s*:?\s*\d{11}\b")
_NIP_RE = re.compile(r"(?i)NIP\s*:?\s*\d{3}[- ]?\d{3}[- ]?\d{2}[- ]?\d{2}\b")
_REGON_RE = re.compile(r"(?i)REGON\s*:?\s*(?:\d{9}|\d{14})\b")
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
_ROW_RE = re.compile(r"<tr\b[^>]*>(.*?)</tr>", re.I | re.S)
_CELL_RE = re.compile(r"<t[dh]\b[^>]*>(.*?)</t[dh]>", re.I | re.S)
_TAG_RE = re.compile(r"<[^>]+>")
_DOCID_RE = re.compile(r"documentId=([0-9A-Fa-f]{32})")
_PDF_RE = re.compile(r'href=["\']([^"\']*?\.pdf)["\']', re.I)
_AGENT_RE = re.compile(
r'href=["\']([^"\']*LiczOpen\?OpenAgent&amp;([0-9A-Fa-f]{32})[^"\']*)["\']', re.I
)
_VIEWID_RE = re.compile(r'name="\$\$viewid"[^>]*value="([^"]+)"')
_PANEL_RE = re.compile(r'id="([^"]*:rok)"')
_COMBO_RE = re.compile(r'name="([^"]*cbYear)"')
_FORM_RE = re.compile(r'<form[^>]*id="([^"]+)"[^>]*class="xspForm"', re.I)
_BIBLIOGRAPHY_HEADING_RE = re.compile(r"Bibliografia|References|Bibiliografia", re.I)
_APPENDIX_HEADING_RE = re.compile(r"^(Załącznik|Aneks|Appendix)\b", re.I)
@dataclass(frozen=True)
class ArchiveIssue:
year: int
number: str
title: str
editor: str
document_id: str
@property
def url(self) -> str:
return f"{BASE}/journal.nsf/pubBAS.xsp?documentId={self.document_id}&lang=PL"
@dataclass(frozen=True)
class Block:
"""Text block reduced to the layout signals needed by the extractor."""
text: str
x0: float
y0: float
x1: float
y1: float
min_size: float
max_size: float
lines: tuple[str, ...] = ()
title_text: str = ""
author_text: str = ""
abstract_text: str = ""
def _html_text(fragment: str) -> str:
return " ".join(html_module.unescape(_TAG_RE.sub(" ", fragment)).replace("\xa0", " ").split())
def parse_archive_rows(fragment: str, year: int) -> list[ArchiveIssue]:
"""Parse the HTML fragment returned by the XPages year refresh."""
issues: list[ArchiveIssue] = []
seen: set[str] = set()
for row in _ROW_RE.findall(fragment):
found = _DOCID_RE.search(row)
if not found:
continue
document_id = found.group(1).upper()
if document_id in seen:
continue
seen.add(document_id)
cells = [_html_text(cell) for cell in _CELL_RE.findall(row)]
cells += [""] * (3 - len(cells))
parenthesized = re.search(r"\((\d{1,3})\)", cells[0])
plain = re.search(r"\d{1,3}", cells[0])
number = parenthesized.group(1) if parenthesized else (plain.group(0) if plain else "")
issues.append(ArchiveIssue(year, number, cells[2], cells[1], document_id))
return issues
def find_issue_pdf_link(page: str, document_id: str) -> str | None:
"""Resolve a direct PDF or the issue-specific download-counting agent."""
for href in _PDF_RE.findall(page):
url = html_module.unescape(href)
if "/xPDF/" in url:
continue
return ORKA + url if url.startswith("/") else url
for href, unid in _AGENT_RE.findall(page):
if unid.upper() != document_id.upper():
continue
url = html_module.unescape(href)
return ORKA + url if url.startswith("/") else url
return None
def normalize_pdf_text(value: str) -> str:
"""Normalize Unicode and whitespace without flattening paragraph breaks."""
value = unicodedata.normalize("NFKC", value)
value = value.replace("\u00ad", "").replace("\u200b", "")
value = re.sub(r"[\u00a0\u2000-\u200a\u202f\u205f\u3000]", " ", value)
value = _CONTROL_RE.sub("", value)
value = value.replace("…", "...")
value = value.replace("„", '"').replace("”", '"').replace("“", '"')
value = value.replace("–", "-").replace("—", "-")
# PDF line wrapping: hard hyphens repeat ("rolno-\n-spożywczy"), soft hyphens don't ("przedsię-\nbiorców").
value = re.sub(r"(?<=\w)-\s*\n\s*-(?=\w)", "-", value)
value = re.sub(r"(?<=\w)-\s*\n\s*(?=[a-ząćęłńóśźż])", "", value)
value = re.sub(r"[ \t]+", " ", value)
value = re.sub(r" *\n *", "\n", value)
value = re.sub(r"\n{3,}", "\n\n", value)
return value.strip()
def scrub_pii(value: str) -> str:
"""Replace contact and national identifiers while retaining sentence shape."""
for pattern in (_EMAIL_RE, _ORCID_RE, _PESEL_RE, _NIP_RE, _REGON_RE, _PHONE_RE):
value = pattern.sub("[PII]", value)
return normalize_pdf_text(value)
def _from_pymupdf(raw: dict) -> Block | None:
lines = raw.get("lines")
if not lines:
return None
line_texts: list[str] = []
title_lines: list[str] = []
author_lines: list[str] = []
abstract_lines: list[str] = []
sizes: list[float] = []
for line in lines:
spans = line.get("spans", [])
text = "".join(str(span.get("text", "")) for span in spans)
if text.strip():
line_texts.append(text.strip())
title = "".join(str(span.get("text", "")) for span in spans if float(span.get("size", 0.0)) >= 12)
author = "".join(
str(span.get("text", ""))
for span in spans
if 8.8 <= float(span.get("size", 0.0)) <= 10.5
)
if title.strip():
title_lines.append(title.strip())
if author.strip():
author_lines.append(author.strip())
if text.strip() and spans and not any(int(span.get("flags", 0)) & 16 for span in spans):
abstract_lines.append(text.strip())
sizes.extend(float(span.get("size", 0.0)) for span in spans)
text = "\n".join(line_texts).strip()
if not text or not sizes:
return None
x0, y0, x1, y1 = map(float, raw["bbox"])
return Block(
text,
x0,
y0,
x1,
y1,
min(sizes),
max(sizes),
tuple(line_texts),
"\n".join(title_lines),
"\n".join(author_lines),
"\n".join(abstract_lines),
)
def pdf_pages(path: Path) -> list[list[Block]]:
"""Read the text layer; scanned/image-only issues fail closed."""
try:
import pymupdf
except ImportError as exc: # pragma: no cover - environment-specific
raise RuntimeError("Studia BAS extraction requires pymupdf: pip install pymupdf") from exc
document = pymupdf.open(path)
pages: list[list[Block]] = []
for page in document:
blocks = [block for raw in page.get_text("dict")["blocks"] if (block := _from_pymupdf(raw))]
pages.append(sorted(blocks, key=lambda item: (item.y0, item.x0)))
if not pages or sum(bool(page) for page in pages) < len(pages) * 0.8:
raise ValueError(f"{path} has too many pages without a usable text layer")
return pages
def _page_text(page: Sequence[Block]) -> str:
return "\n".join(block.text for block in page)
def article_start_indexes(pages: Sequence[Sequence[Block]]) -> list[int]:
"""Find article title pages, rejecting incidental DOI citations."""
starts: list[int] = []
for index, page in enumerate(pages):
text = _page_text(page)
has_title = any(block.max_size >= 12 and 70 <= block.y0 <= 250 for block in page)
if has_title and _DOI_RE.search(text) and _LICENSE_RE.search(text):
starts.append(index)
return starts
def _author_lines(value: str) -> list[tuple[str, bool]]:
"""Author lines, each flagged with the affiliation marker that closes a name.
Studia BAS prints one asterisk run per co-author, so a marked line ends an
author and an unmarked line below it is the wrapped remainder of that name.
Markers are stripped from the name itself; only their position is a signal.
"""
value = re.sub(r"^\s*\d+\s*", "", value, flags=re.MULTILINE)
lines: list[tuple[str, bool]] = []
for line in normalize_pdf_text(value).splitlines():
marked = bool(_MARKER_END_RE.search(line))
line = " ".join(_MARKER_RE.sub("", line).split())
if line:
lines.append((line, marked))
return lines
def _join_author(previous: str, line: str) -> str:
"""Append a wrapped continuation line, healing the hyphen the wrap repeated."""
if previous.endswith("-"):
return previous + line.lstrip("-")
return previous + " " + line
def _front_matter(page: Sequence[Block]) -> dict[str, object]:
title_candidates = [
block
for block in page
if (block.title_text or block.max_size >= 12) and 70 <= block.y0 <= 250
]
if not title_candidates:
raise ValueError("article page has no large Polish title block")
title_candidates.sort(key=lambda block: (block.y0, block.x0))
title = normalize_pdf_text(
"\n".join(block.title_text or block.text for block in title_candidates)
).replace("\n", " ")
title_block = title_candidates[0]
# The author band ends at 155 in every ordinary layout, but a long author
# list simply keeps running down the page, so follow it while the blocks stay
# contiguous and keep the same author typography.
author_values: list[str] = []
author_blocks: list[Block] = []
for block in page:
if block.y0 < 55:
continue
geometric = 8.8 <= block.max_size <= 10.5 and block.x0 < title_block.x0 - 5
if block.y0 > 155:
previous = author_blocks[-1] if author_blocks else None
if previous is None or not geometric or not 0 <= block.y0 - previous.y1 <= 4:
continue
if not (8.8 <= previous.max_size <= 10.5 and previous.x0 < title_block.x0 - 5):
continue
value = block.author_text or (block.text if geometric else "")
if value:
author_values.append(value)
author_blocks.append(block)
# Line pitch cannot tell a wrapped name from the next co-author: the journal
# sets some title pages at 12pt leading and others at 14.9pt, so both look
# alike. The affiliation marker can, and it is present whenever there is
# more than one author to tell apart.
lines = [pair for value in author_values for pair in _author_lines(value)]
authors: list[str] = []
if any(marked for _, marked in lines):
closed = True
for line, marked in lines:
if authors and not closed:
authors[-1] = _join_author(authors[-1], line)
else:
authors.append(line)
closed = marked
else:
# No marker means nothing delimits the names, which is what a sole author
# looks like: a name wrapped over one or two lines ("Agnieszka Paulina" /
# "Smolenska"). Only fall back to guessing per line if the join is too
# long to be one person's name.
joined = functools.reduce(_join_author, [line for line, _ in lines], "").strip()
if len(joined.split()) <= 4:
authors = [joined] if joined else []
else:
for line, _ in lines:
if authors and authors[-1].endswith("-"):
authors[-1] = _join_author(authors[-1], line)
elif authors and len(line.split()) == 1 and len(authors[-1].split()) == 1:
authors[-1] = _join_author(authors[-1], line)
else:
authors.append(line)
authors = [author for author in authors if author and len(author.split()) <= 8]
doi_match = _DOI_RE.search(_page_text(page))
if not doi_match:
raise ValueError("article page has no Studia BAS DOI")
doi = doi_match.group(1)
# DOI suffix format mapping: 2024.03 -> 03, 2024.1.1 -> 01_01.
# We zero-pad each part to 2 digits to ensure deterministic sorting
# and prevent collisions across issues that reset article numbering.
ordinal_raw = doi_match.group(3)
ordinal = "_".join(f"{int(p):02d}" for p in ordinal_raw.split("."))
doi_blocks = [block for block in page if _DOI_RE.search(block.text)]
doi_top = min(block.y0 for block in doi_blocks)
title_bottom = max(block.y1 for block in title_candidates)
abstract_parts: list[str] = []
for block in page:
if block.y0 < title_bottom - 1 or block.y0 >= doi_top or block.max_size > 8.5:
continue
value = block.abstract_text
if not value:
lines = list(block.lines) if block.lines else block.text.splitlines()
value = "\n".join(lines[1:]) if len(lines) >= 2 else ""
if value and not value.lstrip().startswith(("DOI", "Słowa", "Keywords")):
abstract_parts.append(value)
abstract = normalize_pdf_text("\n".join(abstract_parts)).replace("\n", " ")
keywords = ""
for block in page:
compact = normalize_pdf_text(block.text).replace("\n", " ")
if compact.lower().startswith("słowa kluczowe"):
keywords = re.sub(r"(?i)^słowa kluczowe\s*", "", compact).strip()
break
license_blocks = [block for block in page if _LICENSE_RE.search(block.text)]
if not license_blocks:
raise ValueError("article page lacks its CC BY 3.0 PL statement")
license_bottom = max(block.y1 for block in license_blocks)
return {
"title": title,
"authors": authors,
"doi": doi,
"year": int(doi_match.group(2)),
"ordinal": ordinal,
"abstract": abstract,
"keywords": keywords,
"license_bottom": license_bottom,
}
def _content_blocks(pages: Sequence[Sequence[Block]], license_bottom: float) -> list[Block]:
content: list[Block] = []
for page_index, page in enumerate(pages):
for block in page:
if block.y0 < 50: # running header/page number
continue
if page_index == 0 and block.y0 <= license_bottom:
continue
content.append(block)
return content
def _blocks_to_text(blocks: Sequence[Block]) -> str:
paragraphs: list[str] = []
current = ""
previous: Block | None = None
for block in blocks:
value = normalize_pdf_text(block.text)
if not value:
continue
heading = block.max_size >= 10.3 and len(value) < 180
gap = block.y0 - previous.y1 if previous is not None else 99.0
indented = block.x0 >= 65 and previous is not None
font_change = previous is not None and abs(block.max_size - previous.max_size) >= 1.0
new_paragraph = heading or previous is None or gap > 4.5 or indented or font_change
if new_paragraph and current:
paragraphs.append(normalize_pdf_text(current))
current = ""
if heading:
paragraphs.append(value.replace("\n", " "))
else:
piece = value.replace("\n", " ")
if current.endswith("-") and re.match(r"^-?[a-ząćęłńóśźż]", piece):
current = current[:-1] + piece.lstrip("-")
else:
current = f"{current} {piece}".strip()
previous = block
if current:
paragraphs.append(normalize_pdf_text(current))
return "\n\n".join(paragraph for paragraph in paragraphs if paragraph)
def remove_terminal_bibliography(text: str) -> str:
"""Remove terminal bibliography section while restoring any substantive appendix."""
body_parts = text.split("\n\n")
bib_idx = -1
for i in reversed(range(len(body_parts))):
if _BIBLIOGRAPHY_HEADING_RE.fullmatch(body_parts[i].strip()):
bib_idx = i
break
if bib_idx != -1:
end_idx = len(body_parts)
for i in range(bib_idx + 1, len(body_parts)):
if _APPENDIX_HEADING_RE.match(body_parts[i].strip()) and len(body_parts[i]) < 150:
end_idx = i
break
body_parts = body_parts[:bib_idx] + body_parts[end_idx:]
return "\n\n".join(body_parts)
return text
def extract_article(
pages: Sequence[Sequence[Block]],
*,
issue_number: str,
year: int,
issue_url: str = "",
) -> dict[str, object]:
"""Convert one already-sliced article to a provenance-rich JSONL record."""
if not pages:
raise ValueError("article has no pages")
meta = _front_matter(pages[0])
if int(meta["year"]) != int(year):
raise ValueError(f"issue year {year} disagrees with DOI year {meta['year']}")
body = _blocks_to_text(_content_blocks(pages, float(meta["license_bottom"])))
body = remove_terminal_bibliography(body)
parts = [str(meta["title"])]
if meta["abstract"]:
parts.extend(["Streszczenie", str(meta["abstract"])])
if meta["keywords"]:
parts.extend(["Słowa kluczowe", str(meta["keywords"])])
parts.append(body)
text = scrub_pii("\n\n".join(part for part in parts if part).strip())
doi = str(meta["doi"])
ordinal = str(meta["ordinal"])
return {
"id": f"{SOURCE}_{year}_{ordinal}",
"text": text,
"source": SOURCE,
"created": str(year),
"license": LICENSE,
"author": "; ".join(str(author) for author in meta["authors"]),
"doi": doi,
"source_url": f"https://doi.org/{doi}",
"issue_url": issue_url,
"issue": str(issue_number),
"license_url": CC_BY_URL,
}
def issue_metadata(path: Path, pages: Sequence[Sequence[Block]]) -> tuple[str, int]:
number_match = _ISSUE_RE.search(path.stem)
front = "\n".join(_page_text(page) for page in pages[:8])
issue_year = _ISSUE_YEAR_RE.search(front)
number = number_match.group(1) if number_match else (issue_year.group(1) if issue_year else "")
year = int(issue_year.group(2)) if issue_year else 0
if not number or not year:
raise ValueError(f"cannot infer issue/year from {path}")
if int(number) < MIN_LICENSED_ISSUE:
raise ValueError(f"issue {number} predates the CC BY corpus boundary (66)")
if not _LICENSE_RE.search(front):
raise ValueError(f"issue {number} does not expose the expected CC BY 3.0 PL statement")
return number, year
def extract_issue(path: Path, issue_url: str = "") -> list[dict[str, object]]:
pages = pdf_pages(path)
issue_number, year = issue_metadata(path, pages)
starts = article_start_indexes(pages)
if not starts:
raise ValueError(f"no article title pages found in {path}")
records: list[dict[str, object]] = []
for position, start in enumerate(starts):
end = starts[position + 1] if position + 1 < len(starts) else len(pages)
records.append(
extract_article(
pages[start:end],
issue_number=issue_number,
year=year,
issue_url=issue_url,
)
)
ids = [str(record["id"]) for record in records]
if len(ids) != len(set(ids)):
raise ValueError(f"duplicate DOI-derived IDs in {path}")
return records
def _archive_form_state(page: str) -> dict[str, str]:
values = {
"viewid": _VIEWID_RE.search(page),
"panel": _PANEL_RE.search(page),
"combo": _COMBO_RE.search(page),
"form": _FORM_RE.search(page),
}
if not all(values.values()):
raise ValueError("archive page does not expose the expected XPages form state")
return {key: match.group(1) for key, match in values.items()} # type: ignore[union-attr]
def _multipart(fields: dict[str, str]) -> tuple[bytes, str]:
boundary = "----WebKitFormBoundary" + uuid.uuid4().hex[:16]
body = "".join(
f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'
for name, value in fields.items()
) + f"--{boundary}--\r\n"
return body.encode("utf-8"), f"multipart/form-data; boundary={boundary}"
class ArchiveClient:
"""Browser-TLS client for the Imperva-fronted official archive."""
def __init__(self, tries: int = 8, timeout: float = 45.0, pause: float = 2.0):
try:
from curl_cffi import requests
except ImportError as exc: # pragma: no cover - environment-specific
raise RuntimeError(
"Studia BAS archive requires browser TLS: pip install curl_cffi"
) from exc
self._requests = requests
self.tries = tries
self.timeout = timeout
self.pause = pause
self.session = self._new_session()
self.state: dict[str, str] | None = None
def _new_session(self):
return self._requests.Session(impersonate="chrome")
def request(self, method: str, url: str, **kwargs):
last: BaseException | None = None
for attempt in range(self.tries):
try:
response = getattr(self.session, method)(url, timeout=self.timeout, **kwargs)
if int(response.status_code) >= 400:
raise OSError(f"HTTP {response.status_code}")
return response
except BaseException as exc:
if isinstance(exc, (KeyboardInterrupt, SystemExit)):
raise
last = exc
if attempt == self.tries - 1:
break
time.sleep(1.5 * (attempt + 1))
self.session = self._new_session()
self.state = None
raise ConnectionError(f"{method.upper()} {url} failed after {self.tries} attempts") from last
def open(self) -> dict[str, str]:
if self.state is None:
self.state = _archive_form_state(self.request("get", ARCHIVE_URL).text)
return self.state
def issues_for_year(self, year: int) -> list[ArchiveIssue]:
state = self.open()
body, content_type = _multipart(
{
"$$viewid": state["viewid"],
state["form"]: state["form"],
state["combo"]: str(year),
}
)
url = ARCHIVE_URL + "&$$ajaxid=" + urllib.parse.quote(state["panel"], safe="")
response = self.request(
"post",
url,
data=body,
headers={
"X-Requested-With": "XMLHttpRequest",
"Referer": ARCHIVE_URL,
"Origin": BASE,
"Content-Type": content_type,
},
)
return parse_archive_rows(response.text, year)
def download_issue(self, issue: ArchiveIssue, directory: Path) -> Path:
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"Studia_BAS_{issue.number}.pdf"
if path.is_file() and path.stat().st_size and path.read_bytes()[:4] == b"%PDF":
return path
page = self.request("get", issue.url).text
pdf_url = find_issue_pdf_link(page, issue.document_id)
if not pdf_url:
raise ValueError(f"issue {issue.number} page contains no matching PDF link")
content = self.request("get", pdf_url, headers={"Referer": issue.url}).content
if not content.startswith(b"%PDF"):
raise ValueError(f"issue {issue.number} download did not return a PDF")
path.write_bytes(content)
time.sleep(self.pause)
return path
def download_archive_years(
years: Sequence[int], directory: Path, issues: set[int] | None = None
) -> list[Path]:
"""Reproducibly enumerate and cache official issue PDFs."""
client = ArchiveClient()
paths: list[Path] = []
for year in years:
for issue in client.issues_for_year(year):
if not issue.number or int(issue.number) < MIN_LICENSED_ISSUE:
continue
if issues is not None and int(issue.number) not in issues:
continue
paths.append(client.download_issue(issue, directory))
return paths
def _selected_pdfs(directory: Path, issues: set[int] | None) -> list[Path]:
paths: list[tuple[int, Path]] = []
for path in directory.glob("*.pdf"):
match = _ISSUE_RE.search(path.stem)
if not match:
continue
number = int(match.group(1))
if number < MIN_LICENSED_ISSUE or (issues is not None and number not in issues):
continue
paths.append((number, path))
return [path for _, path in sorted(paths)]
PUBLISHER = "Kancelaria Sejmu, Biuro Analiz Sejmowych"
MODIFICATION_NOTICE = (
"Article text was extracted from the text layer of the official issue PDF. "
"Running headers, page numbers, author affiliation/contact blocks, and "
"terminal bibliographies were removed, residual personal data was replaced "
"with [PII], and PDF line wrapping was normalized."
)
def read_jsonl(path: Path) -> list[dict[str, object]]:
"""Read a .jsonl or .jsonl.zst file written by write_jsonl."""
if path.suffix == ".zst":
import zstandard
payload = zstandard.ZstdDecompressor().decompress(
path.read_bytes(), max_output_size=1 << 30
)
text = payload.decode("utf-8")
else:
text = path.read_text(encoding="utf-8")
return [json.loads(line) for line in text.splitlines() if line.strip()]
def build_attribution_rows(
records: Iterable[dict[str, object]],
ids: Sequence[str],
issue_pdfs: dict[str, dict[str, object]] | None = None,
) -> list[dict[str, object]]:
"""One attribution row per Parquet id, in Parquet order.
The canonical Parquet keeps only eight columns, so the per-article DOI and
the issue PDF an article came from live here instead, which is what CC BY
attribution needs. Building from the Parquet id order is what keeps the two
files aligned: an id the source cannot explain raises rather than shifting
every later row onto the wrong article.
"""
issue_pdfs = issue_pdfs or {}
by_id = {str(record["id"]): record for record in records}
rows = []
for record_id in ids:
record = by_id.get(record_id)
if record is None:
raise ValueError(f"Parquet id {record_id!r} is absent from the source records")
issue = str(record["issue"])
pdf = issue_pdfs.get(issue, {})
rows.append(
{
"id": record_id,
"doi": record["doi"],
"attribution_url": record["source_url"],
"archive_url": ARCHIVE_URL,
"issue": issue,
"issue_pdf_filename": pdf.get("filename", ""),
"issue_pdf_sha256": pdf.get("sha256", ""),
"author": record["author"],
"publisher": PUBLISHER,
"license": LICENSE,
"license_url": record.get("license_url", CC_BY_URL),
"modified": True,
"modification_notice": MODIFICATION_NOTICE,
}
)
return rows
def load_issue_pdfs(evidence: Path) -> dict[str, dict[str, object]]:
"""Map issue number to the hashed source PDF recorded in the licence evidence."""
if not evidence.exists():
return {}
payload = json.loads(evidence.read_text(encoding="utf-8"))
return {str(entry["issue"]): entry for entry in payload.get("eligible_pdfs", [])}
def write_attribution_sidecar(source: Path, parquet: Path, output: Path, evidence: Path) -> int:
"""Write the attribution sidecar for an already-built canonical Parquet."""
import pyarrow.parquet as pq
ids = [str(value) for value in pq.read_table(parquet, columns=["id"])["id"].to_pylist()]
rows = build_attribution_rows(read_jsonl(source), ids, load_issue_pdfs(evidence))
output.parent.mkdir(parents=True, exist_ok=True)
with output.open("w", encoding="utf-8", newline="") as handle:
for row in rows:
print(json.dumps(row, ensure_ascii=False, sort_keys=True), file=handle)
return len(rows)
def write_jsonl(records: Iterable[dict[str, object]], output: Path) -> int:
rows = sorted(records, key=lambda row: str(row["id"]))
output.parent.mkdir(parents=True, exist_ok=True)
if output.suffix == ".zst":
with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".jsonl", delete=False) as handle:
temporary = Path(handle.name)
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
try:
executable = shutil.which("zstd")
if executable:
subprocess.run([executable, "-19", "-f", str(temporary), "-o", str(output)], check=True)
else:
try:
import zstandard
except ImportError as exc: # pragma: no cover - environment-specific
raise RuntimeError(
"writing .zst requires zstd or Python zstandard: pip install zstandard"
) from exc
compressor = zstandard.ZstdCompressor(level=19)
with temporary.open("rb") as source, output.open("wb") as target:
compressor.copy_stream(source, target)
finally:
temporary.unlink(missing_ok=True)
else:
output.write_text(
"".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows),
encoding="utf-8",
)
return len(rows)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--pdf-dir",
type=Path,
default=Path("studia_bas_pdfs"),
help="cache directory of official Studia BAS issue PDFs",
)
parser.add_argument(
"--download-years",
type=int,
nargs="*",
help="enumerate these archive years and download missing official PDFs",
)
parser.add_argument("--issues", type=int, nargs="*", help="continuous issue numbers, e.g. 77")
parser.add_argument("--sample", type=int, default=None, help="keep only the first N articles after sorting")
parser.add_argument("--out", type=Path, default=Path("studia_bas.jsonl.zst"))
parser.add_argument(
"--sidecar-parquet",
type=Path,
help="write the attribution sidecar for this already-built canonical Parquet "
"instead of extracting PDFs; --pdf-dir is then unused",
)
parser.add_argument(
"--sidecar-source",
type=Path,
default=Path("studia_bas.jsonl.zst"),
help="source records the Parquet was built from, as written by --out; "
"this intermediate is a build input and is not part of the released shard",
)
parser.add_argument(
"--sidecar-out",
type=Path,
default=Path("data/studia_bas/studia_bas.attribution.jsonl"),
)
parser.add_argument(
"--sidecar-evidence",
type=Path,
default=Path("data/studia_bas/studia_bas.license-evidence.json"),
)
args = parser.parse_args()
if args.sidecar_parquet:
count = write_attribution_sidecar(
args.sidecar_source, args.sidecar_parquet, args.sidecar_out, args.sidecar_evidence
)
print(f"wrote {count} attribution rows to {args.sidecar_out}")
return
wanted_issues = set(args.issues) if args.issues else None
if args.download_years:
download_archive_years(args.download_years, args.pdf_dir, wanted_issues)
paths = _selected_pdfs(args.pdf_dir, wanted_issues)
if not paths:
raise SystemExit("no licensed Studia BAS PDFs matched the selection")
records: list[dict[str, object]] = []
for path in paths:
extracted = extract_issue(path)
records.extend(extracted)
print(f"{path.name}: {len(extracted)} articles", flush=True)
records.sort(key=lambda row: str(row["id"]))
if args.sample is not None:
records = records[: args.sample]
count = write_jsonl(records, args.out)
print(f"wrote {count} records to {args.out}")
if __name__ == "__main__":
main()