File size: 9,996 Bytes
7111e1a | 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 | # mnb/classifier.py
# ============================================================
# MNB CLASSIFIER β wraps the trained DocumentClassifier
#
# TWO SEPARATE CONCERNS:
#
# PATH A β Certifications Page
# User uploads a certification scan.
# MNB identifies which form it is:
# form102 β Form 102 (Certificate of Live Birth)
# form103 β Form 103 (Certificate of Death)
# form97 β Form 97 (Certificate of Marriage)
#
# PATH B β Application for Marriage License Page (Form 90)
# User uploads TWO birth certificates:
# - Groom's Birth Cert (PSA/NSO sealed)
# - Bride's Birth Cert (PSA/NSO sealed)
# MNB is NOT used for form type here β the upload page
# already tells us it's a birth cert.
# classify_sex() reads the SEX field β GROOM (Male) or BRIDE (Female)
# and routes each cert to the correct Form 90 slot.
#
# Files needed:
# form_classifier.py β training + DocumentClassifier
# models/mnb_classifier.pkl
# models/tfidf_vectorizer.pkl
# models/mnb_metadata.json
# ============================================================
import sys
import os
_mnb_dir = os.path.dirname(os.path.abspath(__file__))
if _mnb_dir not in sys.path:
sys.path.insert(0, _mnb_dir)
_root_dir = os.path.dirname(_mnb_dir)
if _root_dir not in sys.path:
sys.path.insert(0, _root_dir)
try:
from form_classifier import DocumentClassifier
_HAVE_DOC_CLASSIFIER = True
except ImportError:
_HAVE_DOC_CLASSIFIER = False
# ββ Keyword fallback (used if .pkl files not found) ββββββββ
# Uses exact Philippine civil registry form headers
_FORM_KEYWORDS = {
"form102": [
"Municipal Form No. 102",
"Municipal Form No.102",
"Certificate of Live Birth",
"live birth",
"name of child",
"date of birth",
"place of birth",
"birth certificate",
"mother", "father",
"infant", "newborn",
"attendant at birth",
],
"form103": [
"Municipal Form No. 103",
"Municipal Form No.103",
"Certificate of Death",
"death certificate",
"name of deceased",
"date of death",
"place of death",
"cause of death",
"burial", "deceased",
"immediate cause",
],
"form97": [
"Municipal Form No. 97",
"Municipal Form No.97",
"Certificate of Marriage",
"marriage certificate",
"name of husband",
"name of wife",
"date of marriage",
"place of marriage",
"solemnizing officer",
"contracting parties",
"witnesses",
],
}
# Sex keywords for Form 90 routing (Groom/Bride)
_SEX_KEYWORDS = {
"GROOM": [
"sex: male",
"sex male",
"2. sex: male",
" male",
"sex m",
],
"BRIDE": [
"sex: female",
"sex female",
"2. sex: female",
" female",
"sex f",
],
}
def _keyword_classify_form(text: str) -> str:
"""Keyword fallback for Certifications page classification."""
t = text.lower()
scores = {k: sum(1 for kw in v if kw.lower() in t) for k, v in _FORM_KEYWORDS.items()}
return max(scores, key=scores.get)
def _keyword_classify_sex(text: str) -> str:
"""Keyword-based sex classifier for Form 90 routing."""
t = text.lower()
scores = {k: sum(1 for kw in v if kw.lower() in t) for k, v in _SEX_KEYWORDS.items()}
return max(scores, key=scores.get)
# ββ Form code β NER hint map ββββββββββββββββββββββββββββββ
_FORM_CODE_TO_HINT = {
"form102": "birth",
"form103": "death",
"form97": "marriage",
# Form 90 is handled by classify_sex() β not this map
}
class MNBClassifier:
"""
MNB Classifier for the Civil Registry Digitization System.
PATH A β Certifications Page:
mnb = MNBClassifier()
form_code = mnb.classify_form_type(ocr_text)
# β 'form102' | 'form103' | 'form97'
hint = mnb.get_ner_hint(ocr_text)
# β 'birth' | 'death' | 'marriage'
result = mnb.classify_full(ocr_text)
# β {'label': 'Form 102 - Certificate of Live Birth',
# 'form_code': 'form102', 'confidence': 0.97, 'probabilities': {...}}
PATH B β Application for Marriage License Page (Form 90):
sex_role = mnb.classify_sex(ocr_text)
# β 'GROOM' (Male birth cert) | 'BRIDE' (Female birth cert)
"""
def __init__(self, model_dir: str = "models"):
self._doc_clf = None
if _HAVE_DOC_CLASSIFIER:
try:
self._doc_clf = DocumentClassifier(model_dir=model_dir)
print(f" [MNB] Loaded DocumentClassifier from {model_dir}/")
except FileNotFoundError as e:
print(f" [MNB] {e}")
print(" [MNB] Using keyword fallback β run: python mnb/form_classifier.py")
else:
print(" [MNB] form_classifier.py not found β using keyword fallback")
# ββ PATH A: Certifications Page ββββββββββββββββββββββββ
def classify_form_type(self, ocr_text: str) -> str:
"""
Certifications page: identify which form was uploaded.
Returns: 'form102' | 'form103' | 'form97'
"""
if self._doc_clf is not None:
return self._doc_clf.predict(ocr_text)["form_code"]
return _keyword_classify_form(ocr_text)
def classify_full(self, ocr_text: str) -> dict:
"""
Certifications page: full result with confidence scores.
Returns:
{
'label': 'Form 102 - Certificate of Live Birth',
'form_code': 'form102',
'confidence': 0.97,
'probabilities': { ... }
}
"""
if self._doc_clf is not None:
return self._doc_clf.predict(ocr_text)
winner = _keyword_classify_form(ocr_text)
return {
"label": winner,
"form_code": winner,
"confidence": 1.0,
"probabilities": {k: (1.0 if k == winner else 0.0) for k in _FORM_KEYWORDS},
}
def get_ner_hint(self, ocr_text: str) -> str:
"""
Returns NER hint string for bridge.py:
'birth' | 'death' | 'marriage'
"""
code = self.classify_form_type(ocr_text)
return _FORM_CODE_TO_HINT.get(code, "birth")
# ββ PATH B: Marriage License Page (Form 90) ββββββββββββ
def classify_sex(self, ocr_text: str) -> str:
"""
Form 90 upload page only.
Reads the SEX field on a PSA/NSO birth certificate.
Returns: 'GROOM' (Male) | 'BRIDE' (Female)
"""
return _keyword_classify_sex(ocr_text)
def classify_sex_proba(self, ocr_text: str) -> dict:
"""
Returns confidence scores for sex classification.
Returns: {'GROOM': 0.9, 'BRIDE': 0.1}
"""
winner = _keyword_classify_sex(ocr_text)
return {k: (1.0 if k == winner else 0.0) for k in _SEX_KEYWORDS}
# ββ Quick test ββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
mnb = MNBClassifier()
print("\n ββ PATH A: Certifications Page Tests ββ")
cert_tests = [
(
"Municipal Form No. 102 Certificate of Live Birth "
"Name of child Maria Santos Date of birth 01/15/1990 "
"Place of birth Brgy. San Jose Tarlac City "
"Name of mother Lani Santos Name of father Jose Santos "
"Sex Female birth certificate infant",
"form102"
),
(
"Municipal Form No.102 Certificate of Live Birth "
"PSA Child Juan Dela Cruz born 03/22/1985 Capas Tarlac "
"mother Rosa father Pedro Sex Male",
"form102"
),
(
"Municipal Form No. 103 Certificate of Death "
"Name of deceased Pedro Reyes Date of death 03/22/2020 "
"Cause of death Cardiac Arrest death certificate burial",
"form103"
),
(
"Municipal Form No.103 Certificate of Death "
"Deceased Ana Torres died 07/04/2000 Pneumonia burial permit",
"form103"
),
(
"Municipal Form No. 97 Certificate of Marriage "
"Name of husband Carlos Bautista Name of wife Ana Torres "
"Date of marriage 07/04/2005 solemnizing officer witnesses",
"form97"
),
(
"Municipal Form No.97 Certificate of Marriage "
"Husband Jose Santos wife Maria Reyes married 11/30/1995 "
"contracting parties",
"form97"
),
]
for text, expected in cert_tests:
result = mnb.classify_full(text)
mark = "β
" if result["form_code"] == expected else "β"
print(f" {mark} Expected={expected:<8} Got={result['form_code']:<8} "
f"Confidence={result['confidence']:.1%} ({result['label']})")
print("\n ββ PATH B: Form 90 Marriage License β Sex Routing Tests ββ")
sex_tests = [
(
"Municipal Form No.102 Certificate of Live Birth PSA "
"CHILD (First): Juan Dela Cruz SEX: Male "
"Date of Birth March 15 1990 Mother Maria Dela Cruz",
"GROOM"
),
(
"Municipal Form No.102 Certificate of Live Birth NSO "
"CHILD (First): Ana Santos SEX: Female "
"Date of Birth August 21 1995 Mother Gloria Santos",
"BRIDE"
),
]
for text, expected in sex_tests:
pred = mnb.classify_sex(text)
mark = "β
" if pred == expected else "β"
print(f" {mark} Expected={expected} Got={pred}")
|