kcsc-mcp / src /standard_codes.py
nicefree19's picture
Upload 105 files
0ee3c92 verified
Raw
History Blame Contribute Delete
2.87 kB
"""Utilities for KCSC standard-code normalization and document typing."""
from __future__ import annotations
import re
from typing import Any, Iterable
STANDARD_CODE_PATTERN = re.compile(
r"(?<![A-Z0-9])([A-Z]{2,8})[\s_-]*(\d{2})[\s_-]*(\d{2})[\s_-]*(\d{2})(?=$|[^0-9])",
re.IGNORECASE,
)
KNOWN_DOC_TYPES = {
"KDS",
"KCS",
"EXCS",
"LHCS",
"SMCS",
"KRCCS",
"NHCS",
"KWCS",
"KRACS",
}
def normalize_standard_code(value: Any) -> str:
"""Return canonical ``KDS 14 20 10`` style code from loose KCSC text."""
match = STANDARD_CODE_PATTERN.search(str(value or ""))
if not match:
return ""
return f"{match.group(1).upper()} {match.group(2)} {match.group(3)} {match.group(4)}"
def code_prefix(value: Any) -> str:
code = normalize_standard_code(value) or str(value or "").strip()
first = code.split()[0].upper() if code else ""
return first if re.fullmatch(r"[A-Z]{2,8}", first) else ""
def canonical_doc_type(code: Any = "", fallback: Any = "") -> str:
"""Prefer the code prefix over legacy metadata doc_type values."""
prefix = code_prefix(code)
if prefix:
return prefix
fallback_text = str(fallback or "").strip().upper()
if fallback_text in KNOWN_DOC_TYPES:
return fallback_text
return fallback_text
def collection_for_doc_type(value: Any) -> str:
"""Map a canonical document type/code to the current Chroma collection name."""
doc_type = canonical_doc_type(value, value)
return "KDS" if doc_type == "KDS" else "KCS"
def collection_names_for_doc_types(doc_types: Iterable[str] | None) -> set[str]:
if not doc_types:
return {"KDS", "KCS"}
return {collection_for_doc_type(doc_type) for doc_type in doc_types}
def doc_type_matches(metadata: dict[str, Any], allowed_doc_types: set[str] | None) -> bool:
if not allowed_doc_types:
return True
code_type = canonical_doc_type(metadata.get("code", ""), metadata.get("doc_type", ""))
legacy_type = str(metadata.get("doc_type", "") or "").upper()
collection_type = str(metadata.get("collection_type", "") or "").upper()
allowed = {doc_type.upper() for doc_type in allowed_doc_types}
return code_type in allowed or legacy_type in allowed or collection_type in allowed
def standard_family_name(doc_type: str) -> str:
doc_type = canonical_doc_type(doc_type, doc_type)
if doc_type == "KDS":
return "\uad6d\uac00\uac74\uc124\uae30\uc900 \uc124\uacc4\uae30\uc900 KDS"
if doc_type == "KCS":
return "\uad6d\uac00\uac74\uc124\uae30\uc900 \ud45c\uc900\uc2dc\ubc29\uc11c KCS"
if doc_type == "EXCS":
return "\uace0\uc18d\ub3c4\ub85c\uacf5\uc0ac \uc804\ubb38\uc2dc\ubc29\uc11c EXCS"
if doc_type:
return f"{doc_type} \uc804\ubb38/\uae30\uad00 \uc2dc\ubc29\uc11c"
return "\uac74\uc124\uae30\uc900"