"""Stage 3: Structured extraction from plant articles via LLM. Uses Z.AI proxy (Anthropic Messages API format) → GLM models. Pydantic validation with retry on parse errors. """ import json import re import sys import time from pathlib import Path import httpx from pydantic import ValidationError from config import ( ARTICLES_DIR, EXTRACTED_DIR, LLM_API_KEY, LLM_BASE_URL, LLM_MODEL, MAX_RETRIES, ) from models import Plant EXTRACTION_PROMPT = """Ты — ботаник-фармацевт. Извлеки структурированные данные из статьи о лекарственном растении. ПРАВИЛА: 1. Верни ТОЛЬКО валидный JSON, без markdown-обёрток, без пояснений 2. Если информации нет в тексте — ставь null (для строк) или [] (для списков) 3. НЕ додумывай информацию, которой нет в тексте 4. Латинские названия пиши как есть в тексте 5. Для chemicals: извлекай конкретные вещества и группы (флавоноиды, дубильные вещества, эфирное масло и т.д.) 6. Для diseases: извлекай конкретные заболевания, при которых применяется растение 7. Для toxicity: "нет" если не упоминается, "высокая" если ядовитое JSON SCHEMA: { "name_ru": "string — русское название", "name_latin": "string|null — латинское название", "family_ru": "string|null — семейство на русском", "family_latin": "string|null — семейство на латыни", "synonyms": ["string — альтернативные названия (народные, татарские, хантыйские и др.)"], "life_form": "string|null — трава / кустарник / дерево / полукустарник", "chemicals": ["string — химические вещества и группы"], "medicinal_properties": ["string — лечебные свойства (противовоспалительное, мочегонное и т.д.)"], "diseases": ["string — заболевания и состояния"], "parts_used": ["string — используемые части растения"], "preparation": ["string — способы приготовления (настой, отвар, мазь и т.д.)"], "habitat": ["string — места произрастания"], "distribution": ["string — географическое распространение"], "toxicity": "string|null — нет / низкая / средняя / высокая", "contraindications": ["string — противопоказания"] } ПРИМЕР ВХОДА: ЧЕРТОПОЛОХ КУРЧАВЫЙ, Carduus crispus L.; убыр уты (тат.). Травянистое растение с прямостоячим колючим стеблем до 1 м высотой. Растет по берегам рек, оврагам, лугам. В народной медицине отваром листьев поят детей при конвульсиях, испуге, поносе. Используется при расстройствах нервной системы, простуде как потогонное. ПРИМЕР ВЫХОДА: {"name_ru": "Чертополох курчавый", "name_latin": "Carduus crispus", "family_ru": null, "family_latin": null, "synonyms": ["убыр уты (тат.)"], "life_form": "трава", "chemicals": [], "medicinal_properties": ["потогонное"], "diseases": ["конвульсии", "испуг", "понос", "расстройства нервной системы", "простуда"], "parts_used": ["листья"], "preparation": ["отвар"], "habitat": ["берега рек", "овраги", "луга"], "distribution": [], "toxicity": null, "contraindications": []} ТЕКСТ СТАТЬИ: """ def call_llm(prompt: str) -> str: """Call LLM via Anthropic Messages API (Z.AI proxy).""" headers = { "x-api-key": LLM_API_KEY, "anthropic-version": "2023-06-01", "content-type": "application/json", } payload = { "model": LLM_MODEL, "max_tokens": 2000, "temperature": 0.0, "messages": [{"role": "user", "content": prompt}], } with httpx.Client(timeout=120) as client: resp = client.post( f"{LLM_BASE_URL}/v1/messages", headers=headers, json=payload, ) resp.raise_for_status() data = resp.json() # Anthropic format: content[0].text return data["content"][0]["text"] def extract_json_from_response(text: str) -> dict: """Extract JSON from LLM response, handling markdown code blocks and extra data.""" text = text.strip() # Always use bracket matching to find the first complete JSON object # This handles the common case where GLM appends extra text after JSON start = text.find("{") if start >= 0: depth = 0 in_string = False escape = False for j in range(start, len(text)): ch = text[j] if escape: escape = False continue if ch == '\\' and in_string: escape = True continue if ch == '"' and not escape: in_string = not in_string continue if in_string: continue if ch == '{': depth += 1 elif ch == '}': depth -= 1 if depth == 0: return json.loads(text[start:j + 1]) raise ValueError(f"No JSON found in response: {text[:200]}") def extract_plant(article_text: str) -> Plant | None: """Extract structured plant data from article text.""" # Truncate very long articles to avoid token limits if len(article_text) > 8000: article_text = article_text[:8000] + "\n[... текст обрезан]" full_prompt = EXTRACTION_PROMPT + article_text for attempt in range(MAX_RETRIES): try: response = call_llm(full_prompt) data = extract_json_from_response(response) plant = Plant.model_validate(data) plant.raw_text = article_text return plant except (json.JSONDecodeError, ValidationError, ValueError) as e: print(f"\n Attempt {attempt + 1}/{MAX_RETRIES} failed: {type(e).__name__}: {str(e)[:100]}") if attempt < MAX_RETRIES - 1: full_prompt = ( EXTRACTION_PROMPT + article_text + f"\n\nОШИБКА: {e}\nВерни корректный JSON без обёрток." ) time.sleep(1) except httpx.HTTPStatusError as e: print(f"\n API error: {e.response.status_code} {e.response.text[:200]}") time.sleep(2) except (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.TimeoutException) as e: print(f"\n Timeout: {e}") time.sleep(3) return None def main(): EXTRACTED_DIR.mkdir(parents=True, exist_ok=True) # Load article index index_file = ARTICLES_DIR / "index.json" if not index_file.exists(): print(f"ERROR: {index_file} not found. Run stage2_split.py first.") sys.exit(1) index = json.loads(index_file.read_text()) # Check for --test flag (process first N only) test_mode = "--test" in sys.argv if test_mode: index = index[:10] print(f"TEST MODE: processing first {len(index)} articles\n") # Skip already extracted skip_existing = "--skip-existing" in sys.argv results = [] errors = [] for entry in index: i = entry["index"] name = entry["name_ru"] latin = entry["name_latin"] safe_latin = latin.replace(' ', '_') # Check if already extracted out_file = EXTRACTED_DIR / f"{i:03d}_{safe_latin}.json" if skip_existing and out_file.exists(): data = json.loads(out_file.read_text()) results.append(data) print(f"[{i}] {name} — cached") continue # Find article file fname = ARTICLES_DIR / f"{i:03d}_{safe_latin}.txt" if not fname.exists(): print(f"[{i}] File not found: {fname}") errors.append({"index": i, "name": name, "error": "file not found"}) continue article_text = fname.read_text(encoding="utf-8") print(f"[{i}] {name} ({latin})...", end=" ", flush=True) plant = extract_plant(article_text) if plant: out_file.write_text( plant.model_dump_json(indent=2, exclude={"raw_text"}), encoding="utf-8", ) results.append(plant.model_dump(exclude={"raw_text"})) print("OK") else: errors.append({"index": i, "name": name, "error": "extraction failed"}) print("FAILED") # Rate limiting time.sleep(0.5) # Save combined results combined_file = EXTRACTED_DIR / "all_plants.json" combined_file.write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8") print(f"\nResults: {len(results)} extracted, {len(errors)} errors") if errors: print("Errors:") for e in errors: print(f" [{e['index']}] {e['name']}: {e['error']}") if __name__ == "__main__": main()