chore: универсализация, скрипты fetch/verify, python>=3.10

- CAG: коэффициенты 421/пр (Прил.10, таблицы 1-5)
- Checker: универсальный lookup НР/СП по сборнику
- Chunker: рефакторинг для всех видов строительства
- RAG: batch embeddings
- python>=3.10 (совместимость с сервером)
- Скрипты: fetch ГЭСН/ФССЦ, verify_knowledge_base

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-29 23:27:55 +10:00
co-authored by Claude Opus 4.6
parent e45a0734d8
commit 45f9d423d9
12 changed files with 1414 additions and 47 deletions
+213
View File
@@ -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()
+191
View File
@@ -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}")
+172
View File
@@ -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'<meta name="description" content="[^"]*Расценка[^"]*ГЭСН \d{2}-\d{2}-\d{3}-\d{2}\.\s*(.*?)(?:\s*&mdash;\s*|\s*—\s*)(.*?)"', html)
if m:
return m.group(1).strip(), m.group(2).strip()
# Fallback: from title
m = re.search(r'<title>Расценка ГЭСН \d{2}-\d{2}-\d{3}-\d{2}\.\s*(.*?)(?:\s*&mdash;\s*|\s*—\s*|\.\s*ГЭСН)(.*?)</title>', 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'<meta name="description" content="ГЭСН-2022\.\s*Расценка[^"]*ГЭСН\s*\d{2}-\d{2}-\d{3}-\d{2}\.\s*([^"]*)"',
html
)
if meta:
desc = meta.group(1).replace("&mdash;", "—").replace("&quot;", '"')
# Try to split name and unit (last part after —)
parts = desc.rsplit("—", 1)
name = parts[0].strip()
unit = parts[1].strip() if len(parts) > 1 else ""
else:
# Try title
title_m = re.search(r'<title>Расценка ГЭСН[^.]*\.\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)
+270
View File
@@ -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()
+338
View File
@@ -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()