File size: 12,149 Bytes
c2ad2bf 80235a9 90ac78d 8f3c0ec 90ac78d 80235a9 c2ad2bf 8f3c0ec 90ac78d 8f3c0ec b31f1da c2ad2bf 1168cd6 8f3c0ec 28b5c1c b7360ba 28b5c1c 42a6d53 80235a9 b6dd794 90ac78d 28b5c1c b6dd794 28b5c1c b6dd794 90ac78d 28b5c1c 8f3c0ec 28b5c1c 8f3c0ec 28b5c1c 90ac78d 28b5c1c 90ac78d 28b5c1c 90ac78d 8f3c0ec 90ac78d 8f3c0ec 28b5c1c 8f3c0ec e11bc4c 8f3c0ec 28b5c1c 42a6d53 28b5c1c 90ac78d 28b5c1c 42a6d53 90ac78d 28b5c1c 8f3c0ec 90ac78d 42a6d53 28b5c1c 42a6d53 8f3c0ec e11bc4c 90ac78d 28b5c1c 90ac78d 28b5c1c f4a1846 28b5c1c 90ac78d 28b5c1c f4a1846 28b5c1c 90ac78d 28b5c1c f4a1846 90ac78d 8f3c0ec 28b5c1c 42a6d53 90ac78d e11bc4c 90ac78d e11bc4c 90ac78d 8f3c0ec 90ac78d f4a1846 28b5c1c 90ac78d 28b5c1c f4a1846 90ac78d 8f3c0ec 4b98210 a32ac8b 90ac78d 8f3c0ec 28b5c1c 90ac78d 28b5c1c 8f3c0ec 90ac78d f4a1846 28b5c1c 90ac78d 28b5c1c f4a1846 28b5c1c 8f3c0ec 90ac78d 28b5c1c b7360ba 90ac78d 28b5c1c 90ac78d 42a6d53 28b5c1c 90ac78d 28b5c1c 80235a9 28b5c1c 90ac78d 28b5c1c 90ac78d 80235a9 28b5c1c 90ac78d 28b5c1c 42a6d53 28b5c1c 969614d 90ac78d 969614d 28b5c1c 90ac78d 28b5c1c b1deeea 28b5c1c e11bc4c 8f3c0ec 28b5c1c 90ac78d 48cf426 e11bc4c 90ac78d e11bc4c 8f3c0ec a32ac8b 90ac78d a32ac8b 90ac78d a32ac8b 90ac78d a32ac8b 28b5c1c b31f1da 80235a9 28b5c1c 90ac78d 42a6d53 28b5c1c 80235a9 42a6d53 82bd734 a32ac8b 7a38401 28b5c1c 8f3c0ec 90ac78d b1deeea 28b5c1c 80235a9 |
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# engine/parser_ext.py
# ======================================================================
# Extended test parser — Stage 12C-fix4
#
# GOAL:
# • Explicit-only parsing
# • ML-safe
# • Deterministic
# • No inference
# • Schema-backed fallback for enum_PNV
# ======================================================================
from __future__ import annotations
import os, re, json
from typing import Dict, Any
EXTENDED_SCHEMA_PATH = os.path.join("data", "extended_schema.json")
UNKNOWN = "Unknown"
# ======================================================================
# Fields NOT parsed here
# ======================================================================
CORE_FIELDS = {
"Genus","Species",
"Gram Stain","Shape","Colony Morphology",
"Haemolysis","Motility","Capsule","Spore Formation",
"Growth Temperature","Oxygen Requirement","Media Grown On",
"Catalase","Oxidase","Indole","Urease","Citrate","Methyl Red","VP",
"H2S","DNase","ONPG","Coagulase","Lipase Test","Nitrate Reduction",
"Lysine Decarboxylase","Arginine dihydrolase",
"Gelatin Hydrolysis","Esculin Hydrolysis",
"Glucose Fermentation","Lactose Fermentation","Sucrose Fermentation",
"Mannitol Fermentation","Sorbitol Fermentation","Maltose Fermentation",
"Xylose Fermentation","Rhamnose Fermentation","Arabinose Fermentation",
"Raffinose Fermentation","Trehalose Fermentation","Inositol Fermentation",
}
# ======================================================================
# Helpers
# ======================================================================
def _clean_text(t: str) -> str:
if not t:
return ""
t = t.replace("°", "").replace("º", "").replace("₂", "2")
return " ".join(t.split())
def _set_if_stronger(parsed: Dict[str,str], field: str, value: str):
if not value:
return
if field not in parsed or parsed[field] == UNKNOWN:
parsed[field] = value
def _parse_pnv_after_anchor(text: str, parsed: Dict[str,str], field: str, anchor: str):
m = re.search(
rf"\b{re.escape(anchor)}\b\s*(positive|negative|variable|unknown)",
text,
re.IGNORECASE,
)
if m:
_set_if_stronger(parsed, field, m.group(1).capitalize())
def _load_extended_schema(path: str) -> Dict[str, Any]:
if not os.path.exists(path):
return {}
try:
with open(path, "r", encoding="utf-8") as f:
obj = json.load(f)
return obj if isinstance(obj, dict) else {}
except Exception:
return {}
# ======================================================================
# 1. Gram Stain Variable (explicit-only)
# ======================================================================
def _parse_gram_variable(text: str, parsed: Dict[str,str]):
t = text.lower()
if (
re.search(r"\bgram[- ]variable\b", t) or
re.search(r"\bgram stain variable\b", t) or
re.search(r"\bvariable gram stain\b", t)
):
_set_if_stronger(parsed, "Gram Stain", "Variable")
# ======================================================================
# 2. Shape (yeast phrasing fix)
# ======================================================================
def _parse_shape_yeast(text: str, parsed: Dict[str,str]):
if re.search(r"\byeast cells?\b", text.lower()):
_set_if_stronger(parsed, "Shape", "Yeast")
# ======================================================================
# 3. Capsule (explicit Variable only)
# ======================================================================
def _parse_capsule_variable(text: str, parsed: Dict[str,str]):
t = text.lower()
patterns = [
r"\bcapsule\s*[:\-]?\s*variable\b",
r"\bcapsule-variable\b",
r"\bvariable\s+capsule\b",
]
if any(re.search(p, t) for p in patterns):
_set_if_stronger(parsed, "Capsule", "Variable")
# ======================================================================
# 4. Gas Production
# ======================================================================
def _parse_gas_production(text: str, parsed: Dict[str,str]):
t = text.lower()
POS = [
"produces gas","gas produced","with gas",
"gas production positive","gas producer",
"production of gas","ferments glucose with gas",
]
NEG = [
"does not produce gas","no gas",
"absence of gas","gas production negative",
]
if any(p in t for p in POS):
_set_if_stronger(parsed,"Gas Production","Positive")
elif any(n in t for n in NEG):
_set_if_stronger(parsed,"Gas Production","Negative")
# ======================================================================
# 5. Motility Type (explicit)
# ======================================================================
MOTILITY_TYPES = {
"Peritrichous","Monotrichous","Polytrichous","Polar",
"Swarming","Tumbling","Gliding","Corkscrew","Axial",
}
def _parse_motility_type(text: str, parsed: Dict[str,str]):
t = text.lower()
mneg = re.search(r"\bmotility type\b\s*[:\-]?\s*(negative|none)\b", t)
if mneg:
_set_if_stronger(parsed, "Motility Type", mneg.group(1).capitalize())
return
m = re.search(r"\bmotility type\b\s*[:\-]?\s*([a-z]+)", t)
if m:
val = m.group(1).capitalize()
if val in MOTILITY_TYPES:
_set_if_stronger(parsed, "Motility Type", val)
return
for mt in MOTILITY_TYPES:
if re.search(rf"\b{mt.lower()}\b", t):
_set_if_stronger(parsed, "Motility Type", mt)
return
# ======================================================================
# 6. Pigment (EXPLICIT + SCIENTIFIC TERMS ONLY)
# ======================================================================
SCIENTIFIC_PIGMENTS = {
"Pyocyanin","Pyoverdine","Pyovacin","Bioluminescent"
}
COLOUR_PIGMENTS = {
"green","yellow","pink","red","orange","brown","black","violet","cream"
}
def _parse_pigment(text: str, parsed: Dict[str,str]):
t = text.lower()
# Joint negative phrase
if re.search(r"\bno pigmentation or odou?r\b", t):
_set_if_stronger(parsed, "Pigment", "None")
_set_if_stronger(parsed, "Odor", "None")
return
has_anchor = re.search(r"\b(pigment|pigmentation)\b", t)
found = set()
# Scientific pigments (allowed without anchor)
for sp in SCIENTIFIC_PIGMENTS:
if re.search(rf"\b{sp.lower()}\b", t):
found.add(sp)
# Colour pigments ONLY if pigment anchor exists
if has_anchor:
for cp in COLOUR_PIGMENTS:
if re.search(rf"\b{cp}\b", t):
found.add(cp.capitalize())
if re.search(r"\bno pigmentation\b|\bpigment none\b", t):
_set_if_stronger(parsed, "Pigment", "None")
elif found:
_set_if_stronger(parsed, "Pigment", "; ".join(sorted(found)))
# ======================================================================
# 7. Colony Pattern (explicit only)
# ======================================================================
COLONY_PATTERNS = {
"Mucoid","Smooth","Rough","Filamentous",
"Spreading","Swarming","Sticky","Irregular",
"Ground-glass","Molar-tooth","Dry","Chalky","Corroding",
}
def _parse_colony_pattern(text: str, parsed: Dict[str,str]):
t = text.lower()
if not re.search(r"\bcolony pattern\b", t):
return
m = re.search(r"\bcolony pattern\b\s*[:\-]?\s*([a-z\-]+)", t)
if m:
val = m.group(1).capitalize()
if val in COLONY_PATTERNS:
_set_if_stronger(parsed, "Colony Pattern", val)
# ======================================================================
# 8. Odor (explicit anchor-based)
# ======================================================================
def _parse_odor(text: str, parsed: Dict[str,str]):
t = text.lower()
m = re.search(r"\b(odor|odour|smell)\b\s*[:\-]?\s*([a-z; ]+)", t)
if not m:
return
vals = [v.strip().capitalize() for v in m.group(2).split(";") if v.strip()]
if vals:
_set_if_stronger(parsed, "Odor", "; ".join(vals))
# ======================================================================
# 9. TSI Pattern
# ======================================================================
def _parse_tsi(text: str, parsed: Dict[str,str]):
t = text.upper()
if "TSI" in t and "UNKNOWN" in t:
_set_if_stronger(parsed, "TSI Pattern", "Unknown")
return
m = re.search(r"\b([KA]/[KA])(\s*\+\s*H2S)?\b", t)
if m:
base = m.group(1)
_set_if_stronger(parsed, "TSI Pattern", f"{base}+H2S" if m.group(2) else base)
# ======================================================================
# 10. NaCl Tolerant (>=6%)
# ======================================================================
def _parse_nacl(text: str, parsed: Dict[str,str]):
m = re.search(
r"NaCl\s*Tolerant\s*\(>=\s*6%\)\s*(positive|negative|variable|unknown)",
text,
re.IGNORECASE,
)
if m:
_set_if_stronger(parsed, "NaCl Tolerant (>=6%)", m.group(1).capitalize())
return
_parse_pnv_after_anchor(text, parsed, "NaCl Tolerant (>=6%)", "NaCl Tolerant")
# ======================================================================
# 11. Haemolysis Type
# ======================================================================
def _parse_haemolysis_type(text: str, parsed: Dict[str,str]):
m = re.search(
r"\bhaemolysis type\b\s*[:\-]?\s*(alpha|beta|gamma|none)",
text,
re.IGNORECASE,
)
if m:
_set_if_stronger(parsed, "Haemolysis Type", m.group(1).capitalize())
# ======================================================================
# 12. Ornithine Decarboxylase (both spellings)
# ======================================================================
def _parse_ornithine_dec(text: str, parsed: Dict[str,str]):
_parse_pnv_after_anchor(text, parsed, "Ornithine Decarboxylase", "Ornithine Decarboxylase")
_parse_pnv_after_anchor(text, parsed, "Ornitihine Decarboxylase", "Ornitihine Decarboxylase")
if "Ornitihine Decarboxylase" in parsed and "Ornithine Decarboxylase" not in parsed:
_set_if_stronger(parsed, "Ornithine Decarboxylase", parsed["Ornitihine Decarboxylase"])
# ======================================================================
# 13. Schema-driven enum_PNV fallback (SAFE)
# ======================================================================
def _parse_schema_enum_pnv(text: str, parsed: Dict[str,str]):
schema = _load_extended_schema(EXTENDED_SCHEMA_PATH)
t = text.lower()
for field, meta in schema.items():
if field in CORE_FIELDS or field in parsed:
continue
if meta.get("value_type") != "enum_PNV":
continue
aliases = meta.get("aliases", [])
for name in [field] + aliases:
m = re.search(
rf"\b{re.escape(name.lower())}\b\s*(positive|negative|variable|unknown)",
t,
)
if m:
_set_if_stronger(parsed, field, m.group(1).capitalize())
break
# ======================================================================
# MAIN
# ======================================================================
def parse_text_extended(text: str) -> Dict[str,Any]:
orig = text or ""
if not orig.strip():
return {"parsed_fields": {}, "source": "extended_parser", "raw": orig}
cleaned = _clean_text(orig)
parsed: Dict[str,str] = {}
_parse_gram_variable(cleaned, parsed)
_parse_shape_yeast(cleaned, parsed)
_parse_capsule_variable(cleaned, parsed)
_parse_gas_production(cleaned, parsed)
_parse_motility_type(cleaned, parsed)
_parse_pigment(cleaned, parsed)
_parse_colony_pattern(cleaned, parsed)
_parse_odor(cleaned, parsed)
_parse_tsi(cleaned, parsed)
_parse_nacl(cleaned, parsed)
_parse_haemolysis_type(cleaned, parsed)
_parse_ornithine_dec(cleaned, parsed)
_parse_schema_enum_pnv(cleaned, parsed)
return {
"parsed_fields": parsed,
"source": "extended_parser",
"raw": orig,
} |