pronunciation-mapper 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ from .mapper import PronunciationMapper
2
+ from .v2 import AgenticPronunciationMapper, RewriteResult
3
+
4
+ __version__ = '2.0.0'
5
+
6
+ __all__ = ["PronunciationMapper", "AgenticPronunciationMapper", "RewriteResult"]
@@ -0,0 +1,7 @@
1
+ """
2
+ python -m pronunciation_mapper 명령으로 실행할 때 진입점
3
+ """
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
@@ -0,0 +1,139 @@
1
+ """
2
+ 발음 매퍼 명령행 인터페이스
3
+ """
4
+ import argparse
5
+ import sys
6
+ import json
7
+ from .mapper import PronunciationMapper
8
+ from .utils import load_mappings_from_file, save_mappings_to_file, get_cache_path
9
+ from .v2 import AgenticPronunciationMapper
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(description='발음 유사도 기반 매핑 도구')
13
+
14
+ # 서브커맨드 설정
15
+ subparsers = parser.add_subparsers(dest='command', help='실행할 명령')
16
+
17
+ # 단어 매핑 명령
18
+ map_word_parser = subparsers.add_parser('map-word', help='단일 단어 매핑')
19
+ map_word_parser.add_argument('word', help='매핑할 단어')
20
+ map_word_parser.add_argument('--db-terms', '-d', help='DB 용어 파일(.json)')
21
+ map_word_parser.add_argument('--threshold', '-t', type=float, help='유사도 임계값')
22
+
23
+ # 문장 매핑 명령
24
+ map_sentence_parser = subparsers.add_parser('map-sentence', help='문장 내 단어 매핑')
25
+ map_sentence_parser.add_argument('sentence', help='매핑할 문장')
26
+ map_sentence_parser.add_argument('--db-terms', '-d', help='DB 용어 파일(.json)')
27
+ map_sentence_parser.add_argument('--threshold', '-t', type=float, help='유사도 임계값')
28
+
29
+ # V2 agentic rewrite 명령
30
+ rewrite_parser = subparsers.add_parser('rewrite', aliases=['rewrite-v2'], help='V2 agentic Query Rewriting')
31
+ rewrite_parser.add_argument('sentence', help='매핑할 문장')
32
+ rewrite_parser.add_argument('--db-terms', '-d', help='DB 용어 파일(.json)')
33
+ rewrite_parser.add_argument('--threshold', '-t', type=float, help='fallback 유사도 임계값')
34
+ rewrite_parser.add_argument('--provider', choices=['azure', 'ollama'], default='azure', help='AI provider (기본: azure)')
35
+ rewrite_parser.add_argument('--model', help='Foundry deployment 또는 Ollama model 이름')
36
+ rewrite_parser.add_argument('--endpoint', help='Foundry project endpoint 또는 Ollama host')
37
+ rewrite_parser.add_argument(
38
+ '--fallback', choices=['heuristic', 'original', 'raise'], default='heuristic',
39
+ help='provider 실패 정책 (기본: heuristic)',
40
+ )
41
+ rewrite_parser.add_argument('--min-confidence', type=float, default=0.55, help='교체를 적용할 최소 모델 confidence')
42
+ rewrite_parser.add_argument('--json', action='store_true', help='상세 결과를 JSON으로 출력')
43
+
44
+ # 매핑 추가 명령
45
+ add_mapping_parser = subparsers.add_parser('add-mapping', help='사용자 정의 매핑 추가')
46
+ add_mapping_parser.add_argument('source', help='원본 단어')
47
+ add_mapping_parser.add_argument('target', help='대상 단어')
48
+ add_mapping_parser.add_argument('--save', '-s', action='store_true', help='매핑을 캐시에 저장')
49
+
50
+ args = parser.parse_args()
51
+
52
+ # 명령어가 지정되지 않은 경우 도움말 출력
53
+ if not args.command:
54
+ parser.print_help()
55
+ return 1
56
+
57
+ # DB 용어 로드
58
+ db_terms = []
59
+ if hasattr(args, 'db_terms') and args.db_terms:
60
+ try:
61
+ with open(args.db_terms, 'r', encoding='utf-8') as f:
62
+ db_config = json.load(f)
63
+ if isinstance(db_config, list):
64
+ db_terms = db_config
65
+ elif isinstance(db_config, dict) and 'terms' in db_config:
66
+ db_terms = db_config['terms']
67
+ except Exception as e:
68
+ print(f"DB 용어 파일 로드 오류: {str(e)}")
69
+ return 1
70
+ else:
71
+ # 기본 DB 용어
72
+ db_terms = [
73
+ "customer", "product", "transaction",
74
+ "payment", "shipping", "invoice",
75
+ "ground", "cloud", "server",
76
+ "데이터베이스", "테이블", "필드",
77
+ "인덱스", "쿼리", "트랜잭션"
78
+ ]
79
+
80
+ # 사용자 매핑 로드
81
+ cache_path = get_cache_path()
82
+ custom_mappings = load_mappings_from_file(cache_path)
83
+
84
+ # 매퍼 초기화
85
+ threshold = args.threshold if hasattr(args, 'threshold') and args.threshold is not None else None
86
+ mapper = PronunciationMapper(db_terms, threshold=threshold, custom_mappings=custom_mappings)
87
+
88
+ # 명령 실행
89
+ if args.command == 'map-word':
90
+ result, score = mapper.find_closest_term(args.word)
91
+ print(f"{args.word} → {result} (유사도: {1-score:.2f})")
92
+
93
+ elif args.command == 'map-sentence':
94
+ result = mapper.map_sentence(args.sentence)
95
+ print(f"원문: {args.sentence}")
96
+ print(f"매핑: {result}")
97
+
98
+ elif args.command in {'rewrite', 'rewrite-v2'}:
99
+ provider_options = {}
100
+ if args.model:
101
+ provider_options['model'] = args.model
102
+ if args.endpoint:
103
+ provider_options['endpoint' if args.provider == 'azure' else 'host'] = args.endpoint
104
+ v2_mapper = AgenticPronunciationMapper(
105
+ db_terms,
106
+ custom_mappings=custom_mappings,
107
+ provider=args.provider,
108
+ provider_options=provider_options,
109
+ threshold=threshold,
110
+ minimum_confidence=args.min_confidence,
111
+ fallback_strategy=args.fallback,
112
+ )
113
+ try:
114
+ result = v2_mapper.rewrite_sync(args.sentence)
115
+ except Exception as error:
116
+ print(f"V2 rewrite 오류: {error}", file=sys.stderr)
117
+ return 1
118
+ finally:
119
+ v2_mapper.close()
120
+ if args.json:
121
+ print(json.dumps(result.to_dict(), ensure_ascii=False, indent=2))
122
+ else:
123
+ print(f"원문: {result.original_text}")
124
+ print(f"매핑: {result.rewritten_text}")
125
+ print(f"provider: {result.provider} (fallback={result.fallback_used})")
126
+
127
+ elif args.command == 'add-mapping':
128
+ mapper.add_custom_mapping(args.source, args.target)
129
+ print(f"매핑 추가: {args.source} → {args.target}")
130
+
131
+ if args.save:
132
+ custom_mappings[args.source] = args.target
133
+ save_mappings_to_file(custom_mappings, cache_path)
134
+ print(f"매핑이 저장됨: {cache_path}")
135
+
136
+ return 0
137
+
138
+ if __name__ == "__main__":
139
+ sys.exit(main())
@@ -0,0 +1,65 @@
1
+ """
2
+ 발음 매퍼 설정 파일
3
+ """
4
+
5
+ # 기본 임계값 설정
6
+ DEFAULT_THRESHOLD = 0.5
7
+
8
+ # 언어별 발음 매핑 규칙
9
+ PRONUNCIATION_RULES = {
10
+ 'korean': [
11
+ # 종성 규칙 (받침)
12
+ (r'([ㄱㄲㅋ])(?=[ㄴㄹㅁㅇ])', 'ㅇ'), # 'ㄱ,ㄲ,ㅋ' + 'ㄴ,ㄹ,ㅁ,ㅇ' -> 'ㅇ'
13
+ (r'ㄹ(?=ㄴ)', 'ㄴ'), # 'ㄹ' + 'ㄴ' -> 'ㄴ'
14
+ # 추가 규칙은 여기에
15
+ ]
16
+ }
17
+
18
+ # 영어-한글 발음 매핑
19
+ ENG_TO_KOR_SOUNDS = {
20
+ 'a': 'ㅏ', 'b': 'ㅂ', 'c': 'ㅋ', 'd': 'ㄷ', 'e': 'ㅔ',
21
+ 'f': 'ㅍ', 'g': 'ㄱ', 'h': 'ㅎ', 'i': 'ㅣ', 'j': 'ㅈ',
22
+ 'k': 'ㅋ', 'l': 'ㄹ', 'm': 'ㅁ', 'n': 'ㄴ', 'o': 'ㅗ',
23
+ 'p': 'ㅍ', 'q': 'ㅋ', 'r': 'ㄹ', 's': 'ㅅ', 't': 'ㅌ',
24
+ 'u': 'ㅜ', 'v': 'ㅂ', 'w': 'ㅝ', 'x': 'ㅋㅅ', 'y': 'ㅣ',
25
+ 'z': 'ㅈ',
26
+ }
27
+
28
+ # 데이터베이스 용어 전사 매핑 (프로젝트에서 사용하는 DB 고유명사 중 특정 용어로 표현되는경우 직접 매핑)
29
+ # 1:N
30
+ # STT초기출력 :원하는 출력
31
+ DB_TERM_MAPPINGS = {
32
+ '커스터머': 'customer',
33
+ '커스타마': 'customer',
34
+ '프로덕트': 'product',
35
+ '트랜잭션': 'transaction',
36
+ '트랜젝션': 'transaction',
37
+ '페이먼트': 'payment',
38
+ '쉬핑': 'shipping',
39
+ '인보이스': 'invoice',
40
+ '그라운드': 'ground',
41
+ '클라우드': 'cloud',
42
+ '서버': 'server',
43
+ '데이타베이스': '데이터베이스',
44
+ '데이타배이스': '데이터베이스',
45
+ # ...프로젝트 고유 용어를 추가하세요.
46
+ }
47
+
48
+
49
+
50
+ #숫자관련 - STT의 숫자처리가 안될경우만 사용, 변화가 큰 부분임.
51
+ # 기존 설정에 추가 - 숫자는 변화가 크니 DB에서 사용하는 값 추출하고 사용하는것을 정제하세요.
52
+ NUMBER_MAPPINGS = {
53
+ # 한글 숫자 표현을 아라비아 숫자로 변환
54
+ '일': '1', '이': '2', '삼': '3', '사': '4', '오': '5',
55
+ '육': '6', '륙': '6', '칠': '7', '팔': '8', '구': '9', '공': '0',
56
+ '십': '10', '백': '100', '천': '1000',
57
+
58
+ # 특수 숫자 조합 (직접 매핑)
59
+ '육심육': '66', '육십육': '66', '륙십륙': '66',
60
+ '구구': '99', '백일': '101'
61
+ }
62
+
63
+ # ``convert_korean_numbers``의 이전 공개 API와의 호환용 직접 매핑입니다.
64
+ # 프로젝트별 숫자형 고유명사는 이 사전에 명시적으로 추가할 수 있습니다.
65
+ SPECIAL_NUMERIC_TERMS = {}
@@ -0,0 +1,380 @@
1
+ """결정적 발음 후보 생성기와 V1 호환 매퍼."""
2
+
3
+ import logging
4
+ import re
5
+ from collections.abc import Mapping
6
+
7
+ from jamo import h2j, j2hcj
8
+
9
+ from .config import DEFAULT_THRESHOLD, DB_TERM_MAPPINGS, ENG_TO_KOR_SOUNDS, PRONUNCIATION_RULES
10
+ from .utils import convert_korean_numbers_correctly
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ KOREAN_PARTICLES = (
16
+ "으로", "에서", "에게", "한테", "처럼", "같이", "보다",
17
+ "께", "이", "가", "을", "를", "의", "에", "로", "과", "와",
18
+ "은", "는", "도", "만",
19
+ )
20
+ LEXICAL_TOKEN_PATTERN = re.compile(r"[가-힣A-Za-z0-9_]+")
21
+
22
+
23
+ def split_korean_particle(word):
24
+ """단어 끝의 대표적인 한국어 조사를 ``(어간, 조사)``로 분리합니다."""
25
+ for particle in KOREAN_PARTICLES:
26
+ if word.endswith(particle) and len(word) > len(particle):
27
+ return word[:-len(particle)], particle
28
+ return word, ""
29
+
30
+
31
+ class PronunciationMapper:
32
+ """V1 공개 API를 유지하는 로컬 발음 기반 매퍼.
33
+
34
+ V2에서는 이 클래스가 네트워크 호출 전에 exact mapping과 top-k 후보를
35
+ 만드는 결정적 안전망으로 사용됩니다.
36
+ """
37
+
38
+ def __init__(self, db_terms, threshold=None, custom_mappings=None):
39
+ if isinstance(db_terms, (str, bytes)):
40
+ raise TypeError("db_terms must be an iterable of strings, not a string")
41
+ raw_terms = list(db_terms)
42
+ if any(not isinstance(term, str) or not term for term in raw_terms):
43
+ raise ValueError("db_terms must contain only non-empty strings")
44
+ if isinstance(threshold, bool) or not isinstance(
45
+ DEFAULT_THRESHOLD if threshold is None else threshold, (int, float)
46
+ ) or not 0.0 <= (DEFAULT_THRESHOLD if threshold is None else threshold) <= 1.0:
47
+ raise ValueError("threshold must be between 0 and 1")
48
+ if custom_mappings is not None:
49
+ if not isinstance(custom_mappings, Mapping):
50
+ raise TypeError("custom_mappings must be a mapping")
51
+ if any(
52
+ not isinstance(source, str)
53
+ or not source
54
+ or not isinstance(target, str)
55
+ or not target
56
+ for source, target in custom_mappings.items()
57
+ ):
58
+ raise ValueError("custom_mappings must contain non-empty string pairs")
59
+
60
+ self.db_terms = list(dict.fromkeys(raw_terms))
61
+ self.threshold = DEFAULT_THRESHOLD if threshold is None else threshold
62
+ self.eng_to_kor_sounds = ENG_TO_KOR_SOUNDS.copy()
63
+ self.term_mappings = DB_TERM_MAPPINGS.copy()
64
+ if custom_mappings:
65
+ self.term_mappings.update(custom_mappings)
66
+
67
+ self.pronunciation_rules = PRONUNCIATION_RULES["korean"]
68
+ self._build_bidirectional_mappings()
69
+ self._refresh_indexes()
70
+
71
+ def _build_bidirectional_mappings(self):
72
+ """발음 인덱스용 reverse alias를 direct rewrite 규칙과 분리합니다.
73
+
74
+ canonical target을 ``term_mappings``에 역방향으로 넣으면 두 표기가 모두
75
+ DB vocabulary일 때 이미 정규형인 target이 source로 되돌아갑니다.
76
+ """
77
+ self.reverse_aliases = {}
78
+ for source, target in self.term_mappings.items():
79
+ if target in self.db_terms and source != target:
80
+ self.reverse_aliases.setdefault(target, source)
81
+
82
+ def _refresh_indexes(self):
83
+ self.aliases_by_target = {term: [] for term in self.db_terms}
84
+ for source, target in self.term_mappings.items():
85
+ if target in self.aliases_by_target and source != target:
86
+ self.aliases_by_target[target].append(source)
87
+
88
+ for aliases in self.aliases_by_target.values():
89
+ aliases.sort(key=lambda value: (-len(value), value))
90
+
91
+ self._alias_pairs = sorted(
92
+ (
93
+ (source, target)
94
+ for source, target in self.term_mappings.items()
95
+ if source and source != target and target in self.aliases_by_target
96
+ ),
97
+ key=lambda item: (-len(item[0]), item[0], item[1]),
98
+ )
99
+ self._canonical_terms_by_length = sorted(
100
+ self.db_terms, key=lambda value: (-len(value), value)
101
+ )
102
+ self.db_term_pronunciations = {
103
+ term: self._get_normalized_pronunciation(term) for term in self.db_terms
104
+ }
105
+ # 하나의 canonical term에 여러 전사가 있을 수 있습니다. 첫 reverse
106
+ # alias 하나만 대표로 쓰면 사용자 alias의 작은 ASR 오차를 놓치므로,
107
+ # canonical 표기와 모든 alias 발음 중 최소 거리를 사용합니다.
108
+ self.pronunciations_by_target = {}
109
+ for term in self.db_terms:
110
+ pronunciations = [self._get_pronunciation(term)]
111
+ pronunciations.extend(
112
+ self._get_pronunciation(alias) for alias in self.aliases_by_target[term]
113
+ )
114
+ self.pronunciations_by_target[term] = tuple(dict.fromkeys(pronunciations))
115
+
116
+ def _get_normalized_pronunciation(self, word):
117
+ mapped = self.term_mappings.get(word)
118
+ if mapped is not None:
119
+ return self._get_pronunciation(mapped)
120
+ return self._get_pronunciation(word)
121
+
122
+ def _get_pronunciation(self, word):
123
+ if any("가" <= char <= "힣" for char in word):
124
+ return self._get_korean_pronunciation(word)
125
+ return self._convert_eng_to_kor_sound(word.lower())
126
+
127
+ def _get_korean_pronunciation(self, word):
128
+ try:
129
+ jamo_sequence = j2hcj(h2j(word))
130
+ for pattern, replacement in self.pronunciation_rules:
131
+ jamo_sequence = re.sub(pattern, replacement, jamo_sequence)
132
+ return jamo_sequence
133
+ except Exception:
134
+ logger.exception("한글 자모 분리에 실패했습니다: %r", word)
135
+ return word
136
+
137
+ def _convert_eng_to_kor_sound(self, word):
138
+ return "".join(self.eng_to_kor_sounds.get(char, char) for char in word)
139
+
140
+ def _calculate_levenshtein_distance(self, s1, s2):
141
+ if len(s1) < len(s2):
142
+ return self._calculate_levenshtein_distance(s2, s1)
143
+ if not s2:
144
+ return len(s1)
145
+
146
+ previous_row = list(range(len(s2) + 1))
147
+ for index, char1 in enumerate(s1):
148
+ current_row = [index + 1]
149
+ for column, char2 in enumerate(s2):
150
+ insertions = previous_row[column + 1] + 1
151
+ deletions = current_row[column] + 1
152
+ substitutions = previous_row[column] + (char1 != char2)
153
+ current_row.append(min(insertions, deletions, substitutions))
154
+ previous_row = current_row
155
+ return previous_row[-1]
156
+
157
+ def _normalized_distance(self, s1, s2):
158
+ max_len = max(len(s1), len(s2))
159
+ if max_len == 0:
160
+ return 0.0
161
+ return self._calculate_levenshtein_distance(s1, s2) / max_len
162
+
163
+ def _direct_target(self, source):
164
+ target = self.term_mappings.get(source)
165
+ return target if target in self.db_terms else None
166
+
167
+ def replace_known_aliases(self, text):
168
+ """명시적 alias만 부분 치환하고 나머지 문자는 그대로 보존합니다.
169
+
170
+ 연속된 두 alias는 검색어가 합쳐지지 않도록 공백으로 구분합니다.
171
+ 예: ``신규커스터머정보`` -> ``신규customer정보``,
172
+ ``클라우드서버`` -> ``cloud server``.
173
+
174
+ 반환값은 ``(치환 문자열 또는 None, canonical term tuple)``입니다.
175
+ """
176
+ if not isinstance(text, str):
177
+ raise TypeError("text must be a string")
178
+
179
+ parts = []
180
+ canonical_terms = []
181
+ position = 0
182
+ previous_was_known_term = False
183
+ changed = False
184
+
185
+ while position < len(text):
186
+ matched = next(
187
+ (
188
+ (alias, target)
189
+ for alias, target in self._alias_pairs
190
+ if text.startswith(alias, position)
191
+ ),
192
+ None,
193
+ )
194
+ if matched is None:
195
+ canonical = next(
196
+ (
197
+ term
198
+ for term in self._canonical_terms_by_length
199
+ if text.startswith(term, position)
200
+ ),
201
+ None,
202
+ )
203
+ if canonical is not None:
204
+ if previous_was_known_term:
205
+ parts.append(" ")
206
+ parts.append(canonical)
207
+ canonical_terms.append(canonical)
208
+ position += len(canonical)
209
+ previous_was_known_term = True
210
+ continue
211
+ parts.append(text[position])
212
+ position += 1
213
+ previous_was_known_term = False
214
+ continue
215
+
216
+ alias, target = matched
217
+ if previous_was_known_term:
218
+ parts.append(" ")
219
+ parts.append(target)
220
+ canonical_terms.append(target)
221
+ position += len(alias)
222
+ previous_was_known_term = True
223
+ changed = True
224
+
225
+ if not changed:
226
+ return None, ()
227
+ return "".join(parts), tuple(canonical_terms)
228
+
229
+ def canonical_ranges(self, text):
230
+ """이미 canonical인 DB term이 차지하는 비중첩 문자 범위를 반환합니다.
231
+
232
+ punctuation을 포함한 식별자(``customer-id``, ``schema.table``)가
233
+ lexical tokenizer에서 여러 조각으로 나뉘더라도 각 조각을 다시 fuzzy
234
+ 치환하지 않기 위한 보호 범위입니다.
235
+ """
236
+ ranges = []
237
+ for term in sorted(self.db_terms, key=lambda value: (-len(value), value)):
238
+ position = 0
239
+ while True:
240
+ start = text.find(term, position)
241
+ if start < 0:
242
+ break
243
+ end = start + len(term)
244
+ ranges.append((start, end))
245
+ position = end
246
+
247
+ merged = []
248
+ for start, end in sorted(ranges):
249
+ if merged and start < merged[-1][1]:
250
+ if end > merged[-1][1]:
251
+ merged[-1] = (merged[-1][0], end)
252
+ continue
253
+ merged.append((start, end))
254
+ return tuple(merged)
255
+
256
+ def rank_candidates(self, query_term, limit=5):
257
+ """DB vocabulary 안에서 발음상 가까운 후보를 거리 오름차순으로 반환합니다.
258
+
259
+ 반환값은 ``[(replacement, distance), ...]``이며 조사가 있으면 replacement에
260
+ 보존됩니다. ``distance``는 V1과 동일하게 0이 가장 가깝습니다.
261
+ """
262
+ if limit < 1:
263
+ return []
264
+
265
+ normalized = convert_korean_numbers_correctly(query_term)
266
+ scores = {}
267
+
268
+ direct = self._direct_target(normalized)
269
+ if direct:
270
+ scores[direct] = 0.0
271
+
272
+ if normalized in self.db_term_pronunciations:
273
+ scores[normalized] = 0.0
274
+
275
+ # identifier 또는 canonical term을 이미 포함한 토큰은 전체를 발음
276
+ # 후보로 덮어쓰지 않습니다. explicit alias 부분 치환은 별도 계층에서
277
+ # 처리하므로 account_id/XPN36prod 같은 suffix가 사라지지 않습니다.
278
+ contains_canonical_substring = any(
279
+ term != normalized and term in normalized for term in self.db_terms
280
+ )
281
+ is_ascii_alphanumeric_identifier = (
282
+ normalized.isascii()
283
+ and any(char.isalpha() for char in normalized)
284
+ and any(char.isdigit() for char in normalized)
285
+ )
286
+ if (
287
+ "_" in normalized
288
+ or contains_canonical_substring
289
+ or is_ascii_alphanumeric_identifier
290
+ ):
291
+ return sorted(scores.items(), key=lambda item: (item[1], item[0]))[:limit]
292
+
293
+ whole_pronunciation = self._get_normalized_pronunciation(normalized)
294
+ for term, pronunciations in self.pronunciations_by_target.items():
295
+ distance = min(
296
+ self._normalized_distance(whole_pronunciation, pronunciation)
297
+ for pronunciation in pronunciations
298
+ )
299
+ scores[term] = min(distance, scores.get(term, 1.0))
300
+
301
+ # 단어 끝이 조사처럼 보이더라도 전체 토큰 후보를 버리지 않습니다.
302
+ # 조사 분리 후보에는 작은 penalty를 주어 ``엠에쓰아이``가 ``MSI이``로
303
+ # 오염되는 것을 막고, 문맥 resolver에는 두 가능성을 모두 제공합니다.
304
+ base, particle = split_korean_particle(normalized)
305
+ if particle:
306
+ base_direct = self._direct_target(base)
307
+ if base_direct:
308
+ scores[base_direct + particle] = 0.0
309
+ if base in self.db_term_pronunciations:
310
+ scores[base + particle] = 0.0
311
+
312
+ base_pronunciation = self._get_normalized_pronunciation(base)
313
+ particle_penalty = 0.15
314
+ for term, pronunciations in self.pronunciations_by_target.items():
315
+ distance = min(
316
+ self._normalized_distance(base_pronunciation, pronunciation)
317
+ for pronunciation in pronunciations
318
+ )
319
+ replacement = term + particle
320
+ distance = min(1.0, distance + particle_penalty)
321
+ scores[replacement] = min(distance, scores.get(replacement, 1.0))
322
+
323
+ return sorted(scores.items(), key=lambda item: (item[1], item[0]))[:limit]
324
+
325
+ def find_closest_term(self, query_term, threshold=None):
326
+ """쿼리 용어와 가장 가까운 DB 용어를 ``(문자열, 거리)``로 반환합니다."""
327
+ threshold = self.threshold if threshold is None else threshold
328
+ normalized = convert_korean_numbers_correctly(query_term)
329
+
330
+ direct = self._direct_target(normalized)
331
+ if direct:
332
+ return direct, 0.0
333
+ if normalized in self.db_terms:
334
+ return normalized, 0.0
335
+
336
+ base, particle = split_korean_particle(normalized)
337
+ base_direct = self._direct_target(base)
338
+ if base_direct:
339
+ return base_direct + particle, 0.0
340
+ if base in self.db_terms:
341
+ return base + particle, 0.0
342
+
343
+ alias_replacement, _ = self.replace_known_aliases(normalized)
344
+ if alias_replacement is not None:
345
+ return alias_replacement, 0.1
346
+
347
+ ranked = self.rank_candidates(normalized, limit=1)
348
+ if ranked and ranked[0][1] <= threshold:
349
+ return ranked[0]
350
+ return normalized, 1.0
351
+
352
+ def map_sentence(self, sentence):
353
+ """공백과 구두점을 보존하며 문장 안의 lexical token을 매핑합니다."""
354
+ normalized = convert_korean_numbers_correctly(sentence)
355
+ canonical_ranges = self.canonical_ranges(normalized)
356
+
357
+ def replace(match):
358
+ overlaps_canonical = any(
359
+ match.start() < end and match.end() > start
360
+ for start, end in canonical_ranges
361
+ )
362
+ alias_replacement, _ = self.replace_known_aliases(match.group(0))
363
+ if overlaps_canonical and alias_replacement is None:
364
+ return match.group(0)
365
+ mapped, _ = self.find_closest_term(match.group(0))
366
+ return mapped
367
+
368
+ return LEXICAL_TOKEN_PATTERN.sub(replace, normalized)
369
+
370
+ def add_custom_mapping(self, source_term, target_term, add_to_db_terms=True):
371
+ """사용자 매핑을 추가하고 후보 인덱스를 즉시 갱신합니다."""
372
+ if not isinstance(source_term, str) or not source_term:
373
+ raise ValueError("source_term must be a non-empty string")
374
+ if not isinstance(target_term, str) or not target_term:
375
+ raise ValueError("target_term must be a non-empty string")
376
+ self.term_mappings[source_term] = target_term
377
+ if add_to_db_terms and target_term not in self.db_terms:
378
+ self.db_terms.append(target_term)
379
+ self._build_bidirectional_mappings()
380
+ self._refresh_indexes()