#!/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"(?]*>(.*?)", re.I | re.S)
_CELL_RE = re.compile(r"