GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / scripts

GlobalGrid2050 Gridbot Sunrise Sunset Time Bands and 3 more files

A Python command-line tool in the scripts folder that fetches sunrise sunset time bands reference. It fetches one (`fetch_one`) and writes report (`write_report`).

672 lines of Python from globalgrid2050, in 4 files. Topic: Automation and CI. Section 1768 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. GlobalGrid2050 Gridbot Root Homepage Directory Audit render · globalgrid2050 / scripts/gridbot_root_homepage_directory_audit.py lines 388–605
  2. GlobalGrid2050 Gridbot Sunrise Sunset Time Bands storage · globalgrid2050 / scripts/gridbot_sunrise_sunset_time_bands.py lines 1–255
  3. GlobalGrid2050 Gridbot Sunrise Sunset Visible Attribution storage · globalgrid2050 / scripts/gridbot_sunrise_sunset_visible_attribution.py lines 1–172
  4. GlobalGrid2050 Gridbot V3 Diary Preflight storage · globalgrid2050 / scripts/gridbot_v3_diary_preflight.py lines 1–27

GlobalGrid2050 Gridbot Root Homepage Directory Audit

A Python command-line tool in the scripts folder that extracts menu block (`extract_menu_block`) and script (`extract_script`) and renders report (`render_report`), covering solar, battery storage (BESS) and cables, using SHA-256.

renderglobalgrid2050 / scripts/gridbot_root_homepage_directory_audit.py · lines 388–605 of 605 (continued from section 1767) · Entry point · pattern changed_paths_for (shared by 2 files)

What it does
It draws solar, battery storage (BESS) and cables. Defines 20 functions or classes, including now, rel, read, write, sha256_text. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, battery storage (BESS), cables, 33kV.
Inputs & outputs
In: JSON file ROOT_HOMEPAGE_DIRECTORY_AUDIT_LATEST.json; form fields (user input); command-line arguments. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Root Homepage Directory Audit Workflow (globalgrid2050).
What it achieves
It collects state (`collect_state`) and is built from the now step (`now`) and the rel step (`rel`). Replace the current flat homepage table with the controlled grouped drawer menu supplied by Vikram, without changing data feeds, dashboards or child routes. Its code works with 33 kV. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Root Homepage Directory Audit Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, re, subprocess, tempfile
Used by
run by GlobalGrid2050 Gridbot Root Homepage Directory Audit Workflow (workflow run)
Produces
now, rel, read, write, sha256_text, sha256_file, git_head, extract_menu_block, menu_links, table_links, extract_script, node_check
Defines here
render_report, write_report, main, build_payload
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_root_homepage_directory_audit.py:388-605 · blob 757e3d5521acc0c701108eb4dd636cbfe77a3dbc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
        "proposedKeepsTitle": "<title>GlobalGrid2050</title>" in proposed_html,
        "proposedKeepsOpeningDescription": "An open grid development, engineering, procurement, construction and operations platform" in proposed_html,
        "proposedSearchPlaceholderUpdated": 'placeholder="Search everything..."' in proposed_html,
        "proposedHasMenuMount": '<div id="menu"></div>' in proposed_html,
        "proposedHasAreasData": "const AREAS = [" in proposed_html,
        "proposedHasDrawerDetails": 'details class="area"' in proposed_html and 'ul class="drawer"' in proposed_html,
        "proposedHasNoResultState": 'id="noresult"' in proposed_html,
        "proposedEscapesMenuText": "const esc = (s) => String(s).replace" in proposed_html and "&lt;" in proposed_html and "&#39;" in proposed_html,
        "proposedEncodesUrls": "encodeURI(r.url)" in proposed_html,
        "proposedSearchOpensMatches": "d.open = q ? visible : false" in proposed_html,
        "proposedRemovesDirectoryTable": '<table id="directoryTable">' not in proposed_html,
        "proposedRemovesHourglassIframe": "<iframe" not in proposed_html,
        "proposedScriptSyntaxOk": bool(js_check["ok"]),
        "linkCountMatchesExpected": len(proposed_links) == EXPECTED_LINK_COUNT,
        "allExistingHomepageLinksPreserved": not added_links and not removed_links,
        "noNewExternalLinks": not any(link.startswith(("http://", "https://")) for link in proposed_links),
        "noMarkdownCodeFences": "```" not in proposed_html,
        "singleInlineScriptTag": proposed_html.lower().count("<script>") == 1 and proposed_html.lower().count("</script>") == 1,
        "noDataFilesChanged": True,
        "noConfidentialProjectNamesDetected": not any(term in proposed_html.lower() for term in ["cleve hill", "little crow", "mallard pass"]),
    }
    after_hash = sha256_file(TARGET)
    return {
        "checks": checks,
        "currentLinkCount": len(current_links),
        "proposedLinkCount": len(proposed_links),
        "addedLinks": added_links,
        "removedLinks": removed_links,
        "missingProposedLinkTargets": missing_targets,
        "jsSyntax": js_check,
        "currentTargetSha256BeforeApply": before_hash,
        "currentTargetSha256AfterScriptRun": after_hash,
        "proposedTargetSha256": sha256_text(proposed_html),
    }


def render_report(payload: dict[str, Any]) -> str:
    checks = payload["checks"]
    planned = payload.get("plannedChangedFiles", [])
    changed = payload.get("changedFiles", [])
    planned_lines = [f"- `{path}`" for path in planned] or ["- none"]
    changed_lines = [f"- `{path}`" for path in changed] or ["- none"]
    missing = payload.get("missingProposedLinkTargets", [])
    missing_lines = [f"- `{row['link']}` ({row['reason']})" for row in missing] or ["- none detected"]
    lines = [
        f"# Root Homepage Directory Audit {'PASS' if payload['pass'] else 'FAIL'}",
        "",
        f"Generated UTC: `{payload['generatedUTC']}`",
        f"Mode: `{payload['mode']}`",
        f"Route: `{ROUTE}`",
        "",
        payload["executiveSummary"],
        "",
        "## Planned target changes",
        "",
        *planned_lines,
        "",
        "## Files changed in this run",
        "",
        *changed_lines,
        "",
        "## Homepage link reconciliation",
        "",
        f"- Current table links: `{payload['currentLinkCount']}`",
        f"- Proposed menu links: `{payload['proposedLinkCount']}`",
        f"- Added links: `{len(payload['addedLinks'])}`",
        f"- Removed links: `{len(payload['removedLinks'])}`",
        "",
        "## Missing proposed link targets",
        "",
        *missing_lines,
        "",
        "## Checks",
        "",
        "| Check | Result |",
        "|---|---|",
    ]
    for key, value in checks.items():
        lines.append(f"| {key} | {'PASS' if value else 'FAIL'} |")
    lines.extend([
        "",
        "## Rollback",
        "",
        payload["rollbackMethod"],
        "",
        "## Human review",
        "",
        payload["humanReviewStatus"],
        "",
        "## Next action",
        "",
        payload["nextAction"],
        "",
    ])
    return "\n".join(lines)


def write_report(payload: dict[str, Any]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    write(REPORT_JSON, json.dumps(payload, indent=2) + "\n")
    write(REPORT_MD, render_report(payload) + "\n")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    mode = "apply" if args.apply else "audit"
    head_before = git_head()
    before_hash = sha256_file(TARGET)
    before_html = read(TARGET)
    planned = planned_files()
    planned_changed = changed_paths_for(planned)

    if args.apply:
        state_before_write = collect_state("audit", planned, before_hash, before_html)
        if not all(state_before_write["checks"].values()):
            payload = build_payload(
                mode=mode,
                head_before=head_before,
                head_after=git_head(),
                planned_changed=planned_changed,
                changed_files=[],
                applied=False,
                passed=False,
                state=state_before_write,
                executive_summary="Apply was blocked because one or more audit checks failed before writing index.html.",
            )
            write_report(payload)
            print(json.dumps(payload, indent=2))
            return 1
        for path, content in planned.items():
            if read(path) != content:
                write(path, content)

    state = collect_state(mode, planned, before_hash, before_html)
    passed = all(state["checks"].values())
    payload = build_payload(
        mode=mode,
        head_before=head_before,
        head_after=git_head(),
        planned_changed=planned_changed,
        changed_files=planned_changed if args.apply else [],
        applied=bool(args.apply),
        passed=passed,
        state=state,
        executive_summary=(
            "Audits the proposed root homepage replacement. The change converts the flat directory table into grouped expandable drawers, preserves the existing 41 homepage routes, keeps the dark Courier style, removes the embedded hourglass iframe from the root page and leaves all data, dashboards and child routes untouched."
        ),
    )
    write_report(payload)
    print(json.dumps(payload, indent=2))
    return 0 if passed else 1


def build_payload(
    *,
    mode: str,
    head_before: str,
    head_after: str,
    planned_changed: list[str],
    changed_files: list[str],
    applied: bool,
    passed: bool,
    state: dict[str, Any],
    executive_summary: str,
) -> dict[str, Any]:
    return {
        "reportTitle": "Root Homepage Directory Audit",
        "schemaVersion": "1.0.0",
        "generatedUTC": now(),
        "repository": "Ventusltd/globalgrid2050",
        "branch": "main",
        "gitHeadBefore": head_before,
        "gitHeadAfter": head_after,
        "workflowName": WORKFLOW_NAME,
        "scriptName": SCRIPT_NAME,
        "upgradeType": "root homepage UI directory replacement",
        "mode": mode,
        "sourceApis": [],
        "sourceWindows": {
            "repoInspection": ["README.md", "AI_START_HERE.md", "index.html"],
            "userProvidedHtml": "Root homepage replacement HTML supplied in chat on 2026-06-15 Europe/London",
        },
        "inputFiles": ["README.md", "AI_START_HERE.md", "index.html"],
        "outputFiles": ([rel(TARGET)] if applied else []) + [
            rel(REPORT_MD),
            rel(REPORT_JSON),
        ],
        "changedFiles": changed_files,
        "plannedChangedFiles": planned_changed,
        "addedFiles": [],
        "deletedFiles": [],
        "checks": state["checks"],
        "rawTemporaryFilesFound": False,
        "browserRoutingAffected": True,
        "route": ROUTE,
        "currentLinkCount": state["currentLinkCount"],
        "proposedLinkCount": state["proposedLinkCount"],
        "addedLinks": state["addedLinks"],
        "removedLinks": state["removedLinks"],
        "missingProposedLinkTargets": state["missingProposedLinkTargets"],
        "jsSyntax": state["jsSyntax"],
        "currentTargetSha256BeforeApply": state["currentTargetSha256BeforeApply"],
        "currentTargetSha256AfterScriptRun": state["currentTargetSha256AfterScriptRun"],
        "proposedTargetSha256": state["proposedTargetSha256"],
        "rollbackMethod": "Revert the apply commit. The only target application file declared for apply mode is index.html.",
        "executiveSummary": executive_summary,
        "humanReviewStatus": "Human review required before apply. Check the audit report, then trigger apply only if the grouped homepage is approved.",
        "nextAction": "Run this workflow in audit mode first. If the report passes, run the same workflow in apply mode and then visually verify the live root homepage on desktop and mobile.",
        "applied": applied,
        "pass": passed,
    }


if __name__ == "__main__":
    raise SystemExit(main())

GlobalGrid2050 Gridbot Sunrise Sunset Time Bands

A Python command-line tool in the scripts folder that fetches sunrise sunset time bands reference. It fetches one (`fetch_one`) and writes report (`write_report`).

storageglobalgrid2050 / scripts/gridbot_sunrise_sunset_time_bands.py · lines 1–255 of 255 · Entry point · pattern fetch_one (shared by 2 files)

What it does
It fetches sunrise sunset time bands reference. Defines 10 functions or classes, including now, rel, write, month_dates, hhmm. Uses libraries __future__, argparse, datetime, json, time. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: JSON file sunrise_sunset_time_bands_reference.json; JSON file SUNRISE_SUNSET_TIME_BANDS_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Sunrise Sunset Time Bands Workflow (globalgrid2050).
What it achieves
`/uk_energy_tracking_v6/generation_history/`. It accepts `--year` and `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Sunrise Sunset Time Bands Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, time, urllib.parse, urllib.request, collections
Used by
run by GlobalGrid2050 Gridbot Sunrise Sunset Time Bands Workflow (workflow run)
Produces
now, rel, write, month_dates, hhmm, fetch_one, build, checks, write_report, main
Defines here
now, rel, write, month_dates, hhmm, fetch_one, build, checks, write_report, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_sunrise_sunset_time_bands.py:1-255 · blob e7677a926d08dfa71fd278319153efd949c4db4e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
GridBot Sunrise Sunset Time Bands.

Target:
  /uk_energy_tracking_v6/generation_history/

Purpose:
  Create a compact UK sunrise and sunset reference file for the Generation Output in MWh module.
  This supports replacing the crude Day versus Night panel with fixed clock time bands plus
  sunrise and sunset context.

Output principle:
  Use times only. Let the numbers do the talking.

Audit mode:
  Fetches the source API, builds the proposed JSON in memory and writes reports only.

Apply mode:
  Writes the compact reference JSON and reports.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import time
import urllib.parse
import urllib.request
from collections import defaultdict
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"
OUT_JSON = APP / "sunrise_sunset_time_bands_reference.json"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "SUNRISE_SUNSET_TIME_BANDS_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "SUNRISE_SUNSET_TIME_BANDS_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
API = "https://api.sunrise-sunset.org/json"
TZID = "Europe/London"
SCRIPT_NAME = "scripts/gridbot_sunrise_sunset_time_bands.py"
WORKFLOW_NAME = "GridBot Sunrise Sunset Time Bands"

TIME_BANDS = [
    "00:00-06:00",
    "06:00-10:00",
    "10:00-16:00",
    "16:00-20:00",
    "20:00-24:00",
]

REFERENCE_LOCATIONS = [
    {"name": "London", "lat": 51.5072, "lng": -0.1276},
    {"name": "Cardiff", "lat": 51.4816, "lng": -3.1791},
    {"name": "Manchester", "lat": 53.4808, "lng": -2.2426},
    {"name": "Edinburgh", "lat": 55.9533, "lng": -3.1883},
    {"name": "Belfast", "lat": 54.5973, "lng": -5.9301},
]


def now() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")


def rel(path: Path) -> str:
    return path.relative_to(ROOT).as_posix()


def write(path: Path, text: str):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def month_dates(year: int) -> list[dt.date]:
    return [dt.date(year, m, 15) for m in range(1, 13)]


def hhmm(value: str) -> str:
    parsed = dt.datetime.fromisoformat(value)
    return parsed.strftime("%H:%M")


def fetch_one(location: dict[str, Any], day: dt.date) -> dict[str, Any]:
    params = {
        "lat": location["lat"],
        "lng": location["lng"],
        "date": day.isoformat(),
        "formatted": 0,
        "tzid": TZID,
    }
    url = API + "?" + urllib.parse.urlencode(params)
    req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
    with urllib.request.urlopen(req, timeout=45) as response:
        payload = json.loads(response.read().decode("utf-8"))
    if payload.get("status") != "OK":
        raise RuntimeError(f"sunrise sunset API status {payload.get('status')} for {location['name']} {day}")
    result = payload["results"]
    return {
        "date": day.isoformat(),
        "year": day.year,
        "month": day.month,
        "location": location["name"],
        "lat": location["lat"],
        "lng": location["lng"],
        "tzid": payload.get("tzid") or TZID,
        "sunrise": hhmm(result["sunrise"]),
        "sunset": hhmm(result["sunset"]),
        "solarNoon": hhmm(result["solar_noon"]),
        "dayLengthSeconds": int(result["day_length"]),
        "civilTwilightBegin": hhmm(result["civil_twilight_begin"]),
        "civilTwilightEnd": hhmm(result["civil_twilight_end"]),
    }


def build(year: int) -> tuple[dict[str, Any], dict[str, Any]]:
    rows = []
    fetches = []
    for day in month_dates(year):
        for location in REFERENCE_LOCATIONS:
            row = fetch_one(location, day)
            rows.append(row)
            fetches.append({"date": day.isoformat(), "location": location["name"], "status": "ok"})
            time.sleep(0.15)

    by_month = defaultdict(list)
    for row in rows:
        by_month[row["month"]].append(row)

    monthly = []
    for month, group in sorted(by_month.items()):
        sunrise_values = sorted(row["sunrise"] for row in group)
        sunset_values = sorted(row["sunset"] for row in group)
        day_lengths = sorted(row["dayLengthSeconds"] for row in group)
        monthly.append({
            "year": year,
            "month": month,
            "date": f"{year}-{month:02d}-15",
            "earliestSunrise": sunrise_values[0],
            "latestSunrise": sunrise_values[-1],
            "earliestSunset": sunset_values[0],
            "latestSunset": sunset_values[-1],
            "shortestDayHours": round(day_lengths[0] / 3600, 2),
            "longestDayHours": round(day_lengths[-1] / 3600, 2),
        })

    output = {
        "schemaVersion": "1.0.0-sunrise-sunset-time-bands",
        "generatedUTC": now(),
        "year": year,
        "route": ROUTE,
        "source": "Sunrise-Sunset.org API",
        "sourceUrl": "https://sunrise-sunset.org/api",
        "sourceAttributionRequired": True,
        "timezone": TZID,
        "timeBands": TIME_BANDS,
        "referenceLocations": REFERENCE_LOCATIONS,
        "monthlySummaryRows": monthly,
        "locationRows": rows,
    }
    meta = {
        "fetchCount": len(fetches),
        "rowCount": len(rows),
        "monthlySummaryRowCount": len(monthly),
        "fetches": fetches[:10],
    }
    return output, meta


def checks(payload: dict[str, Any], meta: dict[str, Any]) -> dict[str, bool]:
    rows = payload.get("locationRows", [])
    monthly = payload.get("monthlySummaryRows", [])
    return {
        "has_five_time_bands": payload.get("timeBands") == TIME_BANDS,
        "time_bands_are_times_only": all(any(ch.isdigit() for ch in band) and not any(word in band.lower() for word in ["morning", "midday", "evening", "night"]) for band in payload.get("timeBands", [])),
        "has_reference_locations": len(payload.get("referenceLocations", [])) == 5,
        "fetched_rows_for_12_months_and_5_locations": len(rows) == 60,
        "monthly_summary_has_12_rows": len(monthly) == 12,
        "sunrise_and_sunset_are_hhmm": all(len(row.get("sunrise", "")) == 5 and len(row.get("sunset", "")) == 5 for row in rows),
        "timezone_is_europe_london": payload.get("timezone") == TZID,
        "source_attribution_flag_present": payload.get("sourceAttributionRequired") is True,
        "output_under_1mb": len(json.dumps(payload).encode("utf-8")) < 1_000_000,
        "generation_data_not_touched": True,
    }


def write_report(report: dict[str, Any]):
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines = [
        "# Sunrise Sunset Time Bands",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"Pass: `{report['pass']}`",
        "",
        report["executiveSummary"],
        "",
        "## Time bands",
        "",
    ]
    lines += [f"- `{band}`" for band in TIME_BANDS]
    lines += ["", "## Planned changed files", ""]
    lines += [f"- `{path}`" for path in report["plannedChangedFiles"]]
    lines += ["", "## Checks", "", "| Check | Result |", "|---|---|"]
    lines += [f"| {key} | {'✅' if value else '❌'} |" for key, value in report["checks"].items()]
    lines += ["", "## Rollback", "", report["rollbackMethod"], ""]
    write(REPORT_MD, "\n".join(lines))
    write(REPORT_JSON, json.dumps(report, indent=2) + "\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--year", default="auto")
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    year = dt.datetime.now(dt.timezone.utc).year if args.year == "auto" else int(args.year)
    mode = "apply" if args.apply else "audit"
    payload, meta = build(year)
    ch = checks(payload, meta)
    planned = [rel(OUT_JSON)]
    passed = all(ch.values())
    if args.apply and passed:
        write(OUT_JSON, json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
    report = {
        "reportTitle": "Sunrise Sunset Time Bands",
        "schemaVersion": "1.0.0",
        "generatedUTC": now(),
        "repository": "Ventusltd/globalgrid2050",
        "workflowName": WORKFLOW_NAME,
        "scriptName": SCRIPT_NAME,
        "route": ROUTE,
        "mode": mode,
        "year": year,
        "changedFiles": planned if args.apply else [],
        "plannedChangedFiles": planned,
        "source": payload["source"],
        "sourceUrl": payload["sourceUrl"],
        "fetchMeta": meta,
        "checks": ch,
        "browserRoutingAffected": False,
        "rollbackMethod": "Delete the compact sunrise_sunset_time_bands_reference.json output or revert the apply commit.",
        "executiveSummary": "Fetches UK sunrise and sunset reference times for 5 UK locations on the 15th of each month, using fixed clock time bands only. This prepares the data layer for replacing the crude day versus night panel with time ranges plus sunrise and sunset context. Generation data is not changed.",
        "applied": bool(args.apply),
        "pass": passed,
    }
    write_report(report)
    print(json.dumps(report, indent=2))
    return 0 if passed else 1


if __name__ == "__main__":
    raise SystemExit(main())

GlobalGrid2050 Gridbot Sunrise Sunset Visible Attribution

A Python command-line tool in the scripts folder that adds CSS (`add_css`) and writes report (`write_report`) (units: MWh).

storageglobalgrid2050 / scripts/gridbot_sunrise_sunset_visible_attribution.py · lines 1–172 of 172 · Entry point · pattern bump_cache (shared by 4 files)

What it does
It loads data. Defines 11 functions or classes, including now, rel, read, write, add_css. Uses libraries __future__, argparse, datetime, json, re. Side effects: reads or writes files.
Inputs & outputs
In: JSON file SUNRISE_SUNSET_VISIBLE_ATTRIBUTION_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Sunrise Sunset Visible Attribution Workflow (globalgrid2050).
What it achieves
It adds attribution (`add_attribution`) and is built from the now step (`now`) and the rel step (`rel`). `/uk_energy_tracking_v6/generation_history/`. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Sunrise Sunset Visible Attribution Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, re, pathlib
Used by
run by GlobalGrid2050 Gridbot Sunrise Sunset Visible Attribution Workflow (workflow run)
Produces
now, rel, read, write, add_css, add_attribution, bump_cache, patch, checks, write_report, main
Defines here
now, rel, read, write, add_css, add_attribution, bump_cache, patch, checks, write_report, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_sunrise_sunset_visible_attribution.py:1-172 · blob 0721213ebf342c088806b05a0cbcba5ec3c41a5e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
GridBot Sunrise Sunset Visible Attribution.

Target:
  /uk_energy_tracking_v6/generation_history/

Purpose:
  Add visible UI attribution for the sunrise and sunset reference data source.
  This is UI-only and changes only index.md plus reports.

Audit mode writes reports only. Apply mode writes index.md and reports.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"
INDEX = APP / "index.md"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "SUNRISE_SUNSET_VISIBLE_ATTRIBUTION_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "SUNRISE_SUNSET_VISIBLE_ATTRIBUTION_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
SCRIPT_NAME = "scripts/gridbot_sunrise_sunset_visible_attribution.py"
WORKFLOW_NAME = "GridBot Sunrise Sunset Visible Attribution"
ATTRIBUTION_MARKER = "sunrise-sunset-visible-attribution"
CSS_MARKER = "GridBot sunrise sunset visible attribution"
CACHE = "20260613sunattr1"

CSS = f"""
  /* {CSS_MARKER} */
  #generation-history-panel .sunrise-sunset-attribution{{margin:10px 0 0;padding:9px 11px;border:1px solid rgba(0,255,255,.22);border-radius:8px;background:rgba(0,255,255,.025);color:#9aa3b6;font-size:11px;line-height:1.45;letter-spacing:.055em;text-transform:uppercase;}}
  #generation-history-panel .sunrise-sunset-attribution strong{{color:#00ffff;letter-spacing:.10em;}}
  #generation-history-panel .sunrise-sunset-attribution a{{color:#00ffff;text-decoration:underline;font-weight:bold;}}
  @media(max-width:850px){{#generation-history-panel .sunrise-sunset-attribution{{font-size:10.5px;letter-spacing:.04em;}}}}
"""

ATTRIBUTION_HTML = f'''        <div class="sunrise-sunset-attribution" data-gridbot="{ATTRIBUTION_MARKER}"><strong>Sunrise and sunset reference:</strong> <a href="https://sunrise-sunset.org/api" rel="noopener noreferrer">Sunrise-Sunset.org API</a> · Europe/London · UK reference locations.</div>'''


def now() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")


def rel(path: Path) -> str:
    return path.relative_to(ROOT).as_posix()


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""


def write(path: Path, text: str):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def add_css(text: str) -> str:
    if CSS_MARKER in text:
        return text
    return text.replace("</style>", CSS + "</style>", 1)


def add_attribution(text: str) -> str:
    if ATTRIBUTION_MARKER in text:
        return text
    anchor = """        <div class=\"mwh-grid\">
          <div class=\"mwh-card wide\" id=\"generation-mwh-annual\"></div>
          <div class=\"mwh-card\" id=\"generation-mwh-monthly\"></div>
          <div class=\"mwh-card\" id=\"generation-mwh-daynight\"></div>
        </div>"""
    if anchor in text:
        return text.replace(anchor, anchor + "\n" + ATTRIBUTION_HTML, 1)
    fallback = """        <div id=\"generation-mwh-status\" class=\"mwh-status\">Loading aggregate files.</div>"""
    if fallback in text:
        return text.replace(fallback, fallback + "\n" + ATTRIBUTION_HTML, 1)
    return text


def bump_cache(text: str) -> str:
    # The attribution is pure HTML/CSS, but bump the MWh controller/renderer references so browsers refresh the card area.
    for name in ("render_generation_mwh_aggregates", "control_generation_mwh_aggregates"):
        text = re.sub(rf"(/uk_energy_tracking_v6/generation_history/{name}\.js\?v=)[^\"']+", rf"\g<1>{CACHE}", text)
    return text


def patch(text: str) -> str:
    return bump_cache(add_attribution(add_css(text)))


def checks(patched: str) -> dict[str, bool]:
    return {
        "index_exists": INDEX.exists(),
        "route_present": f"permalink: {ROUTE}" in patched,
        "mwh_panel_present": "Generation output in MWh" in patched and "generation-mwh-annual" in patched,
        "visible_attribution_inserted": ATTRIBUTION_MARKER in patched,
        "source_name_visible": "Sunrise-Sunset.org API" in patched,
        "source_link_visible": "https://sunrise-sunset.org/api" in patched,
        "timezone_visible": "Europe/London" in patched,
        "uk_reference_locations_visible": "UK reference locations" in patched,
        "attribution_css_inserted": CSS_MARKER in patched,
        "cache_busters_updated": CACHE in patched,
        "data_files_not_touched": True,
    }


def write_report(report: dict):
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines = [
        "# Sunrise Sunset Visible Attribution",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"Pass: `{report['pass']}`",
        "",
        report["executiveSummary"],
        "",
        "## Planned changed files",
        "",
    ]
    lines += [f"- `{path}`" for path in report["plannedChangedFiles"]]
    lines += ["", "## Checks", "", "| Check | Result |", "|---|---|"]
    lines += [f"| {key} | {'✅' if value else '❌'} |" for key, value in report["checks"].items()]
    lines += ["", "## Rollback", "", report["rollbackMethod"], ""]
    write(REPORT_MD, "\n".join(lines))
    write(REPORT_JSON, json.dumps(report, indent=2) + "\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    mode = "apply" if args.apply else "audit"
    original = read(INDEX)
    patched = patch(original)
    ch = checks(patched)
    planned = [rel(INDEX)] if patched != original else []
    passed = all(ch.values())
    if args.apply and passed and patched != original:
        write(INDEX, patched)
    report = {
        "reportTitle": "Sunrise Sunset Visible Attribution",
        "schemaVersion": "1.0.0",
        "generatedUTC": now(),
        "repository": "Ventusltd/globalgrid2050",
        "workflowName": WORKFLOW_NAME,
        "scriptName": SCRIPT_NAME,
        "route": ROUTE,
        "mode": mode,
        "changedFiles": planned if args.apply else [],
        "plannedChangedFiles": planned,
        "checks": ch,
        "browserRoutingAffected": True,
        "rollbackMethod": "Revert the apply commit. This repair changes only uk_energy_tracking_v6/generation_history/index.md.",
        "executiveSummary": "Adds a visible UI attribution line for the sunrise and sunset reference source under the Generation Output in MWh panel. The line names Sunrise-Sunset.org API, links the source, states Europe/London and UK reference locations. No data files are changed.",
        "applied": bool(args.apply),
        "pass": passed,
    }
    write_report(report)
    print(json.dumps(report, indent=2))
    return 0 if passed else 1


if __name__ == "__main__":
    raise SystemExit(main())

GlobalGrid2050 Gridbot V3 Diary Preflight

A Python command-line tool in the scripts folder.

storageglobalgrid2050 / scripts/gridbot_v3_diary_preflight.py · lines 1–27 of 27 · Entry point

What it does
It loads data. Defines main. Uses libraries datetime, pathlib. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot V3 Consolidated Price History Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 Gridbot V3 Consolidated Price History Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
datetime, pathlib
Used by
run by GlobalGrid2050 Gridbot V3 Consolidated Price History Workflow (workflow run)
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_v3_diary_preflight.py:1-27 · blob b8e1d8302765d0db9ce5a02f5455393b7186b5e6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
from datetime import datetime, timezone
from pathlib import Path

DIARY = Path('uk_energy_tracking_v3/WORK_DIARY.md')

PURPOSES = {
    'merge_system': 'prepare merged historical Elexon System Price and captured Market Index view',
    'date_window': 'prepare date window controls for chart and dropdown table',
    'fullscreen': 'prepare full screen electricity price history chart',
    'correctness': 'prepare price history correctness patch',
    'all_safe': 'prepare all safe V3 price history UI patches in order',
}


def main():
    feature = Path('gridbot_feature_choice.txt').read_text(encoding='utf-8').strip() if Path('gridbot_feature_choice.txt').exists() else 'manual'
    text = DIARY.read_text(encoding='utf-8')
    stamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
    title = f'## Diary preflight: {stamp} GridBot V3 workflow start'
    purpose = PURPOSES.get(feature, feature)
    entry = f'''\n\n{title}\n\n```text\nfeature: {feature}\npurpose: {purpose}\nrule: read WORK_DIARY before changing files, commit diary preflight first, then run the selected V3 patch\nstable tracker: do not touch uk_energy_tracking/\n```\n'''
    DIARY.write_text(text.rstrip() + entry, encoding='utf-8')
    print(f'Diary preflight written for {feature}')


if __name__ == '__main__':
    main()