File size: 10,062 Bytes
c699103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e28145
 
 
 
c699103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e28145
 
 
 
 
 
 
 
 
 
c699103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75896b
c699103
 
 
 
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
"""Check a document's applicability independently of its retrieval score."""
from __future__ import annotations

import re
from datetime import date
from urllib.parse import urlparse

from . import department_focus as departments
from .query_plan import AUDIENCES, PROGRAM_CONTEXTS, SCHOOL_ALIASES, SearchTask, department_catalog


def source_department(row: dict) -> str | None:
    m = row.get("metadata") or {}
    identity = m.get("department_id")
    if identity:
        return str(identity)
    dataset = m.get("source_dataset") or m.get("ingestion_dataset")
    catalog = department_catalog()
    if any(e.get("dataset") == dataset for e in catalog):
        return str(dataset)
    url = row.get("url") or row.get("uri") or m.get("doc_url") or ""
    parsed = urlparse(str(url))
    for entry in catalog:
        host = urlparse(entry.get("base_url") or "").hostname
        prefix = entry.get("site_prefix")
        if (host and host not in {"www.pknu.ac.kr", "pknu.ac.kr", "icms.pknu.ac.kr"} and parsed.hostname == host) or (prefix and parsed.hostname == "icms.pknu.ac.kr" and parsed.path.startswith(f"/{prefix}/")):
            return entry.get("dataset")
    return None


def scope_reason(row: dict, task: SearchTask) -> str | None:
    """None means compatible, not proof that every statement is supported."""
    m = row.get("metadata") or {}
    title = str(m.get("doc_title") or row.get("title") or "")
    content = str(row.get("content") or "")
    target = task.target
    table = m.get("structured_table") or {}
    table_rows = table.get("rows") or []
    fields = table_rows[0].get("fields", {}) if table.get("kind") == "spreadsheet" and len(table_rows) == 1 else {}
    staff = str(fields.get("staff_name") or m.get("staff_name") or "")
    spreadsheet = table.get("kind") == "spreadsheet" or str(m.get("source_ext") or "").lower() in {".xlsx", ".xls"}
    if target.instructor and spreadsheet and re.search(r"κ°•μ˜|μˆ˜μ—…|κ³Όλͺ©|κ°•μ’Œ", task.text) and not fields.get("staff_name"):
        return "unverified_spreadsheet_instructor"
    if target.instructor and ((staff and staff != target.instructor) or (task.conditions.kind == "courses" and staff != target.instructor)):
        return "different_instructor"
    if target.level and (fields.get("level") or m.get("level")):
        level = str(fields.get("level") or m["level"])
        if not (level.endswith("λŒ€ν•™μ›") if target.level == "λŒ€ν•™μ›" else level == target.level):
            return "different_course_level"
    if fields:
        for key, expected in (("year", task.conditions.year), ("term", task.conditions.term)):
            if expected is not None and fields.get(key) and str(fields[key]) != str(expected):
                return "different_course_term"
    amendment = re.search(r"(?:κ°œμ •|μ‹œν–‰)\s*\(?\s*(20\d{2})\s*[.-]\s*(\d{1,2})\s*[.-]\s*(\d{1,2})", title)
    if amendment and task.conditions.kind == "search":
        try:
            if date(*(int(x) for x in amendment.groups())) > task.conditions.as_of.date():
                return "future_amendment"
        except ValueError:
            pass
    if task.conditions.kind == "search":
        for context, pattern in PROGRAM_CONTEXTS.items():
            if context not in target.contexts and re.search(pattern, title):
                return "different_program_context"
        syllabus = row.get("_syllabus") or m.get("source_dataset") == "pknu_syllabus" or m.get("rpc_name") == "match_pknu_syllabus_documents"
        if (syllabus and not row.get("_syllabus")
                and re.search(r"전곡\s*(?:ν•„μˆ˜|곡톡)|κ΅μœ‘κ³Όμ •|ꡐ과과정|μ΄μˆ˜ν‘œ", task.text)
                and not re.search(r"κ°•μ˜κ³„νšμ„œ|λ‹΄λ‹Ή\s*ꡐ수|ν•™μˆ˜λ²ˆν˜Έ|λΆ„λ°˜|평가", task.text)):
            return "different_document_purpose"
        if syllabus and not row.get("_syllabus") and not re.search(r"κ°•μ˜|μˆ˜μ—…|κ³Όλͺ©|ꡐ수|ν•™μˆ˜λ²ˆν˜Έ|λΆ„λ°˜", task.text):
            return "different_document_purpose"
        infection_exception = re.search(r"λ°±μ‹ |감염\s*증상|μ½”λ‘œλ‚˜", content)
        common_absence_rules = re.search(r"경쑰사|병역|곡적인?\s*의무|직계|사망|λŒ€νšŒ", content)
        if infection_exception and not common_absence_rules and "감염병" not in target.contexts:
            if re.search(r"곡결|μΆœμ„μΈμ •", task.text):
                return "conditional_exception"
    school = str(m.get("applicable_school") or m.get("university") or m.get("school") or "")
    school = SCHOOL_ALIASES.get(school, school).removeprefix("ꡭ립")
    exchange = re.search(r"타\s*λŒ€ν•™\s*\(([^)]+)\)", title)
    if exchange:
        school = SCHOOL_ALIASES.get(exchange[1], exchange[1]).removeprefix("ꡭ립")
    if school and school != target.school:
        if not (exchange and re.search(r"ꡐλ₯˜|κ΅ν™˜|타\s*λŒ€ν•™", task.text)):
            return "different_school"
    # Publishing a document on pknu.ac.kr does not make another school's rules applicable.
    identity = source_department(row)
    if target.department_id and identity and identity != target.department_id:
        return "different_department"
    # Several majors share one dataset (e.g. ce). A dataset match alone must
    # not make a sibling major's explicit curriculum heading applicable.
    if target.department:
        wanted_major = departments.normalize(target.department)
        heading = departments.normalize(title + " " + str(m.get("subcategory") or ""))
        for entry in department_catalog():
            majors = [departments.normalize(name.strip()) for value in entry.get("majors") or []
                      for name in str(value).split(",") if name.strip()]
            if wanted_major in majors and any(name in heading for name in majors) and wanted_major not in heading:
                return "different_major"
    if task.conditions.kind == "latest" and target.department_id and identity != target.department_id:
        return "department_unverified"
    applicable = m.get("applicable_department")
    if applicable:
        variants = departments.focus_variants(target.department or "")
        if not variants or not departments.mentions(str(applicable), variants):
            return "different_department"
    # A latest-notice catalogue describes documents, not the user's eligibility.
    catalogue = task.conditions.kind == "latest"
    restricted = str(m.get("applicable_audience") or m.get("audience") or "")
    heading = f"{title} {m.get('subcategory') or ''} {restricted}"
    if "ν•™λΆ€" in target.audiences and "λŒ€ν•™μ›" in heading:
        return "different_level"
    if task.conditions.kind == "search" and re.search(r"(?:μˆ˜μ‹œ|μ •μ‹œ)μ „ν˜•\s*ν•©κ²©μž|νŽΈμž…μƒ\s*ν•©κ²©μž", content) and "μž¬ν•™μƒ" not in content:
        if not set(target.audiences) & {"μ‹ μž…μƒ", "νŽΈμž…μƒ"}:
            return "restricted_student_section"
    for audience in ("외ꡭ인", "λŒ€ν•™μ›", "μ‹ μž…μƒ", "νŽΈμž…μƒ"):
        if any(w in heading.lower() for w in AUDIENCES[audience]):
            if not catalogue and audience not in target.audiences:
                # 'μ‹ Β·νŽΈμž…μƒ' is one combined population; either explicit type suffices.
                if audience in {"μ‹ μž…μƒ", "νŽΈμž…μƒ"} and set(target.audiences) & {"μ‹ μž…μƒ", "νŽΈμž…μƒ"}:
                    continue
                return "restricted_audience"
    grades = m.get("applicable_grades")
    if target.grade and isinstance(grades, list) and str(target.grade) not in {str(g) for g in grades}:
        return "different_grade"
    cohorts = m.get("applicable_admission_years")
    if target.admission_year and isinstance(cohorts, list) and str(target.admission_year) not in {str(y) for y in cohorts}:
        return "different_admission_year"
    if task.purpose == "eligibility" and re.search(r"μ‹ μ²­|지원", task.text):
        if re.search(r"이수\s*쑰건", content) and not re.search(r"(?:μ‹ μ²­|지원)\s*(?:자격|λŒ€μƒ|κ°€λŠ₯)|μ‹ μ²­ν• \s*수", content):
            return "completion_not_application_eligibility"
    # Per-major selection rules must not become university-wide requirements.
    named = [name for name in departments.DEPARTMENT_NAMES if departments.normalize(name) in departments.normalize(content)]
    # Historical/renamed majors may no longer appear in today's registry.
    named += [name for name in re.findall(r"[κ°€-힣·]{3,}(?:ν•™κ³Ό|ν•™λΆ€|전곡)", content)
              if name not in {"λ³΅μˆ˜μ „κ³΅", "뢀전곡", "주전곡", "닀전곡", "ν•΄λ‹Ήν•™κ³Ό", "μ†Œμ†ν•™κ³Ό", "해당전곡"}]
    selection_table = bool(re.search(r"μ„ΈλΆ€\s*μ„ λ°œ|μ „μž…\s*μ„ λ°œ|μ „μΆœ\s*μ„ λ°œ|학과별\s*κΈ°μ€€", title + " " + content))
    if selection_table and named:
        variants = departments.focus_variants(target.department or "")
        if not variants:
            return "department_specific_rule"
        if not departments.mentions(content, variants):
            return "different_department"
    if re.search(r"감염병\s*ν™•μ‚°|μ½”λ‘œλ‚˜.{0,15}(?:ν™•μ‚°|μž…κ΅­)", content) and re.search(r"μž…κ΅­μ΄?\s*μ–΄λ €|μž…κ΅­.{0,10}λΆˆκ°€", content):
        if not re.search(r"감염병|μ½”λ‘œλ‚˜|μž…κ΅­", task.text):
            return "conditional_exception"
    return None


def checked_rows(rows: list[dict], task: SearchTask) -> list[dict]:
    kept = []
    for row in rows:
        if scope_reason(row, task):
            continue
        m = dict(row.get("metadata") or {})
        m["validated_target"] = task.target.model_dump()
        m["query_conditions"] = task.conditions.model_dump(mode="json")
        m["request_purpose"] = task.purpose
        m["request_query"] = task.text
        # This label travels with the evidence into generation; URL alone is not scope.
        m["applicability_note"] = "곡톡 κ·œμ •κ³Ό νŠΉμ • λŒ€μƒμ˜ μ˜ˆμ™Έλ₯Ό κ΅¬λΆ„ν•˜κ³ , μ‹ μ²­μžκ²©μ„ 이수쑰건으둜 λŒ€μ²΄ν•˜μ§€ λ§ˆμ„Έμš”. ν•™λ²ˆΒ·ν•™λ…„Β·κ°œμΈ μžκ²©μ„ ν™•μΈν•˜μ§€ λͺ»ν–ˆμœΌλ©΄ ν•΄λ‹Ή ν•™μƒμ—κ²Œ μ μš©λœλ‹€κ³  ν™•μ •ν•˜μ§€ λ§ˆμ„Έμš”."
        kept.append({**row, "metadata": m})
    return kept