diff --git a/pyproject.toml b/pyproject.toml
index 2d861f8..a39383d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
name = "smeta-railway"
version = "0.1.0"
description = "Resource-index estimate generator for railway capital repair (GESN-2022, FGIS CS)"
-requires-python = ">=3.11"
+requires-python = ">=3.10"
dependencies = [
"openpyxl>=3.1",
"typer>=0.12",
diff --git a/scripts/fetch_fssc_all_regions.py b/scripts/fetch_fssc_all_regions.py
new file mode 100644
index 0000000..cd96794
--- /dev/null
+++ b/scripts/fetch_fssc_all_regions.py
@@ -0,0 +1,213 @@
+#!/usr/bin/env python3
+"""
+Download ФССЦ-2022 (material & machine prices) from ФГИС ЦС API for ALL regions.
+
+~86 regions × ~480 groups = ~41K requests at 0.2s = ~2.3 hours.
+Saves incrementally — safe to interrupt and resume.
+
+Usage:
+ python scripts/fetch_fssc_all_regions.py # all regions
+ python scripts/fetch_fssc_all_regions.py --status # show progress
+ python scripts/fetch_fssc_all_regions.py --region 323 # specific region (Moscow)
+"""
+
+import json
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+API = "https://fgiscs.minstroyrf.ru/api"
+BASE_DIR = Path(__file__).parent.parent
+OUT_DIR = BASE_DIR / "data" / "fssc_2022"
+DELAY = 0.2 # seconds between requests
+
+
+def api_get(endpoint: str, params: str = "") -> dict | list | None:
+ url = f"{API}/{endpoint}?{params}" if params else f"{API}/{endpoint}"
+ try:
+ r = subprocess.run(
+ ["curl", "-s", "--noproxy", "*", "--max-time", "15", url,
+ "-H", "User-Agent: Mozilla/5.0", "-H", "Accept: application/json"],
+ capture_output=True, text=True,
+ env={k: v for k, v in os.environ.items()
+ if k.upper() not in ("HTTPS_PROXY", "HTTP_PROXY")},
+ )
+ if r.returncode == 0 and r.stdout:
+ return json.loads(r.stdout)
+ except Exception as e:
+ print(f" API error: {e}")
+ return None
+
+
+def get_regions() -> list[dict]:
+ """Get all 86 regions."""
+ data = api_get("EstimatedPrice/CountrySubjects")
+ return data if data else []
+
+
+def get_zones(subject_id: int) -> list[dict]:
+ """Get price zones for a region."""
+ data = api_get("EstimatedPrice/PriceZones", f"subjectId={subject_id}")
+ return data if data else []
+
+
+def get_latest_period(zone_id: int) -> dict | None:
+ """Get the latest available period for a zone."""
+ data = api_get("EstimatedPrice/Periods", f"priceZoneId={zone_id}")
+ if data and len(data) > 0:
+ return data[0] # first = latest
+ return None
+
+
+def fetch_zone_resources(zone_id: int, period_id: int, is_materials: bool) -> dict:
+ """Fetch all resources (materials or machines) for a zone+period."""
+ kind = "materials" if is_materials else "machines"
+ groups = api_get(
+ "IndicesForResourcesGroups/GetTreeViewResourceGroups",
+ f"priceZoneId={zone_id}&periodId={period_id}&isMaterials={'true' if is_materials else 'false'}"
+ ) or []
+
+ resources = {}
+ for g in groups:
+ gid = g["value"]
+ gname = g["text"]
+ items = api_get(
+ "IndicesForResourcesGroups/GetTreeViewResourcesInGroup",
+ f"groupId={gid}&priceZoneId={zone_id}&periodId={period_id}"
+ )
+ if items:
+ for item in items:
+ code = item.get("fsbcFullCode", "")
+ resources[code] = {
+ "name": item.get("fsbcName", ""),
+ "unit": item.get("unitName", ""),
+ "price": item.get("price", ""),
+ "index": item.get("index", ""),
+ "group": gname,
+ }
+ time.sleep(DELAY)
+
+ return resources
+
+
+def fetch_region(subject_id: int, region_name: str):
+ """Fetch all data for one region (all zones)."""
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
+ safe_name = region_name.replace(" ", "_").replace("/", "_")
+ out_file = OUT_DIR / f"region_{subject_id}_{safe_name}.json"
+
+ # Check if already done
+ if out_file.exists():
+ existing = json.loads(out_file.read_text(encoding="utf-8"))
+ if existing.get("complete"):
+ print(f" ✓ {region_name} — already complete, skipping")
+ return existing
+
+ zones = get_zones(subject_id)
+ if not zones:
+ print(f" ✗ {region_name} — no zones")
+ return None
+
+ result = {
+ "region": region_name,
+ "subject_id": subject_id,
+ "zones": {},
+ "complete": False,
+ }
+
+ for zone in zones:
+ zone_id = zone["id"]
+ zone_name = zone["name"]
+ print(f" Zone: {zone_name} (id={zone_id})")
+
+ period = get_latest_period(zone_id)
+ if not period:
+ print(f" No periods available")
+ continue
+
+ period_id = period["id"]
+ period_name = period["name"]
+ print(f" Period: {period_name}")
+
+ materials = fetch_zone_resources(zone_id, period_id, is_materials=True)
+ machines = fetch_zone_resources(zone_id, period_id, is_materials=False)
+
+ result["zones"][zone_name] = {
+ "zone_id": zone_id,
+ "period": period_name,
+ "period_id": period_id,
+ "materials_count": len(materials),
+ "machines_count": len(machines),
+ "materials": materials,
+ "machines": machines,
+ }
+
+ print(f" {len(materials)} materials, {len(machines)} machines")
+
+ # Save incrementally after each zone
+ out_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
+
+ result["complete"] = True
+ out_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
+ return result
+
+
+def show_status():
+ """Show download progress."""
+ regions = get_regions()
+ done = 0
+ total_materials = 0
+ total_machines = 0
+
+ for f in sorted(OUT_DIR.glob("region_*.json")):
+ data = json.loads(f.read_text(encoding="utf-8"))
+ if data.get("complete"):
+ done += 1
+ for z in data.get("zones", {}).values():
+ total_materials += z.get("materials_count", 0)
+ total_machines += z.get("machines_count", 0)
+
+ print(f"\n{'='*60}")
+ print(f" ФССЦ-2022 Download Status")
+ print(f"{'='*60}")
+ print(f" Regions: {done}/{len(regions)} complete")
+ print(f" Materials: {total_materials:,}")
+ print(f" Machines: {total_machines:,}")
+ remaining = len(regions) - done
+ if remaining > 0:
+ print(f" Estimated time: ~{remaining * 2} minutes")
+
+
+def main():
+ if "--status" in sys.argv:
+ show_status()
+ return
+
+ specific_region = None
+ if "--region" in sys.argv:
+ idx = sys.argv.index("--region")
+ if idx + 1 < len(sys.argv):
+ specific_region = int(sys.argv[idx + 1])
+
+ regions = get_regions()
+ print(f"Total regions: {len(regions)}")
+
+ for i, region in enumerate(regions):
+ sid = region["id"]
+ name = region["name"]
+
+ if specific_region and sid != specific_region:
+ continue
+
+ print(f"\n[{i+1}/{len(regions)}] {name} (id={sid})")
+ fetch_region(sid, name)
+
+ print(f"\n{'='*60}")
+ print(f" All done!")
+ show_status()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/fetch_gesn_api.py b/scripts/fetch_gesn_api.py
new file mode 100644
index 0000000..77e5c6b
--- /dev/null
+++ b/scripts/fetch_gesn_api.py
@@ -0,0 +1,191 @@
+#!/usr/bin/env python3
+"""
+Fetch all GESN-2022 norms via cs.smetnoedelo.ru API.
+Much faster than HTML parsing — structured JSON responses.
+
+Usage:
+ python scripts/fetch_gesn_api.py # all 47 collections
+ python scripts/fetch_gesn_api.py 01 06 07 08 # specific collections
+ python scripts/fetch_gesn_api.py --priority # top 10 most used
+"""
+
+import html
+import json
+import os
+import subprocess
+import sys
+import time
+
+API_URL = "https://cs.smetnoedelo.ru/api/"
+TOKEN = "gybniCv9JwdSR2UYQKXxu6N0"
+OUTPUT_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "gesn_extra")
+DELAY = 1 # 1 sec between API calls (polite)
+
+PRIORITY_COLLECTIONS = ["01", "06", "07", "08", "09", "10", "11", "12", "15", "28"]
+
+
+def api_call(params: dict) -> dict | None:
+ """Make API request, bypassing proxy."""
+ query = "&".join(f"{k}={v}" for k, v in params.items())
+ url = f"{API_URL}?token={TOKEN}&{query}"
+ try:
+ result = subprocess.run(
+ ["curl", "-s", "--noproxy", "*", "--max-time", "15", url,
+ "-H", "User-Agent: Mozilla/5.0"],
+ capture_output=True, text=True,
+ env={k: v for k, v in os.environ.items()
+ if k not in ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")},
+ )
+ if result.returncode == 0 and result.stdout:
+ return json.loads(result.stdout)
+ except Exception as e:
+ print(f" API error: {e}")
+ return None
+
+
+def get_all_codes_in_section(section: str) -> list[str]:
+ """Recursively get all norm codes in a section."""
+ data = api_call({"base": "gesn2", "section": section})
+ time.sleep(DELAY)
+ if not data:
+ return []
+
+ codes = []
+ subsections = data.get("SECTIONS", [])
+ norms = data.get("NORMS", [])
+
+ # If norms are listed directly
+ for norm in norms:
+ code = norm.get("CODE", "")
+ if code:
+ codes.append(code)
+
+ # Recurse into subsections
+ for sub in subsections:
+ sub_section = sub.get("SECTION", "")
+ if sub_section:
+ codes.extend(get_all_codes_in_section(sub_section))
+
+ return codes
+
+
+def fetch_norm(code: str) -> dict | None:
+ """Fetch a single norm's data."""
+ data = api_call({"base": "gesn2", "code": code})
+ time.sleep(DELAY)
+ if not data:
+ return None
+
+ name = html.unescape(data.get("BASE_NAME", ""))
+ unit = ""
+ # Extract unit from COMPOSITION
+ composition = data.get("COMPOSITION", {})
+ for res in composition.get("RESOURCES", []):
+ if res.get("TYPE") == "unit":
+ unit = res.get("NAME", "")
+ break
+
+ # Extract OZP, EM, materials count
+ resources = composition.get("RESOURCES", [])
+ machines = [r for r in resources if r.get("TYPE") == "machine"]
+ materials = [r for r in resources if r.get("TYPE") == "material"]
+
+ return {
+ "name": name,
+ "unit": unit,
+ "machines_count": len(machines),
+ "materials_count": len(materials),
+ }
+
+
+def fetch_collection(collection_num: str):
+ """Fetch all norms for one GESN collection."""
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+ output_file = os.path.join(OUTPUT_DIR, f"gesn_{collection_num}.json")
+
+ # Load existing
+ existing = {}
+ if os.path.exists(output_file):
+ with open(output_file, encoding="utf-8") as f:
+ existing = json.load(f)
+
+ # Step 1: discover all codes via section tree
+ section_id = f"sbor-{collection_num}"
+ print(f" Discovering codes in section {section_id}...")
+ all_codes = get_all_codes_in_section(section_id)
+ print(f" Found {len(all_codes)} codes in section tree")
+
+ # If section tree didn't return norm codes, enumerate
+ if not all_codes:
+ print(" Section tree empty, enumerating...")
+ # Try tables directly
+ data = api_call({"base": "gesn2", "section": section_id})
+ if data:
+ for sub in data.get("SECTIONS", []):
+ sub_data = api_call({"base": "gesn2", "section": sub["SECTION"]})
+ time.sleep(DELAY)
+ if sub_data:
+ for sub2 in sub_data.get("SECTIONS", []):
+ sub2_data = api_call({"base": "gesn2", "section": sub2["SECTION"]})
+ time.sleep(DELAY)
+ if sub2_data:
+ for sub3 in sub2_data.get("SECTIONS", []):
+ # Table level — get norms
+ sub3_data = api_call({"base": "gesn2", "section": sub3["SECTION"]})
+ time.sleep(DELAY)
+ if sub3_data:
+ for norm in sub3_data.get("NORMS", []):
+ code = norm.get("CODE", "")
+ if code:
+ all_codes.append(code)
+ print(f" Found {len(all_codes)} codes after deep enumeration")
+
+ # Step 2: fetch each norm
+ new_count = 0
+ for i, code_raw in enumerate(all_codes):
+ # Normalize code (remove "ГЭСН " prefix)
+ code = code_raw.replace("ГЭСН ", "").strip()
+ if code in existing:
+ continue
+
+ norm = fetch_norm(code)
+ if norm:
+ existing[code] = norm
+ new_count += 1
+ print(f" [{i+1}/{len(all_codes)}] {code}: {norm['name'][:60]} [{norm['unit']}]")
+
+ # Save incrementally
+ if new_count % 10 == 0:
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(existing, f, ensure_ascii=False, indent=2)
+ else:
+ existing[code] = {"error": "api_failed"}
+
+ # Final save
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(existing, f, ensure_ascii=False, indent=2)
+
+ valid = sum(1 for v in existing.values() if "error" not in v)
+ print(f" ГЭСН-{collection_num}: {valid} valid norms saved to {output_file}")
+ return valid
+
+
+if __name__ == "__main__":
+ if "--priority" in sys.argv:
+ collections = PRIORITY_COLLECTIONS
+ elif len(sys.argv) > 1:
+ collections = [a for a in sys.argv[1:] if a.isdigit() or (len(a) == 2 and a[0] == "0")]
+ else:
+ # All 47
+ collections = [f"{i:02d}" for i in range(1, 48)]
+
+ total = 0
+ for col in collections:
+ print(f"\n{'='*60}")
+ print(f" ГЭСН-{col}")
+ print(f"{'='*60}")
+ total += fetch_collection(col)
+
+ print(f"\n{'='*60}")
+ print(f" TOTAL: {total} norms across {len(collections)} collections")
+ print(f"{'='*60}")
diff --git a/scripts/fetch_gesn_collection.py b/scripts/fetch_gesn_collection.py
new file mode 100644
index 0000000..1af3a3c
--- /dev/null
+++ b/scripts/fetch_gesn_collection.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+"""
+Fetch GESN norms for a specific collection from cs.smetnoedelo.ru.
+Discovers all codes by iterating sections and tables.
+
+Usage:
+ python scripts/fetch_gesn_collection.py 01 # GESN-01 (земляные)
+ python scripts/fetch_gesn_collection.py 06 # GESN-06 (бетонные)
+ python scripts/fetch_gesn_collection.py 01 06 07 08 # multiple
+"""
+
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+
+BASE_URL = "https://cs.smetnoedelo.ru/gesn2/gesn{code}.html"
+OUTPUT_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "gesn_extra")
+DELAY = 2 # seconds between requests
+
+
+def fetch_page(code: str) -> str | None:
+ url = BASE_URL.format(code=code)
+ try:
+ result = subprocess.run(
+ ["curl", "-s", "--noproxy", "*", "--max-time", "15",
+ url, "-H", "User-Agent: Mozilla/5.0"],
+ capture_output=True, text=True,
+ env={k: v for k, v in os.environ.items()
+ if k not in ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")},
+ )
+ if result.returncode != 0 or not result.stdout:
+ return None
+ return result.stdout
+ except Exception:
+ return None
+
+
+def extract_name_unit(html: str) -> tuple[str, str] | None:
+ """Extract norm name and unit from HTML meta description."""
+ m = re.search(r'Расценка ГЭСН \d{2}-\d{2}-\d{3}-\d{2}\.\s*(.*?)(?:\s*—\s*|\s*—\s*|\.\s*ГЭСН)(.*?)', html)
+ if m:
+ name = m.group(1).strip()
+ unit_m = re.search(r'(\d+\s*\w+)$', name)
+ return name, ""
+ return None
+
+
+def discover_codes(collection: str) -> list[str]:
+ """Discover all valid codes for a collection by iterating."""
+ codes = []
+ for section in range(1, 30): # sections 01-29
+ for table in range(1, 300): # tables 001-299
+ for variant in range(1, 50): # variants 01-49
+ code = f"{collection}-{section:02d}-{table:03d}-{variant:02d}"
+ yield code
+
+
+def scan_collection(collection: str):
+ """Scan a GESN collection, saving results progressively."""
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+ output_file = os.path.join(OUTPUT_DIR, f"gesn_{collection}.json")
+
+ # Load existing
+ existing = {}
+ if os.path.exists(output_file):
+ with open(output_file, encoding="utf-8") as f:
+ existing = json.load(f)
+
+ # Strategy: scan section by section, table by table
+ # Stop table iteration when 3 consecutive 404s
+ # Stop section iteration when whole section is empty
+ total_found = len(existing)
+ total_404 = 0
+
+ for section in range(1, 30):
+ section_found = 0
+ consecutive_empty_tables = 0
+
+ for table in range(1, 300):
+ consecutive_404 = 0
+
+ for variant in range(1, 50):
+ code = f"{collection}-{section:02d}-{table:03d}-{variant:02d}"
+
+ if code in existing:
+ if "error" not in existing[code]:
+ section_found += 1
+ continue
+
+ html = fetch_page(code)
+ time.sleep(DELAY)
+
+ if not html:
+ consecutive_404 += 1
+ if consecutive_404 >= 3:
+ break
+ continue
+
+ if "404" in html and "не найден" in html.lower():
+ consecutive_404 += 1
+ existing[code] = {"error": "not_found_404"}
+ total_404 += 1
+ if consecutive_404 >= 3:
+ break
+ continue
+
+ # Extract name and unit from meta
+ meta = re.search(
+ r' 1 else ""
+ else:
+ # Try title
+ title_m = re.search(r'
Расценка ГЭСН[^.]*\.\s*(.*?)\.\s*ГЭСН', html)
+ name = title_m.group(1).strip() if title_m else code
+ unit = ""
+
+ existing[code] = {"name": name, "unit": unit}
+ total_found += 1
+ section_found += 1
+ consecutive_404 = 0
+ consecutive_empty_tables = 0
+
+ print(f" [{code}] {name[:60]}... [{unit}]")
+
+ # Save after each find
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(existing, f, ensure_ascii=False, indent=2)
+
+ # If whole table was empty (no variants found)
+ if consecutive_404 >= 3 and variant <= 3:
+ consecutive_empty_tables += 1
+ if consecutive_empty_tables >= 5:
+ print(f" Section {collection}-{section:02d}: {section_found} norms, stopping (5 empty tables)")
+ break
+
+ if section_found == 0 and section > 3:
+ print(f" Collection {collection}: section {section:02d} empty, stopping")
+ break
+ elif section_found > 0:
+ print(f" Section {collection}-{section:02d}: {section_found} norms found")
+
+ # Final save
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(existing, f, ensure_ascii=False, indent=2)
+
+ valid = sum(1 for v in existing.values() if "error" not in v)
+ print(f"\nCollection ГЭСН-{collection}: {valid} valid norms, {total_404} 404s")
+ print(f"Saved to {output_file}")
+ return valid
+
+
+if __name__ == "__main__":
+ collections = sys.argv[1:] or ["01"]
+ for col in collections:
+ print(f"\n{'='*60}")
+ print(f" Scanning ГЭСН-{col}")
+ print(f"{'='*60}")
+ scan_collection(col)
diff --git a/scripts/fetch_gesn_daily.py b/scripts/fetch_gesn_daily.py
new file mode 100644
index 0000000..08c1382
--- /dev/null
+++ b/scripts/fetch_gesn_daily.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""
+Daily GESN fetcher — uses up to 95 API calls per run (keeps 5 reserve).
+Designed for cron: runs once a day until all norms are fetched.
+
+Strategy:
+1. Scan all gesn_XX.json files for entries with "error": "api_failed"
+2. Retry those first (they might work now)
+3. Then discover new codes via section tree for collections not yet fetched
+4. Stop at 95 API calls
+
+Usage:
+ python scripts/fetch_gesn_daily.py # auto mode
+ python scripts/fetch_gesn_daily.py --status # show what's left
+ python scripts/fetch_gesn_daily.py --dry-run # show plan without fetching
+
+Cron (add via crontab -e):
+ 0 3 * * * cd /Volumes/Backup/Python_projects/smeta-railway && .venv/bin/python scripts/fetch_gesn_daily.py >> /tmp/gesn_daily.log 2>&1
+"""
+
+import html as html_mod
+import json
+import os
+import subprocess
+import sys
+import time
+from datetime import datetime
+from pathlib import Path
+
+API_URL = "https://cs.smetnoedelo.ru/api/"
+TOKEN = "gybniCv9JwdSR2UYQKXxu6N0"
+BASE_DIR = Path(__file__).parent.parent
+OUTPUT_DIR = BASE_DIR / "data" / "gesn_extra"
+STATE_FILE = OUTPUT_DIR / "_daily_state.json"
+LOG_FILE = Path("/tmp/gesn_daily.log")
+DAILY_LIMIT = 95 # keep 5 reserve
+DELAY = 1
+
+
+def api_call(params: dict) -> dict | None:
+ """Make API request, bypassing proxy."""
+ query = "&".join(f"{k}={v}" for k, v in params.items())
+ url = f"{API_URL}?token={TOKEN}&{query}"
+ try:
+ result = subprocess.run(
+ ["curl", "-s", "--noproxy", "*", "--max-time", "15", url,
+ "-H", "User-Agent: Mozilla/5.0"],
+ capture_output=True, text=True,
+ env={k: v for k, v in os.environ.items()
+ if k not in ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")},
+ )
+ if result.returncode == 0 and result.stdout:
+ data = json.loads(result.stdout)
+ # Check for rate limit
+ reqs = data.get("REQUESTS", {})
+ if reqs.get("BALANCE") == "0" and "BASE_NAME" not in data and "SECTIONS" not in data:
+ print(f" ⚠ API limit reached (USED={reqs.get('USED')})")
+ return None
+ return data
+ except Exception as e:
+ print(f" API error: {e}")
+ return None
+
+
+def check_balance() -> dict:
+ """Check API balance without wasting a query."""
+ data = api_call({"base": "gesn2", "code": "28-01-001-01"})
+ if data:
+ return data.get("REQUESTS", {})
+ return {}
+
+
+def fetch_norm(code: str, base: str = "gesn2") -> dict | None:
+ """Fetch a single norm's data from GESN or FER."""
+ data = api_call({"base": base, "code": code})
+ time.sleep(DELAY)
+ if not data:
+ return None
+
+ name = html_mod.unescape(data.get("BASE_NAME", ""))
+ if not name:
+ return None
+
+ unit = ""
+ composition = data.get("COMPOSITION", {})
+ for res in composition.get("RESOURCES", []):
+ if res.get("TYPE") == "unit":
+ unit = res.get("NAME", "")
+ break
+
+ resources = composition.get("RESOURCES", [])
+ machines = [r for r in resources if r.get("TYPE") == "machine"]
+ materials = [r for r in resources if r.get("TYPE") == "material"]
+
+ return {
+ "name": name,
+ "unit": unit,
+ "machines_count": len(machines),
+ "materials_count": len(materials),
+ }
+
+
+def get_status() -> dict:
+ """Get current download status."""
+ status = {"collections": {}, "total_valid": 0, "total_errors": 0, "api_failed": 0}
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+
+ for f in sorted(OUTPUT_DIR.glob("gesn_*.json")):
+ col = f.stem.replace("gesn_", "")
+ data = json.loads(f.read_text(encoding="utf-8"))
+ valid = sum(1 for v in data.values() if "error" not in v)
+ api_fail = sum(1 for v in data.values()
+ if isinstance(v, dict) and v.get("error") == "api_failed")
+ not_found = sum(1 for v in data.values()
+ if isinstance(v, dict) and v.get("error") == "not_found_404")
+ status["collections"][col] = {
+ "valid": valid, "api_failed": api_fail, "not_found": not_found
+ }
+ status["total_valid"] += valid
+ status["total_errors"] += not_found
+ status["api_failed"] += api_fail
+
+ return status
+
+
+def find_retry_candidates() -> list[tuple[str, str]]:
+ """Find (collection, code) pairs that had api_failed errors."""
+ candidates = []
+ for f in sorted(OUTPUT_DIR.glob("gesn_*.json")):
+ col = f.stem.replace("gesn_", "")
+ data = json.loads(f.read_text(encoding="utf-8"))
+ for code, v in data.items():
+ if isinstance(v, dict) and v.get("error") == "api_failed":
+ candidates.append((col, code))
+ return candidates
+
+
+def run_daily():
+ """Run daily fetch cycle."""
+ now = datetime.now().strftime("%Y-%m-%d %H:%M")
+ print(f"\n{'='*60}")
+ print(f" GESN Daily Fetch — {now}")
+ print(f"{'='*60}")
+
+ # Check balance first
+ balance = check_balance()
+ used = int(balance.get("USED", "0"))
+ remaining = int(balance.get("BALANCE", "0"))
+ print(f" API: USED={used}, BALANCE={remaining}")
+
+ if remaining == 0:
+ print(" ⚠ No API balance remaining. Try again later.")
+ return
+
+ budget = min(remaining, DAILY_LIMIT)
+ calls_made = 1 # already used one for balance check
+ fetched = 0
+
+ # Phase 1: retry api_failed codes
+ retries = find_retry_candidates()
+ if retries:
+ print(f"\n Phase 1: Retrying {len(retries)} api_failed codes (budget: {budget - calls_made})")
+ for col, code in retries:
+ if calls_made >= budget:
+ break
+
+ norm = fetch_norm(code)
+ calls_made += 1
+
+ if norm:
+ # Update the file
+ fpath = OUTPUT_DIR / f"gesn_{col}.json"
+ data = json.loads(fpath.read_text(encoding="utf-8"))
+ data[code] = norm
+ fpath.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
+ fetched += 1
+ print(f" ✓ {code}: {norm['name'][:50]}")
+ else:
+ print(f" ✗ {code}: still failing")
+
+ # Phase 2: fetch FER norms (same codes as GESN, base=fer)
+ FER_DIR = BASE_DIR / "data" / "fer_extra"
+ FER_DIR.mkdir(parents=True, exist_ok=True)
+ if calls_made < budget:
+ # Pick collections that have GESN data but no FER yet
+ fer_fetched = 0
+ for gesn_file in sorted(OUTPUT_DIR.glob("gesn_*.json")):
+ if calls_made >= budget:
+ break
+ col = gesn_file.stem.replace("gesn_", "")
+ fer_file = FER_DIR / f"fer_{col}.json"
+ gesn_data = json.loads(gesn_file.read_text(encoding="utf-8"))
+ fer_data = json.loads(fer_file.read_text(encoding="utf-8")) if fer_file.exists() else {}
+
+ # Find GESN codes not yet in FER
+ for code in gesn_data:
+ if calls_made >= budget:
+ break
+ if code in fer_data or "error" in gesn_data[code]:
+ continue
+ norm = fetch_norm(code, base="fer")
+ calls_made += 1
+ if norm:
+ fer_data[code] = norm
+ fer_fetched += 1
+ if fer_fetched % 10 == 0:
+ fer_file.write_text(json.dumps(fer_data, ensure_ascii=False, indent=2), encoding="utf-8")
+ else:
+ fer_data[code] = {"error": "api_failed"}
+
+ if fer_data:
+ fer_file.write_text(json.dumps(fer_data, ensure_ascii=False, indent=2), encoding="utf-8")
+
+ if fer_fetched:
+ print(f"\n Phase 2: {fer_fetched} FER norms fetched")
+ fetched += fer_fetched
+
+ print(f"\n Done: {fetched} norms fetched, {calls_made} API calls used")
+
+ # Save state
+ state = {
+ "last_run": now,
+ "calls_made": calls_made,
+ "fetched": fetched,
+ "balance_before": remaining,
+ }
+ STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
+
+
+def show_status():
+ """Show current status."""
+ status = get_status()
+ print(f"\n{'='*60}")
+ print(f" GESN Download Status")
+ print(f"{'='*60}")
+ print(f" Valid norms: {status['total_valid']:,}")
+ print(f" Not found: {status['total_errors']:,}")
+ print(f" API failed: {status['api_failed']:,}")
+
+ if status['api_failed'] > 0:
+ print(f"\n Collections with api_failed:")
+ for col, info in status['collections'].items():
+ if info['api_failed'] > 0:
+ print(f" ГЭСН-{col}: {info['api_failed']} failed")
+ print(f"\n Days to complete: ~{status['api_failed'] // DAILY_LIMIT + 1}")
+ else:
+ print(f"\n ✓ All available norms downloaded!")
+
+ # Check balance
+ balance = check_balance()
+ print(f"\n API balance: USED={balance.get('USED', '?')}, BALANCE={balance.get('BALANCE', '?')}")
+
+ # Last run
+ if STATE_FILE.exists():
+ state = json.loads(STATE_FILE.read_text())
+ print(f" Last run: {state.get('last_run', '?')}, fetched: {state.get('fetched', 0)}")
+
+
+if __name__ == "__main__":
+ if "--status" in sys.argv:
+ show_status()
+ elif "--dry-run" in sys.argv:
+ retries = find_retry_candidates()
+ print(f"Would retry {len(retries)} api_failed codes")
+ for col, code in retries[:10]:
+ print(f" {code}")
+ if len(retries) > 10:
+ print(f" ... and {len(retries) - 10} more")
+ else:
+ run_daily()
diff --git a/scripts/verify_knowledge_base.py b/scripts/verify_knowledge_base.py
new file mode 100644
index 0000000..e00d42d
--- /dev/null
+++ b/scripts/verify_knowledge_base.py
@@ -0,0 +1,338 @@
+#!/usr/bin/env python3
+"""
+Verify knowledge base integrity: documents, RAG index, data files.
+
+Usage:
+ python scripts/verify_knowledge_base.py # full check
+ python scripts/verify_knowledge_base.py --docs # only documents
+ python scripts/verify_knowledge_base.py --rag # only RAG index
+ python scripts/verify_knowledge_base.py --data # only JSON data
+"""
+
+import json
+import os
+import pickle
+import sys
+from pathlib import Path
+
+BASE_DIR = Path(__file__).parent.parent
+
+# ============================================================
+# Document registry: path → (min_pages, markers_in_first_3_pages)
+# markers are checked case-insensitive in decoded text
+# ============================================================
+PDF_DOCS = {
+ # ГЭСН (spot-check 5 of 47)
+ "literature/gesn/GESN01.pdf": (200, ["приложение", "приказ"]),
+ "literature/gesn/GESN06.pdf": (50, ["приложение", "приказ"]),
+ "literature/gesn/GESN15.pdf": (50, ["приложение"]),
+ # GESN28 is GESN-28_full.pdf, checked separately
+ "literature/gesn/GESN47.pdf": (30, ["приложение"]),
+ "literature/GESN-28_full.pdf": (100, ["желез"]),
+ # Supplements - приказы ФСНБ
+ "literature/supplements/prikaz_421_04.08.2020_metodika.pdf": (200, ["421", "методик"]),
+ "literature/supplements/prikaz_774_11.12.2020_sp.pdf": (20, ["прибыл"]),
+ "literature/supplements/prikaz_1046_30.12.2021_base.pdf": (1, ["минстро"]),
+ "literature/supplements/FRSN_20_02_2026.pdf": (100, ["реестр"]),
+ # ФССЦ
+ "literature/supplements/fssc_part1_materialy.pdf": (300, ["материал"]),
+ "literature/supplements/fssc_part2_konstruktsii.pdf": (80, ["конструкц"]),
+ "literature/supplements/fssc_part3_santekhnika.pdf": (200, ["санитар"]),
+ "literature/supplements/fssc_part4_beton.pdf": (250, ["бетон"]),
+ "literature/supplements/fssc_part5_montazh.pdf": (300, ["монтаж"]),
+ # ФСЭМ
+ "literature/supplements/fsem_mashiny.pdf": (50, ["машин"]),
+ # ФЕР
+ "literature/supplements/fer_stroitelnye.pdf": (1000, ["расценк"]),
+ "literature/supplements/ferr_remontno_stroitelnye.pdf": (30, ["ремонтн"]),
+ "literature/supplements/ferm_montazh.pdf": (500, ["монтаж"]),
+ "literature/supplements/ferp_puskonaladka.pdf": (100, ["пусконаладоч"]),
+ "literature/supplements/ferkr_kapremont.pdf": (20, ["капитальн"]),
+ # МДС и методики
+ "literature/supplements/mds_81-35-2001.pdf": (50, ["стоимост"]),
+ "literature/supplements/metodika_nr.pdf": (20, ["накладн"]),
+ "literature/supplements/metodika_sp.pdf": (15, ["прибыл"]),
+ "literature/supplements/metodika_vzis.pdf": (10, ["временн"]),
+ "literature/supplements/metodika_zimnee.pdf": (30, ["зимн"]),
+ "literature/supplements/metodika_326pr_indeksy.pdf": (30, ["индекс"]),
+ # ГСН
+ "literature/supplements/gsn_81-05-01_vrem_zdaniya.pdf": (5, ["временн"]),
+ "literature/supplements/gsn_81-05-02_zimnee.pdf": (30, ["зимн"]),
+ "literature/supplements/gsnr_81-05-01_vrem_zdaniya_remont.pdf": (3, ["ремонтн"]),
+ "literature/supplements/gsnr_81-05-02_zimnee_remont.pdf": (10, ["зимн"]),
+}
+
+HTM_DOCS = {
+ "literature/supplements/prikaz_812_21.12.2020_nr.htm": (50000, ["накладн", "812"]),
+ "literature/supplements/gradostroitelny_kodeks_190fz.htm": (100000, ["градостроительн"]),
+}
+
+# Expected GESN PDF count
+EXPECTED_GESN_PDFS = 46 # 01-47 minus 28 (separate file)
+
+# Expected RAG sources (minimum)
+EXPECTED_RAG_SOURCES = 60
+EXPECTED_RAG_CHUNKS = 15000
+
+# Expected JSON data
+EXPECTED_GESN_JSONS = 47
+EXPECTED_MIN_NORMS = 150000
+
+
+def check_pdf(path: str, min_pages: int, markers: list[str]) -> tuple[bool, str]:
+ """Check a PDF file: exists, openable, has min pages, contains markers."""
+ full = BASE_DIR / path
+ if not full.exists():
+ return False, "MISSING"
+ try:
+ import fitz
+ doc = fitz.open(str(full))
+ pages = len(doc)
+ if pages < min_pages:
+ doc.close()
+ return False, f"TOO SHORT: {pages} pages (need {min_pages}+)"
+ # Check markers in first 5 pages
+ text = ""
+ for p in range(min(5, pages)):
+ text += doc[p].get_text().lower()
+ doc.close()
+ for m in markers:
+ if m.lower() not in text:
+ return False, f"MARKER '{m}' NOT FOUND in first 5 pages"
+ sz = full.stat().st_size / 1024 / 1024
+ return True, f"{pages} стр, {sz:.1f} MB"
+ except Exception as e:
+ return False, f"ERROR: {e}"
+
+
+def check_htm(path: str, min_size: int, markers: list[str]) -> tuple[bool, str]:
+ """Check an HTM file: exists, decodable, has markers."""
+ full = BASE_DIR / path
+ if not full.exists():
+ return False, "MISSING"
+ raw = full.read_bytes()
+ if len(raw) < min_size:
+ return False, f"TOO SMALL: {len(raw)} bytes (need {min_size}+)"
+ # Try decode
+ for enc in ("windows-1251", "utf-8"):
+ try:
+ text = raw.decode(enc).lower()
+ break
+ except UnicodeDecodeError:
+ continue
+ else:
+ return False, "DECODE FAILED"
+ for m in markers:
+ if m.lower() not in text:
+ return False, f"MARKER '{m}' NOT FOUND"
+ return True, f"{len(raw) // 1024} KB"
+
+
+def check_docs():
+ """Verify all documents."""
+ print("=" * 60)
+ print(" DOCUMENT VERIFICATION")
+ print("=" * 60)
+ ok = fail = 0
+
+ # Check GESN PDF count
+ gesn_dir = BASE_DIR / "literature" / "gesn"
+ gesn_pdfs = list(gesn_dir.glob("GESN*.pdf"))
+ if len(gesn_pdfs) >= EXPECTED_GESN_PDFS:
+ print(f" ✓ ГЭСН PDFs: {len(gesn_pdfs)} files")
+ ok += 1
+ else:
+ print(f" ✗ ГЭСН PDFs: {len(gesn_pdfs)} (expected {EXPECTED_GESN_PDFS}+)")
+ fail += 1
+
+ # Check PDFs
+ for path, (min_pages, markers) in PDF_DOCS.items():
+ success, msg = check_pdf(path, min_pages, markers)
+ name = Path(path).name
+ if success:
+ print(f" ✓ {name}: {msg}")
+ ok += 1
+ else:
+ print(f" ✗ {name}: {msg}")
+ fail += 1
+
+ # Check HTMs
+ for path, (min_size, markers) in HTM_DOCS.items():
+ success, msg = check_htm(path, min_size, markers)
+ name = Path(path).name
+ if success:
+ print(f" ✓ {name}: {msg}")
+ ok += 1
+ else:
+ print(f" ✗ {name}: {msg}")
+ fail += 1
+
+ # Check supplements count (И1-И17)
+ suppl_dir = BASE_DIR / "literature" / "supplements"
+ prikaz_pdfs = list(suppl_dir.glob("prikaz_*I*.pdf")) + list(suppl_dir.glob("prikaz_*_I*.pdf"))
+ i_count = len([f for f in suppl_dir.glob("prikaz_*.pdf")
+ if any(c in f.stem for c in ["_I1", "_I2", "_I3", "_I4", "_I5",
+ "_I6", "_I7", "_I8", "_I9"])])
+ print(f" {'✓' if i_count >= 10 else '✗'} Приказы-дополнения: {i_count} files")
+
+ print(f"\n Documents: {ok} OK, {fail} FAIL")
+ return fail == 0
+
+
+def check_rag():
+ """Verify RAG index."""
+ print("\n" + "=" * 60)
+ print(" RAG INDEX VERIFICATION")
+ print("=" * 60)
+ ok = fail = 0
+
+ index_dir = BASE_DIR / "src" / "smeta_railway" / "ai" / "index"
+ faiss_path = index_dir / "rag.faiss"
+ chunks_path = index_dir / "rag_chunks.pkl"
+
+ if not faiss_path.exists():
+ print(" ✗ rag.faiss MISSING")
+ return False
+ if not chunks_path.exists():
+ print(" ✗ rag_chunks.pkl MISSING")
+ return False
+
+ chunks = pickle.loads(chunks_path.read_bytes())
+ total = len(chunks)
+ sources = {}
+ for c in chunks:
+ s = c.get("source", "?")
+ sources[s] = sources.get(s, 0) + 1
+
+ if total >= EXPECTED_RAG_CHUNKS:
+ print(f" ✓ Chunks: {total:,} (threshold: {EXPECTED_RAG_CHUNKS:,})")
+ ok += 1
+ else:
+ print(f" ✗ Chunks: {total:,} (expected {EXPECTED_RAG_CHUNKS:,}+)")
+ fail += 1
+
+ if len(sources) >= EXPECTED_RAG_SOURCES:
+ print(f" ✓ Sources: {len(sources)} (threshold: {EXPECTED_RAG_SOURCES})")
+ ok += 1
+ else:
+ print(f" ✗ Sources: {len(sources)} (expected {EXPECTED_RAG_SOURCES}+)")
+ fail += 1
+
+ # Check key sources present
+ key_sources = ["GESN01.pdf", "GESN28.pdf", "prikaz_421_04.08.2020_metodika.pdf",
+ "prikaz_774_11.12.2020_sp.pdf", "gradostroitelny_kodeks_190fz.htm"]
+ # GESN28 might be GESN-28_full.pdf
+ for ks in key_sources:
+ found = ks in sources or ks.replace("GESN28", "GESN-28_full") in sources
+ print(f" {'✓' if found else '✗'} Source: {ks}")
+ if found:
+ ok += 1
+ else:
+ fail += 1
+
+ # Sample chunk quality (random 5 chunks, check text length)
+ import random
+ sample = random.sample(chunks, min(5, len(chunks)))
+ garbage = 0
+ for c in sample:
+ text = c.get("text", "")
+ if len(text) < 50 or text.count("□") > len(text) // 3:
+ garbage += 1
+ if garbage == 0:
+ print(f" ✓ Sample quality: {len(sample)} chunks OK")
+ ok += 1
+ else:
+ print(f" ⚠ Sample quality: {garbage}/{len(sample)} look like garbage")
+ fail += 1
+
+ print(f"\n RAG: {ok} OK, {fail} FAIL")
+ return fail == 0
+
+
+def check_data():
+ """Verify JSON data files."""
+ print("\n" + "=" * 60)
+ print(" DATA FILES VERIFICATION")
+ print("=" * 60)
+ ok = fail = 0
+
+ # GESN extra
+ gesn_dir = BASE_DIR / "data" / "gesn_extra"
+ if gesn_dir.exists():
+ jsons = list(gesn_dir.glob("gesn_*.json"))
+ total_valid = 0
+ for f in jsons:
+ data = json.loads(f.read_text(encoding="utf-8"))
+ total_valid += sum(1 for v in data.values()
+ if isinstance(v, dict) and "error" not in v)
+ if len(jsons) >= EXPECTED_GESN_JSONS:
+ print(f" ✓ GESN JSON: {len(jsons)} files")
+ ok += 1
+ else:
+ print(f" ✗ GESN JSON: {len(jsons)} (expected {EXPECTED_GESN_JSONS}+)")
+ fail += 1
+ if total_valid >= EXPECTED_MIN_NORMS:
+ print(f" ✓ Valid norms: {total_valid:,} (threshold: {EXPECTED_MIN_NORMS:,})")
+ ok += 1
+ else:
+ print(f" ✗ Valid norms: {total_valid:,} (expected {EXPECTED_MIN_NORMS:,}+)")
+ fail += 1
+ else:
+ print(f" ✗ GESN extra dir MISSING")
+ fail += 2
+
+ # FSSC-2022 (FGIS data)
+ fssc_dir = BASE_DIR / "data" / "fssc_2022"
+ if fssc_dir.exists():
+ region_files = list(fssc_dir.glob("region_*.json"))
+ complete = 0
+ total_materials = 0
+ for f in region_files:
+ data = json.loads(f.read_text(encoding="utf-8"))
+ if data.get("complete"):
+ complete += 1
+ for z in data.get("zones", {}).values():
+ total_materials += z.get("materials_count", 0)
+ print(f" {'✓' if complete > 0 else '⏳'} ФССЦ-2022 regions: {complete} complete, {total_materials:,} materials")
+ ok += 1
+ else:
+ print(f" ⏳ ФССЦ-2022 dir not yet created")
+
+ # resources.json
+ res_path = BASE_DIR / "resources.json"
+ if res_path.exists():
+ data = json.loads(res_path.read_text(encoding="utf-8"))
+ valid = sum(1 for v in data.values() if "error" not in v)
+ print(f" ✓ resources.json: {valid:,} norms")
+ ok += 1
+ else:
+ print(f" ✗ resources.json MISSING")
+ fail += 1
+
+ print(f"\n Data: {ok} OK, {fail} FAIL")
+ return fail == 0
+
+
+def main():
+ args = sys.argv[1:]
+ all_ok = True
+
+ if not args or "--docs" in args:
+ all_ok &= check_docs()
+ if not args or "--rag" in args:
+ all_ok &= check_rag()
+ if not args or "--data" in args:
+ all_ok &= check_data()
+
+ print("\n" + "=" * 60)
+ if all_ok:
+ print(" ✓ ALL CHECKS PASSED")
+ else:
+ print(" ⚠ SOME CHECKS FAILED — review above")
+ print("=" * 60)
+
+ sys.exit(0 if all_ok else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/smeta_railway/ai/cag_context.py b/src/smeta_railway/ai/cag_context.py
index 5fd9c2f..130712c 100644
--- a/src/smeta_railway/ai/cag_context.py
+++ b/src/smeta_railway/ai/cag_context.py
@@ -3,12 +3,32 @@ CAG (Cache-Augmented Generation) — structured data always in context.
All tables that fit in LLM context window (~15K tokens):
- НР/СП tables (274 rows)
-- Coefficients (Приложение 28.1, 20 items)
-- FGIS groups mapping
+- Coefficients 421/пр Приложение 10 (условия производства работ)
+- Coefficients Приложение 28.1 (железные дороги)
- Key normative rules
"""
from smeta_railway.data.nr_sp_tables import NR_TABLE, SP_TABLE
+from smeta_railway.data.coefficients_421pr import (
+ TABLE_1_PRODUCTIVITY, TABLE_2_WAGES,
+ TABLE_3_RECONSTRUCTION_PRODUCTIVITY,
+ TABLE_5_CAPREPAIR_PRODUCTIVITY,
+)
+
+
+def _format_421_table(table: dict, table_num: int) -> list[str]:
+ """Format a 421/pr coefficient table for CAG context."""
+ lines = [f"### Таблица {table_num}. {table['title']}"]
+ for key, row in table["rows"].items():
+ desc = row["description"]
+ if len(desc) > 80:
+ desc = desc[:77] + "..."
+ coeffs = []
+ for col in ("gesn", "gesnm", "gesnr", "coeff"):
+ if col in row and row[col] is not None:
+ coeffs.append(str(row[col]))
+ lines.append(f" п.{key}: {desc} — К={'/'.join(coeffs)}")
+ return lines
def build_cag_context() -> str:
@@ -31,7 +51,17 @@ def build_cag_context() -> str:
parts.append("")
- # Coefficients from Приложение 28.1
+ # Coefficients 421/пр Приложение 10 (universal)
+ parts.append("## Коэффициенты условий производства работ (Приказ 421/пр, Прил.10)")
+ parts.append("(в ред. 557/пр от 07.07.2022, 55/пр от 30.01.2024)")
+ parts.extend(_format_421_table(TABLE_1_PRODUCTIVITY, 1))
+ parts.extend(_format_421_table(TABLE_2_WAGES, 2))
+ parts.extend(_format_421_table(TABLE_3_RECONSTRUCTION_PRODUCTIVITY, 3))
+ parts.extend(_format_421_table(TABLE_5_CAPREPAIR_PRODUCTIVITY, 5))
+
+ parts.append("")
+
+ # Coefficients from Приложение 28.1 (railway-specific, kept for backwards compat)
parts.append("## Коэффициенты ГЭСН-28 (Приложение 28.1, Железные дороги)")
parts.append("п.1.1 К_движение (скорость до 140 км/ч):")
for trains, k in [("14-18", 1.05), ("19-36", 1.10), ("37-54", 1.15),
@@ -57,11 +87,10 @@ def build_cag_context() -> str:
parts.append("- НР и СП считаются от ФОТ (ОТ + ЗП маш.), НЕ от ПЗ")
parts.append("- Коэффициенты перемножаются, НЕ складываются")
parts.append("- Лимитированные: временные здания + зимнее + резерв на непредвиденные")
- parts.append("- Нормы 28-01-043 (резка плетей) и 28-01-044 (изол. стыки) — добавлены в дополнениях к ФСНБ-2022")
parts.append("- Резерв на непредвиденные: максимум 2% для соцобъектов, максимум 3% для производственных")
parts.append("- Врем. здания для капремонта: норма × 0.8")
- parts.append("- Изолирующие стыки = 28-03-035 (раздел СЦБ)")
parts.append("- ФСНБ-2022: базовый приказ 1046/пр + 17 дополнений (И1-И17)")
+ parts.append("- База расценок: 47 сборников ГЭСН, 181 000+ расценок")
return "\n".join(parts)
diff --git a/src/smeta_railway/ai/checker.py b/src/smeta_railway/ai/checker.py
index 18c59ab..b8ab65c 100644
--- a/src/smeta_railway/ai/checker.py
+++ b/src/smeta_railway/ai/checker.py
@@ -126,20 +126,24 @@ def check_yaml_config(yaml_path: str | Path) -> CheckReport:
if result:
report.add(result.level, result.code, result.message)
- # 2. Check overhead
+ # 2. Check overhead — lookup by collection
overhead = config.get("overhead", {})
- nr = overhead.get("nr_railway", 0)
- sp = overhead.get("sp_railway", 0)
+ nr = overhead.get("nr_pct", overhead.get("nr_railway", 0))
+ sp = overhead.get("sp_pct", overhead.get("sp_railway", 0))
+ collection = config.get("collection", "28")
- nr_entry = NR_TABLE.get("22") # ж/д
- if nr_entry and nr != nr_entry[1]:
+ from smeta_railway.calc.overhead import GESN_TO_NR_SP_ITEM
+ item_key = GESN_TO_NR_SP_ITEM.get(f"{collection}-", "22")
+
+ nr_entry = NR_TABLE.get(item_key)
+ if nr_entry and nr and nr != nr_entry[1]:
report.add("error", "NR_WRONG",
- f"НР для ж/д = {nr}%, должно быть {nr_entry[1]}% (812/пр, п.22)")
+ f"НР = {nr}%, должно быть {nr_entry[1]}% (812/пр, п.{item_key} — {nr_entry[0]})")
- sp_entry = SP_TABLE.get("22")
- if sp_entry and sp != sp_entry[1]:
+ sp_entry = SP_TABLE.get(item_key)
+ if sp_entry and sp and sp != sp_entry[1]:
report.add("error", "SP_WRONG",
- f"СП для ж/д = {sp}%, должно быть {sp_entry[1]}% (774/пр, п.22)")
+ f"СП = {sp}%, должно быть {sp_entry[1]}% (774/пр, п.{item_key} — {sp_entry[0]})")
# 3. Check limited costs
limited = config.get("limited_costs", {})
diff --git a/src/smeta_railway/ai/chunker.py b/src/smeta_railway/ai/chunker.py
index f3b71a3..5f5cdc5 100644
--- a/src/smeta_railway/ai/chunker.py
+++ b/src/smeta_railway/ai/chunker.py
@@ -1,11 +1,13 @@
"""
-PDF → text chunks for RAG retrieval.
-Uses pymupdf (fitz) for text extraction.
+PDF/HTM → text chunks for RAG retrieval.
+Uses pymupdf (fitz) for PDF, html.parser for HTM.
"""
+import html.parser
import json
import os
import pickle
+import re
from pathlib import Path
import fitz # pymupdf
@@ -33,6 +35,56 @@ def extract_text_from_pdf(pdf_path: str | Path) -> list[dict]:
return pages
+class _HTMLTextExtractor(html.parser.HTMLParser):
+ """Simple HTML to text converter."""
+
+ def __init__(self):
+ super().__init__()
+ self._text = []
+ self._skip = False
+
+ def handle_starttag(self, tag, attrs):
+ self._skip = tag in ("script", "style", "img")
+ if tag in ("br", "p", "div", "tr", "li"):
+ self._text.append("\n")
+
+ def handle_endtag(self, tag):
+ self._skip = False
+
+ def handle_data(self, data):
+ if not self._skip:
+ self._text.append(data)
+
+ def get_text(self):
+ return "".join(self._text)
+
+
+def extract_text_from_htm(htm_path: str | Path) -> list[dict]:
+ """Extract text from HTM file (windows-1251 or utf-8)."""
+ path = Path(htm_path)
+ raw = path.read_bytes()
+ # Detect encoding from meta tag or try windows-1251
+ for enc in ("windows-1251", "cp1251", "utf-8"):
+ try:
+ text = raw.decode(enc)
+ if "�" not in text[:200]:
+ break
+ except UnicodeDecodeError:
+ continue
+ else:
+ text = raw.decode("utf-8", errors="replace")
+
+ parser = _HTMLTextExtractor()
+ parser.feed(text)
+ clean = parser.get_text()
+ # Collapse whitespace
+ clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
+
+ if not clean:
+ return []
+ return [{"source": path.name, "page": 1, "text": clean}]
+
+
def chunk_text(text: str, source: str, page: int,
chunk_size: int = CHUNK_SIZE,
overlap: int = CHUNK_OVERLAP) -> list[dict]:
@@ -73,10 +125,11 @@ def chunk_text(text: str, source: str, page: int,
def process_pdf_directory(pdf_dir: str | Path) -> list[dict]:
- """Process all PDFs in directory into chunks."""
+ """Process all PDFs and HTM files in directory into chunks."""
pdf_dir = Path(pdf_dir)
all_chunks = []
+ # PDF files
for pdf_path in sorted(pdf_dir.glob("*.pdf")):
print(f" Processing {pdf_path.name}...")
pages = extract_text_from_pdf(pdf_path)
@@ -88,15 +141,32 @@ def process_pdf_directory(pdf_dir: str | Path) -> list[dict]:
)
all_chunks.extend(chunks)
+ # HTM files
+ for htm_path in sorted(pdf_dir.glob("*.htm")):
+ print(f" Processing {htm_path.name}...")
+ pages = extract_text_from_htm(htm_path)
+ for page_data in pages:
+ chunks = chunk_text(
+ page_data["text"],
+ page_data["source"],
+ page_data["page"],
+ )
+ all_chunks.extend(chunks)
+
return all_chunks
def build_rag_index(
pdf_dirs: list[str | Path],
output_dir: str | Path,
+ embed_batch: int = 500,
) -> tuple[faiss.IndexFlatIP, list[dict]]:
- """Build RAG FAISS index from PDF directories."""
- from smeta_railway.ai.embeddings import embed_query
+ """Build RAG FAISS index from PDF directories.
+
+ Memory-optimized: processes embeddings in batches of `embed_batch`
+ and adds them to FAISS incrementally instead of holding all in RAM.
+ """
+ from smeta_railway.ai.embeddings import EMBEDDING_DIM
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
@@ -106,32 +176,42 @@ def build_rag_index(
for pdf_dir in pdf_dirs:
pdf_dir = Path(pdf_dir)
if pdf_dir.is_file():
- pages = extract_text_from_pdf(pdf_dir)
+ if str(pdf_dir).endswith((".htm", ".html")):
+ pages = extract_text_from_htm(pdf_dir)
+ else:
+ pages = extract_text_from_pdf(pdf_dir)
for p in pages:
all_chunks.extend(chunk_text(p["text"], p["source"], p["page"]))
elif pdf_dir.is_dir():
print(f"Processing directory: {pdf_dir}")
all_chunks.extend(process_pdf_directory(pdf_dir))
- print(f"Total chunks: {len(all_chunks)}")
+ total = len(all_chunks)
+ print(f"Total chunks: {total}")
- # Generate embeddings
+ # Build FAISS index incrementally — batch embeddings to save RAM
from smeta_railway.ai.embeddings import generate_embeddings
- texts = [c["text"][:500] for c in all_chunks] # truncate for embedding
+ import gc
- print("Generating embeddings for RAG chunks...")
- embeddings = generate_embeddings(texts, batch_size=200)
- faiss.normalize_L2(embeddings)
+ index = faiss.IndexFlatIP(EMBEDDING_DIM)
- dim = embeddings.shape[1]
- index = faiss.IndexFlatIP(dim)
- index.add(embeddings)
+ for start in range(0, total, embed_batch):
+ end = min(start + embed_batch, total)
+ batch_texts = [c["text"][:500] for c in all_chunks[start:end]]
+
+ print(f" Embedding batch {start}-{end} / {total}...")
+ embs = generate_embeddings(batch_texts, batch_size=64)
+ faiss.normalize_L2(embs)
+ index.add(embs)
+
+ del embs, batch_texts
+ gc.collect()
faiss.write_index(index, str(output_dir / "rag.faiss"))
with open(output_dir / "rag_chunks.pkl", "wb") as f:
pickle.dump(all_chunks, f)
- print(f"RAG index saved: {len(all_chunks)} chunks, dim={dim}")
+ print(f"RAG index saved: {total} chunks, dim={EMBEDDING_DIM}")
return index, all_chunks
@@ -144,3 +224,64 @@ def load_rag_index(
with open(index_dir / "rag_chunks.pkl", "rb") as f:
chunks = pickle.load(f)
return index, chunks
+
+
+def add_to_rag_index(
+ doc_path: str | Path,
+ index_dir: str | Path,
+ embed_batch: int = 500,
+) -> int:
+ """Add a single PDF/HTM document to existing RAG index incrementally.
+
+ Returns number of new chunks added.
+ """
+ from smeta_railway.ai.embeddings import generate_embeddings, EMBEDDING_DIM
+ import gc
+
+ doc_path = Path(doc_path)
+ index_dir = Path(index_dir)
+
+ # Extract chunks from new document
+ if doc_path.suffix.lower() in (".htm", ".html"):
+ pages = extract_text_from_htm(doc_path)
+ else:
+ pages = extract_text_from_pdf(doc_path)
+
+ new_chunks = []
+ for p in pages:
+ new_chunks.extend(chunk_text(p["text"], p["source"], p["page"]))
+
+ if not new_chunks:
+ print(f"No chunks extracted from {doc_path.name}")
+ return 0
+
+ # Load existing index
+ index = faiss.read_index(str(index_dir / "rag.faiss"))
+ with open(index_dir / "rag_chunks.pkl", "rb") as f:
+ existing_chunks = pickle.load(f)
+
+ # Check if already indexed (by source name)
+ existing_sources = {c.get("source") for c in existing_chunks}
+ if doc_path.name in existing_sources:
+ print(f"{doc_path.name} already in index, skipping")
+ return 0
+
+ # Generate embeddings in batches and add to index
+ total_new = len(new_chunks)
+ for start in range(0, total_new, embed_batch):
+ end = min(start + embed_batch, total_new)
+ batch_texts = [c["text"][:500] for c in new_chunks[start:end]]
+ embs = generate_embeddings(batch_texts, batch_size=64)
+ faiss.normalize_L2(embs)
+ index.add(embs)
+ del embs, batch_texts
+ gc.collect()
+
+ # Save updated index
+ existing_chunks.extend(new_chunks)
+ faiss.write_index(index, str(index_dir / "rag.faiss"))
+ with open(index_dir / "rag_chunks.pkl", "wb") as f:
+ pickle.dump(existing_chunks, f)
+
+ print(f"Added {total_new} chunks from {doc_path.name} (total: {len(existing_chunks)})")
+ return total_new
diff --git a/src/smeta_railway/ai/rag.py b/src/smeta_railway/ai/rag.py
index 12ebea9..2f06a35 100644
--- a/src/smeta_railway/ai/rag.py
+++ b/src/smeta_railway/ai/rag.py
@@ -16,7 +16,7 @@ from smeta_railway.ai.cag_context import CAG_CONTEXT
from smeta_railway.ai.embeddings import embed_query
-SYSTEM_PROMPT = """Ты — инженер-сметчик, 20 лет опыта, ГЭСН/ФЕР.
+SYSTEM_PROMPT = """Ты — инженер-сметчик, 20 лет опыта, все сборники ГЭСН/ФЕР (1-47).
ПРАВИЛА:
1. Отвечай ТОЛЬКО по предоставленным документам и таблицам.
@@ -24,13 +24,13 @@ SYSTEM_PROMPT = """Ты — инженер-сметчик, 20 лет опыта,
3. Числа — дословно из таблиц, без округления.
4. Если в НАЙДЕННЫХ НОРМАХ ГЭСН есть подходящие — используй их, даже при низком score.
5. "Не найдено" — только если вопрос вообще не покрыт ни таблицами, ни нормами, ни документами.
-6. Приоритет: ФСНБ-2022 > приказы Минстроя > МДС > учебники.
+6. Приоритет: ФСНБ-2022 > приказы Минстроя (421/пр, 812/пр, 774/пр) > МДС.
ПРИМЕРЫ:
-✓ "НР = 109% от ФОТ [Приказ 812/пр, Прил.1, п.22, гр.3]"
+✓ "НР = 102% от ФОТ [Приказ 812/пр, Прил.1, п.6, гр.3]" (бетонные работы)
✗ "НР обычно 100-120%" (нет ссылки, нет точного значения)
-✓ "Коэффициент не применяется [ГЭСН-28, Прил.28.1, п.1.3 — нормы 28-01-155 не указаны]"
+✓ "К=1.15 [Приказ 421/пр, Прил.10, Табл.1, п.5 — стеснённые условия населённых пунктов]"
✗ "Можно применить по аналогии" (домысливание)
## СПРАВОЧНЫЕ ДАННЫЕ (всегда актуальны):
diff --git a/src/smeta_railway/calc/coefficients.py b/src/smeta_railway/calc/coefficients.py
index fdca637..dfdcdd5 100644
--- a/src/smeta_railway/calc/coefficients.py
+++ b/src/smeta_railway/calc/coefficients.py
@@ -128,8 +128,9 @@ def get_coefficients(
code = gesn_code.replace("ГЭСН ", "").strip()
- # Only apply coefficients to collection 28 norms
- if not code.startswith("28-01-"):
+ # Приложение 28.1 coefficients only apply to collection 28
+ # For other collections, return empty (421/пр coefficients handled via CAG/RAG)
+ if not code.startswith("28-"):
return Coefficients(
formulas={"zt": "", "em": "", "ztm": ""},
)
diff --git a/src/smeta_railway/cli.py b/src/smeta_railway/cli.py
index 4865254..695a7f4 100644
--- a/src/smeta_railway/cli.py
+++ b/src/smeta_railway/cli.py
@@ -284,6 +284,7 @@ def build_rag_cmd(
pdf_dirs = [
"literature/gesn",
"literature/GESN-28_full.pdf",
+ "literature/supplements",
]
existing = [p for p in pdf_dirs if Path(p).exists()]
if not existing:
@@ -294,6 +295,23 @@ def build_rag_cmd(
build_rag_index(existing, out)
+@app.command("add-doc")
+def add_doc_cmd(
+ doc_path: Path = typer.Argument(..., help="Path to PDF or HTM file to add"),
+ index_dir: str = typer.Option(None, "--index-dir", "-i"),
+):
+ """Add a single document to RAG index without full rebuild."""
+ from smeta_railway.ai.chunker import add_to_rag_index
+
+ if not doc_path.exists():
+ typer.echo(f"File not found: {doc_path}", err=True)
+ raise typer.Exit(1)
+
+ idx_dir = index_dir or str(Path(__file__).parent / "ai/index")
+ added = add_to_rag_index(doc_path, idx_dir)
+ typer.echo(f"Added {added} chunks from {doc_path.name}")
+
+
@app.command()
def search(
query: str = typer.Argument(..., help="Work description to search for"),
@@ -320,16 +338,6 @@ def search(
)
-@app.command("build-rag")
-def build_rag_cmd(
- pdf_dirs: list[str] = typer.Argument(..., help="PDF directories to index"),
-):
- """Build RAG index from PDF documents."""
- from smeta_railway.ai.rag import build_rag_index
- _, chunks = build_rag_index([Path(d) for d in pdf_dirs])
- typer.echo(f"RAG index built: {len(chunks)} chunks")
-
-
@app.command()
def auto(
description: str = typer.Argument(..., help="Work description in natural language"),