#!/usr/bin/env python3 """ Fetch full resource breakdown for each ГЭСН norm from cs.smetnoedelo.ru. Parses HTML table and saves to resources.json. Usage: python fetch_resources.py # skip already fetched norms python fetch_resources.py --force # re-fetch all norms """ import json import os import re import subprocess import sys import time from html.parser import HTMLParser NORMS = [ "28-01-037-01", "28-01-037-02", "28-01-068-07", "28-01-031-01", "28-01-041-01", "28-01-155-01", "28-01-155-11", "28-01-155-12", "28-01-155-13", "28-01-155-14", "28-01-155-15", "28-01-155-16", "28-01-155-17", "28-01-155-18", "28-01-075-01", "28-01-073-01", "28-01-054-01", "28-01-027-04", "28-01-007-04", "28-01-043-01", "28-01-008-01", "28-01-033-01", "28-01-076-01", "28-01-075-02", "28-01-044-01", "01-02-057-02", "01-01-036-01", ] BASE_URL = "https://cs.smetnoedelo.ru/gesn2/gesn{code}.html" OUTPUT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources.json") def fetch_page(code: str) -> str | None: """Fetch HTML page bypassing VPN proxy (site is geo-blocked, needs Russian IP).""" 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: print(f" [ERROR] curl failed for {code}: rc={result.returncode}") return None html = result.stdout if not html or "" not in html: print(f" [ERROR] Empty or invalid response for {code}") return None return html except Exception as e: print(f" [ERROR] Exception fetching {code}: {e}") return None class TableParser(HTMLParser): """Extract rows from the second table with class 'table-bordered'.""" def __init__(self): super().__init__() self.table_count = 0 self.in_target_table = False self.in_row = False self.in_cell = False self.rows: list[list[str]] = [] self.current_row: list[str] = [] self.current_cell = "" self.row_classes: list[str] = [] self.current_row_class = "" def handle_starttag(self, tag, attrs): attrs_dict = dict(attrs) if tag == "table": cls = attrs_dict.get("class", "") if "table-bordered" in cls: self.table_count += 1 if self.table_count == 2: self.in_target_table = True elif self.in_target_table: if tag == "tr": self.in_row = True self.current_row = [] self.current_row_class = attrs_dict.get("class", "") elif tag == "td" and self.in_row: self.in_cell = True self.current_cell = "" def handle_endtag(self, tag): if tag == "table" and self.in_target_table: self.in_target_table = False elif tag == "tr" and self.in_row and self.in_target_table: self.rows.append(self.current_row) self.row_classes.append(self.current_row_class) self.in_row = False elif tag == "td" and self.in_cell and self.in_target_table: self.current_row.append(self.current_cell.strip()) self.in_cell = False def handle_data(self, data): if self.in_cell and self.in_target_table: self.current_cell += data def parse_number(s: str) -> float | None: """Parse a number like '122 149,32' or '337.28'.""" s = s.strip().replace("\xa0", " ").replace("\u00a0", " ") if not s or s == "-": return None # Remove spaces (thousands separator), replace comma with dot s = s.replace(" ", "").replace(",", ".") try: return float(s) except ValueError: return None def parse_table(html: str) -> dict | None: """Parse the second table-bordered and extract resource breakdown.""" parser = TableParser() parser.feed(html) rows = parser.rows classes = parser.row_classes if len(rows) < 5: return None result = { "norm_code": None, "norm_name": None, "unit": None, "ozp": None, "machines": [], "materials": [], "totals": {}, } # Find the row with ГЭСН code — it has "ГЭСН XX-XX-XXX-XX" in column 2 (index 1) for row in rows: if len(row) >= 4: m = re.search(r"ГЭСН\s+(\d{2}-\d{2}-\d{3}-\d{2})", row[1] if len(row) > 1 else "") if m: result["norm_code"] = m.group(1) result["norm_name"] = row[2].strip() if len(row) > 2 else None result["unit"] = row[3].strip() if len(row) > 3 else None break section = None # current section: 'em' or 'mat' last_machine_idx = -1 for i, row in enumerate(rows): cls = classes[i] if i < len(classes) else "" if len(row) < 3: continue # Detect section headers col2 = row[2].strip() if len(row) > 2 else "" col1 = row[1].strip() if len(row) > 1 else "" # ОТ(ЗТ) - labor costs header if col2 == "ОТ(ЗТ)" and "font-weight-bold" in cls: section = "ozp" continue # Средний разряд line (labor details) if "Средний разряд" in col2 and section == "ozp": razryad_match = re.search(r"(\d+[.,]\d+|\d+)", col2.replace("Средний разряд работы", "").replace("Средний разряд -", "").replace("Средний разряд", "").strip()) razryad = razryad_match.group(1).replace(",", ".") if razryad_match else None chel_hours = parse_number(row[4]) if len(row) > 4 else None # Try column 7 first (всего с учетом коэфф), then 4 if chel_hours is None and len(row) > 6: chel_hours = parse_number(row[6]) cost_base = parse_number(row[9]) if len(row) > 9 else None result["ozp"] = { "razryad": float(razryad) if razryad else None, "chel_hours": chel_hours, "cost_base": cost_base, } section = None continue # ЭМ - equipment section if col2 == "ЭМ" and "font-weight-bold" in cls: section = "em" continue # ОТм(ЗТм) total machine operator labor (bold, in EM section header) if col2 in ("ОТм(ЗТм)", "ОТм(Зтм)") and "font-weight-bold" in cls: # This is the total OTm line, skip it (we capture per-machine OTm) continue # М - materials section if col2 == "М" and "font-weight-bold" in cls: section = "mat" continue # Итого прямые затраты if "Итого прямые затраты" in col2: total_val = parse_number(row[-1]) if row else None result["totals"]["pz"] = total_val section = None continue # ФОТ line (after итого) if col2 == "ФОТ": continue # Machine operator details for preceding machine if "text-secondary" in cls and "Средний разряд машинистов" in col2: razryad_match = re.search(r"(\d+[.,]\d+|\d+)\s*$", col2) if razryad_match and result["machines"]: result["machines"][-1]["razryad_mash"] = float( razryad_match.group(1).replace(",", ".") ) continue # Resource rows (machines or materials) if section == "em" and len(row) >= 10: code = col1.strip() # Machine codes look like 91.xx.xx-xxx if re.match(r"\d{2}\.\d{2}\.\d{2}-\d{3}", code): name = col2 unit = row[3].strip() if len(row) > 3 else "" qty = parse_number(row[4]) if len(row) > 4 else None if qty is None and len(row) > 6: qty = parse_number(row[6]) cost_base = parse_number(row[9]) if len(row) > 9 else None result["machines"].append({ "code": code, "name": name, "unit": unit, "qty": qty, "cost_base": cost_base, }) continue if section == "mat" and len(row) >= 10: code = col1.strip() # Material codes look like xx.x.xx.xx-xxxx or xx.xx.xx.xx-xxxx if re.match(r"\d{2}\.\d+\.\d{2}\.\d{2}-\d{4}", code): name = col2 unit = row[3].strip() if len(row) > 3 else "" qty = parse_number(row[4]) if len(row) > 4 else None if qty is None and len(row) > 6: qty = parse_number(row[6]) cost_base = parse_number(row[9]) if len(row) > 9 else None result["materials"].append({ "code": code, "name": name, "unit": unit, "qty": qty, "cost_base": cost_base, }) continue # Extract totals from the bold summary rows # Look for ОТ(ЗТ), ЭМ, М bold rows and their values in last column for i, row in enumerate(rows): cls = classes[i] if i < len(classes) else "" if "font-weight-bold" not in cls or len(row) < 3: continue col2 = row[2].strip() val = parse_number(row[-1]) if row else None if col2 == "ОТ(ЗТ)": result["totals"]["ozp"] = val elif col2 == "ЭМ": result["totals"]["em"] = val elif col2 in ("ОТм(ЗТм)", "ОТм(Зтм)") and "font-weight-bold" in cls: result["totals"]["em_zp"] = val elif col2 == "М": result["totals"]["mat"] = val return result def main(): force = "--force" in sys.argv # Load existing data existing = {} if os.path.exists(OUTPUT_FILE) and not force: with open(OUTPUT_FILE, "r", encoding="utf-8") as f: try: existing = json.load(f) except json.JSONDecodeError: existing = {} results = dict(existing) fetched = 0 skipped = 0 errors = 0 for code in NORMS: if code in results and not force: print(f"[SKIP] {code} (already fetched)") skipped += 1 continue print(f"[FETCH] {code} ...", end=" ", flush=True) html = fetch_page(code) if not html: errors += 1 results[code] = {"error": "fetch_failed"} continue # Detect 404 pages if "404" in html and "не найден" in html.lower(): print("NOT FOUND (404)") errors += 1 results[code] = {"error": "not_found_404"} time.sleep(2) continue parsed = parse_table(html) if not parsed or not parsed["norm_code"]: print("PARSE ERROR") errors += 1 results[code] = {"error": "parse_failed"} continue results[code] = parsed fetched += 1 n_mach = len(parsed.get("machines", [])) n_mat = len(parsed.get("materials", [])) print(f"OK ({n_mach} machines, {n_mat} materials)") # Save after each successful fetch (crash-safe) with open(OUTPUT_FILE, "w", encoding="utf-8") as f: json.dump(results, f, ensure_ascii=False, indent=2) # Be polite to the server if code != NORMS[-1]: time.sleep(2) # Final save with open(OUTPUT_FILE, "w", encoding="utf-8") as f: json.dump(results, f, ensure_ascii=False, indent=2) print(f"\nDone: {fetched} fetched, {skipped} skipped, {errors} errors") print(f"Saved to {OUTPUT_FILE}") if __name__ == "__main__": main()