Files
smeta-railway/scripts/fetch_fssc_all_regions.py
T
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

214 lines
6.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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()