Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

capa_check.py

Helper script for capa-plan-writer · 123 lines

Manufacturing & Industrial Operations / Quality Management & ISO 9001v1.0.0Updated OCT 25 20262 references2 scripts
scripts/capa_check.py
#!/usr/bin/env python3
"""Review a corrective action (CAPA) plan against ISO 9001 10.2 and the action-strength hierarchy.

CAPA JSON keys: capa_id, source, problem, correction, root_causes (list of {id, cause, verified, evidence}),
actions (list of {action, type corrective/preventive/correction, cause_id, owner, due}),
effectiveness ({criteria, method, due}), similar_check, updates (FMEA, control plan, procedures, risks)

Checks:
  CP001 high    no root cause, or the root cause is a symptom or blames a person ('operator error', 'not trained')
  CP002 high    no corrective action that changes the system: only correction (sort, rework, scrap, replace)
  CP003 high    no measurable effectiveness criteria, method and due date
  CP004 medium  weak actions only (retrain, remind, warn, re-brief): add error-proofing or a design/process change
  CP005 medium  action without owner or due date
  CP006 medium  root cause with no action, or action linked to no root cause
  CP007 medium  root cause not verified (switched on/off, reproduced, or data-confirmed)
  CP008 low     no check for similar nonconformities elsewhere (10.2.1 b 3)
  CP009 low     no update to risks, FMEA, control plan or documents (10.2.1 e, f)

Action strength (highest first): eliminate > error-proof > automate/detect > standardise > train > remind.

Usage:
    python capa_check.py capa.json

Exit codes: 0 no high findings, 1 high findings, 2 read or JSON error.
"""

import argparse
import json
import re
import sys

BLAME = re.compile(r"\b(operator|human|worker|inspector)\s+(error|mistake|fault)|\bnot (properly )?trained|\bcareless|\black of (attention|care|training|awareness)|\bdid not follow|\bforgot\b|\bmistake\b|\bnegligen", re.I)
SYMPTOM = re.compile(r"^\s*(part|parts|dimension|bore|hole)\b.*\b(out of (spec|tolerance)|oversize|undersize|wrong)\b", re.I)
CORRECTION = re.compile(r"\b(sort(ed)?|rework(ed)?|scrap(ped)?|replace(d)?|re-?inspect(ed)?|repaired|returned|credited|segregat)", re.I)
STRENGTH = [  # (rank, label, pattern)
    (5, "eliminate", r"\b(redesign|eliminat|remove the (step|need)|change (the )?(design|material|supplier))"),
    (4, "error-proof", r"\b(poka[- ]?yoke|error[- ]?proof|mistake[- ]?proof|fixture|interlock|sensor|go/?no-?go|physical stop|keyed)"),
    (3, "automate / detect", r"\b(automat|vision|in-?process (gauge|measurement)|100% (check|inspection)|alarm|spc|control chart|tool life (counter|monitor))"),
    (2, "standardise", r"\b(procedure|work instruction|wi-|standard work|checklist|control plan|setup sheet|update (the )?(sop|instruction))"),
    (1, "train", r"\b(train|retrain|coach|re-?brief|educat)"),
    (0, "remind", r"\b(remind|warn|toolbox talk|memo|be (more )?careful|awareness|email)"),
]


def strength(text):
    for rank, label, pat in STRENGTH:
        if re.search(pat, text, re.I):
            return rank, label
    return 2, "other"


def check(c):
    f = []
    causes = c.get("root_causes") or []
    if isinstance(causes, str):
        causes = [{"id": "RC1", "cause": causes}]
    actions = c.get("actions") or []
    if not causes:
        f.append(("CP001", "high", "no root cause stated"))
    for rc in causes:
        txt = str(rc.get("cause", ""))
        if BLAME.search(txt):
            f.append(("CP001", "high", f"{rc.get('id', '')} '{txt[:60]}' blames a person: ask why the process allowed it"))
        elif SYMPTOM.search(txt):
            f.append(("CP001", "high", f"{rc.get('id', '')} '{txt[:60]}' restates the symptom, not its cause"))
        if not rc.get("verified"):
            f.append(("CP007", "medium", f"{rc.get('id', '')} not verified: reproduce it, switch it on/off, or confirm with data"))
    real = [x for x in actions if str(x.get("type", "corrective")).lower() != "correction" and not
            (CORRECTION.search(str(x.get("action", ""))) and strength(str(x.get("action", "")))[0] <= 2 and
             not re.search(r"procedure|instruction|fixture|design|process", str(x.get("action", "")), re.I))]
    if not real:
        f.append(("CP002", "high", "only corrections (sort/rework/scrap/replace): add actions that remove the cause"))
    ranks = [(strength(str(x.get("action", ""))), x) for x in real]
    best = max((r[0][0] for r in ranks), default=-1)
    if real and best <= 1:
        f.append(("CP004", "medium", "strongest action is training/reminder: add error-proofing, automation or a design change"))
    for (rank, label), x in ranks:
        if not (x.get("owner") and x.get("due")):
            f.append(("CP005", "medium", f"'{str(x.get('action'))[:50]}' has no owner or due date"))
    ids = {str(rc.get("id")) for rc in causes if rc.get("id")}
    linked = {str(x.get("cause_id")) for x in real if x.get("cause_id")}
    for i in sorted(ids - linked):
        f.append(("CP006", "medium", f"root cause {i} has no corrective action"))
    for x in real:
        if x.get("cause_id") and str(x["cause_id"]) not in ids:
            f.append(("CP006", "medium", f"action '{str(x.get('action'))[:40]}' points to unknown cause {x['cause_id']}"))
    eff = c.get("effectiveness") or {}
    if not (eff.get("criteria") and re.search(r"\d", str(eff.get("criteria"))) and eff.get("method") and eff.get("due")):
        f.append(("CP003", "high", "effectiveness check needs a measurable criterion, a method and a date"))
    if not c.get("similar_check"):
        f.append(("CP008", "low", "record whether similar products, machines or sites have the same cause"))
    if not c.get("updates"):
        f.append(("CP009", "low", "update PFMEA, control plan, procedures or the risk register as needed"))
    return f, ranks


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("capa", help="CAPA JSON, or - for stdin")
    a = ap.parse_args()
    try:
        c = json.load(sys.stdin if a.capa == "-" else open(a.capa, encoding="utf-8"))
        if not isinstance(c, dict):
            raise ValueError("CAPA JSON must be an object")
    except (OSError, ValueError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    f, ranks = check(c)
    print(f"{c.get('capa_id', '(no id)')}: {c.get('problem', '')[:80]}")
    if ranks:
        print("Action strength:")
        for (rank, label), x in sorted(ranks, key=lambda r: -r[0][0]):
            print(f"  [{rank}] {label:<18}{str(x.get('action'))[:70]}")
    print()
    for code, sev, msg in f:
        print(f"{code} [{sev}] {msg}")
    print(f"\n{len(f)} issue(s)" if f else "Plan meets 10.2 and uses strong actions.")
    return 1 if any(x[1] == "high" for x in f) else 0


if __name__ == "__main__":
    sys.exit(main())
More in Quality Management & ISO 9001

8d-problem-solving-report-writer

Write and review 8D problem-solving reports for customer complaints and serious nonconformities (automotive and aerospace practice: Ford Global 8D, VDA, GM, Stellantis formats): D0 emergency response, D1 cross-functional team and champion, D2 problem description with 5W2H and is / is-not and no cause in the statement, D3 interim containment within 24 hours with verification and clean point, D4 verified occurrence and escape (non-detection) root causes plus systemic cause, D5 permanent corrective actions for each cause verified before implementation, D6 implementation, validation with production data and removal of containment, D7 PFMEA, control plan and read-across to similar products, D8 closure and recognition. Checks an 8D discipline by discipline for missing content, human-error root causes, missing escape cause or action, late containment and dates out of order.

acceptance-sampling-plan-selector

Select and evaluate acceptance sampling plans for incoming, in-process and final inspection: ANSI/ASQ Z1.4 / ISO 2859-1 single sampling under normal inspection (code letter from lot size and inspection level I, II, III, S-1 to S-4; sample size, Ac and Re from AQL, following the table's arrows to the correct plan; 100% when n reaches the lot size; AQLs above 10 per 100 units), operating characteristic curves (Pa at any quality, producer's quality level, indifference point, LTPD, AOQ and AOQL, binomial or hypergeometric), plans designed from producer and consumer risk, and c = 0 zero-acceptance plans. Covers AQL choice by defect class, switching rules between normal, tightened and reduced inspection, when sampling is not appropriate, and random sampling.

approved-supplier-list-manager

Manage and audit an approved supplier list (ASL) / external provider register for ISO 9001 8.4.1, IATF 16949 8.4 and AS9100 8.4.1: supplier status (approved, conditional, probation, pending, disqualified), scope of approval by commodity and process, risk class, certification and expiry, re-evaluation intervals by risk, conditions with end dates, single-source contingency, approver and customer-directed sources. Audits the list for expired or expiring certificates, overdue re-evaluations, conditional or probation status past its decision date, high-risk suppliers without the required certification, single-source suppliers without backup and missing approvers, and checks purchase orders for suppliers that are off-list, disqualified or pending, or buying outside the approved scope. Covers ERP blocks, PO requirements, off-list and emergency purchases.

apqp-phase-planner

Plan and track Advanced Product Quality Planning (AIAG APQP 3rd edition, IATF 16949) for a new or changed automotive part: back-schedule the five phases (plan and define, product design, process design, product and process validation, launch and feedback) from the start-of-production date by program complexity, with overlap, PPAP lead and safe-launch period; list the deliverables and gate for each phase (DFMEA, DVP&R, feasibility, process flow, PFMEA, control plans, MSA, Ppk, run at rate, PPAP, safe launch, lessons learned); adjust for build-to-print suppliers; flag compressed timelines and late or untracked deliverables against a status list. Covers gate reviews, red/yellow/green status reporting, run at rate and safe-launch exit criteria.

as9100-gap-analyzer

Run an AS9100D / EN 9100:2018 gap analysis for aviation, space and defence suppliers on the requirements added to ISO 9001: on-time delivery and conformity focus, management representative, ethics and human-factors awareness, operational planning and operational risk management, configuration management, product safety, counterfeit-part prevention, special requirements, critical items and key characteristics, external provider register and flow-down, FOD prevention, tooling and NC program control, special process validation, first article inspection (AS9102), traceability, in-service data and nonconforming product control. Generates and scores a worksheet, grades missing core controls as major, and checks invalid n/a claims. Covers AS9101/AS9104, OASIS, AS9102 FAI forms, counterfeit standards (AS5553, AS6174, AS6081), NADCAP and the planned IA9100 transition.

audit-report-writer

Write internal, supplier and pre-certification audit reports with the content ISO 19011:2018 6.5 expects: audit objectives, scope, criteria with revisions, dates, team and auditees, method and sampling statement, specific strengths, findings table and three-part finding details (requirement, evidence, statement), conclusion on the degree of fulfilment of criteria, diverging opinions, follow-up deadlines and distribution. Builds a Markdown report from a JSON audit record, generates the conclusion from the findings (major / minor / none) and flags reports missing required content or findings without clause or evidence. Covers conclusion wording, closing meetings, response expectations and verifying corrective actions.