pronunciation-mapper 2.0.0__tar.gz

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.
Files changed (37) hide show
  1. pronunciation_mapper-2.0.0/LICENSE +21 -0
  2. pronunciation_mapper-2.0.0/PKG-INFO +304 -0
  3. pronunciation_mapper-2.0.0/README.md +269 -0
  4. pronunciation_mapper-2.0.0/pronunciation_mapper/__init__.py +6 -0
  5. pronunciation_mapper-2.0.0/pronunciation_mapper/__main__.py +7 -0
  6. pronunciation_mapper-2.0.0/pronunciation_mapper/cli.py +139 -0
  7. pronunciation_mapper-2.0.0/pronunciation_mapper/config.py +65 -0
  8. pronunciation_mapper-2.0.0/pronunciation_mapper/mapper.py +380 -0
  9. pronunciation_mapper-2.0.0/pronunciation_mapper/utils.py +276 -0
  10. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/__init__.py +42 -0
  11. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/candidates.py +180 -0
  12. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/engine.py +417 -0
  13. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/errors.py +25 -0
  14. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/models.py +226 -0
  15. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/prompts.py +18 -0
  16. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/providers/__init__.py +11 -0
  17. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/providers/azure_foundry.py +244 -0
  18. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/providers/base.py +89 -0
  19. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/providers/factory.py +22 -0
  20. pronunciation_mapper-2.0.0/pronunciation_mapper/v2/providers/ollama.py +165 -0
  21. pronunciation_mapper-2.0.0/pronunciation_mapper.egg-info/PKG-INFO +304 -0
  22. pronunciation_mapper-2.0.0/pronunciation_mapper.egg-info/SOURCES.txt +35 -0
  23. pronunciation_mapper-2.0.0/pronunciation_mapper.egg-info/dependency_links.txt +1 -0
  24. pronunciation_mapper-2.0.0/pronunciation_mapper.egg-info/entry_points.txt +2 -0
  25. pronunciation_mapper-2.0.0/pronunciation_mapper.egg-info/requires.txt +14 -0
  26. pronunciation_mapper-2.0.0/pronunciation_mapper.egg-info/top_level.txt +1 -0
  27. pronunciation_mapper-2.0.0/pyproject.toml +61 -0
  28. pronunciation_mapper-2.0.0/setup.cfg +4 -0
  29. pronunciation_mapper-2.0.0/setup.py +6 -0
  30. pronunciation_mapper-2.0.0/tests/test_advanced.py +126 -0
  31. pronunciation_mapper-2.0.0/tests/test_eval_runner.py +100 -0
  32. pronunciation_mapper-2.0.0/tests/test_foundry_live.py +59 -0
  33. pronunciation_mapper-2.0.0/tests/test_mapper.py +58 -0
  34. pronunciation_mapper-2.0.0/tests/test_numbers.py +71 -0
  35. pronunciation_mapper-2.0.0/tests/test_using_as_lib.py +27 -0
  36. pronunciation_mapper-2.0.0/tests/test_v2.py +289 -0
  37. pronunciation_mapper-2.0.0/tests/test_v2_providers.py +412 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Hyeon Sang Jeon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,304 @@
1
+ Metadata-Version: 2.4
2
+ Name: pronunciation-mapper
3
+ Version: 2.0.0
4
+ Summary: Bounded agentic Korean ASR query rewriting with Microsoft Foundry and Ollama
5
+ Author: Hyeonsang Jeon
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://hyeonsangjeon.github.io/pronunciation-mapper/
8
+ Project-URL: Repository, https://github.com/hyeonsangjeon/pronunciation-mapper
9
+ Project-URL: Documentation, https://hyeonsangjeon.github.io/pronunciation-mapper/
10
+ Project-URL: Changelog, https://github.com/hyeonsangjeon/pronunciation-mapper/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/hyeonsangjeon/pronunciation-mapper/issues
12
+ Keywords: ASR,query-rewriting,Korean,Microsoft-Foundry,Ollama
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: jamo<0.5,>=0.4.1
24
+ Provides-Extra: foundry
25
+ Requires-Dist: azure-ai-projects<3,>=2.3; extra == "foundry"
26
+ Requires-Dist: azure-identity<2,>=1.25; extra == "foundry"
27
+ Requires-Dist: openai<3,>=2.8; extra == "foundry"
28
+ Provides-Extra: ollama
29
+ Requires-Dist: ollama<1,>=0.5.3; extra == "ollama"
30
+ Provides-Extra: dev
31
+ Requires-Dist: build<2,>=1.2; extra == "dev"
32
+ Requires-Dist: pytest<10,>=8; extra == "dev"
33
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # Pronunciation Mapper V2
37
+
38
+ 한국어 ASR 결과를 DB의 고유명사·기술 용어로 안전하게 정규화하는 Query Rewriting 라이브러리입니다.
39
+
40
+ V2는 기존 자모/편집거리 휴리스틱을 버리지 않습니다. 로컬에서 exact mapping과 발음 top‑K 후보를 만든 뒤, **Microsoft Foundry를 기본 decision agent**로 사용해 문맥상 올바른 후보 ID만 선택합니다. Ollama는 로컬 옵션이며 OpenAI·Claude provider는 reference-only입니다.
41
+
42
+ - Python 3.10+
43
+ - 기본 provider: Microsoft Foundry Project Responses API + Microsoft Entra ID
44
+ - 선택 provider: Ollama native API
45
+ - OpenAI / Claude: 확장 계약 참고용이며 V2 adapter 없음
46
+ - 기존 `PronunciationMapper` API와 CLI 유지
47
+
48
+ ## 왜 하이브리드인가
49
+
50
+ LLM에게 문장 전체를 자유롭게 다시 쓰게 하면 DB vocabulary 밖의 단어 생성, 대소문자·ID 훼손, 비용 증가, 재현성 저하가 생깁니다. V2는 모델의 권한을 의도적으로 줄입니다.
51
+
52
+ ```mermaid
53
+ flowchart LR
54
+ A["ASR text"] --> B["Local number and alias normalization"]
55
+ B --> C["Jamo / edit-distance top-K retrieval"]
56
+ C --> D{"Exact decision?"}
57
+ D -->|Yes| E["Apply locally"]
58
+ D -->|No| F["Foundry or Ollama decision agent"]
59
+ F --> G["Validate schema, span, candidate ID, DB vocabulary"]
60
+ G -->|Valid and confident| H["Apply selected candidate"]
61
+ G -->|Abstain / low confidence| I["Keep source"]
62
+ F -->|Unavailable / invalid| J["Deterministic fallback policy"]
63
+ E --> K["RewriteResult with trace metadata"]
64
+ H --> K
65
+ I --> K
66
+ J --> K
67
+ ```
68
+
69
+ 핵심 불변식은 다음과 같습니다.
70
+
71
+ - 모델은 로컬에서 생성된 candidate ID만 선택할 수 있습니다.
72
+ - 최종 canonical term은 항상 `db_terms` 안에 있어야 합니다.
73
+ - 허용된 span 밖의 공백·구두점·텍스트는 보존합니다.
74
+ - `keep`과 `abstain`을 정상 결과로 취급합니다.
75
+ - provider 장애나 잘못된 JSON은 설정된 fallback으로 처리합니다.
76
+ - provider 간 자동 전환은 하지 않습니다. Azure에서 Ollama로 데이터를 보내는 정책은 사용자가 명시해야 합니다.
77
+
78
+ ## 설치
79
+
80
+ 기존 로컬 매퍼만 사용할 때:
81
+
82
+ ```bash
83
+ pip install -e .
84
+ ```
85
+
86
+ Microsoft Foundry 기본 구성:
87
+
88
+ ```bash
89
+ pip install -e '.[foundry]'
90
+ az login
91
+
92
+ export FOUNDRY_PROJECT_ENDPOINT='https://<account>.services.ai.azure.com/api/projects/<project>'
93
+ export FOUNDRY_MODEL='<deployment-name>'
94
+ ```
95
+
96
+ `FOUNDRY_MODEL`은 catalog model ID가 아니라 Foundry의 **배포 이름**이며 Responses API structured output을 지원하는 배포여야 합니다. 로컬에서는 `DefaultAzureCredential`이 `az login` 세션을 사용하고, Azure 운영 환경에서는 Managed Identity credential 주입을 권장합니다.
97
+
98
+ `foundry` extra에 `openai` 패키지가 포함되지만 이는 `AIProjectClient.get_openai_client()`가 사용하는 Azure Responses 전송 클라이언트입니다. `OPENAI_API_KEY`나 OpenAI 계정은 필요하지 않습니다.
99
+
100
+ Ollama 옵션:
101
+
102
+ ```bash
103
+ pip install -e '.[ollama]'
104
+ ollama pull qwen3.5:4b
105
+
106
+ export OLLAMA_HOST='http://localhost:11434'
107
+ export OLLAMA_MODEL='qwen3.5:4b'
108
+ ```
109
+
110
+ Ollama 모델은 자동으로 pull하지 않습니다. structured output 품질과 한국어 고유명사 정확도는 모델마다 다르므로 이 저장소의 eval set으로 확인해야 합니다.
111
+
112
+ ## 빠른 시작
113
+
114
+ ### Microsoft Foundry — 기본
115
+
116
+ ```python
117
+ import asyncio
118
+
119
+ from pronunciation_mapper import AgenticPronunciationMapper
120
+
121
+
122
+ async def main():
123
+ async with AgenticPronunciationMapper(
124
+ db_terms=["XPN36", "account_no", "transaction", "server", "log"],
125
+ custom_mappings={
126
+ "엑스피엔36": "XPN36",
127
+ "어카운트넘버": "account_no",
128
+ "서버": "server",
129
+ "로그": "log",
130
+ },
131
+ # provider를 생략하면 azure가 기본입니다.
132
+ ) as mapper:
133
+ query = "엑스피엔36 서버에서 어카운트넘버 사삼삼오삼칠의 트랜잭숑 로그"
134
+ result = await mapper.rewrite(query)
135
+
136
+ print(f"입력: {query}")
137
+ print(f"출력: {result.rewritten_text}")
138
+ print(f"provider: {result.provider}")
139
+ print(f"fallback: {result.fallback_used}")
140
+
141
+
142
+ asyncio.run(main())
143
+ ```
144
+
145
+ 실행 결과:
146
+
147
+ ```text
148
+ 입력: 엑스피엔36 서버에서 어카운트넘버 사삼삼오삼칠의 트랜잭숑 로그
149
+ 출력: XPN36 server에서 account_no 433537의 transaction log
150
+ provider: azure-foundry
151
+ fallback: False
152
+ ```
153
+
154
+ 이 예제에서 exact mapping과 숫자 변환은 로컬에서 처리되고, 발음 후보인 `트랜잭숑 → transaction`은 Foundry가 후보 ID를 선택합니다. 모델이 `keep` 또는 `abstain`을 선택하면 해당 입력은 그대로 보존될 수 있습니다.
155
+
156
+ ### Ollama — 명시적 선택
157
+
158
+ ```python
159
+ with AgenticPronunciationMapper(
160
+ db_terms=["customer", "transaction", "server", "log"],
161
+ custom_mappings={
162
+ "서버": "server",
163
+ "로그": "log",
164
+ },
165
+ provider="ollama",
166
+ provider_options={"model": "qwen3.5:4b"},
167
+ ) as mapper:
168
+ query = "트랜잭숑 서버 로그"
169
+ result = mapper.rewrite_sync(query)
170
+
171
+ print(f"입력: {query}")
172
+ print(f"출력: {result.rewritten_text}")
173
+ print(f"provider: {result.provider}")
174
+ ```
175
+
176
+ 실행 결과 예시:
177
+
178
+ ```text
179
+ 입력: 트랜잭숑 서버 로그
180
+ 출력: transaction server log
181
+ provider: ollama
182
+ ```
183
+
184
+ 모델의 `confidence`, 판단 근거, latency와 token usage는 실행마다 달라질 수 있습니다. 상세 정보가 필요하면 `result.to_dict()`를 출력하세요.
185
+
186
+ 이미 event loop가 실행 중이면 `rewrite_sync()` 대신 `await rewrite()`를 사용해야 합니다.
187
+ factory가 만든 provider는 mapper context manager가 종료합니다. 직접 주입한 custom provider/client의 수명은 호출자가 관리합니다.
188
+
189
+ ## 결과 계약
190
+
191
+ `rewrite()`는 문자열뿐 아니라 판단 근거와 운영 metadata를 포함한 `RewriteResult`를 반환합니다.
192
+
193
+ ```python
194
+ result.rewritten_text # 최종 검색 질의
195
+ result.provider # local-deterministic / azure-foundry / ollama
196
+ result.model # 실제 deployment/model 이름
197
+ result.fallback_used # provider 실패 fallback 여부
198
+ result.decisions # span별 candidate, action, confidence, reason, distance
199
+ result.latency_ms
200
+ result.usage # provider가 제공한 token/시간 정보
201
+ result.diagnostics
202
+ ```
203
+
204
+ `confidence`는 모델의 bounded decision confidence입니다. V1 tuple의 두 번째 값은 반대로 **0이 가장 좋은 편집 거리**이므로 서로 같은 값으로 취급하면 안 됩니다.
205
+
206
+ ## 실패 정책
207
+
208
+ ```python
209
+ AgenticPronunciationMapper(..., fallback_strategy="heuristic") # 기본: V1 후보 적용
210
+ AgenticPronunciationMapper(..., fallback_strategy="original") # 원문/숫자 정규화만 유지
211
+ AgenticPronunciationMapper(..., fallback_strategy="raise") # provider 오류 전파
212
+ ```
213
+
214
+ 모델이 정상적으로 `keep` 또는 `abstain`을 선택한 경우는 provider 실패가 아니며 heuristic fallback을 적용하지 않습니다. confidence가 `minimum_confidence`보다 낮아도 원문을 보존합니다.
215
+ V2의 기본 heuristic fallback 거리는 `0.35`로 V1 기본값보다 보수적이며, `threshold=`를 명시하면 그 값을 사용합니다.
216
+
217
+ ## 안전 한계와 숫자 처리
218
+
219
+ 기본값은 입력 4,096자, lexical span 64개, token 256자까지입니다. `max_input_chars`, `max_spans`, `max_token_chars`로 조절할 수 있으며 초과 입력은 임의로 잘라 보내지 않고 거부합니다. Foundry transport도 기본 timeout 30초, retry 1회, output 2,048 token으로 제한합니다.
220
+
221
+ 한글 숫자는 명백한 단위·counter(`일억 원`, `321번`) 또는 긴 번호 문맥만 결정적으로 바꿉니다. `일일이`, `사이사이`, `천만 다행`처럼 숫자와 모양이 같은 일반어는 보존합니다. 프로젝트별 짧은 ID나 숫자형 고유명사는 golden set과 명시적 mapping으로 관리하는 것이 안전합니다.
222
+
223
+ ## CLI
224
+
225
+ V1 명령은 그대로 유지됩니다.
226
+
227
+ ```bash
228
+ pronunciation-mapper map-word 커스터머
229
+ pronunciation-mapper map-sentence '그라운드에 있는 데이타베이스 확인'
230
+ pronunciation-mapper add-mapping 고객 customer --save
231
+ ```
232
+
233
+ V2:
234
+
235
+ ```bash
236
+ pronunciation-mapper rewrite \
237
+ '엑스피엔36 서버에서 트랜잭숑 로그' \
238
+ --db-terms examples/db_terms.json \
239
+ --provider azure \
240
+ --json
241
+
242
+ pronunciation-mapper rewrite '트랜잭숑 로그' \
243
+ --provider ollama \
244
+ --model qwen3.5:4b
245
+ ```
246
+
247
+ DB 용어 파일은 문자열 배열 또는 `{"terms": [...]}` 형식을 지원합니다.
248
+
249
+ ## V1 호환 API
250
+
251
+ ```python
252
+ from pronunciation_mapper import PronunciationMapper
253
+
254
+ mapper = PronunciationMapper(
255
+ ["customer", "server", "데이터베이스"],
256
+ custom_mappings={"서버": "server"},
257
+ )
258
+
259
+ term, distance = mapper.find_closest_term("커스터머")
260
+ sentence = mapper.map_sentence("커스터머, 서버에서 조회")
261
+
262
+ print(f"단어: 커스터머 → {term} (distance={distance:.1f})")
263
+ print(f"문장: 커스터머, 서버에서 조회 → {sentence}")
264
+ ```
265
+
266
+ 실행 결과:
267
+
268
+ ```text
269
+ 단어: 커스터머 → customer (distance=0.0)
270
+ 문장: 커스터머, 서버에서 조회 → customer, server에서 조회
271
+ ```
272
+
273
+ V1 클래스는 네트워크나 Azure credential을 요구하지 않습니다. V2에서도 exact mapping, 발음 후보 생성, provider fallback의 로컬 계층으로 사용됩니다.
274
+
275
+ ## 테스트와 평가
276
+
277
+ ```bash
278
+ python -m unittest discover -v
279
+ python -m pytest -q
280
+
281
+ # 외부 provider 없이 deterministic fallback baseline
282
+ python evals/run_v2.py --provider offline
283
+
284
+ # 실제 환경에서 opt-in
285
+ python evals/run_v2.py --provider azure
286
+ python evals/run_v2.py --provider ollama
287
+ ```
288
+
289
+ 배포 전에는 최소한 exact accuracy, false rewrite rate, abstention 품질, latency, provider 실패율을 비교하세요. 자동 LLM judge보다 이 도메인의 golden mapping exact match를 1차 release gate로 두는 편이 적합합니다.
290
+
291
+ ## 문서
292
+
293
+ - [문서와 기록 안내](docs/README.md)
294
+ - [변경 기록](CHANGELOG.md)
295
+ - [V2.0.0 릴리스 기록](docs/releases/v2.0.0.md)
296
+ - [V2 아키텍처와 마이그레이션](docs/V2_ARCHITECTURE.md)
297
+ - [아키텍처 결정 기록](docs/decisions/README.md)
298
+ - [GitHub Actions와 외부 tenant Foundry OIDC 설정](docs/CI_SETUP.md)
299
+ - [V2 eval dataset](evals/cases.jsonl)
300
+ - [환경 변수 예시](.env.example)
301
+
302
+ ## 라이선스
303
+
304
+ MIT
@@ -0,0 +1,269 @@
1
+ # Pronunciation Mapper V2
2
+
3
+ 한국어 ASR 결과를 DB의 고유명사·기술 용어로 안전하게 정규화하는 Query Rewriting 라이브러리입니다.
4
+
5
+ V2는 기존 자모/편집거리 휴리스틱을 버리지 않습니다. 로컬에서 exact mapping과 발음 top‑K 후보를 만든 뒤, **Microsoft Foundry를 기본 decision agent**로 사용해 문맥상 올바른 후보 ID만 선택합니다. Ollama는 로컬 옵션이며 OpenAI·Claude provider는 reference-only입니다.
6
+
7
+ - Python 3.10+
8
+ - 기본 provider: Microsoft Foundry Project Responses API + Microsoft Entra ID
9
+ - 선택 provider: Ollama native API
10
+ - OpenAI / Claude: 확장 계약 참고용이며 V2 adapter 없음
11
+ - 기존 `PronunciationMapper` API와 CLI 유지
12
+
13
+ ## 왜 하이브리드인가
14
+
15
+ LLM에게 문장 전체를 자유롭게 다시 쓰게 하면 DB vocabulary 밖의 단어 생성, 대소문자·ID 훼손, 비용 증가, 재현성 저하가 생깁니다. V2는 모델의 권한을 의도적으로 줄입니다.
16
+
17
+ ```mermaid
18
+ flowchart LR
19
+ A["ASR text"] --> B["Local number and alias normalization"]
20
+ B --> C["Jamo / edit-distance top-K retrieval"]
21
+ C --> D{"Exact decision?"}
22
+ D -->|Yes| E["Apply locally"]
23
+ D -->|No| F["Foundry or Ollama decision agent"]
24
+ F --> G["Validate schema, span, candidate ID, DB vocabulary"]
25
+ G -->|Valid and confident| H["Apply selected candidate"]
26
+ G -->|Abstain / low confidence| I["Keep source"]
27
+ F -->|Unavailable / invalid| J["Deterministic fallback policy"]
28
+ E --> K["RewriteResult with trace metadata"]
29
+ H --> K
30
+ I --> K
31
+ J --> K
32
+ ```
33
+
34
+ 핵심 불변식은 다음과 같습니다.
35
+
36
+ - 모델은 로컬에서 생성된 candidate ID만 선택할 수 있습니다.
37
+ - 최종 canonical term은 항상 `db_terms` 안에 있어야 합니다.
38
+ - 허용된 span 밖의 공백·구두점·텍스트는 보존합니다.
39
+ - `keep`과 `abstain`을 정상 결과로 취급합니다.
40
+ - provider 장애나 잘못된 JSON은 설정된 fallback으로 처리합니다.
41
+ - provider 간 자동 전환은 하지 않습니다. Azure에서 Ollama로 데이터를 보내는 정책은 사용자가 명시해야 합니다.
42
+
43
+ ## 설치
44
+
45
+ 기존 로컬 매퍼만 사용할 때:
46
+
47
+ ```bash
48
+ pip install -e .
49
+ ```
50
+
51
+ Microsoft Foundry 기본 구성:
52
+
53
+ ```bash
54
+ pip install -e '.[foundry]'
55
+ az login
56
+
57
+ export FOUNDRY_PROJECT_ENDPOINT='https://<account>.services.ai.azure.com/api/projects/<project>'
58
+ export FOUNDRY_MODEL='<deployment-name>'
59
+ ```
60
+
61
+ `FOUNDRY_MODEL`은 catalog model ID가 아니라 Foundry의 **배포 이름**이며 Responses API structured output을 지원하는 배포여야 합니다. 로컬에서는 `DefaultAzureCredential`이 `az login` 세션을 사용하고, Azure 운영 환경에서는 Managed Identity credential 주입을 권장합니다.
62
+
63
+ `foundry` extra에 `openai` 패키지가 포함되지만 이는 `AIProjectClient.get_openai_client()`가 사용하는 Azure Responses 전송 클라이언트입니다. `OPENAI_API_KEY`나 OpenAI 계정은 필요하지 않습니다.
64
+
65
+ Ollama 옵션:
66
+
67
+ ```bash
68
+ pip install -e '.[ollama]'
69
+ ollama pull qwen3.5:4b
70
+
71
+ export OLLAMA_HOST='http://localhost:11434'
72
+ export OLLAMA_MODEL='qwen3.5:4b'
73
+ ```
74
+
75
+ Ollama 모델은 자동으로 pull하지 않습니다. structured output 품질과 한국어 고유명사 정확도는 모델마다 다르므로 이 저장소의 eval set으로 확인해야 합니다.
76
+
77
+ ## 빠른 시작
78
+
79
+ ### Microsoft Foundry — 기본
80
+
81
+ ```python
82
+ import asyncio
83
+
84
+ from pronunciation_mapper import AgenticPronunciationMapper
85
+
86
+
87
+ async def main():
88
+ async with AgenticPronunciationMapper(
89
+ db_terms=["XPN36", "account_no", "transaction", "server", "log"],
90
+ custom_mappings={
91
+ "엑스피엔36": "XPN36",
92
+ "어카운트넘버": "account_no",
93
+ "서버": "server",
94
+ "로그": "log",
95
+ },
96
+ # provider를 생략하면 azure가 기본입니다.
97
+ ) as mapper:
98
+ query = "엑스피엔36 서버에서 어카운트넘버 사삼삼오삼칠의 트랜잭숑 로그"
99
+ result = await mapper.rewrite(query)
100
+
101
+ print(f"입력: {query}")
102
+ print(f"출력: {result.rewritten_text}")
103
+ print(f"provider: {result.provider}")
104
+ print(f"fallback: {result.fallback_used}")
105
+
106
+
107
+ asyncio.run(main())
108
+ ```
109
+
110
+ 실행 결과:
111
+
112
+ ```text
113
+ 입력: 엑스피엔36 서버에서 어카운트넘버 사삼삼오삼칠의 트랜잭숑 로그
114
+ 출력: XPN36 server에서 account_no 433537의 transaction log
115
+ provider: azure-foundry
116
+ fallback: False
117
+ ```
118
+
119
+ 이 예제에서 exact mapping과 숫자 변환은 로컬에서 처리되고, 발음 후보인 `트랜잭숑 → transaction`은 Foundry가 후보 ID를 선택합니다. 모델이 `keep` 또는 `abstain`을 선택하면 해당 입력은 그대로 보존될 수 있습니다.
120
+
121
+ ### Ollama — 명시적 선택
122
+
123
+ ```python
124
+ with AgenticPronunciationMapper(
125
+ db_terms=["customer", "transaction", "server", "log"],
126
+ custom_mappings={
127
+ "서버": "server",
128
+ "로그": "log",
129
+ },
130
+ provider="ollama",
131
+ provider_options={"model": "qwen3.5:4b"},
132
+ ) as mapper:
133
+ query = "트랜잭숑 서버 로그"
134
+ result = mapper.rewrite_sync(query)
135
+
136
+ print(f"입력: {query}")
137
+ print(f"출력: {result.rewritten_text}")
138
+ print(f"provider: {result.provider}")
139
+ ```
140
+
141
+ 실행 결과 예시:
142
+
143
+ ```text
144
+ 입력: 트랜잭숑 서버 로그
145
+ 출력: transaction server log
146
+ provider: ollama
147
+ ```
148
+
149
+ 모델의 `confidence`, 판단 근거, latency와 token usage는 실행마다 달라질 수 있습니다. 상세 정보가 필요하면 `result.to_dict()`를 출력하세요.
150
+
151
+ 이미 event loop가 실행 중이면 `rewrite_sync()` 대신 `await rewrite()`를 사용해야 합니다.
152
+ factory가 만든 provider는 mapper context manager가 종료합니다. 직접 주입한 custom provider/client의 수명은 호출자가 관리합니다.
153
+
154
+ ## 결과 계약
155
+
156
+ `rewrite()`는 문자열뿐 아니라 판단 근거와 운영 metadata를 포함한 `RewriteResult`를 반환합니다.
157
+
158
+ ```python
159
+ result.rewritten_text # 최종 검색 질의
160
+ result.provider # local-deterministic / azure-foundry / ollama
161
+ result.model # 실제 deployment/model 이름
162
+ result.fallback_used # provider 실패 fallback 여부
163
+ result.decisions # span별 candidate, action, confidence, reason, distance
164
+ result.latency_ms
165
+ result.usage # provider가 제공한 token/시간 정보
166
+ result.diagnostics
167
+ ```
168
+
169
+ `confidence`는 모델의 bounded decision confidence입니다. V1 tuple의 두 번째 값은 반대로 **0이 가장 좋은 편집 거리**이므로 서로 같은 값으로 취급하면 안 됩니다.
170
+
171
+ ## 실패 정책
172
+
173
+ ```python
174
+ AgenticPronunciationMapper(..., fallback_strategy="heuristic") # 기본: V1 후보 적용
175
+ AgenticPronunciationMapper(..., fallback_strategy="original") # 원문/숫자 정규화만 유지
176
+ AgenticPronunciationMapper(..., fallback_strategy="raise") # provider 오류 전파
177
+ ```
178
+
179
+ 모델이 정상적으로 `keep` 또는 `abstain`을 선택한 경우는 provider 실패가 아니며 heuristic fallback을 적용하지 않습니다. confidence가 `minimum_confidence`보다 낮아도 원문을 보존합니다.
180
+ V2의 기본 heuristic fallback 거리는 `0.35`로 V1 기본값보다 보수적이며, `threshold=`를 명시하면 그 값을 사용합니다.
181
+
182
+ ## 안전 한계와 숫자 처리
183
+
184
+ 기본값은 입력 4,096자, lexical span 64개, token 256자까지입니다. `max_input_chars`, `max_spans`, `max_token_chars`로 조절할 수 있으며 초과 입력은 임의로 잘라 보내지 않고 거부합니다. Foundry transport도 기본 timeout 30초, retry 1회, output 2,048 token으로 제한합니다.
185
+
186
+ 한글 숫자는 명백한 단위·counter(`일억 원`, `321번`) 또는 긴 번호 문맥만 결정적으로 바꿉니다. `일일이`, `사이사이`, `천만 다행`처럼 숫자와 모양이 같은 일반어는 보존합니다. 프로젝트별 짧은 ID나 숫자형 고유명사는 golden set과 명시적 mapping으로 관리하는 것이 안전합니다.
187
+
188
+ ## CLI
189
+
190
+ V1 명령은 그대로 유지됩니다.
191
+
192
+ ```bash
193
+ pronunciation-mapper map-word 커스터머
194
+ pronunciation-mapper map-sentence '그라운드에 있는 데이타베이스 확인'
195
+ pronunciation-mapper add-mapping 고객 customer --save
196
+ ```
197
+
198
+ V2:
199
+
200
+ ```bash
201
+ pronunciation-mapper rewrite \
202
+ '엑스피엔36 서버에서 트랜잭숑 로그' \
203
+ --db-terms examples/db_terms.json \
204
+ --provider azure \
205
+ --json
206
+
207
+ pronunciation-mapper rewrite '트랜잭숑 로그' \
208
+ --provider ollama \
209
+ --model qwen3.5:4b
210
+ ```
211
+
212
+ DB 용어 파일은 문자열 배열 또는 `{"terms": [...]}` 형식을 지원합니다.
213
+
214
+ ## V1 호환 API
215
+
216
+ ```python
217
+ from pronunciation_mapper import PronunciationMapper
218
+
219
+ mapper = PronunciationMapper(
220
+ ["customer", "server", "데이터베이스"],
221
+ custom_mappings={"서버": "server"},
222
+ )
223
+
224
+ term, distance = mapper.find_closest_term("커스터머")
225
+ sentence = mapper.map_sentence("커스터머, 서버에서 조회")
226
+
227
+ print(f"단어: 커스터머 → {term} (distance={distance:.1f})")
228
+ print(f"문장: 커스터머, 서버에서 조회 → {sentence}")
229
+ ```
230
+
231
+ 실행 결과:
232
+
233
+ ```text
234
+ 단어: 커스터머 → customer (distance=0.0)
235
+ 문장: 커스터머, 서버에서 조회 → customer, server에서 조회
236
+ ```
237
+
238
+ V1 클래스는 네트워크나 Azure credential을 요구하지 않습니다. V2에서도 exact mapping, 발음 후보 생성, provider fallback의 로컬 계층으로 사용됩니다.
239
+
240
+ ## 테스트와 평가
241
+
242
+ ```bash
243
+ python -m unittest discover -v
244
+ python -m pytest -q
245
+
246
+ # 외부 provider 없이 deterministic fallback baseline
247
+ python evals/run_v2.py --provider offline
248
+
249
+ # 실제 환경에서 opt-in
250
+ python evals/run_v2.py --provider azure
251
+ python evals/run_v2.py --provider ollama
252
+ ```
253
+
254
+ 배포 전에는 최소한 exact accuracy, false rewrite rate, abstention 품질, latency, provider 실패율을 비교하세요. 자동 LLM judge보다 이 도메인의 golden mapping exact match를 1차 release gate로 두는 편이 적합합니다.
255
+
256
+ ## 문서
257
+
258
+ - [문서와 기록 안내](docs/README.md)
259
+ - [변경 기록](CHANGELOG.md)
260
+ - [V2.0.0 릴리스 기록](docs/releases/v2.0.0.md)
261
+ - [V2 아키텍처와 마이그레이션](docs/V2_ARCHITECTURE.md)
262
+ - [아키텍처 결정 기록](docs/decisions/README.md)
263
+ - [GitHub Actions와 외부 tenant Foundry OIDC 설정](docs/CI_SETUP.md)
264
+ - [V2 eval dataset](evals/cases.jsonl)
265
+ - [환경 변수 예시](.env.example)
266
+
267
+ ## 라이선스
268
+
269
+ MIT
@@ -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())