OldChurchSlavonic / preprocess_data.py
z00logist's picture
add preprocessing script
1e381bc verified
#!/usr/bin/env python3
"""
parse_data.py — scrape and preprocess the Old Church Slavonic corpus pages
from dic.feb-web.ru/slavonic/corpus/ into a clean CSV.
This script is a "cleaned up" version of the exploratory notebook `parse_data.ipynb`:
- no duplicated function definitions
- one coherent CLI
- optional de-duplication of produced text segments
Typical usage
-------------
1) Scrape pages into folders:
python parse_data.py scrape --out scraped_sections
2) Build a CSV dataset:
python parse_data.py build --in-dir scraped_sections --out-csv ocs.csv --unit line --dedupe text_source
Dependencies
------------
pip install requests beautifulsoup4 pandas
"""
import argparse
import csv
import logging
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator, Optional, Tuple
from urllib.parse import urlparse, urljoin
import requests
from bs4 import BeautifulSoup
import pandas as pd
LOG = logging.getLogger("parse_data")
def setup_logging(verbosity: int) -> None:
level = logging.WARNING
if verbosity == 1:
level = logging.INFO
elif verbosity >= 2:
level = logging.DEBUG
logging.basicConfig(
level=level,
format="%(asctime)s | %(levelname)s | %(message)s",
datefmt="%H:%M:%S",
)
DEFAULT_BASE_URL = "http://dic.feb-web.ru/slavonic/corpus/"
DEFAULT_MAX_NAME_LEN = 100
def truncate_name(name: str, max_length: int = DEFAULT_MAX_NAME_LEN) -> str:
name = name.strip()
if len(name) <= max_length:
return name
return name[:max_length].rstrip() + "…"
def safe_filename(name: str) -> str:
name = name.replace("/", "-").replace("\\", "-")
name = re.sub(r"[\x00-\x1f]+", " ", name).strip()
return name
def get_folder_name_from_url(href: str, base_url: str) -> str:
if href.startswith("/"):
full_url = base_url.rstrip("/") + href
else:
full_url = urljoin(base_url, href)
parsed = urlparse(full_url)
parts = [p for p in parsed.path.strip("/").split("/") if p]
if "corpus" in parts:
idx = parts.index("corpus")
after = parts[idx + 1 :]
else:
after = parts
if len(after) >= 2:
folder = after[1]
elif len(after) == 1:
folder = after[0]
else:
folder = "unknown"
return truncate_name(folder)
def make_session(timeout_s: int = 20) -> requests.Session:
sess = requests.Session()
try:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=5,
backoff_factor=0.5,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=("GET",),
raise_on_status=False,
)
adapter = HTTPAdapter(max_retries=retry)
sess.mount("http://", adapter)
sess.mount("https://", adapter)
except Exception:
pass
sess.headers.update({"User-Agent": "parse_data/1.0 (+https://openai.com)"})
sess.request_timeout = timeout_s
return sess
def fetch_html(session: requests.Session, url: str) -> BeautifulSoup:
timeout = getattr(session, "request_timeout", 20)
resp = session.get(url, timeout=timeout)
resp.raise_for_status()
return BeautifulSoup(resp.content, "html.parser")
def extract_text_blocks(session: requests.Session, url: str) -> str:
try:
soup = fetch_html(session, url)
blocks = soup.find_all("p")
text = "\n".join(b.get_text(strip=True) for b in blocks)
return text
except Exception as e:
LOG.warning("Failed to extract text from %s: %s", url, e)
return ""
def discover_tree_links(session: requests.Session, base_url: str) -> list[Tuple[str, str]]:
soup = fetch_html(session, base_url)
frame = soup.find("frame", {"name": "tree"})
if not frame or not frame.get("src"):
raise RuntimeError("Could not find <frame name='tree'> on the base page")
frame_src = str(frame["src"])
frame_url = urljoin(base_url, frame_src)
tree = fetch_html(session, frame_url)
links = []
for a in tree.find_all("a", href=True):
href = str(a["href"])
title = a.get_text(strip=True) or href
links.append((href, truncate_name(title)))
return links
def scrape(
base_url: str,
out_dir: Path,
max_name_length: int = DEFAULT_MAX_NAME_LEN,
skip_existing: bool = True,
timeout_s: int = 20,
) -> None:
global DEFAULT_MAX_NAME_LEN
DEFAULT_MAX_NAME_LEN = max_name_length
out_dir.mkdir(parents=True, exist_ok=True)
session = make_session(timeout_s=timeout_s)
links = discover_tree_links(session, base_url)
LOG.info("Found %d links", len(links))
for href, section_name in links:
full_url = urljoin(base_url, href)
folder_name = get_folder_name_from_url(href, base_url)
folder_path = out_dir / folder_name
folder_path.mkdir(parents=True, exist_ok=True)
file_name = safe_filename(truncate_name(f"{section_name}.txt")).strip()
if not file_name.endswith(".txt"):
file_name += ".txt"
file_path = folder_path / file_name
if skip_existing and file_path.exists():
LOG.debug("Skip existing: %s", file_path)
continue
LOG.debug("Processing: %s -> %s (folder=%s)", section_name, full_url, folder_name)
page_text = extract_text_blocks(session, full_url)
if page_text.strip():
file_path.write_text(page_text, encoding="utf-8")
else:
LOG.info("Empty extraction for: %s (%s)", section_name, full_url)
LOG.warning("Scraping completed. Output: %s", out_dir)
_RE_UPPER_CYR = re.compile(r"\b[А-ЯЁҐІЇЄѢЪѲѴ]+(?:\s+[А-ЯЁҐІЇЄѢЪѲѴ]+)*\b")
_RE_BRACKETS = re.compile(r"\[.*?\]|\(.*?\)")
_RE_ZACH = re.compile(r"зач̑.*?$", flags=re.MULTILINE)
_RE_VECHARA = re.compile(r"Въ\s[а-яА-Я҃]+?\sве́чера.*?:")
_RE_STIH = re.compile(r"Сті́хъ:.*?$", flags=re.MULTILINE)
_RE_HEADERS = re.compile(r"Ча́сть\s*[а-яА-Я҃\d]+|Глава̀\s*[а-яА-Я҃\s\d]+|Кѡндакъ\s*(\d+|[а-я]+)\.?$")
def normalize_markers(text: str) -> str:
return re.sub(r"рл҃г\.", "рл҃г. ", text)
def remove_unwanted_sections(text: str) -> str:
text = _RE_HEADERS.sub("", text)
text = _RE_BRACKETS.sub(" ", text)
text = _RE_ZACH.sub("", text)
text = _RE_VECHARA.sub("", text)
text = _RE_STIH.sub("", text)
return text
def remove_capitalized_words(text: str) -> str:
text = _RE_UPPER_CYR.sub("", text)
return re.sub(r"\s+", " ", text).strip()
def clean_whitespace(text: str) -> str:
return re.sub(r"\s+", " ", text).strip()
def iter_units(text: str, unit: str) -> Iterator[str]:
unit = unit.lower()
if unit == "file":
yield text
return
if unit == "line":
for ln in text.splitlines():
ln = ln.strip()
if ln:
yield ln
return
if unit == "sentence":
parts = re.split(r"(?<=[\.\!\?\:\;·…])\s+", text)
for p in parts:
p = p.strip()
if p:
yield p
return
raise ValueError(f"Unknown unit: {unit!r}. Use one of: file, line, sentence.")
@dataclass(frozen=True)
class BuildConfig:
in_dir: Path
out_csv: Path
unit: str = "line"
min_chars: int = 20
dedupe: str = "text_source"
encoding: str = "utf-8"
def build_dataset(cfg: BuildConfig) -> None:
cfg.out_csv.parent.mkdir(parents=True, exist_ok=True)
seen: Optional[set[Tuple[str, str]]] = set() if cfg.dedupe != "none" else None
written = 0
skipped_short = 0
skipped_dupe = 0
with cfg.out_csv.open("w", encoding=cfg.encoding, newline="") as f_out:
w = csv.writer(f_out)
w.writerow(["Text", "Source"])
for source_dir in sorted(p for p in cfg.in_dir.iterdir() if p.is_dir()):
source = source_dir.name
for txt in sorted(source_dir.glob("*.txt")):
raw = txt.read_text(encoding=cfg.encoding, errors="replace")
raw = normalize_markers(raw)
raw = remove_unwanted_sections(raw)
raw = remove_capitalized_words(raw)
for unit_text in iter_units(raw, cfg.unit):
unit_text = clean_whitespace(unit_text)
if len(unit_text) < cfg.min_chars:
skipped_short += 1
continue
if seen is not None:
key = (unit_text, source) if cfg.dedupe == "text_source" else (unit_text, "")
if key in seen:
skipped_dupe += 1
continue
seen.add(key)
w.writerow([unit_text, source])
written += 1
LOG.warning(
"Build complete: wrote=%d | skipped_short=%d | skipped_dupe=%d | out=%s",
written, skipped_short, skipped_dupe, cfg.out_csv
)
def combine_folder_csvs(folder_csv_dir: Path, out_csv: Path) -> None:
if pd is None:
raise RuntimeError("pandas is required for combine_folder_csvs. Install: pip install pandas")
frames = []
for p in sorted(folder_csv_dir.glob("*.csv")):
frames.append(pd.read_csv(p))
if not frames:
raise RuntimeError(f"No CSV files found in {folder_csv_dir}")
df = pd.concat(frames, ignore_index=True)
df.reset_index(drop=True, inplace=True)
out_csv.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(out_csv, index=False)
LOG.warning("Combined %d CSVs into %s (rows=%d)", len(frames), out_csv, len(df))
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description="Scrape and preprocess OCS corpus pages into CSV.")
p.add_argument("-v", "--verbose", action="count", default=0, help="Increase verbosity (-v, -vv).")
sub = p.add_subparsers(dest="cmd", required=True)
ps = sub.add_parser("scrape", help="Scrape the corpus site into a folder structure.")
ps.add_argument("--base-url", default=DEFAULT_BASE_URL, help="Base URL to scrape.")
ps.add_argument("--out", dest="out_dir", default="scraped_sections", help="Output directory.")
ps.add_argument("--max-name-length", type=int, default=DEFAULT_MAX_NAME_LEN, help="Max filename length.")
ps.add_argument("--no-skip-existing", action="store_true", help="Re-download even if file exists.")
ps.add_argument("--timeout", type=int, default=20, help="Request timeout seconds.")
pb = sub.add_parser("build", help="Build a single CSV dataset from scraped folders.")
pb.add_argument("--in-dir", default="scraped_sections", help="Input directory created by 'scrape'.")
pb.add_argument("--out-csv", default="old_church_slavonic_dataset.csv", help="Output CSV path.")
pb.add_argument("--unit", choices=["file", "line", "sentence"], default="line",
help="Dataset unit granularity.")
pb.add_argument("--min-chars", type=int, default=20, help="Drop units shorter than this.")
pb.add_argument("--dedupe", choices=["none", "text_source", "text"], default="text_source",
help="De-duplication strategy.")
pc = sub.add_parser("combine", help="Combine per-folder CSVs into one (pandas).")
pc.add_argument("--in-dir", default="preprocessed_for_generation", help="Directory with *.csv files.")
pc.add_argument("--out-csv", default="old_church_slavonic_dataset.csv", help="Output CSV path.")
return p
def main(argv: Optional[list[str]] = None) -> int:
args = build_parser().parse_args(argv)
setup_logging(args.verbose)
if args.cmd == "scrape":
scrape(
base_url=args.base_url,
out_dir=Path(args.out_dir),
max_name_length=args.max_name_length,
skip_existing=not args.no_skip_existing,
timeout_s=args.timeout,
)
return 0
if args.cmd == "build":
cfg = BuildConfig(
in_dir=Path(args.in_dir),
out_csv=Path(args.out_csv),
unit=args.unit,
min_chars=args.min_chars,
dedupe=args.dedupe,
)
build_dataset(cfg)
return 0
if args.cmd == "combine":
combine_folder_csvs(Path(args.in_dir), Path(args.out_csv))
return 0
raise AssertionError("unreachable")
if __name__ == "__main__":
raise SystemExit(main())