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