#!/usr/bin/env python3 """Build cleaned Fresh10 text files and provenance metadata for five domains.""" from __future__ import annotations import hashlib import html from html.parser import HTMLParser import json import os from pathlib import Path import re import subprocess import xml.etree.ElementTree as ET ROOT = Path( os.environ.get( "FRESH10_SOURCE_PACK", Path(__file__).resolve().parent / "source_pack", ) ) class PLOSBodyParser(HTMLParser): """Extract semantic article prose from PLOS HTML, excluding non-prose matter.""" BLOCK_TAGS = {"p", "h1", "h2", "h3", "h4", "h5", "li", "blockquote"} SKIP_CLASSES = { "figure", "table-wrap", "supplementary-material", "figshare_widget", "reflinks", "find-nolinks", "metrics-tab-content", } STOP_HEADINGS = { "references", "supporting information", "acknowledgments", "acknowledgements", "author contributions", } VOID_TAGS = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"} def __init__(self) -> None: super().__init__(convert_charrefs=True) self.in_article = False self.article_depth = 0 self.skip_depth = 0 self.block_depth = 0 self.block_parts: list[str] = [] self.blocks: list[str] = [] self.stopped = False @staticmethod def _attrs(attrs: list[tuple[str, str | None]]) -> dict[str, str]: return {key: value or "" for key, value in attrs} def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: values = self._attrs(attrs) classes = set(values.get("class", "").split()) if not self.in_article and tag == "div" and values.get("id") == "artText": self.in_article = True self.article_depth = 1 return if not self.in_article or self.stopped: return is_void = tag in self.VOID_TAGS if not is_void: self.article_depth += 1 if self.skip_depth: if not is_void: self.skip_depth += 1 return if tag in {"script", "style", "noscript"} or classes & self.SKIP_CLASSES: self.skip_depth = 1 return if tag in self.BLOCK_TAGS: if self.block_depth == 0: self.block_parts = [] self.block_depth += 1 elif tag in {"br"} and self.block_depth: self.block_parts.append(" ") elif tag == "sup" and self.block_depth: self.block_parts.append("^") def handle_endtag(self, tag: str) -> None: if not self.in_article or self.stopped: return if self.skip_depth: self.skip_depth -= 1 elif tag in self.BLOCK_TAGS and self.block_depth: self.block_depth -= 1 if self.block_depth == 0: block = normalize_inline("".join(self.block_parts)) if block.casefold().rstrip(":") in self.STOP_HEADINGS: self.stopped = True elif block: self.blocks.append(block) self.block_parts = [] if tag not in self.VOID_TAGS: self.article_depth -= 1 if self.article_depth == 0: self.in_article = False def handle_data(self, data: str) -> None: if self.in_article and not self.stopped and not self.skip_depth and self.block_depth: self.block_parts.append(data) def normalize_inline(value: str) -> str: value = html.unescape(value).replace("\u00a0", " ").replace("\u200b", "") value = re.sub(r"\s+", " ", value).strip() # Drop PLOS's inline citation-number remnants while retaining substantive numbers. value = re.sub(r"\s*\[(?:\d+(?:\s*[–-]\s*\d+)?)(?:\s*,\s*\d+)*\]", "", value) return value def clean_plos(raw_path: Path, out_path: Path) -> None: parser = PLOSBodyParser() parser.feed(raw_path.read_text(encoding="utf-8")) blocks: list[str] = [] for block in parser.blocks: # These metadata paragraphs and embedded captions are not article prose. if block.startswith(("Citation:", "Editor:", "Received:", "Copyright:", "Data Availability:", "Funding:", "Competing interests:")): continue if re.match(r"^(Fig(?:ure)?|Table)\s+\d+[.:]", block, flags=re.I): continue if block in {"Article Metrics", "Reader Comments", "Top", "Print"}: continue blocks.append(block) out_path.write_text("\n\n".join(blocks).strip() + "\n", encoding="utf-8") def clean_crs(raw_path: Path, out_path: Path, title: str, page_ranges: list[tuple[int, int]]) -> None: """Extract CRS prose by font geometry, omitting small-print notes and visual matter.""" paragraphs: list[str] = [] for start_page, end_page in page_ranges: result = subprocess.run( ["pdftohtml", "-f", str(start_page), "-l", str(end_page), "-i", "-xml", "-stdout", str(raw_path)], check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) tree = ET.fromstring(result.stdout) font_sizes: dict[str, int] = {} for page in tree.findall("page"): font_sizes.update( { spec.attrib["id"]: int(spec.attrib["size"]) for spec in page.findall("fontspec") } ) fragments: list[tuple[int, int, int, str]] = [] for item in page.findall("text"): size = font_sizes.get(item.attrib.get("font", ""), 0) top = int(item.attrib.get("top", "0")) left = int(item.attrib.get("left", "0")) # Body prose is 15-16 pt in pdftohtml coordinates. Footnotes, # sources, captions, table cells, headers, and footers are <=13 pt. if size < 15 or top < 100 or top > 1100: continue value = normalize_inline("".join(item.itertext())) if value: fragments.append((top, left, size, value)) fragments.sort() lines: list[tuple[int, int, str]] = [] for top, left, size, value in fragments: if lines and abs(lines[-1][0] - top) <= 2: old_top, old_size, old_value = lines[-1] lines[-1] = (old_top, max(old_size, size), normalize_inline(old_value + " " + value)) else: lines.append((top, size, value)) current: list[str] = [] previous_top: int | None = None for top, size, value in lines: is_heading = size >= 18 if is_heading or (previous_top is not None and top - previous_top > 25): if current: paragraphs.append(normalize_inline(" ".join(current))) current = [] if is_heading: paragraphs.append(value) else: current.append(value) previous_top = top if current: paragraphs.append(normalize_inline(" ".join(current))) kept: list[str] = [] for para in paragraphs: if para in {title, "Congressional Research Service"}: continue if re.match(r"^(?:Table|Figure)\s+\d+[A-Za-z]?[.:]", para): continue if para.startswith(("Source:", "Notes:", "Note:")): continue if re.fullmatch(r"(?:[-−]?\$?[\d,.%]+\s*)+", para): continue kept.append(para) out_path.write_text(title + "\n\n" + "\n\n".join(kept).strip() + "\n", encoding="utf-8") DOCS = { "history": [ ("dead-sea-scrolls", "Dating ancient manuscripts using radiocarbon and AI-based writing style analysis", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0323185", "2025-06-04"), ("thera-eruption", "The Minoan Thera eruption predates Pharaoh Ahmose: Radiocarbon dating of Egyptian 17th to early 18th Dynasty museum objects", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0330702", "2025-09-10"), ("mesoamerican-cuisine", "Amorphous carbonized objects and their contribution to reconstructing ancient Mesoamerican cuisine", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0334457", "2025-11-19"), ("mongolian-pastoralism", "3000 yr-old patterns of mobile pastoralism revealed by multiple isotopes and radiocarbon dating of ancient horses from the Mongolian Altai", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0322431", "2025-05-07"), ], "climate": [ ("urban-thermal-inequity", "Urban thermal inequity: Advancing thermal justice transitions for vulnerable low-income populations", "PLOS Climate", "https://journals.plos.org/climate/article?id=10.1371%2Fjournal.pclm.0000968", "2026-06-18"), ("climate-hygiene-roadmap", "Climate change, hygiene, and health: A research roadmap for climate adaptation", "PLOS Climate", "https://journals.plos.org/climate/article?id=10.1371%2Fjournal.pclm.0000907", "2026-05-11"), ("india-post-ar6", "A post-AR6 update on observed and projected climate change in India", "PLOS Climate", "https://journals.plos.org/climate/article?id=10.1371%2Fjournal.pclm.0000724", "2025-11-20"), ("multidecadal-variability", "Comparison of multidecadal variability in climate reanalyses and global models", "PLOS Climate", "https://journals.plos.org/climate/article?id=10.1371%2Fjournal.pclm.0000519", "2025-10-07"), ], "education": [ ("sports-ed-dual-path", "A dual-path framework for enhancing student engagement and learning outcomes in sports education", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0345809", "2026-03-25"), ("online-learning-cognitive-load", "Cognitive load and pedagogical tension in multi-platform online learning: Evidence from Chinese higher education", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0347566", "2026-04-21"), ("genai-design-education", "Teacher support for generative AI use and design learning outcomes in fashion design education", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0347428", "2026-05-06"), ("student-achievement-ml", "What factors enhance students' achievement? A machine learning and interpretable methods approach", "PLOS ONE", "https://journals.plos.org/plosone/article?id=10.1371%2Fjournal.pone.0323345", "2025-05-16"), ], "medicine": [ ("pneumonia-hospitalisation", "Prediction of hospitalisation in young children with pneumonia in Malawi: A machine learning-based approach", "PLOS Medicine", "https://journals.plos.org/plosmedicine/article?id=10.1371%2Fjournal.pmed.1005122", "2026-06-09"), ("lung-allograft-multiomics", "Multi-omics biomarkers of endothelial dysregulation preceding chronic lung allograft dysfunction", "PLOS Medicine", "https://journals.plos.org/plosmedicine/article?id=10.1371%2Fjournal.pmed.1004725", "2026-06-23"), ("statins-type2-diabetes", "Cardiovascular outcomes and safety associated with statin therapy for primary prevention in older adults with type 2 diabetes", "PLOS Medicine", "https://journals.plos.org/plosmedicine/article?id=10.1371%2Fjournal.pmed.1005136", "2026-06-24"), ("retinal-neurodegeneration", "Plasma proteomic signatures of early retinal neurodegeneration in diabetes: a multi-cohort study", "PLOS Medicine", "https://journals.plos.org/plosmedicine/article?id=10.1371%2Fjournal.pmed.1004868", "2026-06-02"), ], } CRS_DOCS = [ ("congressional-commissions", "Congressional Commissions: Overview and Considerations for Congress", "https://www.congress.gov/crs_external_products/R/PDF/R40076/R40076.31.pdf", "2026-01-21", [(5, 11)]), ("federal-reserve-policy", "Federal Reserve: Policy Issues in the 119th Congress", "https://www.congress.gov/crs_external_products/R/PDF/R48390/R48390.6.pdf", "2026-01-14", [(4, 15)]), ("universal-service-fund", "The Universal Service Fund and Related FCC Broadband Programs: Overview and Considerations for Congress", "https://www.congress.gov/crs_external_products/R/PDF/R47621/R47621.10.pdf", "2026-01-21", [(5, 6), (8, 15)]), ("federal-rd-funding", "Federal Research and Development (R&D) Funding: FY2026", "https://www.congress.gov/crs_external_products/R/PDF/R48694/R48694.9.pdf", "2025-12-23", [(5, 18)]), ] # One third-party quotation appears in the selected CRS pages. Remove its whole # containing sentence rather than publishing quoted text or a synthetic paraphrase. CRS_THIRD_PARTY_SENTENCES = { "federal-reserve-policy": [ r"At a press conference on January 29, 2025, Chair Powell said,\s*“[^”]+”\s*", r"In response, Chair Powell made a statement where he said that\s*", ], } def digest(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def record_for_text( *, domain: str, slug: str, title: str, publisher: str, url: str, date: str, license_name: str, license_url: str, raw: Path, text: Path, notes: str, ) -> dict[str, object]: return { "domain": domain, "id": slug, "title": title, "publisher": publisher, "source_url": url, "published_date": date, "retrieved_date": "2026-08-12", "license": {"name": license_name, "url": license_url}, "raw_file": str(raw.relative_to(ROOT)), "text_file": str(text.relative_to(ROOT)), "raw_sha256": digest(raw), "text_sha256": digest(text), "extraction_notes": notes, } def main() -> None: records: list[dict[str, object]] = [] for domain, docs in DOCS.items(): domain_dir = ROOT / domain for slug, title, publisher, url, date in docs: raw = domain_dir / "raw" / f"{slug}.html" text = domain_dir / f"{slug}.txt" clean_plos(raw, text) records.append(record_for_text( domain=domain, slug=slug, title=title, publisher=publisher, url=url, date=date, license_name="Creative Commons Attribution 4.0 International", license_url="https://creativecommons.org/licenses/by/4.0/", raw=raw, text=text, notes="Parsed the PLOS #artText body; retained headings and prose; removed site chrome, article metadata, references, supporting information, figures, tables, captions, and inline citation markers.", )) domain_dir = ROOT / "government" for slug, title, url, date, page_ranges in CRS_DOCS: raw = domain_dir / "raw" / f"{slug}.pdf" text = domain_dir / f"{slug}.txt" clean_crs(raw, text, title, page_ranges) cleaned = text.read_text(encoding="utf-8") for sentence in CRS_THIRD_PARTY_SENTENCES.get(slug, []): cleaned, replacements = re.subn(sentence, "", cleaned) if replacements != 1: raise RuntimeError( f"{slug}: expected one third-party sentence, removed {replacements}" ) text.write_text(cleaned, encoding="utf-8") records.append(record_for_text( domain="government", slug=slug, title=title, publisher="Congressional Research Service / Library of Congress", url=url, date=date, license_name="United States government work (public domain in the United States)", license_url="https://www.congress.gov/crs-products", raw=raw, text=text, notes=f"Converted selected report page ranges {page_ranges} with pdftohtml XML; retained body/heading font geometry and removed small-print footnotes/references, repeated headers/footers, figures, tables, captions, and sources. Selected pages omit cover, contents, and end matter. Removed the whole sentence containing one identified third-party quotation from the Federal Reserve selection.", )) (ROOT / "sources.json").write_text( json.dumps({"schema_version": 1, "retrieved_date": "2026-08-12", "documents": records}, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) if __name__ == "__main__": main()