"""Stage 2: Split OCR text into individual plant articles. Pattern detected from book "Земли Тюменской травы целебные": - Articles start with UPPERCASE RUSSIAN NAME followed by Latin name - Example: "БОДЯК ПОЛЕВОЙ (осот розовый), Cirsium arvense L.," - Example: "БЕРЕЗА ПОВИСЛАЯ, ИЛИ БОРОДАВЧАТАЯ, Betula pendula Roth," - Plant articles span pages ~85-569 """ import json import re import sys from pathlib import Path # Pattern: line starts with 2+ uppercase Cyrillic words, then comma/dash/em-dash, then Latin genus # Latin name may be split across lines by OCR, so we allow \n between genus and species ARTICLE_START = re.compile( r'^([А-ЯЁ][А-ЯЁа-яё\s,\-()]+)[,—\-]\s*' # Russian name r'([A-Z][a-z]+[\s\n]+[a-z]+)', # Latin binomial (may span 2 lines) re.MULTILINE ) def split_articles(text: str) -> list[dict]: """Split full OCR text into individual plant articles.""" matches = list(ARTICLE_START.finditer(text)) if not matches: print("WARNING: No article headers found!") return [] articles = [] for i, match in enumerate(matches): start = match.start() end = matches[i + 1].start() if i + 1 < len(matches) else len(text) article_text = text[start:end].strip() # Extract basic info from header name_ru = match.group(1).strip().rstrip(',').rstrip('—').rstrip('-').strip() # Fix newlines in Latin name (OCR artifact) name_latin = re.sub(r'\s+', ' ', match.group(2).strip()) # Remove page markers from article text article_text = re.sub(r'--- PAGE \d+ ---\n?', '', article_text) # Remove standalone page numbers article_text = re.sub(r'\n\d{1,3}\n', '\n', article_text) # Skip articles that are too short (likely false positives) if len(article_text) < 100: continue articles.append({ "index": len(articles), "name_ru": name_ru, "name_latin": name_latin, "text": article_text, }) return articles def trim_to_plant_section(text: str) -> str: """Trim text to only the plant articles section (before ГЛАВА IV).""" # Find start of phytotherapy chapter (organized by diseases, not plants) markers = ["ГЛАВА IV", "ГЛАВА 4"] for marker in markers: idx = text.find(marker) if idx > 0: return text[:idx] return text def main(): input_file = Path("data/raw/full_text.txt") output_dir = Path("data/articles") output_dir.mkdir(parents=True, exist_ok=True) if not input_file.exists(): print(f"ERROR: {input_file} not found. Run stage1_ocr.sh first.") sys.exit(1) text = input_file.read_text(encoding="utf-8") print(f"Total text length: {len(text)} chars") text = trim_to_plant_section(text) print(f"Plant section length: {len(text)} chars") articles = split_articles(text) print(f"Found {len(articles)} articles") # Save individual articles for art in articles: safe_latin = art['name_latin'].replace(' ', '_').replace('\n', '_') fname = output_dir / f"{art['index']:03d}_{safe_latin}.txt" fname.write_text(art["text"], encoding="utf-8") # Save index index = [{"index": a["index"], "name_ru": a["name_ru"], "name_latin": a["name_latin"]} for a in articles] index_file = output_dir / "index.json" index_file.write_text(json.dumps(index, ensure_ascii=False, indent=2), encoding="utf-8") print(f"Articles saved to {output_dir}/") print(f"Index saved to {index_file}") # Show first 5 and last 5 print("\nFirst 5 articles:") for a in articles[:5]: print(f" [{a['index']}] {a['name_ru']} — {a['name_latin']}") print("Last 5 articles:") for a in articles[-5:]: print(f" [{a['index']}] {a['name_ru']} — {a['name_latin']}") if __name__ == "__main__": main()