Files
smeta-railway/scripts/fetch_gesn_collection.py
anorandClaude Opus 4.6 45f9d423d9 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>
2026-03-29 23:27:55 +10:00

173 lines
6.3 KiB
Python

#!/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)