File size: 9,157 Bytes
2379054 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | """
PSR Processor - Extract Project Specification Requirements
Network Rail Standards - Professional Edition
"""
import re
from typing import Dict, List, Optional, Any
from datetime import datetime
class PSRProcessor:
"""Extract engineering requirements from PSR documents"""
def __init__(self):
self.raw_text = ""
self.project_info = {}
self.requirements = {}
self.constraints = []
self.standards = []
def process_text(self, text: str) -> Dict:
"""Process PSR text and extract all requirements"""
self.raw_text = text
# Extract all information
self._extract_project_info(text)
self._extract_speed_limits(text)
self._extract_clearance_requirements(text)
self._extract_sandc_requirements(text)
self._extract_standards(text)
self._extract_constraints(text)
self._extract_track_category(text)
return self.get_summary()
def _extract_project_info(self, text: str):
"""Extract project information"""
patterns = {
"project_name": r"(?:Project|Scheme)\s*(?:Name|Title)?\s*[:=]\s*([^\n]+)",
"client": r"Client\s*[:=]\s*([^\n]+)",
"date": r"Date\s*[:=]\s*([^\n]+)",
"stage": r"(?:Design|Stage|Phase)\s*[:=]\s*([^\n]+)",
"engineer": r"(?:Engineer|Designed by|Prepared by)\s*[:=]\s*([^\n]+)"
}
for key, pattern in patterns.items():
match = re.search(pattern, text, re.I)
if match:
self.project_info[key] = match.group(1).strip()
def _extract_speed_limits(self, text: str):
"""Extract speed limits"""
speeds = {}
# Pattern: "75 mph" or "Speed: 75 mph"
pattern = r"(?:Speed|Design Speed|Line Speed)\s*[:=]?\s*(\d+)\s*(?:mph|MPH|km/h)"
matches = re.findall(pattern, text, re.I)
if matches:
# If multiple speeds, assign to tracks
for i, speed in enumerate(matches, 1):
speeds[i] = int(speed)
elif matches:
speeds[1] = int(matches[0])
self.requirements["speed_limits"] = speeds
def _extract_clearance_requirements(self, text: str):
"""Extract clearance requirements"""
clearances = {}
# Bridge clearance
bridge_match = re.search(r"Bridge\s*(?:clearance|headroom)\s*[:=]?\s*([\d.]+)\s*(?:m|metres)", text, re.I)
if bridge_match:
clearances["bridge"] = float(bridge_match.group(1))
# Platform clearance
platform_match = re.search(r"Platform\s*(?:clearance|gauge)\s*[:=]?\s*([\d.]+)\s*(?:m|metres)", text, re.I)
if platform_match:
clearances["platform"] = float(platform_match.group(1))
# OLE clearance
ole_match = re.search(r"(?:OLE|Overhead Line|OHL)\s*(?:clearance)\s*[:=]?\s*([\d.]+)\s*(?:m|metres)", text, re.I)
if ole_match:
clearances["ole"] = float(ole_match.group(1))
# Sixfoot clearance
sixfoot_match = re.search(r"(?:Sixfoot|6ft)\s*(?:clearance|gauge)\s*[:=]?\s*([\d.]+)\s*(?:m|metres)", text, re.I)
if sixfoot_match:
clearances["sixfoot"] = float(sixfoot_match.group(1))
self.requirements["clearances"] = clearances
def _extract_sandc_requirements(self, text: str):
"""Extract S&C requirements"""
sandc = {}
# Turnout type
turnout_match = re.search(r"Turnout\s*(?:type)?\s*[:=]?\s*(\d+)\s*[::]\s*(\d+)", text, re.I)
if turnout_match:
sandc["turnout"] = f"{turnout_match.group(1)}:{turnout_match.group(2)}"
# Turnout location
location_match = re.search(r"Turnout\s*(?:at|location)\s*[:=]?\s*CH\s*([\d.]+)", text, re.I)
if location_match:
sandc["turnout_chainage"] = float(location_match.group(1))
# Crossing type
crossing_match = re.search(r"Crossing\s*(?:type)?\s*[:=]?\s*(.+)", text, re.I)
if crossing_match:
sandc["crossing"] = crossing_match.group(1).strip()
self.requirements["sandc"] = sandc
def _extract_standards(self, text: str):
"""Extract standard references"""
standards = []
# NR standards
pattern = r"NR[/\-]?([A-Z]+\d*[/\-]\d+[/\-]\d+)"
matches = re.findall(pattern, text, re.I)
for match in matches:
standards.append(f"NR/{match}")
# Other standards
other_pattern = r"(?:BS|EN|ISO)\s*\d+"
matches = re.findall(other_pattern, text, re.I)
for match in matches:
standards.append(match)
self.standards = standards
def _extract_constraints(self, text: str):
"""Extract project constraints"""
constraints = []
keywords = [
"constraint", "restriction", "limitation",
"requirement", "condition", "limitation"
]
for keyword in keywords:
pattern = rf"{keyword}s?\s*[:=]?\s*([^\n\.]+)"
matches = re.findall(pattern, text, re.I)
for match in matches:
constraints.append(match.strip())
self.constraints = constraints
def _extract_track_category(self, text: str):
"""Extract track category"""
match = re.search(r"Track\s*(?:Category|Cat)\s*[:=]?\s*([A-D])", text, re.I)
if match:
self.requirements["track_category"] = match.group(1).upper()
def get_summary(self) -> Dict:
"""Get complete PSR summary"""
return {
"status": "success",
"project_info": self.project_info,
"requirements": self.requirements,
"standards": self.standards,
"constraints": self.constraints,
"summary": {
"has_project_name": bool(self.project_info.get("project_name")),
"has_speed": bool(self.requirements.get("speed_limits")),
"has_clearances": bool(self.requirements.get("clearances")),
"has_sandc": bool(self.requirements.get("sandc")),
"has_standards": bool(self.standards),
"has_constraints": bool(self.constraints),
"has_track_category": bool(self.requirements.get("track_category"))
}
}
def process_file(self, data: bytes, filename: str = "psr.txt") -> Dict:
text = ""
name = (filename or "").lower()
if name.endswith(".pdf"):
try:
import io
import pdfplumber
with pdfplumber.open(io.BytesIO(data)) as pdf:
text = "\n".join((p.extract_text() or "") for p in pdf.pages)
except Exception:
text = data.decode("utf-8", errors="ignore")
elif name.endswith(".docx"):
try:
import io
import docx
doc = docx.Document(io.BytesIO(data))
text = "\n".join(p.text for p in doc.paragraphs)
except Exception:
text = data.decode("utf-8", errors="ignore")
else:
text = data.decode("utf-8", errors="ignore")
return self.process_text(text)
def get_speed_limit(self, track_no: int = 1) -> Optional[int]:
"""Get speed limit for a track"""
speeds = self.requirements.get("speed_limits", {})
return speeds.get(track_no) or speeds.get(1)
def get_clearance(self, clearance_type: str) -> Optional[float]:
"""Get a specific clearance requirement"""
clearances = self.requirements.get("clearances", {})
return clearances.get(clearance_type)
def check_design_compliance(self, engineering_data: Dict) -> Dict:
"""Check design compliance against PSR requirements"""
compliance = {
"speed": [],
"clearance": [],
"sandc": [],
"status": "PASS"
}
# Check speed compliance
speeds = self.requirements.get("speed_limits", {})
for track_no, speed_limit in speeds.items():
track_data = engineering_data.get("calculations", {}).get(track_no, {})
radii = track_data.get("pr_radius", {})
for chainage, radius in radii.items():
from core.engineering import check_radius_for_speed
sufficient, required = check_radius_for_speed(radius, speed_limit)
compliance["speed"].append({
"track": track_no,
"chainage": chainage,
"speed_limit": speed_limit,
"radius": radius,
"required": required,
"status": "PASS" if sufficient else "FAIL"
})
if not sufficient:
compliance["status"] = "FAIL"
return compliance
|