Download core/form_ab_assistant.py from Surajnitp/flowmarg: direct link, hf CLI and curl.
- Browser
- Download file 9.02 kB
-
https://huggingface.co/spaces/Surajnitp/flowmarg/resolve/main/core/form_ab_assistant.py
- Command line
-
hf download hf://spaces/Surajnitp/flowmarg/core/form_ab_assistant.py
-
curl -L -o form_ab_assistant.py https://huggingface.co/spaces/Surajnitp/flowmarg/resolve/main/core/form_ab_assistant.py
9.02 kB
| """ | |
| core/form_ab_assistant.py | |
| Form A/B draft generator using REAL project data from SQLite. | |
| """ | |
| from typing import Dict, List, Optional | |
| from core.database import query_chainages, get_project_metadata | |
| from core.standards_loader import load_standards | |
| class FormABAssistant: | |
| """Generate Form A/B drafts from real project data.""" | |
| def __init__(self, session_state=None): | |
| self.session_state = session_state | |
| self.standards = load_standards() | |
| self._cache = {} | |
| def generate_draft(self, project_data: Optional[Dict] = None) -> Dict[str, str]: | |
| """Generate all sections for Form A/B draft.""" | |
| if project_data is None: | |
| project_data = {} | |
| sections = { | |
| "project_background": self._draft_project_background(project_data), | |
| "existing_condition": self._draft_existing_condition(), | |
| "proposed_design": self._draft_proposed_design(project_data), | |
| "assumptions": self._draft_assumptions(project_data), | |
| "constraints": self._draft_constraints(project_data), | |
| "standards": self._draft_standards(), | |
| "risks": self._draft_risks(), | |
| "missing_info": self._draft_missing_info(), | |
| "design_justification": self._draft_justification(), | |
| } | |
| return sections | |
| def _get_metadata(self, key: str, default: str = "Unknown") -> str: | |
| """Get project metadata from SQLite.""" | |
| return get_project_metadata(key) or default | |
| def _draft_project_background(self, data: Dict) -> str: | |
| name = data.get("project_name") or self._get_metadata("project_name", "Unknown Project") | |
| stage = data.get("stage") or self._get_metadata("stage", "Detailed Design") | |
| engineer = data.get("designed_by") or self._get_metadata("engineer", "Track Design Engineer") | |
| date = data.get("date") or self._get_metadata("date", "2026-08-19") | |
| return f""" | |
| This document covers the track design for {name} at {stage} stage. | |
| The design has been prepared by {engineer} on {date}. | |
| The design is based on the provided existing and proposed alignment data, | |
| site survey, and PSR requirements as detailed in the following sections. | |
| """ | |
| def _draft_existing_condition(self) -> str: | |
| df = query_chainages(type_label="existing") | |
| if df.empty: | |
| return "Existing track condition data is not available. Please upload existing XML." | |
| min_ch = df["chainage"].min() | |
| max_ch = df["chainage"].max() | |
| speed = self._get_metadata("design_speed", "75") | |
| track_type = self._get_metadata("track_type", "mixed-traffic") | |
| track_category = self._get_metadata("track_category", "C") | |
| return f""" | |
| The existing track alignment covers chainages from {min_ch:.3f} to {max_ch:.3f}. | |
| The track is a {track_type} line with a design speed of up to {speed} mph. | |
| Track Category: {track_category} according to NR/L2/TRK/2500. | |
| """ | |
| def _draft_proposed_design(self, data: Dict) -> str: | |
| df = query_chainages(type_label="proposed") | |
| if df.empty: | |
| return "Proposed design data is not available. Please upload proposed XML." | |
| min_ch = df["chainage"].min() | |
| max_ch = df["chainage"].max() | |
| speed = self._get_metadata("design_speed", "75") | |
| track_category = self._get_metadata("track_category", "C") | |
| return f""" | |
| The proposed design replaces the existing track with a renewed alignment | |
| from CH {min_ch:.3f} to {max_ch:.3f}. | |
| The design speed is {speed} mph for Category {track_category} track. | |
| Key design parameters have been optimised to meet Network Rail standards. | |
| """ | |
| def _draft_assumptions(self, data: Dict) -> str: | |
| assumptions = data.get("assumptions", []) | |
| if assumptions: | |
| return "The following assumptions were made:\n" + "\n".join([f"- {a}" for a in assumptions]) | |
| # Default assumptions based on project data | |
| df = query_chainages() | |
| if df.empty: | |
| return "Assumptions will be populated once project data is loaded." | |
| return f""" | |
| - The survey data accurately represents site conditions. | |
| - Existing track geometry is within tolerances specified in NR/L2/TRK/2500. | |
| - No unforeseen ground conditions or buried services will be encountered. | |
| - Proposed alignments maintain required clearances to all infrastructure. | |
| - Ballast and formation treatments will be designed in accordance with NR2102. | |
| """ | |
| def _draft_constraints(self, data: Dict) -> str: | |
| constraints = data.get("constraints", []) | |
| if constraints: | |
| return "The following constraints are considered:\n" + "\n".join([f"- {c}" for c in constraints]) | |
| # Check if survey features exist | |
| from core.database import query_survey_features | |
| survey_df = query_survey_features() | |
| if not survey_df.empty: | |
| bridges = survey_df[survey_df["category"] == "Bridge"] | |
| platforms = survey_df[survey_df["category"] == "Platform"] | |
| lines = [] | |
| if not bridges.empty: | |
| lines.append(f"- {len(bridges)} bridge(s) identified in survey") | |
| if not platforms.empty: | |
| lines.append(f"- {len(platforms)} platform(s) identified in survey") | |
| if lines: | |
| return "The following constraints are considered:\n" + "\n".join(lines) | |
| return "No specific constraints identified. Please update with project-specific information." | |
| def _draft_standards(self) -> str: | |
| std = self.standards.get("NR/L2/TRK/2500", {}) | |
| version = std.get("version", "2024") | |
| return f""" | |
| The design complies with the following Network Rail standards: | |
| - NR/L2/TRK/2500 (Track Design Standards) version {version} | |
| - NR/L2/TRK/2102 (Ballast, Formation and Drainage) | |
| - NR/L3/TRK/2049 (S&C Geometry and Switch Standards) | |
| - Applicable BS/EN standards as referenced in the above. | |
| """ | |
| def _draft_risks(self) -> str: | |
| return """ | |
| Risk items identified from design data: | |
| 1. Alignment changes may affect drainage and signal sighting. | |
| 2. S&C installation requires careful coordination with signalling. | |
| 3. Temporary works and possession planning required. | |
| 4. Interface with OLE and platform clearances must be verified. | |
| These risks will be managed through the Design Risk Management Schedule. | |
| """ | |
| def _draft_missing_info(self) -> str: | |
| missing = [] | |
| if query_chainages(type_label="existing").empty: | |
| missing.append("Existing XML data") | |
| if query_chainages(type_label="proposed").empty: | |
| missing.append("Proposed XML data") | |
| if not self._get_metadata("psr_speed"): | |
| missing.append("PSR speed") | |
| if missing: | |
| return "Missing information: " + ", ".join(missing) + ". Please upload the required data." | |
| return "All critical information is available." | |
| def _draft_justification(self) -> str: | |
| return """ | |
| The proposed design has been developed to: | |
| 1. Maintain or improve track geometry and ride quality. | |
| 2. Provide safe and maintainable infrastructure. | |
| 3. Minimise disturbance to existing services and interfaces. | |
| 4. Achieve the required design speed with appropriate cant and transitions. | |
| 5. Comply with Network Rail standards and best practice. | |
| All design decisions have been documented and are traceable to source data. | |
| """ | |
| def save_draft(self, sections: Dict, output_path: str): | |
| """Save the draft to a text file.""" | |
| with open(output_path, "w") as f: | |
| for title, text in sections.items(): | |
| f.write(f"{title.upper().replace('_', ' ')}\n{'-'*50}\n{text}\n\n") | |
| def save_draft_docx(self, sections: Dict, output_path: str): | |
| """Save the draft to a Word document (requires python-docx).""" | |
| try: | |
| from docx import Document | |
| from docx.shared import Pt, Inches | |
| doc = Document() | |
| # Title | |
| doc.add_heading("Form A/B – Track Design Report", 0) | |
| for title, text in sections.items(): | |
| doc.add_heading(title.replace("_", " ").title(), level=1) | |
| doc.add_paragraph(text) | |
| doc.save(output_path) | |
| return True | |
| except ImportError: | |
| self.save_draft(sections, output_path.replace(".docx", ".txt")) | |
| return False | |
| # ============================================================ | |
| # Standalone test | |
| # ============================================================ | |
| if __name__ == "__main__": | |
| print("=" * 60) | |
| print("🧪 FORM A/B ASSISTANT TEST") | |
| print("=" * 60) | |
| assistant = FormABAssistant() | |
| draft = assistant.generate_draft({"project_name": "Test Project"}) | |
| for section, text in draft.items(): | |
| print(f"\n📋 {section.upper()}") | |
| print("-" * 40) | |
| print(text[:200] + "...") | |