"""Stage 4b: Extract disease → plant links from Chapter IV (Phytotherapy). Uses text matching to find known plant names within disease sections. No LLM calls needed — matches against the 158 plants already extracted. """ import json import re from pathlib import Path from config import DATA_DIR, EXTRACTED_DIR def load_plant_names() -> dict[str, str]: """Load plant names for matching. Returns {lowercase_name: latin_name}.""" plants = json.loads((EXTRACTED_DIR / "all_plants.json").read_text()) names = {} for p in plants: # Russian name ru = p["name_ru"].lower().strip() latin = p.get("name_latin") or p["name_ru"] names[ru] = latin # Also add short forms (first word if multi-word) words = ru.split() if len(words) >= 2: # "ромашка аптечная" → also match "ромашка" names[words[0]] = latin # Add synonyms for syn in p.get("synonyms", []): syn_clean = syn.lower().strip() # Remove language markers like "(тат.)" syn_clean = re.sub(r'\([^)]*\)', '', syn_clean).strip() if len(syn_clean) > 3: names[syn_clean] = latin return names def split_chapter4(text: str) -> list[dict]: """Split Chapter IV into disease sections.""" start = text.find("ГЛАВА IV") end = text.find("УКАЗАТЕЛЬ") if start < 0 or end < 0: return [] chapter = text[start:end] # Find section headers (all-caps lines) header_pattern = re.compile(r'^([А-ЯЁ][А-ЯЁ\s,()]+)$', re.MULTILINE) matches = list(header_pattern.finditer(chapter)) sections = [] # Filter: skip very short headers, meta-sections, and non-disease topics skip_words = { "ФИТОТЕРАПИЯ", "ГЛАВА IV", "ГЛАВА V", "ВЛИЯНИЕ ЦВЕТА НА ЗДОРОВЬЕ", "АРОМОТЕРАПИЯ", "ГИРУДОТЕРАПИЯ", "БАНЯ И ВАННЫ ЛЕЧЕБНЫЕ", "МУЗЫКА, ТАНЦЫ, ИСКУССТВО И ЗДОРОВЬЕ", "МАСКИ ДЛЯ ОЧИСТКИ КОЖИ ЛИЦА", "МОРЩИНЫ НА КОЖЕ ЛИЦА", "УГРЕВАЯ СЫПЬ", "МОЗОЛИ НА НОГАХ И ПОТЛИВОСТЬ НОГ", "УХОД ЗА ВОЛОСАМИ", "КИЛЛОИДНЫЕ РУБЦЫ", } skip_prefixes = ( "ГЛАВА ", "КОСМЕТИКА", "ОЧИЩЕНИЕ", "ОЧИСТКА", "ЗАШЛАКОВАННОСТЬ", "НЕТРАДИЦИОННЫЕ", ) for i, m in enumerate(matches): name = m.group(1).strip() if len(name) < 6 or name in skip_words: continue if any(name.startswith(p) for p in skip_prefixes): continue # Skip category headers (БОЛЕЗНИ ...) if name.startswith("БОЛЕЗНИ ") and len(name) > 30: continue section_start = m.end() section_end = matches[i + 1].start() if i + 1 < len(matches) else len(chapter) section_text = chapter[section_start:section_end].strip() if len(section_text) < 50: continue sections.append({ "disease": name.title(), "text": section_text, }) return sections def find_plants_in_text(text: str, plant_names: dict[str, str]) -> list[str]: """Find plant names mentioned in text. Returns list of Latin names.""" text_lower = text.lower() found = set() # Sort by name length (longest first) to avoid partial matches for name, latin in sorted(plant_names.items(), key=lambda x: -len(x[0])): if len(name) < 4: continue # Word boundary matching pattern = r'\b' + re.escape(name) + r'\b' if re.search(pattern, text_lower): found.add(latin) return sorted(found) def main(): text = (DATA_DIR / "raw" / "full_text.txt").read_text() plant_names = load_plant_names() print(f"Loaded {len(plant_names)} plant name variants for matching") sections = split_chapter4(text) print(f"Found {len(sections)} disease sections in Chapter IV") # Extract disease → plant links disease_plants = [] for sec in sections: plants = find_plants_in_text(sec["text"], plant_names) if plants: disease_plants.append({ "disease": sec["disease"], "plants": plants, "plant_count": len(plants), }) # Sort by number of plants disease_plants.sort(key=lambda x: -x["plant_count"]) # Save out_file = EXTRACTED_DIR / "chapter4_disease_plants.json" out_file.write_text(json.dumps(disease_plants, ensure_ascii=False, indent=2)) # Stats total_links = sum(dp["plant_count"] for dp in disease_plants) print(f"\nResults:") print(f" Diseases with plant links: {len(disease_plants)}") print(f" Total disease→plant links: {total_links}") print(f"\nTop 15 diseases by number of plants:") for dp in disease_plants[:15]: print(f" {dp['plant_count']:3d} plants — {dp['disease']}") print(f"\nSaved to {out_file}") if __name__ == "__main__": main()