Repos Certificate Assistant
CA Certificate Assistant
Certificate Assistant is a hackathon decision-support tool for Chhattisgarh caste and domicile certificates: it links an applicant to relatives' archived certificates and drafts orders, with the officer deciding.
- Stack
- Python, FastAPI, Splink (Fellegi-Sunter, EM), DuckDB, rapidfuzz, Jinja2, React + TypeScript, tesseract.js, jsQR
- Examples
- 38: 37 solid, 1 naive, 0 missing
- Chapters
- 13 of 34
- Who wrote it
- 6 commits at the pin: 5 by GAURAV singh and 1 by Gaurav, so all by Gaurav.
How the AI path is built
There is no LLM in this repo. An applicant record is normalised, blocked against a synthetic certificate archive and scored by a Splink-trained Fellegi-Sunter model exported to JSON. Rules produce flags and a checklist; bilingual Jinja2 templates draft orders and messages, and an entity checker verifies them against the source record. The browser runs OCR and QR decoding locally and sends only a perceptual hash. Officers confirm or dismiss each match, and those acts feed a ridge-regularised recalibration. Evaluation is on held-out synthetic families. The 'AI' chapters map to classical retrieval, evals, guardrails and product UX only.
Request flows
End-to-end journeys through the code, each step pinned to a file and line. Good material for "walk me through your system".
Case opened -> suggested family match -> officer decision7 steps · ch 15, 22, 29, 34
- case analysed via engine.analyse
app/backend/engine.py:840 - blocking candidates
matcher.py:166 - score_view sums weights
matcher.py:230 - trace built
agent_trace.py:23 - officer marks same/not
api.py:430 - approve gate
api.py:684 - template message + entity check
messages.py:121
Reader: paper photo -> compared with archive5 steps · ch 13, 14, 34
- tesseract OCR in browser
ocr.ts:40 - extractFields
extract.ts:88 - phash only sent
reader_api.py:80 - archive lookup
reader_api.py:42 - compareBi with confidence gate
extract.ts:192
Not in this repo
Hands-on sections this repo does not demonstrate. See Gaps for the whole picture.
12.0113.0217.1120.0121.0122.0527.0131.0333.02
Every example, by chapter
12Prompting Fundamentals● 1Read with these
CAReviewed Jinja2 templates with StrictUndefined as versioned 'prompts'●
def render_pair(template: str, **ctx) -> dict:
out = {lang: env.get_template(f"{template}.{lang}.j2").render(**ctx).strip() for lang in ("en", "hi")}
for a, b in HI_AGREEMENT:
out["hi"] = out["hi"].replace(a, b)
return outAll citizen-message wording lives in reviewed .j2 files; StrictUndefined makes a missing variable a hard error. This is the template-bound alternative to generating text with a model.
Lesson If an LLM were added, it would sit behind the entity checker below.
13Structured Output● 1 ◐ 1Read with these
CATyped request schema validates the fingerprint input●
class Fingerprint(BaseModel):
app_id: str = Field(min_length=3, max_length=40)
phash: str = Field(pattern=r"^[0-9a-f]{16}$")
kind: str = Field(default="unknown", max_length=20)
label: str = Field(default="", max_length=80)A Pydantic model constrains the perceptual hash to 16 hex digits and bounds the string lengths before any logic runs.
Lesson Not LLM output, but the same validate-at-the-boundary habit.
CARule-based field extraction from OCR text◐
// ---- prose (affidavit): "मैं सुनीता मरकाम पुत्री श्री रामलाल मरकाम, ..."
const NAME3 = `(${WORD}(?:\\s+${WORD}){0,2}?)`; // up to three words ("रमेश कुमार साहू")
const me = t.match(new RegExp(`मैं\\s+${NAME3}\\s+(?:पुत्री|पुत्र|पत्नी|पिता)\\s+(?:श्री\\s+)?${NAME3}\\s*[,।]`));
if (me) {
put("name", { hi: me[1] });
put("father", { hi: me[2] });
}
// ---- certificate prose: "... कि श्री रामलाल मरकाम (Ram Lal Markaam) पिता श्री बुधराम मरकाम, ..."
const cert = t.match(new RegExp(`(?:कि\\s+)?(?:श्री|श्रीमती|कुमारी|सुश्री)\\s+${NAME2}\\s*(?:\\(([A-Za-z .]+)\\))?\\s*(?:पिता|पुत्र|पुत्री)\\s+(?:श्री\\s+)?(\\S+(?:\\s+${WORD})?)`));
if (cert) {
put("name", { hi: cert[1], en: cert[2]?.trim() });
put("father", { hi: stripQuotes(cert[3]) });
}Regexes pull name and father from affidavit and certificate prose. Deterministic and offline, but brittle to any wording change; no model or schema-constrained extraction.
Lesson An LLM or layout model with a typed schema would handle wording drift; the regexes are fine for three known paper types.
14Multimodal and Realtime Voice● 2Read with these
CAIn-browser OCR worker served from own origin●
if (!workerP) {
const t0 = performance.now();
const origin = window.location.origin;
// English first: research (and our tests) found Hindi-first garbles the digits in certificate numbers and dates
workerP = createWorker(["eng", "hin"], 1, {
workerPath: `${origin}/tesseract/worker.min.js`,
corePath: `${origin}/tesseract`,
langPath: `${origin}/tessdata`,
gzip: false,
logger: (m: { status: string; progress: number }) => listener?.({ status: m.status, progress: m.progress }),
}).then((w) => {
engineReadyMs = Math.round(performance.now() - t0);
return w;tesseract.js is loaded lazily as a single shared worker with local wasm and language data (English first, then Hindi), with a progress listener for the UI.
Lesson English-first language order is an empirical fix: Hindi-first garbled digits in certificate numbers.
CAOCR confidence per field, low confidence shown as 'unclear' not 'mismatch'●
export function compareBi(field: Field | undefined, ref: { hi?: string; en?: string } | undefined): Verdict {
if (!field || !ref) return "na";
const vs = [compareText(field.hi, ref.hi), compareText(field.en, ref.en)].filter((v) => v !== "na");
if (!vs.length) return "na";
const order: Verdict[] = ["match", "variant", "mismatch"];
const best = vs.sort((x, y) => order.indexOf(x) - order.indexOf(y))[0];
if (best === "mismatch" && field.confidence < 60) return "unclear";
return best;
}A text mismatch is downgraded to 'unclear' when the field's OCR confidence is under 60, so a shaky read never reads as a finding against the applicant.
15Information Retrieval Foundations● 8Read with these
CARelevance expressed as a calibrated match probability●
def match_level(p: float) -> str | None:
if p >= 0.95:
return "exact"
if p >= 0.60:
return "possible"
return NoneTwo tiers decide what the officer sees: >=0.95 'exact' and >=0.60 'possible'; below 0.60 nothing is shown. The probability is the relevance judgment.
CABlocking indexes as an inverted index over name keys●
def candidates(self, qf: dict) -> list[int]:
"""Blocking — identical to the Splink prediction blocking rules."""
out: set[int] = set()
for hyp in HYP:
if qf.get("district_lgd"):
out.update(self.idx_dist_sur.get((hyp, qf["district_lgd"], qf["rel_surname_skel"]), []))
if qf.get("village_lgd"):
out.update(self.idx_village.get((hyp, qf["village_lgd"]), []))
if qf["rel_given_skel"]:
out.update(self.idx_names.get((hyp, qf["rel_given_skel"], qf["rel_surname_skel"]), []))
return sorted(out)Candidate generation looks up three precomputed dict indexes (district+surname skeleton, village, given+surname skeleton) and unions the hits, so only a few certificates are scored instead of the whole archive.
Lesson Same idea as an inverted index: cheap recall-oriented candidate generation first, expensive scoring second.
CAAnalyzer for Indian names (transliterate, fold, skeleton)●
Pipeline for one name string:
1. strip honorifics / relation markers (Shri, Smt, श्री, S/O, पिता ...)
2. Devanagari -> Latin with indic_transliteration (ITRANS) + Hindi schwa deletion
3. lowercase, phonetic folding (aa->a, ee->i, w->v, sh->s, ksh->x ...),
collapse doubled letters ("Markaam" -> "markam")
4. tokens; surname = last token; given = the rest joined WITHOUT spaces
("Ram Lal" == "Ramlal")
5. consonant skeleton = folded string with vowels removed
"""One normalisation pipeline (strip honorifics, Devanagari to Latin, phonetic folding, consonant skeleton) is shared by training and runtime so both sides tokenise names identically.
Lesson Index-time and query-time analyzers must be the same code; here the same module serves Splink training and the live scorer.
CAGraded fuzzy comparison levels for a name field●
def level_given(a_given: str, a_skel: str, b_given: str, b_skel: str) -> str:
if not a_given or not b_given:
return "null"
if a_given == b_given:
return "exact"
if a_skel and a_skel == b_skel:
return "skeleton"
s = jw(a_given, b_given)
if s >= 0.92:
return "jw>=0.92"
if s >= 0.80:
return "jw>=0.80"
return "else"A name pair is bucketed into null, exact, skeleton, Jaro-Winkler >=0.92, >=0.80 or else. Each bucket later gets a learned weight, so fuzziness is graded rather than a single threshold.
CAScore fusion by summing learned log-odds weights●
def log2_odds(self, levels: dict[str, str]) -> float:
return self.model.prior + sum(self.model.weight(k, lv) for k, lv in levels.items())The final score is the model prior plus the weight of each field's comparison level (naive-Bayes style Fellegi-Sunter), then converted to a probability. This is the classical-ML analogue of fusing several retrieval signals.
Lesson RRF fuses ranks; this fuses calibrated evidence. The weights come from EM, not hand tuning.
CAPrecision/recall/F1 and recall that counts blocking misses●
for ci, rel in truth.items():
n_pos_total += 1
if ci not in seen:
missed_by_blocking += 1
c = certs[ci]
sl = set(base)
if c["village_lgd"] == q["village_lgd"] and norm(c["_holder_raw"]).surname_skel == qn.surname_skel:
sl.add("hard")
if c["_script"] != q["script"]:
sl.add("cross_script")
rows.append((0.0, True, False, sl))Every true link the blocking never surfaced is added as a score-0 positive, so end-to-end recall is not flattered by a candidate generator that dropped relatives.
Lesson Recall must be measured over the whole corpus, not only over the candidates the retriever returned.
CASlice metrics: precision/recall per cohort●
slice_defs = [
("hard", {"en": "Same village & common surname (the relative is in the candidate set; the test is telling families apart)", "hi": "एक ही ग्राम व सामान्य उपनाम (संबंधी उम्मीदवार-सूची में रहता है; परीक्षा परिवारों को अलग पहचानना है)"}),
("tribal_div", {"en": "Bastar & Surguja divisions", "hi": "बस्तर और सरगुजा संभाग"}),
("plains", {"en": "Plains divisions (Raipur, Durg, Bilaspur)", "hi": "मैदानी संभाग (रायपुर, दुर्ग, बिलासपुर)"}),
("women", {"en": "Women applicants", "hi": "महिला आवेदक"}),
("cross_script", {"en": "Cross-script (Devanagari ↔ Latin)", "hi": "भिन्न लिपि (देवनागरी ↔ लैटिन)"}),
]Metrics are reported separately for hard same-village cases, tribal divisions, plains, women and cross-script pairs rather than one global number.
Lesson Slices expose where a system fails for specific groups; matches the chapter on failure taxonomies.
CAMetadata filter: like-for-like certificate kind and LGD place levels●
if is_self(qf, v, c):
continue
if kind and (c["service"] == "domicile") != (kind == "domicile"):
continueCandidates are filtered by certificate kind (caste vs domicile) before scoring, and place comparison uses Local Government Directory codes, i.e. structured metadata rather than free text.
Lesson Evidence of the wrong kind is excluded up front rather than down-weighted.
17RAG Pipelines● 1Read with these
CAGrounding: message checked against only the records used●
text = render_pair(f"msg_{action}", **ctx)
source = [app, office, SHORT_SERVICE[app["service"]], deficiencies or [], findings or "", records]
return {"channel": "whatsapp", "text": text, "generator": "template", "checker": check_entities(text, source)}The message is rendered from the case data, then checked with the application, office, service and deficiencies as the allowed source set.
19Evals I: Methodology and Error Analysis● 3Read with these
CAFailure slices as a taxonomy of hard cases●
base = set()
if q["division"] in ("Bastar", "Surguja"):
base.add("tribal_div")
else:
base.add("plains")
if q["gender"] == "F":
base.add("women")Each scored pair is tagged with slice labels (tribal division, plains, women) so errors can be grouped; hard and cross-script tags are added below.
CAHeld-out eval set built from generator ground truth●
"""Evaluate the lineage matcher on HELD-OUT synthetic families (30% of lineages, never used
for training) against the generator's ground truth. Writes model/eval.json in the
/api/eval shape.
A candidate pair is (applicant, archived certificate). It is a TRUE link when the
certificate holder is the applicant's father or a sibling (ground truth from
population.csv). Recall counts every true link in the archive, including those the
blocking never surfaced (so blocking misses are counted as misses).Evaluation uses 30% of synthetic lineages never used for training, scored against the generator's known father/sibling truth.
Lesson Honest about being synthetic; real-archive accuracy is explicitly deferred.
CASynthetic officer labels with injected error rate●
def simulated_labels() -> list[dict]:
u = universe()
shown = [p for p in u["pairs"] if p["part"] == "pool" and _p(p["s"]) >= POSSIBLE]
rng = random.Random(SEED)
out = []
for p in rng.sample(shown, min(N_SIMULATED, len(shown))):
y = p["y"]
if rng.random() < OFFICER_ERROR:
y = 1 - y
out.append({"pair_id": p["id"], "y": y, "source": "simulated", "officer_error": y != p["y"]})
return out300 simulated officer confirmations are drawn from ground truth with a 3% flipped-label rate, labelled 'simulated' everywhere, to exercise the learning loop when few real labels exist.
Lesson Injecting annotator noise is a good habit; the label is tagged so it is never mistaken for a real one.
20Evals II: Judges, RAG/Agent Evals and Continuous Evaluation● 1Read with these
CACalibrating the scorer against human (officer) labels with ridge shrinkage●
def fit(kind: str, rows: list[tuple[float, list[float], int]], prior: float) -> np.ndarray:
"""Ridge-regularised logistic regression (IRLS), shrunk towards the EM model (theta0)."""
th0 = _init(kind, prior)
if not rows:
return th0
X = np.array([_features(kind, s, w) for s, w, _ in rows])
y = np.array([yy for _, _, yy in rows], dtype=float)
lam = RIDGE[kind]
def loss(t):
z = X @ t
return float(np.sum(np.logaddexp(0, z) - y * z) + 0.5 * lam * np.sum((t - th0) ** 2))Officer 'same family' / 'not this family' labels fit a ridge-regularised logistic recalibration shrunk toward the EM weights, so a few hundred labels cannot swing the model.
Lesson Validate an automated judge against human labels; here the human labels also tune it.
21Tool Use / Function Calling● 1Read with these
CAApproval gate: reject needs show-cause, approve needs every possible match disposed●
if body.action == "reject" and not (an.get("show_cause") and an["show_cause"].get("reply")):
raise HTTPException(422, "a rejection needs a show-cause notice first: issue it (action 'show_cause') and record the "
"reply or its absence before the final order")
if body.action == "approve" and an["disposition_required"] and not native:
raise HTTPException(422, "every possible family record shown must be disposed of first ('same family' or "
f"'not this family'): {an['disposition_required']}")The server returns 422 unless a show-cause reply is recorded before rejection, and unless every possible family record has been marked 'same' or 'not' before approval.
Lesson Human approval enforced in the API, not just the UI.
22The Agent Loop and Architectures● 1Read with these
CAWorkflow, not an agent: the 'Certificate Assistant agent' never decides●
"""Round 8b: the visible "प्रमाण एजेंट" trace — what the system did for one file, step by step.
Built only from the real analysis and the timing marks engine.analyse() records while it runs (additive; the
analysis itself is unchanged). Honest labels: the agent reads, searches, scores, checks and drafts. It never decides.
The last step is always "waiting for the officer"; the frontend shows it as done once the file is decided.
"""The module documents that the 'agent' only reads, searches, scores, checks and drafts, and that the last step is always the officer. It is a fixed pipeline of rules and one ML scorer.
Lesson Honest labelling: a deterministic workflow with a human final step.
29Guardrails and Safety● 3Read with these
CAData minimisation: only a perceptual hash leaves the browser●
# ------------------------------------------------------------------ duplicate-paper check (perceptual hash)
# The browser sends only a 64-bit perceptual hash (pHash, DCT-based, as in Python's imagehash) of the page image —
# never the image. A rescan or a tilted phone photo of the same paper lands within a few bits (synthetic aff.png vs
# aff_noisy.jpg: 4 bits; different papers: >= 18). Held in memory, cleared by a demo reset.The page image is never uploaded; the browser sends a 64-bit DCT perceptual hash, and the server compares hash distances to flag the same paper on another file.
CAEntity checker validates finished output against the source record●
for tok in _tokens(text.get(lang, "")):
low = tok.lower()
is_id = "/" in tok or any(ch.isdigit() for ch in tok)
is_name_like = tok[:1].isupper() or "ऀ" <= tok[:1] <= "ॿ"
if not is_id and (low in vocab or not is_name_like):
continue
if low in vocab and not is_id:
continue
if tok not in checked:
checked.append(tok)
if low not in corpus and low not in vocab:
if tok not in unsupported:
unsupported.append(tok)
return {"passed": not unsupported, "unsupported_entities": unsupported, "checked_entities": checked}Every number, certificate id and name-like word in the message must appear in the template's fixed wording or the source record; anything else is returned as an unsupported entity.
Lesson Docstring says it is the same guard an LLM rewrite would have to pass.
CAUnit test proves the guard catches invented entities●
def test_entity_checker_catches_invented_entities():
from messages import check_entities
app = client.get(f"/api/applications/{enc(HERO)}").json()["application"]
ok = check_entities({"en": f"Namaste Sunita Markam. Your application {HERO} is APPROVED.", "hi": ""}, [app])
assert ok["passed"]
bad = check_entities({"en": f"Namaste Sunita Markam. Certificate CG/KDG/SDO/2011/999999 for Rahul, fee 500.", "hi": ""}, [app])
assert not bad["passed"] and "CG/KDG/SDO/2011/999999" in bad["unsupported_entities"] and "500" in bad["unsupported_entities"]A positive case passes and a message with an invented certificate number and fee '500' fails with both listed as unsupported entities.
Lesson Guardrails need their own positive and adversarial tests.
30Observability● 3Read with these
CAAudit log of every record access and decision●
def add_audit(self, role: str, action: str, app_id: str | None = None, records: list[str] | None = None,
note: str | None = None, actor: str | None = None, extra: dict | None = None) -> dict:
entry = {"ts": datetime.now(IST).isoformat(timespec="seconds"), "actor_role": role,
"actor": actor or DEFAULT_ACTOR.get(role, role), "action": action,
"records_accessed": records or []}
if app_id:
entry["app_id"] = app_id
if note:
entry["note"] = note
if extra:
entry.update(extra)
with self.lock:
self.audit.append(entry)
self.save()Each action is appended with timestamp, role, actor, action and the records accessed, then persisted.
Lesson Logs records touched; no prompts exist here, but the pattern carries over.
CAStep-by-step trace of one file's analysis●
# ⑥ waiting for the officer (the agent never decides)
steps.append({
"code": "officer", "status": "waiting", "ms": None,
"title": {"en": "Waiting for the officer", "hi": "अधिकारी की प्रतीक्षा"},
"detail": {"en": "The agent never decides, approves or rejects. You decide; the audit records what this screen showed.",
"hi": "एजेंट निर्णय, स्वीकृति या अस्वीकृति नहीं करता। निर्णय आपका है; इस स्क्रीन पर दिखी जानकारी ऑडिट में दर्ज होती है।"},
})
for i, s in enumerate(steps, 1):
s["step"] = i
return stepsThe trace ends with a mandatory 'waiting for the officer' step and numbers the steps; earlier steps carry timings and a status of ok, attention or waiting.
CAPer-stage latency and count metrics●
if stats is not None:
stats.update({"archive_certs": len(self.archive.certs), "blocked_views": len(set(cand)),
"candidates": len(best), "above_threshold": len(out),
"block_ms": round((tb - t0) * 1000, 2), "score_ms": round((time.perf_counter() - tb) * 1000, 2)})Blocking and scoring report archive size, candidate counts and block_ms/score_ms, which the trace later shows.
Lesson Counts and timings per stage are the same metrics an LLM pipeline needs.
32Deployment and LLMOps● 1Read with these
CAModel version stamped on every export and shown in the trace●
model = {
"model": "Splink Fellegi–Sunter (EM)",
"model_version": f"lineage-fs-splink-{date.today().isoformat()}",
"trained_on": {"applicant_rows": n_left, "certificate_rows": n_right,
"description": "SYNTHETIC Chhattisgarh population, training families only (70%)",The exported model records name, a dated version and training-set size, so a result can be traced to the model that made it.
34Product UX for AI and the Feedback Loop● 11Read with these
CAUX that states facts and never pre-selects an outcome●
/**
* Round 3: ONE evidence verdict at the top of the case view. It answers, in fixed rows and fixed icons,
* what the evidence is, what the officer must decide, what needs attention, what the file relies on and
* what is missing. Every other restatement of the same facts was removed from the page.
* It states facts and the officer's task; it never pre-selects an outcome (round-2 anti-anchoring).
*/One fixed-row evidence verdict tells the officer what is known and what they must decide; it avoids anchoring the decision on the machine's guess.
CAHonesty note on every eval result●
"honesty_note": {
"en": "Measured on synthetic data generated by us; real-archive accuracy must be re-measured on a labelled sample before any pilot.",
"hi": "यह माप हमारे द्वारा बनाए गए नमूना डेटा पर है; किसी भी पायलट से पहले वास्तविक अभिलेखों के लेबल किए गए नमूने पर पुनः मापना आवश्यक है।",
},The eval output carries a bilingual note saying the numbers are measured on synthetic data and must be re-measured on a labelled real sample before any pilot.
Lesson Expectation setting shipped in the data, not just in a slide.
CACollapsible trace with step icons and timings●
export default function AgentTrace({ trace, decided }: { trace?: TraceStep[]; decided: boolean }) {
const { t, tx } = useI18n();
const [open, setOpen] = useState(false);
if (!trace || trace.length === 0) return null;
const steps = trace.map((s) =>
s.code === "officer" && decided
? { ...s, status: "ok" as const, title: { en: "Decided by the officer", hi: "अधिकारी ने निर्णय लिया" } }
: s,
);
const total = steps.reduce((a, s) => a + (s.ms ?? 0), 0);
const attention = steps.filter((s) => s.status === "attention").length;
const ico = (s: TraceStep) => (s.status === "ok" ? "✓" : s.status === "attention" ? "!" : "⏳");A one-line summary (steps, total ms, items to check) opens into the full list; the officer step flips to 'Decided by the officer' only once decided.
CAPer-field evidence weights shown for each suggested match●
label = COMP_LABEL.get((comp, v.hyp)) or COMP_LABEL[(comp, None)]
items.append({"field": FIELD[comp], "label": label, "comparison": {"en": en, "hi": hi},
"level": lv, "weight": round(self.model.weight(comp, lv), 3)})Each comparison returns a bilingual label, level and learned weight so the officer sees why a record was proposed.
CAUncertainty vocabulary in the Reader●
const VERDICT: Record<Verdict, { hi: string; en: string; cls: string }> = {
match: { hi: "✓ मेल", en: "✓ matches", cls: "v-match" },
variant: { hi: "≈ वर्तनी भिन्न", en: "≈ spelling variant", cls: "v-variant" },
mismatch: { hi: "⚠ भिन्न — मूल देखें", en: "⚠ differs — check original", cls: "v-mismatch" },
unclear: { hi: "? पढ़ाई अस्पष्ट", en: "? unclear read", cls: "v-unclear" },
na: { hi: "—", en: "—", cls: "v-na" },
};Five verdict states (match, spelling variant, differs - check original, unclear read, n/a) express certainty and avoid a binary fake/genuine label.
CAMissing record is never a ground for rejection●
if not c:
# returned (not raised): the app-wide handler flattens HTTPException details to a string
return JSONResponse(status_code=404, content={"found": False, "cert_no": no, "detail": {"en": f"No record {no} in the archive. This is not a ground for rejection; "
"check the original paper or ask the issuing office.",
"hi": f"अभिलेखागार में {no} का अभिलेख नहीं मिला। यह अस्वीकृति का आधार नहीं है; "
"मूल दस्तावेज़ देखें या जारीकर्ता कार्यालय से पूछें।"}})When the archive has no matching record, the API returns a 404 payload telling the officer this is not grounds for rejection and to check the original paper.
CAOne-tap explicit feedback schema●
class FeedbackBody(BaseModel):
useful: Literal["yes", "no", "wrong_family"]
note: Optional[str] = None
@app.post("/api/applications/{app_id:path}/tool-feedback")
def tool_feedback(app_id: str, body: FeedbackBody):The officer rates the check with yes, no or wrong_family and an optional note, after the decision is made.
CAImplicit feedback: officer dispositions become training labels●
for lm in an.get("lineage_matches") or []:
no = lm["certificate"]["cert_no"]
d = per.get(no)
if not d:
continue
w = {FIELD_TO_COMP.get(x["field"]): x["weight"] for x in lm.get("weights") or []}
out.append({"pair_id": f"{app_id}|{no}", "y": 1 if d["decision"] == "same" else 0, "source": "officer_case",
"app_id": app_id, "cert_no": no, "ts": d.get("ts"),
"w": [w.get(c, 0.0) for c in COMPARISONS], "s": lm.get("prior_weight", 0) + sum(w.get(c, 0.0) for c in COMPARISONS)})
return outEach officer confirmation or dismissal on a live file is converted to a labelled pair with its model features; approve/reject decisions are deliberately not used as labels.
Lesson Choosing which user acts count as labels is the key design decision.
CAFeedback pitfalls: one tap per decision and never an officer metric●
if d.get("tool_feedback"): # one tap per decision; a repeat would silently flip the Collector's feedback tile
raise HTTPException(409, "tool feedback is already recorded for this decision")
with STATE.lock:
d["tool_feedback"] = {"useful": body.useful, "note": (body.note or "").strip() or None,
"ts": datetime.now(IST).isoformat(timespec="seconds")}
d["snapshot"]["tool_feedback"] = d["tool_feedback"]
STATE.add_audit(STATE.entries[app_id]["application"]["routed_to"], "tool_feedback", app_id, [],
note=f"Tool feedback (for improving the tool, not an officer metric): {body.useful}"
+ (f" — {body.note.strip()}" if (body.note or "").strip() else ""))A repeat submission returns 409 so it cannot flip the dashboard tile, and the audit note says the feedback is for the tool, not for judging the officer.
CAReversibility: undo a confirmation until the decision is signed●
@app.post("/api/applications/{app_id:path}/clear-match")
def clear_match(app_id: str, body: ClearMatchBody):
"""Undo a 'same family' / 'not this family' act — allowed until the decision is signed."""
e = STATE.entry(app_id)
_pending_or_409(e["application"])
an = STATE.analysis(app_id)
_match_or_400(an, body.cert_no)
with STATE.lock:
prev = STATE.dispositions.get(app_id, {}).pop(body.cert_no, None)
STATE.invalidate(app_id)
if prev is None:
raise HTTPException(400, f"no confirmation or dismissal recorded for {body.cert_no}")
an = STATE.analysis(app_id)clear-match removes a 'same family' or 'not this family' act while the file is still pending, and the audit trail records the withdrawal.
CAPilot targets and stop rules mix model and product metrics●
PILOT_TARGETS = [
{"metric": {"en": "Lineage link precision (random review of 'same family' files)", "hi": "वंश-कड़ी की परिशुद्धता ('वही परिवार' फ़ाइलों की यादृच्छिक समीक्षा)"},
"target": {"en": "≥ 98%", "hi": "≥ 98%"}, "stop_rule": {"en": "Pause if < 95% in any fortnight", "hi": "किसी पखवाड़े में < 95% हो तो रोकें"}},
{"metric": {"en": "Exclusion guard: rejection rate, pilot minus control (ST women, SC, OBC, no-record, migrants)", "hi": "बहिष्करण सुरक्षा: अस्वीकृति दर, पायलट घटा नियंत्रण (अ.ज.जा. महिलाएँ, अ.जा., अ.पि.व., बिना अभिलेख, प्रवासी)"},
"target": {"en": "Δ ≤ +1 pp in every group", "hi": "हर समूह में Δ ≤ +1 प्रतिशत बिंदु"}, "stop_rule": {"en": "Pause at +2 pp in any group", "hi": "किसी समूह में +2 प्रतिशत बिंदु पर रोकें"}},
{"metric": {"en": "Send-backs cured on the same application", "hi": "उसी आवेदन में पूर्ण हुई वापसियाँ"},
"target": {"en": "≥ 50%", "hi": "≥ 50%"}, "stop_rule": {"en": "Review the reason library if < 35%", "hi": "< 35% हो तो कारण-सूची की समीक्षा"}},
{"metric": {"en": "Officers who find the check useful (one-tap feedback, anonymous)", "hi": "जांच को उपयोगी मानने वाले अधिकारी (एक-टैप प्रतिक्रिया, अनाम)"},
"target": {"en": "≥ 60%", "hi": "≥ 60%"}, "stop_rule": {"en": "Redesign if < 40% after 30 days", "hi": "30 दिन बाद < 40% हो तो पुनः डिज़ाइन"}},Link precision, exclusion guard by group, cured send-backs and officer usefulness each carry a target and a pause rule.