z00logist commited on
Commit
1e381bc
·
verified ·
1 Parent(s): 27dc51b

add preprocessing script

Browse files
Files changed (1) hide show
  1. preprocess_data.py +389 -0
preprocess_data.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ parse_data.py — scrape and preprocess the Old Church Slavonic corpus pages
4
+ from dic.feb-web.ru/slavonic/corpus/ into a clean CSV.
5
+
6
+ This script is a "cleaned up" version of the exploratory notebook `parse_data.ipynb`:
7
+ - no duplicated function definitions
8
+ - one coherent CLI
9
+ - optional de-duplication of produced text segments
10
+
11
+ Typical usage
12
+ -------------
13
+ 1) Scrape pages into folders:
14
+ python parse_data.py scrape --out scraped_sections
15
+
16
+ 2) Build a CSV dataset:
17
+ python parse_data.py build --in-dir scraped_sections --out-csv ocs.csv --unit line --dedupe text_source
18
+
19
+ Dependencies
20
+ ------------
21
+ pip install requests beautifulsoup4 pandas
22
+ """
23
+
24
+ import argparse
25
+ import csv
26
+ import logging
27
+ import re
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+ from typing import Iterator, Optional, Tuple
31
+ from urllib.parse import urlparse, urljoin
32
+
33
+ import requests
34
+ from bs4 import BeautifulSoup
35
+ import pandas as pd
36
+
37
+
38
+
39
+ LOG = logging.getLogger("parse_data")
40
+
41
+
42
+ def setup_logging(verbosity: int) -> None:
43
+ level = logging.WARNING
44
+ if verbosity == 1:
45
+ level = logging.INFO
46
+ elif verbosity >= 2:
47
+ level = logging.DEBUG
48
+ logging.basicConfig(
49
+ level=level,
50
+ format="%(asctime)s | %(levelname)s | %(message)s",
51
+ datefmt="%H:%M:%S",
52
+ )
53
+
54
+
55
+
56
+ DEFAULT_BASE_URL = "http://dic.feb-web.ru/slavonic/corpus/"
57
+ DEFAULT_MAX_NAME_LEN = 100
58
+
59
+
60
+ def truncate_name(name: str, max_length: int = DEFAULT_MAX_NAME_LEN) -> str:
61
+ name = name.strip()
62
+ if len(name) <= max_length:
63
+ return name
64
+ return name[:max_length].rstrip() + "…"
65
+
66
+
67
+ def safe_filename(name: str) -> str:
68
+ name = name.replace("/", "-").replace("\\", "-")
69
+ name = re.sub(r"[\x00-\x1f]+", " ", name).strip()
70
+ return name
71
+
72
+
73
+ def get_folder_name_from_url(href: str, base_url: str) -> str:
74
+ if href.startswith("/"):
75
+ full_url = base_url.rstrip("/") + href
76
+ else:
77
+ full_url = urljoin(base_url, href)
78
+
79
+ parsed = urlparse(full_url)
80
+ parts = [p for p in parsed.path.strip("/").split("/") if p]
81
+
82
+ if "corpus" in parts:
83
+ idx = parts.index("corpus")
84
+ after = parts[idx + 1 :]
85
+ else:
86
+ after = parts
87
+
88
+ if len(after) >= 2:
89
+ folder = after[1]
90
+ elif len(after) == 1:
91
+ folder = after[0]
92
+ else:
93
+ folder = "unknown"
94
+
95
+ return truncate_name(folder)
96
+
97
+
98
+ def make_session(timeout_s: int = 20) -> requests.Session:
99
+ sess = requests.Session()
100
+ try:
101
+ from requests.adapters import HTTPAdapter
102
+ from urllib3.util.retry import Retry
103
+
104
+ retry = Retry(
105
+ total=5,
106
+ backoff_factor=0.5,
107
+ status_forcelist=(429, 500, 502, 503, 504),
108
+ allowed_methods=("GET",),
109
+ raise_on_status=False,
110
+ )
111
+ adapter = HTTPAdapter(max_retries=retry)
112
+ sess.mount("http://", adapter)
113
+ sess.mount("https://", adapter)
114
+ except Exception:
115
+ pass
116
+
117
+ sess.headers.update({"User-Agent": "parse_data/1.0 (+https://openai.com)"})
118
+ sess.request_timeout = timeout_s
119
+ return sess
120
+
121
+
122
+ def fetch_html(session: requests.Session, url: str) -> BeautifulSoup:
123
+ timeout = getattr(session, "request_timeout", 20)
124
+ resp = session.get(url, timeout=timeout)
125
+ resp.raise_for_status()
126
+ return BeautifulSoup(resp.content, "html.parser")
127
+
128
+
129
+ def extract_text_blocks(session: requests.Session, url: str) -> str:
130
+ try:
131
+ soup = fetch_html(session, url)
132
+ blocks = soup.find_all("p")
133
+ text = "\n".join(b.get_text(strip=True) for b in blocks)
134
+ return text
135
+ except Exception as e:
136
+ LOG.warning("Failed to extract text from %s: %s", url, e)
137
+ return ""
138
+
139
+
140
+ def discover_tree_links(session: requests.Session, base_url: str) -> list[Tuple[str, str]]:
141
+ soup = fetch_html(session, base_url)
142
+ frame = soup.find("frame", {"name": "tree"})
143
+ if not frame or not frame.get("src"):
144
+ raise RuntimeError("Could not find <frame name='tree'> on the base page")
145
+
146
+ frame_src = str(frame["src"])
147
+ frame_url = urljoin(base_url, frame_src)
148
+
149
+ tree = fetch_html(session, frame_url)
150
+ links = []
151
+ for a in tree.find_all("a", href=True):
152
+ href = str(a["href"])
153
+ title = a.get_text(strip=True) or href
154
+ links.append((href, truncate_name(title)))
155
+ return links
156
+
157
+
158
+ def scrape(
159
+ base_url: str,
160
+ out_dir: Path,
161
+ max_name_length: int = DEFAULT_MAX_NAME_LEN,
162
+ skip_existing: bool = True,
163
+ timeout_s: int = 20,
164
+ ) -> None:
165
+ global DEFAULT_MAX_NAME_LEN
166
+ DEFAULT_MAX_NAME_LEN = max_name_length
167
+
168
+ out_dir.mkdir(parents=True, exist_ok=True)
169
+ session = make_session(timeout_s=timeout_s)
170
+
171
+ links = discover_tree_links(session, base_url)
172
+ LOG.info("Found %d links", len(links))
173
+
174
+ for href, section_name in links:
175
+ full_url = urljoin(base_url, href)
176
+
177
+ folder_name = get_folder_name_from_url(href, base_url)
178
+ folder_path = out_dir / folder_name
179
+ folder_path.mkdir(parents=True, exist_ok=True)
180
+
181
+ file_name = safe_filename(truncate_name(f"{section_name}.txt")).strip()
182
+ if not file_name.endswith(".txt"):
183
+ file_name += ".txt"
184
+ file_path = folder_path / file_name
185
+
186
+ if skip_existing and file_path.exists():
187
+ LOG.debug("Skip existing: %s", file_path)
188
+ continue
189
+
190
+ LOG.debug("Processing: %s -> %s (folder=%s)", section_name, full_url, folder_name)
191
+ page_text = extract_text_blocks(session, full_url)
192
+
193
+ if page_text.strip():
194
+ file_path.write_text(page_text, encoding="utf-8")
195
+ else:
196
+ LOG.info("Empty extraction for: %s (%s)", section_name, full_url)
197
+
198
+ LOG.warning("Scraping completed. Output: %s", out_dir)
199
+
200
+
201
+ _RE_UPPER_CYR = re.compile(r"\b[А-ЯЁҐІЇЄѢЪѲѴ]+(?:\s+[А-ЯЁҐІЇЄѢЪѲѴ]+)*\b")
202
+ _RE_BRACKETS = re.compile(r"\[.*?\]|\(.*?\)")
203
+ _RE_ZACH = re.compile(r"зач̑.*?$", flags=re.MULTILINE)
204
+ _RE_VECHARA = re.compile(r"Въ\s[а-яА-Я҃]+?\sве́чера.*?:")
205
+ _RE_STIH = re.compile(r"Сті́хъ:.*?$", flags=re.MULTILINE)
206
+
207
+ _RE_HEADERS = re.compile(r"Ча́сть\s*[а-яА-Я҃\d]+|Глава̀\s*[а-яА-Я҃\s\d]+|Кѡндакъ\s*(\d+|[а-я]+)\.?$")
208
+
209
+
210
+ def normalize_markers(text: str) -> str:
211
+ return re.sub(r"рл҃г\.", "рл҃г. ", text)
212
+
213
+
214
+ def remove_unwanted_sections(text: str) -> str:
215
+ text = _RE_HEADERS.sub("", text)
216
+ text = _RE_BRACKETS.sub(" ", text)
217
+ text = _RE_ZACH.sub("", text)
218
+ text = _RE_VECHARA.sub("", text)
219
+ text = _RE_STIH.sub("", text)
220
+ return text
221
+
222
+
223
+ def remove_capitalized_words(text: str) -> str:
224
+ text = _RE_UPPER_CYR.sub("", text)
225
+ return re.sub(r"\s+", " ", text).strip()
226
+
227
+
228
+ def clean_whitespace(text: str) -> str:
229
+ return re.sub(r"\s+", " ", text).strip()
230
+
231
+
232
+ def iter_units(text: str, unit: str) -> Iterator[str]:
233
+ unit = unit.lower()
234
+ if unit == "file":
235
+ yield text
236
+ return
237
+
238
+ if unit == "line":
239
+ for ln in text.splitlines():
240
+ ln = ln.strip()
241
+ if ln:
242
+ yield ln
243
+ return
244
+
245
+ if unit == "sentence":
246
+ parts = re.split(r"(?<=[\.\!\?\:\;·…])\s+", text)
247
+ for p in parts:
248
+ p = p.strip()
249
+ if p:
250
+ yield p
251
+ return
252
+
253
+ raise ValueError(f"Unknown unit: {unit!r}. Use one of: file, line, sentence.")
254
+
255
+
256
+ @dataclass(frozen=True)
257
+ class BuildConfig:
258
+ in_dir: Path
259
+ out_csv: Path
260
+ unit: str = "line"
261
+ min_chars: int = 20
262
+ dedupe: str = "text_source"
263
+ encoding: str = "utf-8"
264
+
265
+
266
+ def build_dataset(cfg: BuildConfig) -> None:
267
+ cfg.out_csv.parent.mkdir(parents=True, exist_ok=True)
268
+
269
+ seen: Optional[set[Tuple[str, str]]] = set() if cfg.dedupe != "none" else None
270
+
271
+ written = 0
272
+ skipped_short = 0
273
+ skipped_dupe = 0
274
+
275
+ with cfg.out_csv.open("w", encoding=cfg.encoding, newline="") as f_out:
276
+ w = csv.writer(f_out)
277
+ w.writerow(["Text", "Source"])
278
+
279
+ for source_dir in sorted(p for p in cfg.in_dir.iterdir() if p.is_dir()):
280
+ source = source_dir.name
281
+
282
+ for txt in sorted(source_dir.glob("*.txt")):
283
+ raw = txt.read_text(encoding=cfg.encoding, errors="replace")
284
+
285
+ raw = normalize_markers(raw)
286
+ raw = remove_unwanted_sections(raw)
287
+ raw = remove_capitalized_words(raw)
288
+
289
+ for unit_text in iter_units(raw, cfg.unit):
290
+ unit_text = clean_whitespace(unit_text)
291
+ if len(unit_text) < cfg.min_chars:
292
+ skipped_short += 1
293
+ continue
294
+
295
+ if seen is not None:
296
+ key = (unit_text, source) if cfg.dedupe == "text_source" else (unit_text, "")
297
+ if key in seen:
298
+ skipped_dupe += 1
299
+ continue
300
+ seen.add(key)
301
+
302
+ w.writerow([unit_text, source])
303
+ written += 1
304
+
305
+ LOG.warning(
306
+ "Build complete: wrote=%d | skipped_short=%d | skipped_dupe=%d | out=%s",
307
+ written, skipped_short, skipped_dupe, cfg.out_csv
308
+ )
309
+
310
+
311
+ def combine_folder_csvs(folder_csv_dir: Path, out_csv: Path) -> None:
312
+ if pd is None:
313
+ raise RuntimeError("pandas is required for combine_folder_csvs. Install: pip install pandas")
314
+
315
+ frames = []
316
+ for p in sorted(folder_csv_dir.glob("*.csv")):
317
+ frames.append(pd.read_csv(p))
318
+ if not frames:
319
+ raise RuntimeError(f"No CSV files found in {folder_csv_dir}")
320
+ df = pd.concat(frames, ignore_index=True)
321
+ df.reset_index(drop=True, inplace=True)
322
+ out_csv.parent.mkdir(parents=True, exist_ok=True)
323
+ df.to_csv(out_csv, index=False)
324
+ LOG.warning("Combined %d CSVs into %s (rows=%d)", len(frames), out_csv, len(df))
325
+
326
+
327
+ def build_parser() -> argparse.ArgumentParser:
328
+ p = argparse.ArgumentParser(description="Scrape and preprocess OCS corpus pages into CSV.")
329
+ p.add_argument("-v", "--verbose", action="count", default=0, help="Increase verbosity (-v, -vv).")
330
+
331
+ sub = p.add_subparsers(dest="cmd", required=True)
332
+
333
+ ps = sub.add_parser("scrape", help="Scrape the corpus site into a folder structure.")
334
+ ps.add_argument("--base-url", default=DEFAULT_BASE_URL, help="Base URL to scrape.")
335
+ ps.add_argument("--out", dest="out_dir", default="scraped_sections", help="Output directory.")
336
+ ps.add_argument("--max-name-length", type=int, default=DEFAULT_MAX_NAME_LEN, help="Max filename length.")
337
+ ps.add_argument("--no-skip-existing", action="store_true", help="Re-download even if file exists.")
338
+ ps.add_argument("--timeout", type=int, default=20, help="Request timeout seconds.")
339
+
340
+ pb = sub.add_parser("build", help="Build a single CSV dataset from scraped folders.")
341
+ pb.add_argument("--in-dir", default="scraped_sections", help="Input directory created by 'scrape'.")
342
+ pb.add_argument("--out-csv", default="old_church_slavonic_dataset.csv", help="Output CSV path.")
343
+ pb.add_argument("--unit", choices=["file", "line", "sentence"], default="line",
344
+ help="Dataset unit granularity.")
345
+ pb.add_argument("--min-chars", type=int, default=20, help="Drop units shorter than this.")
346
+ pb.add_argument("--dedupe", choices=["none", "text_source", "text"], default="text_source",
347
+ help="De-duplication strategy.")
348
+
349
+ pc = sub.add_parser("combine", help="Combine per-folder CSVs into one (pandas).")
350
+ pc.add_argument("--in-dir", default="preprocessed_for_generation", help="Directory with *.csv files.")
351
+ pc.add_argument("--out-csv", default="old_church_slavonic_dataset.csv", help="Output CSV path.")
352
+
353
+ return p
354
+
355
+
356
+ def main(argv: Optional[list[str]] = None) -> int:
357
+ args = build_parser().parse_args(argv)
358
+ setup_logging(args.verbose)
359
+
360
+ if args.cmd == "scrape":
361
+ scrape(
362
+ base_url=args.base_url,
363
+ out_dir=Path(args.out_dir),
364
+ max_name_length=args.max_name_length,
365
+ skip_existing=not args.no_skip_existing,
366
+ timeout_s=args.timeout,
367
+ )
368
+ return 0
369
+
370
+ if args.cmd == "build":
371
+ cfg = BuildConfig(
372
+ in_dir=Path(args.in_dir),
373
+ out_csv=Path(args.out_csv),
374
+ unit=args.unit,
375
+ min_chars=args.min_chars,
376
+ dedupe=args.dedupe,
377
+ )
378
+ build_dataset(cfg)
379
+ return 0
380
+
381
+ if args.cmd == "combine":
382
+ combine_folder_csvs(Path(args.in_dir), Path(args.out_csv))
383
+ return 0
384
+
385
+ raise AssertionError("unreachable")
386
+
387
+
388
+ if __name__ == "__main__":
389
+ raise SystemExit(main())