from __future__ import annotations import json import uuid import base64 import re import os import threading import urllib.error import urllib.request from datetime import datetime, timedelta, timezone from html import escape from pathlib import Path from typing import Any # Load .env file if present (for GEMINI_API_KEY etc.) _env_path = Path(__file__).with_name(".env") if _env_path.exists(): for _line in _env_path.read_text(encoding="utf-8").splitlines(): _line = _line.strip() if not _line or _line.startswith("#"): continue if "=" in _line: _key, _, _val = _line.partition("=") _key = _key.strip() _val = _val.strip().strip("\"'") if _key and _key not in os.environ: os.environ[_key] = _val from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, JSONResponse from pydantic import BaseModel # ── Persistence & structured logging ──────────────────────────────────────── from report_service_persistence import create_draft_store, create_rate_limiter, DraftStore, RateLimiter import logging class _JSONFormatter(logging.Formatter): """Structured JSON logging for production observability.""" def format(self, record: logging.LogRecord) -> str: import json obj = { "timestamp": self.formatTime(record), "level": record.levelname, "logger": record.name, "message": record.getMessage(), "module": record.module, "func": record.funcName, "line": record.lineno, } if record.exc_info: obj["exception"] = self.formatException(record.exc_info) return json.dumps(obj, default=str) # Set up root logger for the service _root_logger = logging.getLogger("tia_report_service") _root_logger.setLevel(logging.INFO) if not _root_logger.handlers: _handler = logging.StreamHandler() _handler.setFormatter(_JSONFormatter()) _root_logger.addHandler(_handler) logger = _root_logger # ── Service start time (for uptime in health checks) ─────────────────────── _SERVICE_START_TIME = datetime.now(timezone.utc) # ── Pluggable backends ───────────────────────────────────────────────────── # Replace in-memory dicts with configurable backends (memory/redis/firestore). # Falls back to in-memory if no external store is configured. draft_store: DraftStore = create_draft_store() rate_limiter: RateLimiter = create_rate_limiter() logger.info( "Persistence backends initialised", extra={ "draft_store": draft_store.health(), "rate_limiter": rate_limiter.health(), }, ) app = FastAPI(title="TIA Python Report Service", version="1.0.0") def _parse_allowed_origins_from_env() -> list[str]: raw = os.environ.get("REPORT_ALLOWED_ORIGINS", "") if not raw.strip(): return [] origins = [item.strip() for item in raw.split(",") if item.strip()] return origins ALLOWED_ORIGINS = _parse_allowed_origins_from_env() ALLOWED_ORIGIN_REGEX = os.environ.get( "REPORT_ALLOWED_ORIGIN_REGEX", r"^https://[a-z0-9-]+\.github\.io$" r"|^https://([a-z0-9-]+\.)?cromptonapps\.com$" r"|^https://[a-z0-9-]+\.web\.app$" r"|^https://[a-z0-9-]+\.firebaseapp\.com$" r"|^https?://(localhost|127\.0\.0\.1)(:\d+)?$", ) MAX_REQUEST_BODY_BYTES = max(100_000, int(os.environ.get("REPORT_MAX_REQUEST_BYTES", "12000000"))) MAX_DRAFTS = max(10, int(os.environ.get("REPORT_MAX_DRAFTS", "200"))) DRAFT_TTL_HOURS = max(1, int(os.environ.get("REPORT_DRAFT_TTL_HOURS", "12"))) app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_origin_regex=ALLOWED_ORIGIN_REGEX, allow_credentials=False, allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], expose_headers=["Retry-After", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset"], ) @app.middleware("http") async def add_private_network_access_headers(request: Request, call_next): content_length = request.headers.get("content-length") if content_length: try: content_length_value = int(content_length) if content_length_value > MAX_REQUEST_BODY_BYTES: max_mb = MAX_REQUEST_BODY_BYTES / (1024 * 1024) actual_mb = content_length_value / (1024 * 1024) return JSONResponse( status_code=413, content={ "detail": ( f"Request body too large ({actual_mb:.2f} MB). " f"Server limit is {max_mb:.2f} MB. " "Set REPORT_MAX_REQUEST_BYTES to increase the limit if needed." ) }, ) except ValueError: return JSONResponse( status_code=400, content={"detail": "Invalid Content-Length header"}, ) response = await call_next(request) # Required for browser Private Network Access preflight when calling localhost # from a secure origin (for example, GitHub Pages over HTTPS). response.headers["Access-Control-Allow-Private-Network"] = "true" response.headers["Vary"] = "Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network" response.headers["X-Content-Type-Options"] = "nosniff" response.headers["X-Frame-Options"] = "DENY" response.headers["Referrer-Policy"] = "no-referrer" response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()" # Keep CSP compatible with the inline editor while limiting remote execution vectors. content_type = str(response.headers.get("content-type", "")).lower() if "text/html" in content_type: response.headers["Content-Security-Policy"] = ( "default-src 'self'; " "img-src 'self' data:; " "style-src 'self' 'unsafe-inline'; " "script-src 'self' 'unsafe-inline'; " "font-src 'self' data:; " "connect-src 'self'; " "frame-ancestors 'none'; " "base-uri 'self'; " "form-action 'self'" ) return response class DraftRequest(BaseModel): title: str = "TIA Report" payload: dict[str, Any] # Legacy in-memory globals are replaced by pluggable backends (see imports above). # Kept as aliases for backward compatibility in tests that import them. DRAFTS: dict[str, dict[str, Any]] = {} # populated lazily; do not use directly _RATE_BUCKETS: dict[str, list[float]] = {} # populated lazily; do not use directly _RATE_LOCK = threading.Lock() VERIFY_RATE_MAX = max(1, int(os.environ.get("REPORT_VERIFY_RATE_MAX", "20"))) VERIFY_RATE_WINDOW_S = max(1, int(os.environ.get("REPORT_VERIFY_RATE_WINDOW_S", "600"))) def _utcnow() -> datetime: return datetime.now(timezone.utc) def _parse_datetime_utc(value: str, fallback: datetime) -> datetime: text = str(value or "").strip() if not text: return fallback try: parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) except ValueError: return fallback if parsed.tzinfo is None: return parsed.replace(tzinfo=timezone.utc) return parsed.astimezone(timezone.utc) def _client_ip(request: Request) -> str: fwd = request.headers.get("x-forwarded-for", "") if fwd: return fwd.split(",")[0].strip() return request.client.host if request.client else "unknown" def _check_rate_limit(request: Request, max_hits: int, window_s: int) -> dict[str, int]: """Delegate to the configured rate limiter backend.""" ip = _client_ip(request) meta = rate_limiter.check(ip, max_hits, window_s) if meta.get("exceeded"): raise HTTPException( status_code=429, detail="Rate limit exceeded. Try again later.", headers={ "Retry-After": str(meta["retry_after"]), "X-RateLimit-Limit": str(meta["limit"]), "X-RateLimit-Remaining": "0", "X-RateLimit-Reset": str(meta["reset_epoch"]), }, ) return { "limit": meta["limit"], "remaining": meta["remaining"], "reset_epoch": meta["reset_epoch"], } def _prune_drafts(now: datetime | None = None) -> int: """Delegate to the configured draft store backend. Returns number removed.""" removed = draft_store.prune(DRAFT_TTL_HOURS, MAX_DRAFTS) # Also sync the legacy DRAFTS dict for tests that inspect it directly. if hasattr(draft_store, "_data"): DRAFTS.clear() DRAFTS.update(draft_store._data) return removed def _load_logo_data_url() -> str: logo_path = Path(__file__).with_name("logo.jpeg") if not logo_path.exists(): return "" try: raw = logo_path.read_bytes() encoded = base64.b64encode(raw).decode("ascii") return f"data:image/jpeg;base64,{encoded}" except Exception: return "" def _safe_text(value: Any, fallback: str = "-") -> str: if value is None: return fallback text = str(value).strip() return text if text else fallback def _escape(value: Any, fallback: str = "-") -> str: return escape(_safe_text(value, fallback)) def _to_float(value: Any) -> float | None: if value is None: return None if isinstance(value, (int, float)): return float(value) text = str(value).replace(",", "").strip() if not text: return None match = re.search(r"[-+]?\d+(?:\.\d+)?", text) if not match: return None try: return float(match.group(0)) except Exception: return None def _to_bool(value: Any) -> bool: if isinstance(value, bool): return value return str(value).strip().lower() in {"1", "true", "yes", "y"} def _format_number(value: Any, decimals: int = 0, fallback: str = "-") -> str: num = _to_float(value) if num is None: return fallback if decimals <= 0: return f"{round(num):,}" return f"{num:,.{decimals}f}" def _format_au_date(value: Any, fallback: str | None = None) -> str: text = _safe_text(value, "") if not text: return fallback or _utcnow().strftime("%d/%m/%Y") parse_candidates = [text] if "T" in text: parse_candidates.append(text.split("T", 1)[0]) for candidate in parse_candidates: for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%d-%m-%Y", "%B %d, %Y", "%d %B %Y"): try: return datetime.strptime(candidate, fmt).strftime("%d/%m/%Y") except ValueError: continue try: parsed = _parse_datetime_utc(candidate, _utcnow()) return parsed.strftime("%d/%m/%Y") except ValueError: continue return text def _table_rows_to_mapping(table: dict[str, Any]) -> dict[str, Any]: if not isinstance(table, dict): return {} rows = table.get("rows", []) if isinstance(table.get("rows"), list) else [] mapping: dict[str, Any] = {} for row in rows: if not isinstance(row, list) or len(row) < 2: continue key = _normalize_title_key(row[0]) if not key: continue mapping[key] = row[1] return mapping def _find_payload_table(payload: dict[str, Any], title_keywords: tuple[str, ...]) -> dict[str, Any] | None: tables = payload.get("tables", []) if isinstance(payload.get("tables"), list) else [] for table in tables: if not isinstance(table, dict): continue title_key = _normalize_title_key(_safe_text(table.get("title"), "")) if all(keyword in title_key for keyword in title_keywords): return table return None def _find_2min_queue_peak(payload: dict[str, Any]) -> float | None: """Return the highest 2-minute hold-cycle queue value across all Directional Queue Summary tables.""" tables = payload.get("tables", []) if isinstance(payload.get("tables"), list) else [] best: float | None = None swt_best: float | None = None for tbl in tables: if not isinstance(tbl, dict): continue title_lc = _safe_text(tbl.get("title"), "").lower() if "queue" not in title_lc: continue rows = tbl.get("rows", []) if isinstance(tbl.get("rows"), list) else [] columns = tbl.get("columns", []) if isinstance(tbl.get("columns"), list) else [] col_keys = [_safe_text(c, "").lower() for c in columns] for row in rows: if not isinstance(row, list) or not row: continue label = _safe_text(row[0], "").lower() # SWT queue tables often store the 2-minute hold-cycle peak as "Queue Peak" # without explicitly including "2 min" in the row label. if "swt" in title_lc and ("queue" in label or "peak" in label): for cell in row[1:]: val_str = re.sub(r"[^\d.]", "", _safe_text(cell, "")) try: val = float(val_str) if swt_best is None or val > swt_best: swt_best = val except (ValueError, TypeError): pass if "2 min" not in label and "2min" not in label and "per 2" not in label and "agttm" not in label: continue for idx, cell in enumerate(row[1:], start=1): val_str = re.sub(r"[^\d.]", "", _safe_text(cell, "")) try: val = float(val_str) if best is None or val > best: best = val except (ValueError, TypeError): pass return best if best is not None else swt_best def _build_report_context(payload: dict[str, Any]) -> dict[str, Any]: project = payload.get("project", {}) if isinstance(payload.get("project"), dict) else {} inputs = payload.get("inputs", {}) if isinstance(payload.get("inputs"), dict) else {} results = payload.get("results", {}) if isinstance(payload.get("results"), dict) else {} raw = payload.get("raw_js_results", {}) if isinstance(payload.get("raw_js_results"), dict) else {} notes = payload.get("notes", []) if isinstance(payload.get("notes"), list) else [] site_details = payload.get("selected_site_details", {}) if isinstance(payload.get("selected_site_details"), dict) else {} peak_diagnostics = payload.get("peak_diagnostics", {}) if isinstance(payload.get("peak_diagnostics"), dict) else {} summary_results_table = _find_payload_table(payload, ("summary", "computed", "results")) summary_results_map = _table_rows_to_mapping(summary_results_table or {}) def _from_summary(*keys: str) -> Any: for key in keys: normalized = _normalize_title_key(key) if normalized in summary_results_map: return summary_results_map.get(normalized) return None d1_vadt = _to_float( inputs.get("d1_vadt_opening_year") or inputs.get("d1_vadt") or raw.get("d1_vadt") ) d2_vadt = _to_float( inputs.get("d2_vadt_opening_year") or inputs.get("d2_vadt") or raw.get("d2_vadt") ) total_vadt = _to_float( inputs.get("opening_year_aadt") or inputs.get("aadt") or raw.get("vadt") ) base_year_aadt = _to_float(inputs.get("base_year_aadt") or inputs.get("aadt") or raw.get("vadt")) opening_year = _safe_text(inputs.get("opening_year") or raw.get("opening_year"), "") growth_rate = _to_float(inputs.get("growth_rate_percent") or raw.get("growth_rate_percent")) worst_vcr = _to_float( _from_summary("worst_vcr", "worst v c ratio", "worst hourly vcr") or results.get("worst_vcr") or raw.get("worst_vcr") ) q_2min = _find_2min_queue_peak(payload) queue_peak = q_2min if q_2min is not None else _to_float( _from_summary("queue_peak_m", "peak_queue_m", "peak queue") or results.get("queue_peak_m") or raw.get("queue_peak_m") ) d1_queue_peak = _to_float(raw.get("d1_queue_peak_m")) d2_queue_peak = _to_float(raw.get("d2_queue_peak_m")) direction_total = (d1_vadt or 0) + (d2_vadt or 0) d1_pct = ((d1_vadt or 0) / direction_total * 100) if direction_total > 0 else None d2_pct = ((d2_vadt or 0) / direction_total * 100) if direction_total > 0 else None return { "project_name": _safe_text(project.get("name"), "Traffic Impact Assessment"), "location": _safe_text(project.get("location"), "Site location not specified"), "report_date": _format_au_date(project.get("report_date")), "prepared_by": _safe_text(project.get("prepared_by"), "Planner's Name"), "cc_number": _safe_text(project.get("cc_number"), "CC0000"), "road_mode": _safe_text(inputs.get("road_operation_mode"), "TWO-WAY"), "base_year": _safe_text(inputs.get("base_year") or raw.get("base_year"), "Current year"), "opening_year": opening_year, "total_vadt": total_vadt, "base_year_aadt": base_year_aadt, "d1_vadt": d1_vadt, "d2_vadt": d2_vadt, "d1_pct": d1_pct, "d2_pct": d2_pct, "growth_rate": growth_rate, "worst_vcr": worst_vcr, "queue_peak": queue_peak, "queue_2min_peak": _find_2min_queue_peak(payload), "d1_queue_peak": d1_queue_peak, "d2_queue_peak": d2_queue_peak, "los": _safe_text(_from_summary("los", "level of service") or results.get("los"), "-"), "detour_recommended": _to_bool(_from_summary("detour_recommended", "detour recommended") or results.get("detour_recommended")), "notes": [str(note).strip() for note in notes if str(note).strip()], "selected_site_details": { _safe_text(key, ""): _safe_text(value, "") for key, value in site_details.items() if _safe_text(key, "") and _safe_text(value, "") }, "peak_diagnostics": { _safe_text(key, ""): value for key, value in peak_diagnostics.items() if _safe_text(key, "") }, } def _normalize_title_key(value: Any) -> str: text = _safe_text(value, "").lower() text = text.replace("direction 1", "d1") text = text.replace("direction 2", "d2") text = text.replace("directional", "direction") text = re.sub(r"[^a-z0-9]+", " ", text) return re.sub(r"\s+", " ", text).strip() def _title_tokens(value: Any) -> set[str]: ignored = { "the", "and", "for", "with", "from", "table", "chart", "analysis", "summary", "detailed", "traffic", "results", "report", } return {token for token in _normalize_title_key(value).split() if token and token not in ignored} def _mapping_to_table(title: str, data: Any, key_label: str, value_label: str, table_id: str = "") -> dict[str, Any]: if not isinstance(data, dict): return {"table_id": table_id, "title": title, "columns": [key_label, value_label], "rows": []} rows = [[str(key).replace("_", " ").title(), _safe_text(value)] for key, value in data.items()] return {"table_id": table_id, "title": title, "columns": [key_label, value_label], "rows": rows} def _build_report_tables(payload: dict[str, Any]) -> list[dict[str, Any]]: inputs = payload.get("inputs", {}) if isinstance(payload.get("inputs"), dict) else {} results = payload.get("results", {}) if isinstance(payload.get("results"), dict) else {} payload_tables = payload.get("tables", []) if isinstance(payload.get("tables"), list) else [] # Check what title keys already exist in the payload tables to avoid duplicates existing_title_keys = { _normalize_title_key(_safe_text(t.get("title"), "")) for t in payload_tables if isinstance(t, dict) } tables: list[dict[str, Any]] = [] # Only add simplified fallback tables if the richer DOM versions aren't already present if inputs and not any("analysis parameters" in k for k in existing_title_keys): tables.append(_mapping_to_table("Analysis Parameters", inputs, "Parameter", "Value", "analysis_parameters")) if results and not any("summary of computed results" in k for k in existing_title_keys): tables.append(_mapping_to_table("Summary of Computed Results", results, "Metric", "Value", "summary_computed_results")) tables.extend(table for table in payload_tables if isinstance(table, dict)) return tables def _analyze_table_data(table_data: dict[str, Any]) -> dict[str, Any]: columns = table_data.get("columns", []) if isinstance(table_data.get("columns"), list) else [] rows = table_data.get("rows", []) if isinstance(table_data.get("rows"), list) else [] cleaned_rows: list[list[str]] = [] numeric_cells: list[tuple[float, str, str]] = [] first_column_labels: list[str] = [] for row in rows: if not isinstance(row, list) or not row: continue cleaned_row = [_safe_text(cell, "-") for cell in row] cleaned_rows.append(cleaned_row) if cleaned_row and cleaned_row[0] not in {"-", ""}: first_column_labels.append(cleaned_row[0]) for idx, cell in enumerate(cleaned_row): if idx == 0: continue num = _to_float(cell) if num is None: continue row_label = cleaned_row[0] if cleaned_row else f"Row {len(cleaned_rows)}" column_label = _safe_text(columns[idx], f"Column {idx + 1}") if idx < len(columns) else f"Column {idx + 1}" numeric_cells.append((num, row_label, column_label)) top_numeric = sorted(numeric_cells, key=lambda item: item[0], reverse=True)[:3] bottom_numeric = sorted(numeric_cells, key=lambda item: item[0])[:2] distinct_labels = list(dict.fromkeys(first_column_labels)) return { "title": _safe_text(table_data.get("title"), "Untitled Table"), "columns": columns, "rows": cleaned_rows, "row_count": len(cleaned_rows), "column_count": len(columns) if columns else max((len(row) for row in cleaned_rows), default=0), "numeric_count": len(numeric_cells), "numeric_min": min((cell[0] for cell in numeric_cells), default=None), "numeric_max": max((cell[0] for cell in numeric_cells), default=None), "top_numeric": top_numeric, "bottom_numeric": bottom_numeric, "labels": distinct_labels[:6], "sample_rows": cleaned_rows[:6], } def _summarize_table_for_prompt(table_data: dict[str, Any]) -> dict[str, Any]: analysis = _analyze_table_data(table_data) top_cells = [ { "value": value, "row_label": row_label, "column_label": column_label, } for value, row_label, column_label in analysis["top_numeric"] ] return { "table_id": _safe_text(table_data.get("table_id"), ""), "title": analysis["title"], "columns": analysis["columns"][:16], "row_count": analysis["row_count"], "column_count": analysis["column_count"], "numeric_count": analysis["numeric_count"], "numeric_min": analysis["numeric_min"], "numeric_max": analysis["numeric_max"], "labels": analysis["labels"], "sample_rows": analysis["sample_rows"][:12], "top_numeric_cells": top_cells, "bottom_numeric_cells": [ {"value": v, "row_label": r, "column_label": c} for v, r, c in analysis["bottom_numeric"] ], } def _build_table_scenario_text(title: str) -> str: title_key = _normalize_title_key(title) if "summary of computed results" in title_key: return ( "These controlling outputs typically emerge when directional demand, lane closure constraints, and work-zone control delays align during the peak operating period. " "A high queue or V/C outcome usually signals that short disturbances, heavy-vehicle platoons, or an extended stop-go cycle can rapidly push the corridor into unstable operation." ) if "analysis parameters" in title_key or "input" in title_key: return ( "This parameter set becomes critical when the field operating conditions differ from the assumed road mode, growth rate, or lane availability. " "Any departure between assumed inputs and actual site conditions should be checked first because it can materially shift queue and V/C outcomes." ) if "queue" in title_key and "hourly" in title_key: return ( "Hourly queue stress is usually concentrated in the hours where arrival demand exceeds discharge opportunities during lane closure or stop-go control. " "The controlling condition often occurs when queue storage from one hour is not fully recovered before the next peak hour begins." ) if "queue" in title_key: return ( "Elevated queue conditions commonly occur when temporary traffic control phases, reduced lane capacity, or strong directional peaks limit discharge opportunities. " "This is the table to review when assessing whether queue storage may extend into upstream accesses, intersections, or sensitive frontages." ) if "vcr" in title_key or "los" in title_key: return ( "High V/C conditions occur when effective work-zone capacity is constrained by lane closure, heavy vehicles, turning friction, or peak directional loading. " "Values near or above practical capacity indicate the network has limited resilience, so relatively minor disturbances can trigger disproportionate delay and recovery time." ) if "detour" in title_key or "diversion" in title_key: return ( "Detour pressure becomes material when diverted traffic is reassigned to roads with limited spare capacity during the same peak period as the primary corridor impact. " "These conditions are most important where side-road intersections, local access, or school and freight activity are already operating close to their normal thresholds." ) if "grouped directional summary" in title_key or "directional" in title_key: return ( "Directional imbalance becomes important when one travel direction attracts a dominant commuter, freight, or school-period demand profile. " "That imbalance often explains why one carriageway controls queue and V/C risk even though the combined daily volume appears reasonable at corridor level." ) return ( "The conditions reflected in this table usually become important when multiple moderate effects combine within the same operating window. " "Review the controlling rows and periods together rather than in isolation so the mitigation response remains aligned with the actual operational trigger." ) def _build_fallback_table_analysis(table_data: dict[str, Any], payload: dict[str, Any] | None = None) -> dict[str, str]: analysis = _analyze_table_data(table_data) title = analysis["title"] title_key = _normalize_title_key(title) ctx = _build_report_context(payload or {}) site_details = ctx.get("selected_site_details", {}) if isinstance(ctx.get("selected_site_details"), dict) else {} peak = ctx.get("peak_diagnostics", {}) if isinstance(ctx.get("peak_diagnostics"), dict) else {} if "analysis parameters" in title_key: site_bits = [] if site_details.get("site_id"): site_bits.append(f"Site ID {site_details['site_id']}") if site_details.get("road_name"): site_bits.append(site_details["road_name"]) if site_details.get("count_year"): site_bits.append(f"count year {site_details['count_year']}") applied_hv_rt = [] if site_details.get("applied_d1_hv_percent"): applied_hv_rt.append(f"D1 HV {site_details['applied_d1_hv_percent']}%") if site_details.get("applied_d2_hv_percent"): applied_hv_rt.append(f"D2 HV {site_details['applied_d2_hv_percent']}%") if site_details.get("applied_d1_rt_percent"): applied_hv_rt.append(f"D1 RT {site_details['applied_d1_rt_percent']}%") if site_details.get("applied_d2_rt_percent"): applied_hv_rt.append(f"D2 RT {site_details['applied_d2_rt_percent']}%") summary_parts = [ f"Analysis parameters capture the selected site, growth, and directional demand assumptions used for the opening-year assessment." ] if site_bits: summary_parts.append(f"The assessment is anchored to {'; '.join(site_bits)}.") if site_details.get("site_hv_percent"): summary_parts.append(f"The selected site reports HV content of {site_details['site_hv_percent']}.") if applied_hv_rt: summary_parts.append(f"Applied heavy-vehicle and rigid-truck inputs are {', '.join(applied_hv_rt)}.") if site_details.get("google_maps_url"): summary_parts.append("A Google Maps reference is included in the Selected Site Details section for field verification.") return { "title": title, "summary": " ".join(summary_parts), "scenario": ( "These inputs should be checked first during review because any change to the selected site source data, opening year, growth rate, HV share, or RT share will flow directly through the hourly profile, queue, and V/C outputs." ), "chart_caption": "Current selected-site hourly traffic profile showing the base directional pattern used for peak-hour interpretation.", } if "hourly queue" in title_key: wait_minutes = "2" peak_time = _safe_text(peak.get("queue_peak_time"), "the controlling hour") peak_direction = _safe_text(peak.get("queue_peak_direction"), "the controlling direction") peak_value = _format_number(peak.get("queue_peak_value_m"), 0, "-") return { "title": title, "summary": ( f"{title} sets out the hourly queue result based on a standard {wait_minutes}-minute hold and release cycle. " f"The controlling queue occurs around {peak_time} on {peak_direction}, where the peak queue reaches approximately {peak_value} m." ), "scenario": ( f"Review this section to confirm when queue storage becomes critical under the {wait_minutes}-minute cycle, whether the queue is isolated to one direction, and whether the modeled wait-time is appropriate for site-specific stakeholder expectations." ), "chart_caption": ( f"Hourly queue plot assuming a standard {wait_minutes}-minute hold and release cycle. The controlling queue occurs around {peak_time} on {peak_direction}." ), } if "hourly vcr" in title_key or ("vcr" in title_key and "hourly" in title_key): peak_time = _safe_text(peak.get("los_peak_time"), "the controlling hour") peak_direction = _safe_text(peak.get("los_peak_direction"), "the controlling direction") peak_vcr = _format_number(peak.get("worst_hourly_vcr"), 2, "-") peak_los = _safe_text(peak.get("worst_hourly_los"), "-") return { "title": title, "summary": ( f"{title} tracks the hourly work-zone V/C profile and associated LOS. " f"The controlling LOS condition occurs around {peak_time} on {peak_direction}, where the worst hourly VCR reaches {peak_vcr} (LOS {peak_los})." ), "scenario": ( "This section shows when capacity stress becomes most acute through the day. Use it to identify whether mitigation is needed only in short peak windows or whether the corridor remains sensitive across multiple hours." ), "chart_caption": ( f"Hourly V/C plot highlighting the controlling hour around {peak_time} on {peak_direction}, where the worst modeled condition reaches VCR {peak_vcr} (LOS {peak_los})." ), } summary_parts = [] title_lower = title_key if "peak hour" in title_lower and "hourly" in title_lower: if analysis["top_numeric"]: top_value, row_label, column_label = analysis["top_numeric"][0] periods = ", ".join(analysis["labels"][:3]) if analysis["labels"] else "the surveyed periods" summary_parts.append( f"{title} records peak-hour traffic volumes across {periods}. " f"The highest recorded volume is {_format_number(top_value, 0)} veh/h for {row_label} in the {column_label} period." ) else: periods = ", ".join(analysis["labels"][:3]) if analysis["labels"] else "the surveyed periods" summary_parts.append(f"{title} provides peak-hour traffic volumes across {periods}.") elif "grouped" in title_lower and "direction" in title_lower: if analysis["top_numeric"]: top_value, row_label, column_label = analysis["top_numeric"][0] periods = ", ".join(analysis["labels"][:3]) if analysis["labels"] else "the surveyed periods" summary_parts.append( f"The directional traffic summary covers {periods}. " f"The highest recorded value is {_format_number(top_value, 0)} for {row_label} in the {column_label} column." ) if analysis["numeric_min"] is not None and analysis["numeric_max"] is not None and analysis["numeric_min"] != analysis["numeric_max"]: summary_parts.append( f"Values range from {_format_number(analysis['numeric_min'], 0)} to {_format_number(analysis['numeric_max'], 0)} across all periods." ) else: summary_parts.append(f"The directional traffic summary is presented for review and confirmation.") else: if analysis["top_numeric"]: top_value, row_label, column_label = analysis["top_numeric"][0] periods_text = f"covering {', '.join(analysis['labels'][:3])}" if analysis["labels"] else "" summary_parts.append( f"{title} sets out the {analysis['row_count']}-row result dataset" + (f" {periods_text}" if periods_text else "") + f". The highest recorded value is {_format_number(top_value, 2)} for {row_label} ({column_label})." ) elif analysis["labels"]: summary_parts.append(f"{title} covers {', '.join(analysis['labels'][:4])}.") else: summary_parts.append( f"{title} provides reference data supporting the assessment findings. " "Review and confirm values against site-specific conditions." ) chart_caption = ( f"This chart highlights the key pattern for {title.lower()} so the controlling periods can be identified before reviewing the detailed table below." ) return { "title": title, "summary": " ".join(summary_parts), "scenario": _build_table_scenario_text(title), "chart_caption": chart_caption, } def _build_fallback_professional_commentary( payload: dict[str, Any], table_analyses: list[dict[str, str]], ) -> dict[str, list[str]]: ctx = _build_report_context(payload) commentary: list[str] = [] traffic_statement = [] if ctx["total_vadt"] is not None: traffic_statement.append(f"approximately {_format_number(ctx['total_vadt'])} vehicles per day") if ctx["growth_rate"] is not None: traffic_statement.append(f"a growth allowance of {_format_number(ctx['growth_rate'], 2)}% per annum") traffic_suffix = " with " + " and ".join(traffic_statement) if traffic_statement else "" commentary.append( f"The assessment for {ctx['project_name']} at {ctx['location']} indicates that the modeled road network should be interpreted as a constrained work-stage environment rather than a normal operating condition{traffic_suffix}. " "The reported outputs are therefore most useful as a screening tool for operational risk, queue storage exposure, and the timing of mitigation triggers." ) performance_bits: list[str] = [] if ctx["worst_vcr"] is not None: performance_bits.append(f"a worst V/C ratio of {_format_number(ctx['worst_vcr'], 2)} corresponding to LOS {ctx['los']}") _q2 = ctx.get("queue_2min_peak") _qfallback = ctx["queue_peak"] _q_display = _q2 if _q2 is not None else _qfallback _q_label = f"{_format_number(_q_display)} m (2-minute hold cycle)" if _q2 is not None else f"{_format_number(_qfallback)} m" if _q_display is not None: performance_bits.append(f"a peak queue on the order of {_q_label}") if performance_bits: commentary.append( "Operationally, the model points to " + " and ".join(performance_bits) + ". " "These values suggest that traffic performance is being controlled by a limited number of peak-period constraints, so site management should focus on those controlling periods rather than average daily conditions." ) commentary.append( "From an engineering perspective, mitigation should prioritise maintaining discharge opportunities, reducing unnecessary blockage time, and protecting upstream intersections and accesses from queue spillback. " "Where detour planning is triggered, the diversion strategy should be treated as an operational management measure with active monitoring rather than a one-off desktop assumption." ) conclusion_points = [ "The controlling risk is concentrated in peak operating periods rather than uniformly across the day.", "Queue and V/C results should be used to set monitoring triggers, traffic controller response actions, and escalation points for temporary traffic management.", "Any material change in closure duration, lane availability, or directional demand should prompt the assessment to be refreshed before implementation.", ] if ctx["detour_recommended"]: conclusion_points.insert( 0, "Detour planning should be retained as an active mitigation measure because the modeled condition indicates insufficient resilience under the controlling scenario.", ) else: conclusion_points.insert( 0, "A full detour response is not automatically required by the current model, but field observation and staged contingency planning remain appropriate.", ) if table_analyses: conclusion_points.append( f"The detailed table set has been interpreted together with {len(table_analyses)} supporting result table(s) so that mitigation can be tied to the specific controlling scenario." ) return { "professional_commentary_paragraphs": commentary, "conclusion_points": conclusion_points[:5], } def _build_fallback_executive_paragraphs(payload: dict[str, Any]) -> list[str]: ctx = _build_report_context(payload) paragraphs: list[str] = [] paragraphs.append( f"This Traffic Impact Assessment relates to {ctx['project_name']} at {ctx['location']}. The assessment has been prepared for {ctx['report_date']} using the current {ctx['road_mode']} operating configuration and focuses on queue performance, directional demand balance, and whether mitigation or diversion is warranted under the modeled condition." ) traffic_bits: list[str] = [] year_tag = f" at opening year ({ctx['opening_year']})" if ctx.get("opening_year") else " at opening year" if ctx["total_vadt"] is not None: traffic_bits.append(f"the modeled daily traffic volume is approximately {_format_number(ctx['total_vadt'])} vehicles per day{year_tag}") if ctx["d1_vadt"] is not None and ctx["d2_vadt"] is not None: d1_share = f", {ctx['d1_pct']:.1f}% of total" if ctx["d1_pct"] is not None else "" d2_share = f", {ctx['d2_pct']:.1f}% of total" if ctx["d2_pct"] is not None else "" traffic_bits.append( f"directional demand is split between D1 ({_format_number(ctx['d1_vadt'])} vpd{d1_share}) and D2 ({_format_number(ctx['d2_vadt'])} vpd{d2_share})" ) if ctx["growth_rate"] is not None: base_yr = ctx.get("base_year", "") open_yr = ctx.get("opening_year", "") yr_range = f" ({base_yr} → {open_yr})" if base_yr and open_yr and base_yr != open_yr else "" traffic_bits.append(f"an annual growth rate of {_format_number(ctx['growth_rate'], 2)}% has been applied{yr_range}") if traffic_bits: paragraphs.append("Traffic demand context indicates that " + ", ".join(traffic_bits) + ".") operational_bits: list[str] = [] if ctx["worst_vcr"] is not None: operational_bits.append(f"the worst modeled V/C ratio is {_format_number(ctx['worst_vcr'], 2)} (LOS {ctx['los']})") _q2 = ctx.get("queue_2min_peak") _qf = ctx["queue_peak"] _qv = _q2 if _q2 is not None else _qf _ql = f"{_format_number(_qv)} m (e.g. {_format_number(_qv, 0)} m queue for 2-minute hold)" if _q2 is not None else f"{_format_number(_qf)} m" if _qv is not None: operational_bits.append(f"the peak queue demand is approximately {_ql}") if ctx["d1_queue_peak"] is not None or ctx["d2_queue_peak"] is not None: operational_bits.append(f"directional peak queues are D1 {_format_number(ctx['d1_queue_peak'])} m and D2 {_format_number(ctx['d2_queue_peak'])} m") if operational_bits: paragraphs.append("Operational performance outcomes show that " + "; ".join(operational_bits) + ".") implication = ( "On the basis of the current queue and capacity outputs, detour planning should be treated as an active mitigation requirement." if ctx["detour_recommended"] else "On the basis of the current queue and capacity outputs, an immediate detour trigger is not indicated, although staged monitoring and field verification remain important during implementation." ) notes_suffix = f" Key supporting observations include: {'; '.join(ctx['notes'])}." if ctx["notes"] else "" paragraphs.append(implication + notes_suffix) return paragraphs def _build_fallback_explanation_notes(payload: dict[str, Any]) -> list[str]: ctx = _build_report_context(payload) notes: list[str] = [ f"Assessment location and basis: {ctx['project_name']} at {ctx['location']} under {ctx['road_mode']} road operation settings." ] if ctx["total_vadt"] is not None: year_tag = f" at {ctx['opening_year']}" if ctx.get("opening_year") else " at opening year" notes.append( f"Demand profile: total modeled traffic{year_tag} is about {_format_number(ctx['total_vadt'])} vpd, with D1 at {_format_number(ctx['d1_vadt'])} vpd and D2 at {_format_number(ctx['d2_vadt'])} vpd." ) if ctx["worst_vcr"] is not None: notes.append( f"Network performance: worst V/C ratio is {_format_number(ctx['worst_vcr'], 2)}, which places the controlling condition at LOS {ctx['los']}." ) _q2 = ctx.get("queue_2min_peak") _qf = ctx["queue_peak"] _qv = _q2 if _q2 is not None else _qf if _qv is not None: _suffix = " (2-minute hold cycle)" if _q2 is not None else "" notes.append( f"Queue implications: the longest modeled queue is approximately {_format_number(_qv, 0)} m{_suffix}, with D1 peak queue {_format_number(ctx['d1_queue_peak'])} m and D2 peak queue {_format_number(ctx['d2_queue_peak'])} m." ) notes.append( "Mitigation interpretation: detour planning is recommended because the modeled queue and/or capacity outcomes indicate material operational risk during the work stage." if ctx["detour_recommended"] else "Mitigation interpretation: no immediate detour trigger is indicated by the current model, but field validation and staged monitoring should still be undertaken during implementation." ) notes.extend(ctx["notes"]) return notes[:8] def _request_gemini_report_notes(payload: dict[str, Any]) -> dict[str, Any] | None: api_key = os.environ.get("GEMINI_API_KEY", "").strip() if not api_key: return None report_tables = _build_report_tables(payload) prompt = { "task": "Write a professional, readable traffic engineering report with per-table summaries. Summaries must feel like they were written by a senior traffic engineer for a council submission — not auto-generated.", "instructions": [ "Return strict JSON only.", "Use Australian traffic engineering wording and conventions.", "State where the assessment applies and what the modeled outputs mean operationally.", "Do not invent values beyond the supplied context.", "Provide 3 or 4 executive summary paragraphs and 4 to 6 explanation notes.", "For every supplied table title, return a 'summary' field that is a natural-language interpretation of what the table data shows — NOT a description of the table structure like row/column counts.", "Table summaries must explain the engineering significance: what the numbers mean for traffic operations, which values are controlling, and what the practitioner should focus on.", "For directional summaries, explain the demand split and what it means for queue management.", "For queue tables, describe when and where the worst queuing occurs, how long queues extend, and what that means for upstream intersections or access points.", "For VCR/LOS tables, explain which periods exceed capacity and what that signals for work-zone management.", "For peak hour tables, describe the dominant traffic pattern and when the critical operating windows occur.", "For detour tables, describe the impact of diversion on receiving roads and whether there is spare capacity.", "For pedestrian detour tables, explain the added travel time burden on pedestrians.", "Each table summary should be 2-4 sentences of professional engineering narrative.", "Each scenario field should explain when and why the condition in the table typically becomes critical.", "Emphasize the standard 2-minute hold and release cycle as the primary basis for queue length interpretations.", "Use the exact supplied table titles in the response so they can be mapped deterministically.", "Provide 3 professional commentary paragraphs and 3 to 5 conclusion points.", "Write as though this will be read by a council traffic engineer or road authority reviewer." ], "response_schema": { "executive_paragraphs": ["string"], "explanation_notes": ["string"], "table_analyses": [ { "title": "string", "summary": "string", "scenario": "string", "chart_caption": "string" } ], "professional_commentary_paragraphs": ["string"], "conclusion_points": ["string"] }, "context": _build_report_context(payload), "tables": [_summarize_table_for_prompt(table) for table in report_tables[:24]], } request_body = json.dumps( { "contents": [{"parts": [{"text": json.dumps(prompt, ensure_ascii=True)}]}], "generationConfig": { "temperature": 0.35, "responseMimeType": "application/json", }, } ).encode("utf-8") request = urllib.request.Request( f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}", data=request_body, headers={"Content-Type": "application/json"}, method="POST", ) import time as _time body = None for attempt in range(3): try: with urllib.request.urlopen(request, timeout=30) as response: body = response.read().decode("utf-8") break except urllib.error.HTTPError as http_err: if http_err.code == 429 and attempt < 2: _time.sleep(2 * (attempt + 1)) continue return None except (urllib.error.URLError, TimeoutError): return None if not body: return None try: parsed = json.loads(body) text = ( parsed.get("candidates", [{}])[0] .get("content", {}) .get("parts", [{}])[0] .get("text", "") ) if not text: return None data = json.loads(text) paragraphs = [str(item).strip() for item in data.get("executive_paragraphs", []) if str(item).strip()] notes = [str(item).strip() for item in data.get("explanation_notes", []) if str(item).strip()] table_analyses = [] for item in data.get("table_analyses", []): if not isinstance(item, dict): continue title = str(item.get("title", "")).strip() summary = str(item.get("summary", "")).strip() scenario = str(item.get("scenario", "")).strip() chart_caption = str(item.get("chart_caption", "")).strip() if not title: continue table_analyses.append( { "title": title, "summary": summary, "scenario": scenario, "chart_caption": chart_caption, } ) professional_commentary = [ str(item).strip() for item in data.get("professional_commentary_paragraphs", []) if str(item).strip() ] conclusion_points = [str(item).strip() for item in data.get("conclusion_points", []) if str(item).strip()] if not paragraphs and not notes and not table_analyses and not professional_commentary and not conclusion_points: return None return { "executive_paragraphs": paragraphs, "explanation_notes": notes, "table_analyses": table_analyses, "professional_commentary_paragraphs": professional_commentary, "conclusion_points": conclusion_points, } except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, KeyError, IndexError, TypeError, ValueError): return None def _build_executive_content(payload: dict[str, Any]) -> dict[str, Any]: report_tables = _build_report_tables(payload) fallback_table_analyses = [_build_fallback_table_analysis(table, payload) for table in report_tables] fallback_commentary = _build_fallback_professional_commentary(payload, fallback_table_analyses) fallback = { "executive_paragraphs": _build_fallback_executive_paragraphs(payload), "explanation_notes": _build_fallback_explanation_notes(payload), "table_analyses": fallback_table_analyses, "professional_commentary_paragraphs": fallback_commentary["professional_commentary_paragraphs"], "conclusion_points": fallback_commentary["conclusion_points"], } generated = _request_gemini_report_notes(payload) if not generated: return fallback fallback_map = { _normalize_title_key(item["title"]): item for item in fallback_table_analyses } generated_map = { _normalize_title_key(item.get("title")): item for item in generated.get("table_analyses", []) if isinstance(item, dict) and _normalize_title_key(item.get("title")) } merged_table_analyses = [] for table in report_tables: title_key = _normalize_title_key(table.get("title")) fallback_item = fallback_map.get(title_key, _build_fallback_table_analysis(table, payload)) generated_item = generated_map.get(title_key, {}) # For hourly queue and hourly vcr tables, keep fallback chart_caption only # (preserves formula-specific peak references) but use Gemini for summary/scenario force_fallback_caption = any( key in title_key for key in ["hourly queue", "hourly vcr"] ) merged_table_analyses.append( { "title": fallback_item["title"], "summary": generated_item.get("summary") or fallback_item["summary"], "scenario": generated_item.get("scenario") or fallback_item["scenario"], "chart_caption": fallback_item["chart_caption"] if force_fallback_caption else (generated_item.get("chart_caption") or fallback_item["chart_caption"]), } ) return { "executive_paragraphs": generated.get("executive_paragraphs") or fallback["executive_paragraphs"], "explanation_notes": generated.get("explanation_notes") or fallback["explanation_notes"], "table_analyses": merged_table_analyses, "professional_commentary_paragraphs": generated.get("professional_commentary_paragraphs") or fallback["professional_commentary_paragraphs"], "conclusion_points": generated.get("conclusion_points") or fallback["conclusion_points"], } def _render_paragraph_block(paragraphs: list[str]) -> str: cleaned = [str(item).strip() for item in paragraphs if str(item).strip()] if not cleaned: cleaned = ["[Insert executive summary details here...]"] return "".join(f"

{_escape(item)}

" for item in cleaned) def _collect_chart_items(payload: dict[str, Any]) -> list[dict[str, Any]]: def _safe_data_image_url(value: Any) -> str: text = _safe_text(value, "") if not text: return "" if len(text) > 6_000_000: return "" if not re.match(r"^data:image\/(png|jpe?g|webp|gif);base64,[A-Za-z0-9+/=\s]+$", text, re.IGNORECASE): return "" return text raw_charts = payload.get("charts", []) if isinstance(payload.get("charts"), list) else [] chart_items: list[dict[str, Any]] = [] for idx, chart in enumerate(raw_charts): if not isinstance(chart, dict): continue image_data_url = _safe_data_image_url(chart.get("image_data_url")) if not image_data_url: continue raw_table_ids = chart.get("table_ids", []) if isinstance(chart.get("table_ids"), list) else [] table_ids = [_safe_text(item, "") for item in raw_table_ids if _safe_text(item, "")] chart_items.append( { "title": _safe_text(chart.get("title"), f"Chart {idx + 1}"), "image": image_data_url, "canvas_id": _safe_text(chart.get("canvas_id"), ""), "table_ids": table_ids, } ) if not chart_items: fallback = _safe_data_image_url(payload.get("chart_image_data_url")) if fallback: chart_items.append( { "title": "Primary Chart", "image": fallback, "canvas_id": _safe_text(payload.get("chart_image_canvas_id"), ""), } ) return chart_items def _score_chart_match(table_data: dict[str, Any], chart_item: dict[str, Any]) -> int: score = 0 table_title = _safe_text(table_data.get("title"), "") table_id = _normalize_title_key(table_data.get("table_id")) title_key = _normalize_title_key(table_title) chart_key = _normalize_title_key(chart_item.get("title")) canvas_id = _normalize_title_key(chart_item.get("canvas_id")) table_tokens = _title_tokens(table_title) chart_tokens = _title_tokens(chart_key + " " + canvas_id) score += len(table_tokens & chart_tokens) * 3 if table_id in {"analysis parameters", "analysis_parameters"} and "macrohourlychart" in canvas_id: score += 80 if table_id in {"summary computed results", "summary_computed_results"} and "managementvizcanvas" in canvas_id: score += 80 if table_id == "groupedtabled1" and "queuechartd1" in canvas_id: score += 100 if table_id == "groupedtabled1" and "vcrchartd1" in canvas_id: score += 100 if table_id == "groupedtabled2" and "queuechartd2" in canvas_id: score += 100 if table_id == "groupedtabled2" and "vcrchartd2" in canvas_id: score += 100 if table_id == "queuegroupedtabled1" and "queuechartd1" in canvas_id: score += 120 if table_id == "queuegroupedtabled2" and "queuechartd2" in canvas_id: score += 120 if table_id == "queueswtsummarytable" and "hourlyqueuechart" in canvas_id: score += 90 if table_id in {"hourlyqueuetabled1", "hourlyqueuetabled2"} and "hourlyqueuechart" in canvas_id: score += 120 if table_id == "vcrgroupedtabled1" and "vcrchartd1" in canvas_id: score += 120 if table_id == "vcrgroupedtabled2" and "vcrchartd2" in canvas_id: score += 120 if table_id in {"hourlyvcrtabled1", "hourlyvcrtabled2"} and "hourlyvcrchart" in canvas_id: score += 120 if table_id == "detoursegmentdetailedtable" and ("managementvizcanvas" in canvas_id or "macrohourlychart" in canvas_id): score += 20 if "queuechartd1" in canvas_id and "queue" in title_key and ("d1" in title_key or "direction 1" in title_key): score += 30 if "queuechartd2" in canvas_id and "queue" in title_key and ("d2" in title_key or "direction 2" in title_key): score += 30 if "vcrchartd1" in canvas_id and "vcr" in title_key and ("d1" in title_key or "direction 1" in title_key): score += 30 if "vcrchartd2" in canvas_id and "vcr" in title_key and ("d2" in title_key or "direction 2" in title_key): score += 30 if "hourlyqueuechart" in canvas_id and "hourly" in title_key and "queue" in title_key: score += 30 if "hourlyvcrchart" in canvas_id and "hourly" in title_key and ("vcr" in title_key or "los" in title_key): score += 30 if "macrohourlychart" in canvas_id and ("direction" in title_key or "analysis parameters" in title_key): score += 16 if "managementvizcanvas" in canvas_id and "summary of computed results" in title_key: score += 24 if "queue" in title_key and "queue" in chart_key: score += 8 if "vcr" in title_key and "vcr" in chart_key: score += 8 if "hourly" in title_key and "hourly" in chart_key: score += 5 if "directional" in title_key and "traffic data visualization" in chart_key: score += 6 return score def _select_charts_for_table( table_data: dict[str, Any], chart_items: list[dict[str, Any]], ) -> list[dict[str, Any]]: table_id = _normalize_title_key(table_data.get("table_id")) explicit_matches: list[dict[str, Any]] = [] has_explicit_links = False for chart_item in chart_items: raw_table_ids = chart_item.get("table_ids") if isinstance(chart_item, dict) else None if not isinstance(raw_table_ids, list) or not raw_table_ids: continue normalized_table_ids = { _normalize_title_key(item) for item in raw_table_ids if _safe_text(item, "") } if not normalized_table_ids: continue has_explicit_links = True if table_id and table_id in normalized_table_ids: explicit_matches.append(chart_item) if explicit_matches: return explicit_matches[:2] if has_explicit_links: return [] scored: list[tuple[int, dict[str, Any]]] = [] for chart_item in chart_items: score = _score_chart_match(table_data, chart_item) if score <= 0: continue scored.append((score, chart_item)) if not scored: return [] scored.sort(key=lambda item: item[0], reverse=True) top_score = scored[0][0] selected = [item for score, item in scored if score == top_score] return selected[:2] def _render_embedded_chart(chart_item: dict[str, Any] | None, title: str, caption: str) -> str: if not chart_item: return "" chart_title = _escape(_safe_text(chart_item.get("title"), title)) chart_caption = _escape(caption or "This chart summarises the controlling pattern before the detailed table below.") image_title = _escape(chart_item.get("title"), title) return ( "
" "
" "" "
" f"
{chart_title}
" f"\"{image_title}\"" f"
{chart_caption}
" "
" ) def _render_embedded_charts(chart_items: list[dict[str, Any]] | None, title: str, caption: str) -> str: if not chart_items: return "" return "".join(_render_embedded_chart(item, title, caption) for item in chart_items) def _render_key_value_table( title: str, data: dict[str, Any], analysis: dict[str, str] | None = None, chart_items: list[dict[str, Any]] | None = None, ) -> str: if not isinstance(data, dict) or not data: return "" rows: list[str] = [] for key, val in data.items(): label = _escape(str(key).replace("_", " ").title()) value = _escape(val) rows.append( f"{label}" f"{value}" ) summary_text = _escape((analysis or {}).get("summary"), "This section summarises the key values used to interpret the modeled outcome.") scenario_text = _escape((analysis or {}).get("scenario"), "Review these values together with the detailed result tables to confirm when the controlling condition is expected to emerge.") chart_caption = (analysis or {}).get("chart_caption", "") chart_html = _render_embedded_charts(chart_items, title, chart_caption) return ( f"
" f"
" f" " f" " f"" f"
" f"

{_escape(title)}

" f"

{summary_text}

" f"{chart_html}" "
Detailed table below sets out the supporting values used for the engineering interpretation.
" f"{''.join(rows)}
" f"

{scenario_text}

" f"
" ) def _render_selected_site_details_section(site_details: dict[str, Any]) -> str: if not isinstance(site_details, dict) or not site_details: return "" ordered_fields = [ ("Site ID", "site_id"), ("Source", "source"), ("Road Name", "road_name"), ("Description", "description"), ("Coordinates", "coordinates"), ("Google Maps", "google_maps_url"), ("Count Year", "count_year"), ("Applied Growth Rate", "growth_rate"), ("Selected Site HV%", "site_hv_percent"), ("Data Quality", "data_quality"), ("D1 Direction", "d1_direction"), ("D2 Direction", "d2_direction"), ("D1 VADT", "d1_vadt"), ("D2 VADT", "d2_vadt"), ("Total VADT", "total_vadt"), ("Applied D1 HV%", "applied_d1_hv_percent"), ("Applied D2 HV%", "applied_d2_hv_percent"), ("Applied D1 RT%", "applied_d1_rt_percent"), ("Applied D2 RT%", "applied_d2_rt_percent"), ] rows: list[str] = [] for label, key in ordered_fields: value = _safe_text(site_details.get(key), "") if not value: continue if key == "google_maps_url" and value.startswith(("http://", "https://")): safe_href = escape(value, quote=True) value_html = f'View on Google Maps' else: value_html = _escape(value) rows.append( f"{_escape(label)}" f"{value_html}" ) if not rows: return "" summary_text = ( "Selected site details record the source counter, field description, mapping reference, and the heavy-vehicle / rigid-truck assumptions that feed the assessment." ) scenario_text = ( "Use this section to verify that the adopted counter, mapped location, and HV / RT settings match the corridor actually being assessed before relying on the downstream queue or V/C outputs." ) return ( "
" "
" " " " " "" "
" "

Selected Site Details

" f"

{_escape(summary_text)}

" "
Detailed table below confirms the selected counter, map reference, and applied vehicle-mix inputs used in the report.
" f"{''.join(rows)}
" f"

{_escape(scenario_text)}

" "
" ) def _render_notes(notes: Any) -> str: if not isinstance(notes, list) or not notes: return "
  • No supplementary notes provided.
  • " return "".join(f"
  • {_escape(item)}
  • " for item in notes) def _infer_result_context(key: str, value: str) -> str: """Infer when/context description for a computed result metric.""" key_lc = key.replace("_", " ").lower() if "am" in key_lc and ("peak" in key_lc or "hour" in key_lc): return "AM Peak Period (typically 7–9 am)" if "pm" in key_lc and ("peak" in key_lc or "hour" in key_lc): return "PM Peak Period (typically 4–6 pm)" if ("ev" in key_lc or "evening" in key_lc) and ("peak" in key_lc or "hour" in key_lc): return "Evening Peak Period (typically 6–8 pm)" if "off peak" in key_lc or "off-peak" in key_lc or " op " in f" {key_lc} ": return "Off-Peak / Inter-Peak Period" if "vcr" in key_lc or "v/c" in key_lc or "volume capacity" in key_lc: try: raw = re.sub(r"[^\d.]", "", str(value or "").split()[0]) v = float(raw) if raw else None if v is not None: if v >= 1.5: return "Significantly over capacity (LOS F) — urgent mitigation required" if v >= 1.0: return "Over capacity (LOS F) — mitigation required" if v >= 0.9: return "Near or at capacity (LOS E) — mitigation likely required" if v >= 0.8: return "Approaching capacity (LOS D) — monitor closely" return "Within acceptable capacity threshold (LOS A–C, V/C < 0.80)" except Exception: pass return "Volume-to-Capacity Ratio — compare against LOS thresholds" if "los" in key_lc or "level of service" in key_lc: return "Level of Service — A=free-flow, F=breakdown" if "queue" in key_lc: return "Maximum queue length (2/5/10/15-minute hold scenarios; shockwave model where applicable)" if "delay" in key_lc: return "Average per-vehicle delay at the intersection" if "growth" in key_lc: return "Annual traffic growth rate applied to base volumes" if "peak" in key_lc and "hour" in key_lc: return "Controlling peak-hour period for this analysis" if "total" in key_lc and ("vpd" in key_lc or "vadt" in key_lc or "volume" in key_lc): return "Total daily two-way traffic volume" if "d1" in key_lc or "direction 1" in key_lc: return "Direction 1 (primary / approach direction)" if "d2" in key_lc or "direction 2" in key_lc: return "Direction 2 (secondary / opposing direction)" if "hv" in key_lc or "heavy vehicle" in key_lc: return "Heavy vehicle percentage adopted for analysis" return "—" def _render_computed_results_section( title: str, results: dict[str, Any], analysis: dict[str, str] | None = None, chart_items: list[dict[str, Any]] | None = None, ) -> str: """Render the Summary of Computed Results as a 3-column table (Metric | Value | Context/When).""" if not isinstance(results, dict) or not results: return "" rows: list[str] = [] for key, val in results.items(): label = _escape(str(key).replace("_", " ").title()) value = _escape(val) context = _escape(_infer_result_context(key, _safe_text(val, ""))) rows.append( f"" f"{label}" f"{value}" f"{context}" f"" ) summary_text = _escape( (analysis or {}).get("summary", "This table summarises the key computed traffic metrics. The third column provides context on when each metric is expected to be controlling.") ) scenario_text = _escape( (analysis or {}).get("scenario", "Review these computed results together with the detailed tables and VCR/queue charts to confirm the controlling period and identify any required mitigation.") ) chart_caption = (analysis or {}).get("chart_caption", "") chart_html = _render_embedded_charts(chart_items, title, chart_caption) header_row = ( "" "Metric" "Value" "Context / When" "" ) return ( f"
    " f"
    " f" " f" " f"" f"
    " f"

    {_escape(title)}

    " f"

    {summary_text}

    " f"{chart_html}" "
    Detailed table below sets out the computed metrics with context on when each controlling condition occurs.
    " f"{header_row}{''.join(rows)}
    " f"

    {scenario_text}

    " f"
    " ) def _render_short_detour_route_block(route_label: str, route_tables: list[dict], analysis_map: dict, chart_items: list[dict] | None = None, is_short: bool = False) -> str: """Render the detour block per route. Detailed: Detour Route Information / VPD Calculation / Detour Road Capacity Summary / Estimated Detour Delay Calculation / Detour Road Summary / Road Status After Diversion / Pedestrian Detour Impact Short: Detour Route Information / Estimated Detour Delay - Vehicles / Pedestrian Detour Impact """ if chart_items is None: chart_items = [] label_esc = _escape(route_label) # Classify each table into ordered slots. route_info_tables: list[dict] = [] # Table 27 — route overview vpd_tables: list[dict] = [] dir_capacity_tables: list[dict] = [] road_capacity_tables: list[dict] = [] road_status_tables: list[dict] = [] delay_tables: list[dict] = [] pedestrian_tables: list[dict] = [] detour_summary_tables: list[dict] = [] # Table 28/29 — detour road summary other_tables: list[dict] = [] for table in route_tables: title_raw = _safe_text(table.get("title"), "") title_lc = title_raw.lower().strip() title_stripped = title_lc.strip() # Table 27 or synthetic route info -> route info if re.match(r"table\s*27", title_stripped) or "route information" in title_lc: route_info_tables.append(table) # Table 28/29 -> detour road summary elif re.match(r"table\s*(28|29)", title_stripped): detour_summary_tables.append(table) # Tables 30-32 -> fold into road capacity elif re.match(r"table\s*(3[0-2])", title_stripped): road_capacity_tables.append(table) elif "pedestrian" in title_lc: pedestrian_tables.append(table) elif "delay" in title_lc: delay_tables.append(table) elif "status" in title_lc or "diversion" in title_lc or "existing road" in title_lc: road_status_tables.append(table) elif "directional capacity" in title_lc: # Only include if period columns (index 3+) have at least one real computed value _DASH_SET = {"-", "—", "–", "", "n/a"} _has_period_data = any( _safe_text(cell, "").strip().lower() not in _DASH_SET for row in table.get("rows", []) if isinstance(row, list) for cell in row[3:] if row ) if _has_period_data: dir_capacity_tables.append(table) elif "capacity" in title_lc: road_capacity_tables.append(table) elif "vpd" in title_lc or "segment detailed" in title_lc: vpd_tables.append(table) else: other_tables.append(table) def _render_group(tables: list[dict], fallback_html: str) -> str: if tables: rendered = "".join( _render_data_table(t, analysis_map.get(_normalize_title_key(t.get("title"))), _select_charts_for_table(t, chart_items)) for t in tables ) if rendered.strip(): return rendered return fallback_html # Any unclassified table belongs to "Detour Route Information" (section 1). # This catches route overview tables whose titles don't contain "table 28" literally. route_info_tables.extend(other_tables) # --- HARDCODED EDITABLE TABLE FALLBACKS --- fallback_vpd = ( "" "" "
    DirectionBase VADT (vpd)Growth FactorDesign Year VADT (vpd)Diverted Traffic (vpd)Total VPD on Detour
    D1—————
    D2—————

    Edit to insert calculated VPD values for the detour route under full diversion conditions.

    " ) fallback_dir_capacity = ( "" "" "
    DirectionLane CountPer-Lane Capacity (veh/h)Total Capacity (veh/h)Peak Hour Volume (veh/h)VCRLOS
    D1——————
    D2——————

    Edit to confirm directional capacity and VCR under diversion conditions for the detour road.

    " ) fallback_road_capacity = ( "" "
    ParameterValueNotes
    Road Classification——
    Posted Speed (km/h)——
    Total Two-Way Capacity (vpd)——
    Remaining Surplus Capacity (vpd)——

    Edit to confirm overall road capacity relative to diverted demand.

    " ) fallback_road_status = ( "

    Following full diversion of traffic to this route, confirm that the detour road remains within acceptable operating conditions. Key considerations include: pavement condition, geometric constraints (narrow lanes, sharp curves, limited sight-distance), intersection control adequacy, and pedestrian / cyclist conflicts. Edit this section to record findings.

    " ) fallback_delay = ( "
    ParameterValue
    Detour Route Length (km)—
    Original Route Length (km)—
    Extra Distance (km)—
    Average Travel Speed on Detour (km/h)—
    Estimated Additional Travel Time (min)—
    Delay Classification—

    Edit to calculate and record the additional delay imposed on motorists by the detour route.

    " ) fallback_pedestrian = ( "

    Assess whether the detour route provides safe and accessible pedestrian connectivity. Key items to address: availability of footpath / shared path; suitable crossing facilities at intersections; WCAG / DDA compliance; additional walking distance for pedestrians and approximate delay. Edit this section to record pedestrian impact findings.

    " "
    ParameterValue
    Pedestrian Detour Distance (m)—
    Additional Walking Time (min)—
    Pedestrian Delay Classification—
    Mitigation Recommended—
    " ) fallback_route_info = ( "" "" "" "" "" "
    ParameterDetails
    Detour Route Name—
    Selected Path—
    Route Length (km)—
    Road Classification—

    Edit to insert the selected detour route and path details.

    " ) fallback_detour_summary = ( "" "" "" "
    DirectionLOSVCRCapacity (veh/h)Volume (veh/h)
    D1————
    D2————

    Edit to record the detour road LOS and capacity summary.

    " ) base_html = ( f"
    " f"
    " f"

    {label_esc}

    " "

    1. DETOUR ROUTE INFORMATION

    " + _render_group(route_info_tables, fallback_route_info) + "
    " ) if is_short: # Short report: # 1. Detour Route Information / 2. Estimated Detour Delay - Vehicles / 3. Pedestrian Detour Impact return ( base_html + "

    2. ESTIMATED DETOUR DELAY - VEHICLES

    " + _render_group(delay_tables, fallback_delay) + "
    " + "

    3. PEDESTRIAN DETOUR IMPACT

    " + _render_group(pedestrian_tables, fallback_pedestrian) + "
    " + "
    " ) else: # Detailed report: # 1. Detour Route Information # 2. VPD Calculation for the Detour Route Roads # 3. Detour Road Capacity Summary # 4. Estimated Detour Delay Calculation # 5. Detour Road Summary # 6. Road Status After Diversion # 7. Pedestrian Detour Impact return ( base_html + "

    2. VPD Calculation for the Detour Route Roads

    " + _render_group(vpd_tables, fallback_vpd) + "
    " + "

    3. Detour Road Capacity Summary

    " + _render_group(road_capacity_tables, fallback_road_capacity) + "
    " + "

    4. Estimated Detour Delay Calculation

    " + _render_group(delay_tables, fallback_delay) + "
    " + "

    5. Detour Road Summary

    " + _render_group(detour_summary_tables + dir_capacity_tables, fallback_detour_summary) + "
    " + "

    6. Road Status After Diversion

    " + _render_group(road_status_tables, fallback_road_status) + "
    " + "

    7. Pedestrian Detour Impact

    " + _render_group(pedestrian_tables, fallback_pedestrian) + "
    " + "" ) def _build_short_detour_section(detour_tables: list[dict], route_count: int, analysis_map: dict, chart_items: list[dict] | None = None, is_short: bool = False, section_num: str = "4") -> str: """Build the Detour Analysis section HTML.""" if chart_items is None: chart_items = [] if not detour_tables and route_count < 1: return "" from collections import defaultdict route_groups: dict[str, list[dict]] = defaultdict(list) # Group tables by route number extracted from title; tables named "Table 28-32" go to route 1. for table in detour_tables: title = _safe_text(table.get("title"), "") m = re.search(r"Detour Route\s*(\d+)", title, re.IGNORECASE) if m: key = m.group(1) elif re.match(r"table\s*\d+", title.strip(), re.IGNORECASE): key = "1" # numbered payload tables belong to route 1 else: key = "1" route_groups[key].append(table) effective_count = max(route_count, len(route_groups), 1) rendered: list[str] = [] for i in range(1, effective_count + 1): key = str(i) route_label_str = f"Detour Route {i}" block = _render_short_detour_route_block(route_label_str, route_groups.get(key, []), analysis_map, chart_items, is_short=is_short) rendered.append(block) if not rendered: return "" return ( f"

    {section_num}. Detour Analysis

    " "
    " "

    This section summarises the detour route analysis. For each alternative route, the road capacity, estimated motorist delay, and pedestrian impact are assessed.

    " "
    " + "".join(rendered) ) def _render_detour_subsections(route_label: str = "") -> str: """Render expanded detour analysis subsections for a route.""" label = _escape(route_label) if route_label else "Detour Route" return ( f"
    " f"
    " f"

    {label} — Detailed Analysis

    " # 1. VPD Calculated "
    " "
    i. VPD Calculated
    " "" "" "" "" "" "" "" "" "" "" "
    DirectionBase VADT (vpd)Growth FactorDesign Year VADT (vpd)Diverted Traffic (vpd)Total VPD on Detour
    D1—————
    D2—————
    " "

    Edit to insert calculated VPD values for the detour route under full diversion conditions.

    " "
    " # 2. Detour Road Directional Capacity Summary "
    " "
    ii. Detour Road Directional Capacity Summary
    " "" "" "" "" "" "" "" "" "" "" "" "
    DirectionLane CountPer-Lane Capacity (veh/h)Total Capacity (veh/h)Peak Hour Volume (veh/h)VCRLOS
    D1——————
    D2——————
    " "

    Edit to confirm directional capacity and VCR under diversion conditions for the detour road.

    " "
    " # 3. Detour Road Capacity Summary "
    " "
    iii. Detour Road Capacity Summary
    " "" "" "" "" "" "" "" "" "" "
    ParameterValueNotes
    Road Classification——
    Posted Speed (km/h)——
    Total Two-Way Capacity (vpd)——
    Remaining Surplus Capacity (vpd)——
    " "

    Edit to confirm overall road capacity relative to diverted demand.

    " "
    " # 4. Existing Road Status After Diversion "
    " "
    iv. Existing Road Status After Diversion
    " "
    " "

    Following full diversion of traffic to this route, confirm that the detour road remains within acceptable operating conditions. " "Key considerations include: pavement condition, geometric constraints (narrow lanes, sharp curves, limited sight-distance), " "intersection control adequacy, and pedestrian / cyclist conflicts. Edit this section to record findings.

    " "
    " "
    " # 5. Estimated Delay "
    " "
    v. Estimated Delay — Detour Route
    " "" "" "" "" "" "" "" "" "" "" "
    ParameterValue
    Detour Route Length (km)—
    Original Route Length (km)—
    Extra Distance (km)—
    Average Travel Speed on Detour (km/h)—
    Estimated Additional Travel Time (min)—
    Delay Classification—
    " "

    Edit to calculate and record the additional delay imposed on motorists by the detour route.

    " "
    " # 6. Pedestrian Detour Impact "
    " "
    vi. Pedestrian Detour Impact — Delay Calculation
    " "
    " "

    Assess whether the detour route provides safe and accessible pedestrian connectivity. Key items to address: " "availability of footpath / shared path; suitable crossing facilities at intersections; WCAG / DDA compliance; " "additional walking distance for pedestrians and approximate delay. Edit this section to record pedestrian impact findings.

    " "
    " "" "" "" "" "" "" "" "" "
    ParameterValue
    Pedestrian Detour Distance (m)—
    Additional Walking Time (min)—
    Pedestrian Delay Classification—
    Mitigation Recommended—
    " "
    " "
    " ) def _render_engineering_observations(notes: Any) -> str: """Render engineering observations as structured, categorised subsections.""" raw_notes: list[str] = [] if isinstance(notes, list): raw_notes = [str(n).strip() for n in notes if str(n).strip()] traffic_ops: list[str] = [] intersection: list[str] = [] detour_notes: list[str] = [] general: list[str] = [] for note in raw_notes: note_lc = note.lower() if any(k in note_lc for k in ["queue", "vcr", "volume", "v/c", "capacity", "los", "level of service"]): traffic_ops.append(note) elif any(k in note_lc for k in ["intersection", "signal", "turning", "movement", "approach"]): intersection.append(note) elif any(k in note_lc for k in ["detour", "diversion", "alternate route", "closure"]): detour_notes.append(note) else: general.append(note) def _note_list(items: list[str], placeholder: str) -> str: if not items: return ( f"
  • {_escape(placeholder)}
  • " ) return "".join( f"
  • {_escape(n)}
  • " for n in items ) return ( "
    " "
    " "
    " "

    5.1 Traffic Operations

    " "
    " "

    The following observations relate to traffic volume, speed, VCR, and queue performance on the subject road network during the study period.

    " "
    " f"" "
    " "
    " "

    5.2 Intersection Performance

    " "
    " "

    Intersection performance observations cover turning movement adequacy, signal phasing, and approach-lane capacity during peak periods.

    " "
    " f"" "
    " "
    " "

    5.3 Detour Route Observations

    " "
    " "

    Observations relating to the proposed detour route, including adequacy of alternative roads, capacity headroom, and pedestrian / cyclist impacts.

    " "
    " f"" "
    " "
    " "

    5.4 General Engineering Notes

    " "
    " "

    Additional engineering observations that do not fall within the above categories, including data quality notes, assumptions, and recommendations.

    " "
    " f"" "
    " "
    " ) def _render_data_table( table_data: Any, analysis: dict[str, str] | None = None, chart_items: list[dict[str, Any]] | None = None, ) -> str: if not isinstance(table_data, dict): return "" title = _escape(table_data.get("title", "Untitled Table")) columns = table_data.get("columns", []) rows = table_data.get("rows", []) if not isinstance(columns, list): columns = [] if not isinstance(rows, list): rows = [] if not columns and not rows: return "" def _clean_cell_value(cell: Any) -> str: txt = _safe_text(cell, "") if not txt: return "-" # Keep exported table values as-is (except whitespace normalization). txt = re.sub(r"\s+", " ", txt).strip() return txt or "-" def _normalize_columns(raw_columns: list[Any], sample_rows: list[Any], table_title: str) -> list[str]: cols = [_safe_text(col, "").strip() for col in (raw_columns or [])] cols = [c if c else "-" for c in cols] row_width = 0 for row in sample_rows: if isinstance(row, list): row_width = max(row_width, len(row)) title_lc = _safe_text(table_title, "").lower() if "grouped directional summary" in title_lc and row_width == 14: return [ "Year", "AM LV", "AM HV", "AM RT", "OP LV", "OP HV", "OP RT", "PM LV", "PM HV", "PM RT", "EV LV", "EV HV", "EV RT", "Total", ] if row_width and len(cols) > row_width: # Prefer right-most leaf headers when the source included multi-row header groups. return cols[-row_width:] if row_width and len(cols) < row_width: return cols + [f"Column {idx + 1}" for idx in range(len(cols), row_width)] return cols def _parse_numeric(cell_text: str) -> float | None: raw = str(cell_text or "").replace(",", "").strip() m = re.search(r"[-+]?\d+(?:\.\d+)?", raw) if not m: return None try: return float(m.group(0)) except Exception: return None head_html = "" normalized_columns = _normalize_columns(columns, rows, title) if normalized_columns: head_html = "" + "".join(f"{_escape(col)}" for col in normalized_columns) + "" body_html_parts: list[str] = [] cleaned_rows: list[list[str]] = [] # We no longer drop rows based on density. Render everything. for row in rows: if not isinstance(row, list) or not row: continue cleaned_row = [_clean_cell_value(cell) for cell in row] cleaned_rows.append(cleaned_row) rendered_cells = [f"{_escape(cell)}" for cell in cleaned_row] body_html_parts.append(f"{''.join(rendered_cells)}") body_html = "" + "".join(body_html_parts) + "" row_count = len(cleaned_rows) col_count = len(normalized_columns) if normalized_columns else max((len(r) for r in cleaned_rows), default=0) informative_default = (analysis or {}).get( "summary", f"This table presents {_safe_text(title)} supporting the assessment. " "Edit this text to add assumptions, methodology, or interpretation for stakeholders." ) numeric_values: list[float] = [] for row in cleaned_rows: for idx, cell in enumerate(row): if idx == 0: continue value = _parse_numeric(cell) if value is not None: numeric_values.append(value) if numeric_values: n_min = min(numeric_values) n_max = max(numeric_values) summary_default = (analysis or {}).get( "scenario", f"Numeric values in this table range from {n_min:,.2f} to {n_max:,.2f}. " "Edit this summary to capture key implications and recommended actions." ) else: summary_default = (analysis or {}).get( "scenario", f"Review {_safe_text(title)} against site-specific conditions and edit this summary to record key findings and decisions." ) _title_key_norm = _normalize_title_key(title) # Major classification tables get h3 (section-level), others get h4 (sub-section) _is_major_table = any(kw in _title_key_norm for kw in [ "grouped directional", "directional queue", "directional vcr", "hourly queue", "hourly vcr", "analysis parameters" ]) heading_tag = "h3" if _is_major_table else "h4" detail_lead = "Detailed table below sets out the supporting values used for the engineering interpretation." if "queue" in _title_key_norm: detail_lead = "The table below provides queue length results by time period and direction." elif "vcr" in _title_key_norm or "los" in _title_key_norm: detail_lead = "The table below provides volume-to-capacity ratio and Level of Service results by time period." elif "detour" in _title_key_norm or "pedestrian" in _title_key_norm: detail_lead = "The table below provides supporting values for the detour or pedestrian impact assessment." elif "peak hour" in _title_key_norm: detail_lead = "The table below provides peak-hour traffic volumes by period and direction." table_classes = "wide-table" if col_count >= 10 else "" chart_html = _render_embedded_charts(chart_items, title, (analysis or {}).get("chart_caption", "")) return ( f"
    " f"
    " f" " f" " f" " f" " f"" f"
    " f"<{heading_tag} class=\"editable-text\" contenteditable=\"true\">{title}" f"

    {_escape(informative_default)}

    " f"{chart_html}" f"
    {detail_lead}
    " f"{head_html}{body_html}
    " f"

    {_escape(summary_default)}

    " f"
    " ) def _render_additional_chart_blocks( chart_items: list[dict[str, Any]], embedded_chart_keys: set[str], ) -> str: # Only show charts that were NOT already embedded inline with their associated tables. # This prevents the same chart appearing twice (once inline, once in the Charts section). if not chart_items: return "" blocks: list[str] = [] for idx, item in enumerate(chart_items): blocks.append( "
    " "
    " f"

    {_escape(item['title'], f'Chart {idx + 1}')}

    " f"\"{_escape(item['title']," "
    " "Visual reference for this chart. Edit this caption to describe key findings, trends, and engineering interpretation." "
    " "
    " ) return "".join(blocks) def _render_commentary_block(paragraphs: list[str], conclusion_points: list[str]) -> str: paragraph_html = _render_paragraph_block(paragraphs) bullet_items = [str(item).strip() for item in conclusion_points if str(item).strip()] if not bullet_items: bullet_items = ["Insert conclusion points here."] conclusion_html = "".join( f"
  • {_escape(item)}
  • " for item in bullet_items ) return ( f"
    {paragraph_html}
    " f"" ) @app.get("/health") def health() -> dict[str, Any]: uptime_seconds = int((_utcnow() - _SERVICE_START_TIME).total_seconds()) return { "status": "ok", "version": "1.0.0", "uptime_seconds": uptime_seconds, "draft_store": draft_store.health(), "rate_limiter": rate_limiter.health(), } @app.post("/report/draft") def create_draft(req: DraftRequest) -> dict[str, str]: _prune_drafts() safe_title = str(req.title or "").strip() if not safe_title: safe_title = "TIA Report" if len(safe_title) > 160: raise HTTPException(status_code=400, detail="Title too long") try: payload_raw = json.dumps(req.payload, ensure_ascii=False) except (TypeError, ValueError): raise HTTPException(status_code=400, detail="Invalid payload") payload_size = len(payload_raw.encode("utf-8")) if payload_size > MAX_REQUEST_BODY_BYTES: max_mb = MAX_REQUEST_BODY_BYTES / (1024 * 1024) actual_mb = payload_size / (1024 * 1024) raise HTTPException( status_code=413, detail=( f"Payload too large ({actual_mb:.2f} MB). " f"Server limit is {max_mb:.2f} MB. " "Set REPORT_MAX_REQUEST_BYTES to increase the limit if needed." ), ) now = _utcnow() draft_id = uuid.uuid4().hex draft_data = { "title": safe_title, "payload": req.payload, "created_at": now.isoformat(timespec="seconds").replace("+00:00", "Z"), "created_epoch": now.timestamp(), } draft_store.set(draft_id, draft_data) # Sync to legacy dict for backward compatibility in tests DRAFTS[draft_id] = draft_data logger.info("Draft created", extra={"draft_id": draft_id, "title": safe_title}) _prune_drafts() return {"editor_url": f"/report/editor/{draft_id}"} @app.get("/report/editor/{draft_id}", response_class=HTMLResponse) def editor_page(draft_id: str) -> str: _prune_drafts() if True: if not re.fullmatch(r"[a-f0-9]{32}", str(draft_id or "")): raise HTTPException(status_code=400, detail="Invalid draft id") draft = draft_store.get(draft_id) if not draft: raise HTTPException(status_code=404, detail="Draft not found") title = _escape(draft.get("title", "Traffic Impact Assessment")) payload = draft.get("payload", {}) if isinstance(draft.get("payload"), dict) else {} project = payload.get("project", {}) if isinstance(payload.get("project"), dict) else {} inputs = payload.get("inputs", {}) if isinstance(payload.get("inputs"), dict) else {} results = payload.get("results", {}) if isinstance(payload.get("results"), dict) else {} notes = payload.get("notes", []) executive_content = _build_executive_content(payload) executive_summary_html = _render_paragraph_block(executive_content.get("executive_paragraphs", [])) variant_raw = _safe_text(payload.get("report_variant"), "").lower() title_hint = _safe_text(draft.get("title", "")).lower() is_short_hint = ( "short report" in title_hint or "short python report" in title_hint or ( "short" in title_hint and "report" in title_hint and "detailed" not in title_hint ) ) is_detailed_hint = ( "detailed report" in title_hint or "detailed python report" in title_hint or ( "detailed" in title_hint and "report" in title_hint ) ) is_short = variant_raw == "short" or is_short_hint # Detailed report includes explanation notes; short report omits them. executive_notes_html = "" if is_short else _render_notes(executive_content.get("explanation_notes", [])) commentary_html = _render_commentary_block( executive_content.get("professional_commentary_paragraphs", []), executive_content.get("conclusion_points", []), ) logo_data_url = _load_logo_data_url() cover_logo_html = f'' if logo_data_url else "" if is_short: report_mode_label = "Python Short Report" elif variant_raw == "detailed" or is_detailed_hint: report_mode_label = "Detailed Python Report" else: report_mode_label = "Python Report" report_mode_label_escaped = _escape(report_mode_label) ctx = _build_report_context(payload) project_name = _escape(project.get("name", title)) location = _escape(project.get("location", "Location Not Specified")) report_date = _escape(ctx.get("report_date"), _utcnow().strftime("%d/%m/%Y")) prepared_by = _escape(ctx.get("prepared_by"), "Planner's Name") cc_number = _escape(ctx.get("cc_number"), "CC0000") selected_site_details = ctx.get("selected_site_details", {}) if isinstance(ctx.get("selected_site_details"), dict) else {} notes_html = _render_notes(notes) raw_tables = payload.get("tables", []) if isinstance(payload.get("tables"), list) else [] tables = [table for table in raw_tables if isinstance(table, dict)] table_analysis_map = { _normalize_title_key(item.get("title")): item for item in executive_content.get("table_analyses", []) if isinstance(item, dict) and _normalize_title_key(item.get("title")) } chart_items = _collect_chart_items(payload) chart_items_to_render = [] if is_short else chart_items hydrate_js_call = '' if is_short else 'hydrateChartsFromPayload();' embedded_chart_keys: set[str] = set() # --- Section 1: Design & Traffic Inputs --- analysis_parameters_table = { "table_id": "analysis_parameters", "title": "Analysis Parameters", "columns": ["Parameter", "Value"], "rows": [[str(key).replace("_", " ").title(), _safe_text(value)] for key, value in inputs.items()], } _ap_dom_table: dict[str, Any] | None = None _sr_dom_table: dict[str, Any] | None = None for _t in tables: _title_key = _normalize_title_key(_safe_text(_t.get("title"), "")) if "analysis parameters" in _title_key: _ap_dom_table = _t if "summary of computed results" in _title_key: _sr_dom_table = _t input_charts = _select_charts_for_table(analysis_parameters_table, chart_items_to_render) embedded_chart_keys.update(_normalize_title_key(item.get("canvas_id") or item.get("title")) for item in input_charts) if _ap_dom_table: inputs_section_html = _render_data_table( _ap_dom_table, table_analysis_map.get(_normalize_title_key(_safe_text(_ap_dom_table.get("title"), ""))), input_charts, ) else: inputs_section_html = _render_key_value_table( 'Analysis Parameters', inputs, table_analysis_map.get(_normalize_title_key('Analysis Parameters')), input_charts, ) site_section_html = _render_selected_site_details_section(selected_site_details) if _ap_dom_table: site_section_html = "" # --- Hourly Traffic Volume & Profile (Section 2, detailed only) --- _hourly_profile_tables_s2: list[Any] = [] if not is_short: for _t in tables: _t_key = _normalize_title_key(_safe_text(_t.get("title"), "")) if "hourly traffic profile" in _t_key or "hourly profile" in _t_key: _hourly_profile_tables_s2.append(_t) if _hourly_profile_tables_s2: _hp_blocks: list[str] = [] for _t in _hourly_profile_tables_s2: _t_key = _normalize_title_key(_safe_text(_t.get("title"), "")) _hp_charts = _select_charts_for_table(_t, chart_items_to_render) embedded_chart_keys.update(_normalize_title_key(item.get("canvas_id") or item.get("title")) for item in _hp_charts) _hp_blocks.append(_render_data_table(_t, table_analysis_map.get(_t_key), _hp_charts)) hourly_peak_section_html = ( "
    " "

    Hourly Traffic Volume (D1 and D2)

    " + "".join(_hp_blocks) + "
    " ) else: hourly_peak_section_html = "" # --- Section 2: Traffic Analysis & Results --- # Patterns are matched in order; "swt" is excluded from the base queue/vcr summary patterns # to prevent SWT tables appearing under the wrong heading. TA_ORDER = [ "summary of computed results", "hourly queue", "hourly vcr", "grouped directional summary", "directional queue summary", "directional queue summary swt", "directional vcr summary", ] if is_short: TA_ORDER = [ "summary of computed results", "grouped directional summary", "directional queue summary", "directional queue summary swt", "directional vcr summary", ] ta_blocks: list[str] = [] _seen_ta_patterns: set[str] = set() # Summary table first if _sr_dom_table: results_charts = _select_charts_for_table(_sr_dom_table, chart_items_to_render) embedded_chart_keys.update(_normalize_title_key(item.get("canvas_id") or item.get("title")) for item in results_charts) ta_blocks.append(_render_data_table( _sr_dom_table, table_analysis_map.get(_normalize_title_key(_safe_text(_sr_dom_table.get("title"), ""))), results_charts, )) _seen_ta_patterns.add("summary of computed results") else: computed_results_table = { "table_id": "summary_computed_results", "title": "Summary of Computed Results", "columns": ["Metric", "Value"], "rows": [[str(key).replace("_", " ").title(), _safe_text(value)] for key, value in results.items()], } results_charts = _select_charts_for_table(computed_results_table, chart_items_to_render) embedded_chart_keys.update(_normalize_title_key(item.get("canvas_id") or item.get("title")) for item in results_charts) ta_blocks.append(_render_computed_results_section( 'Summary of Computed Results', results, table_analysis_map.get(_normalize_title_key('Summary of Computed Results')), results_charts, )) _seen_ta_patterns.add("summary of computed results") # Remaining TA tables — render ALL tables (D1 + D2) matching each pattern. # Deduplication via _seen_ta_table_ids ensures each table appears exactly once. # "directional queue summary" excludes SWT tables (handled by its own pattern below it). _seen_ta_table_ids: set[str] = set() for pattern in TA_ORDER: if pattern in _seen_ta_patterns: continue for table in tables: t_title = _safe_text(table.get("title"), "") t_key = _normalize_title_key(t_title) if _normalize_title_key(pattern) not in t_key: continue # Exclude SWT tables from the base "directional queue summary" pattern so they # are rendered under the dedicated "directional queue summary swt" pattern. if pattern == "directional queue summary" and "swt" in t_key: continue t_id = _safe_text(table.get("table_id", ""), "") or t_key if t_id in _seen_ta_table_ids: continue _seen_ta_table_ids.add(t_id) matched_charts = _select_charts_for_table(table, chart_items_to_render) embedded_chart_keys.update(_normalize_title_key(item.get("canvas_id") or item.get("title")) for item in matched_charts) ta_blocks.append(_render_data_table( table, table_analysis_map.get(t_key), matched_charts, )) _seen_ta_patterns.add(pattern) traffic_analysis_results_html = "".join(ta_blocks) # --- Detour Analysis --- detour_tables: list[Any] = [] _DEDICATED_TABLE_PATTERNS = ["analysis parameters", "summary of computed results", "input summary", "selected site", "hourly traffic profile", "hourly profile"] _DEDICATED_TABLE_PATTERNS.extend(TA_ORDER) other_tables: list[Any] = [] _seen_table_ids: set[str] = set() _seen_title_keys: set[str] = set() for table in tables: tkey = _normalize_title_key(_safe_text(table.get("title"), "")) if any(_normalize_title_key(pat) in tkey for pat in _DEDICATED_TABLE_PATTERNS): continue table_id = _safe_text(table.get("table_id", ""), "") # Use compound key (table_id + title) so that the same DOM table_id scraped once # per detour route scenario is NOT collapsed — each route has a unique title suffix. if table_id: compound_key = f"{table_id}|{tkey}" if compound_key in _seen_table_ids: continue _seen_table_ids.add(compound_key) elif tkey: if tkey in _seen_title_keys: continue _seen_title_keys.add(tkey) title_lc = tkey title_stripped = title_lc.strip() _m = re.match(r"^table\s+(\d+)", title_stripped) if _m and int(_m.group(1)) not in (28, 29, 30, 31, 32): continue if re.match(r"table\s*(2[89]|3[0-2])", title_stripped) or any(k in title_lc for k in ("detour", "diversion", "pedestrian detour")): detour_tables.append(table) else: other_tables.append(table) raw_js = payload.get("raw_js_results", {}) if isinstance(payload.get("raw_js_results"), dict) else {} detour_route_count = int(raw_js.get("detour_route_count") or 0) detour_section_html = _build_short_detour_section(detour_tables, detour_route_count, table_analysis_map, chart_items_to_render, is_short=is_short, section_num="4") # --- Other sections and numbering --- # Short reports only include the structured sections; ad-hoc tables are suppressed. other_blocks: list[str] = [] if not is_short: for table in other_tables: matched_charts = _select_charts_for_table(table, chart_items_to_render) embedded_chart_keys.update(_normalize_title_key(item.get("canvas_id") or item.get("title")) for item in matched_charts) other_blocks.append(_render_data_table(table, table_analysis_map.get(_normalize_title_key(table.get('title'))), matched_charts)) other_sections_html = "".join(other_blocks) if is_short: sec_charts_num = "" sec_conclusion_num = "5" chart_section_html = "" else: sec_charts_num = "5" sec_conclusion_num = "6" chart_sections = _render_additional_chart_blocks(chart_items_to_render, embedded_chart_keys) chart_section_html = f"

    {sec_charts_num}. Charts

    {chart_sections}" if chart_sections else "" # BUG FIX: Do NOT html.escape() JSON intended for """ # ─── FORMULA VERIFICATION ENDPOINT ────────────────────────────────────────── class FormulaFailure(BaseModel): id: str name: str group: str reference: Any actual: Any deviation: Any = None error: str | None = None class FormulaVerifyRequest(BaseModel): failures: list[FormulaFailure] def _call_claude_verify(failures: list[FormulaFailure]) -> str: """Call Claude API to analyse formula failures. Returns analysis string.""" api_key = os.environ.get("ANTHROPIC_API_KEY", "") if not api_key: return "ANTHROPIC_API_KEY not set — AI analysis unavailable." failure_lines = [] for f in failures: dev_str = f"deviation={f.deviation}" if f.deviation is not None else f"error={f.error}" failure_lines.append( f" [{f.group}] {f.name}: reference={f.reference}, actual={f.actual}, {dev_str}" ) failures_text = "\n".join(failure_lines) system_prompt = ( "You are a traffic engineering specialist and software auditor. " "You verify that traffic calculation formulas in a Traffic Impact Assessment (TIA) tool " "conform to Austroads and TMR (Queensland) engineering standards. " "When formula deviations are reported, diagnose the root cause and give concrete remediation steps." ) user_prompt = f"""The TIA Formula Verification Agent found {len(failures)} formula failure(s). Each failure shows: [group] test-name: reference=, actual=, deviation or error. Failures: {failures_text} For each failure: 1. Identify the most likely cause (wrong constant, rounding difference, formula variant, code drift, or genuine bug). 2. State whether the deviation is safety-critical for a traffic engineering assessment. 3. Provide a one-line corrective action the developer should take. Keep your response concise and structured.""" body = json.dumps({ "model": "claude-sonnet-4-6", "max_tokens": 1024, "system": system_prompt, "messages": [{"role": "user", "content": user_prompt}], }).encode("utf-8") req = urllib.request.Request( "https://api.anthropic.com/v1/messages", data=body, headers={ "x-api-key": api_key, "anthropic-version": "2023-06-01", "content-type": "application/json", }, method="POST", ) try: with urllib.request.urlopen(req, timeout=25) as resp: data = json.loads(resp.read().decode("utf-8")) return data["content"][0]["text"] except urllib.error.HTTPError as exc: body_bytes = exc.read() return f"Claude API error {exc.code}: {body_bytes.decode('utf-8', errors='replace')}" except Exception as exc: return f"Claude API request failed: {exc}" @app.post("/verify-formulas") async def verify_formulas(req: FormulaVerifyRequest, request: Request): """ Accepts formula failures from the in-browser Formula Verification Agent, forwards them to Claude for expert analysis, and returns a structured report. Rate-limited per client IP because it spends the server's ANTHROPIC_API_KEY. """ rate_meta = _check_rate_limit(request, VERIFY_RATE_MAX, VERIFY_RATE_WINDOW_S) if not req.failures: return JSONResponse( {"status": "ok", "analysis": "No failures to analyse."}, headers={ "X-RateLimit-Limit": str(rate_meta["limit"]), "X-RateLimit-Remaining": str(rate_meta["remaining"]), "X-RateLimit-Reset": str(rate_meta["reset_epoch"]), }, ) analysis = _call_claude_verify(req.failures) return JSONResponse( { "status": "failures_analysed", "failure_count": len(req.failures), "analysis": analysis, }, headers={ "X-RateLimit-Limit": str(rate_meta["limit"]), "X-RateLimit-Remaining": str(rate_meta["remaining"]), "X-RateLimit-Reset": str(rate_meta["reset_epoch"]), }, ) if __name__ == "__main__": import uvicorn # Run the server on localhost:8060 by default # Set environment variables to customize: # - HOST: defaults to 127.0.0.1 (localhost) # - PORT: defaults to 8060 (matches frontend REPORT_SERVICE_BASE_URL) # - RELOAD: set to "true" for auto-reload in development host = os.environ.get("HOST", "127.0.0.1") port = int(os.environ.get("PORT", "8060")) reload = os.environ.get("RELOAD", "").lower() == "true" print(f"Starting TIA Report Service at http://{host}:{port}") print(f" Health check: http://{host}:{port}/health") print(f" API docs: http://{host}:{port}/docs") uvicorn.run( "report_service:app", host=host, port=port, reload=reload, log_level="info" )