- 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>
192 lines
6.5 KiB
Python
192 lines
6.5 KiB
Python
#!/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}")
|