bareunpy 2.1.0__tar.gz → 2.2.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 (33) hide show
  1. {bareunpy-2.1.0 → bareunpy-2.2.0}/PKG-INFO +79 -6
  2. {bareunpy-2.1.0 → bareunpy-2.2.0}/README.md +76 -0
  3. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/__init__.py +8 -0
  4. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_corrector.py +53 -1
  5. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_revision_service_client.py +42 -0
  6. bareunpy-2.2.0/bareunpy/_session.py +108 -0
  7. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_tagger.py +5 -1
  8. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_tokenizer.py +5 -1
  9. bareunpy-2.2.0/bareunpy/_truncation.py +122 -0
  10. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_version.py +1 -1
  11. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/lang_common_pb2.py +7 -5
  12. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/lang_common_pb2.pyi +16 -0
  13. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/language_service_pb2.py +20 -20
  14. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/language_service_pb2.pyi +14 -6
  15. bareunpy-2.2.0/bareunpy/bareun/revision_service_connect.py +391 -0
  16. bareunpy-2.2.0/bareunpy/bareun/revision_service_pb2.py +102 -0
  17. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/revision_service_pb2.pyi +111 -12
  18. {bareunpy-2.1.0 → bareunpy-2.2.0}/pyproject.toml +1 -1
  19. bareunpy-2.1.0/bareunpy/bareun/revision_service_connect.py +0 -196
  20. bareunpy-2.1.0/bareunpy/bareun/revision_service_pb2.py +0 -84
  21. {bareunpy-2.1.0 → bareunpy-2.2.0}/LICENSE +0 -0
  22. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_custom_dict.py +0 -0
  23. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_custom_dict_client.py +0 -0
  24. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/_lang_service_client.py +0 -0
  25. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/__init__.py +0 -0
  26. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/custom_dict_connect.py +0 -0
  27. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/custom_dict_pb2.py +0 -0
  28. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/custom_dict_pb2.pyi +0 -0
  29. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/dict_common_pb2.py +0 -0
  30. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/dict_common_pb2.pyi +0 -0
  31. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/language_service_connect.py +0 -0
  32. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/bareun/py.typed +0 -0
  33. {bareunpy-2.1.0 → bareunpy-2.2.0}/bareunpy/py.typed +0 -0
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.1
2
2
  Name: bareunpy
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Summary: The bareun python library using connect-rpc
5
+ Home-page: https://bareun.ai/
5
6
  License: BSD-3-Clause
6
- License-File: LICENSE
7
7
  Keywords: NLP,Korean,Deep Learning,POS tagger,bareun
8
8
  Author: Gihyun YUN
9
9
  Author-email: gih2yun@baikal.ai
@@ -24,8 +24,6 @@ Classifier: Programming Language :: Python :: 3
24
24
  Classifier: Programming Language :: Python :: 3.10
25
25
  Classifier: Programming Language :: Python :: 3.11
26
26
  Classifier: Programming Language :: Python :: 3.12
27
- Classifier: Programming Language :: Python :: 3.13
28
- Classifier: Programming Language :: Python :: 3.14
29
27
  Classifier: Topic :: Scientific/Engineering
30
28
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
31
29
  Classifier: Topic :: Scientific/Engineering :: Information Analysis
@@ -34,7 +32,6 @@ Classifier: Topic :: Software Development :: Libraries
34
32
  Classifier: Typing :: Typed
35
33
  Requires-Dist: connectrpc (>=0.10.1,<0.11)
36
34
  Requires-Dist: protobuf (>=7.35,<8)
37
- Project-URL: Homepage, https://bareun.ai/
38
35
  Project-URL: Repository, https://github.com/bareun-nlp/bareunpy
39
36
  Description-Content-Type: text/markdown
40
37
 
@@ -48,6 +45,18 @@ Description-Content-Type: text/markdown
48
45
 
49
46
  ## 변경사항
50
47
 
48
+ ### 2.2.0
49
+
50
+ - **교정 세션 지원**: 긴 문서를 여러 번에 나눠 교정할 때 `corrector.open_session()` 으로 세션을 엽니다. 서버가 같은 문서임을 알고 동작해, 앞 호출에서 두 번 이상 나온 미등록 단어를 뒤 호출에서 고치지 않습니다.
51
+ - `RevisionSession`: `correct_error()`, `correct_error_stream()`, `events()`, `close()`, `with` 문 지원
52
+ - 서버가 세션을 지원해야 합니다(바른 3.3.1 이상).
53
+ - **긴 글 요청의 잘림(truncation) 응답 지원**: 바른 엔진 자체에는 글자 수 제약이 없지만 클라우드 서비스(`api.bareun.ai`)는 용량 때문에 요청 한 번에 5,000자까지 처리하고, 넘으면 앞부분만 처리한 뒤 버린 부분을 응답으로 알립니다. 이제 이 정보를 읽을 수 있습니다.
54
+ - `Tagged` / `Tokenized`: `is_truncated()`, `truncation()`, `dropped_text()`
55
+ - `Corrector`: `Corrector.is_truncated(res)`, `Corrector.truncation(res)`, `print_results()` 가 안내 문구를 함께 출력
56
+ - `TruncationInfo`: 요청 글 전체·처리한·버린 글자 수, 버린 구간의 시작 위치, 안내 문구, 글자 중간에서 잘랐는지
57
+ - 새 메서드만 더했습니다. **기존 코드의 동작은 그대로**이고, 잘리지 않은 응답에는 정보가 없습니다(`None`).
58
+ - 서버 쪽에서 긴 요청 자르기를 지원해야 정보가 옵니다. 지원하지 않는 서버는 길면 거절하거나 그대로 처리합니다(`None`).
59
+
51
60
  ### 2.1.0
52
61
 
53
62
  - **동형이의어 의미 구분(WSD) API 추가 — 베타**: 표기·품사가 같은데 뜻이 다른 단어(`다리`(橋)/`다리`(脚))를 문맥으로 구분합니다.
@@ -342,6 +351,70 @@ for res in corrector.correct_error_stream("영수 도 줄기가 얇어서 시들
342
351
  print("취소:", res.cancelled.thinking_id)
343
352
  ```
344
353
 
354
+ ### 긴 글 처리와 잘림 확인
355
+
356
+ 바른 엔진 자체에는 글자 수 제약이 없지만, 클라우드 서비스(`api.bareun.ai`)는 용량 때문에 요청 한 번에 처리하는 양을 **5,000자**로 둡니다. 5,000자를 넘는 글은 거절하지 않고 앞부분만 처리하며(문장 끝, 공백 순으로 끊을 자리를 찾아 최대 500자 짧게), 버린 부분을 응답의 `truncation` 필드로 알립니다. 형태소 분석·토크나이징·맞춤법 교정 모두 같습니다. 긴 글은 5,000자 이하씩 나눠 보내세요(교정은 아래 세션을 쓰면 좋습니다). 이 기준은 운영 상황에 따라 바뀔 수 있으니 숫자를 코드에 박지 말고 `truncation` 의 `processed_chars`·`dropped_chars` 로 판단하세요.
357
+
358
+ 글자 수는 한글 한 글자, 영문 한 자, 공백, 줄바꿈이 각각 한 글자입니다. 지금 기준으로 5,000자까지는 전부 처리되고 5,001자부터 잘립니다. 자체 서버(설치형)는 기본으로 제한이 없고 설정으로 기준을 둘 수 있습니다.
359
+
360
+ 응답 좌표(`begin_offset` 등)는 잘려도 요청 글의 처음 기준 그대로입니다. 잘렸는지는 응답으로 확인합니다.
361
+
362
+ ```python
363
+ from bareunpy import Corrector, Tagger, Tokenizer
364
+
365
+ text = "..." # 5,001자 이상의 긴 글
366
+
367
+ tagged = Tagger(API_KEY).tag(text)
368
+ if tagged.is_truncated():
369
+ t = tagged.truncation()
370
+ print(t.original_chars) # 요청 글 전체 글자 수
371
+ print(t.processed_chars) # 처리한 글자 수
372
+ print(t.dropped_chars) # 버린 글자 수
373
+ print(t.message) # 서버 안내 문구
374
+ print(t.cut_mid_word) # True 면 글자 중간에서 잘라 마지막 어절을 믿기 어려움
375
+ rest = tagged.dropped_text() # 처리되지 않은 뒷부분 원문
376
+
377
+ # 토크나이저도 같습니다: Tokenizer(API_KEY).tokenize(text).truncation()
378
+
379
+ # 교정기는 응답을 넘깁니다. 스트리밍이면 first 응답을 넘깁니다.
380
+ res = Corrector(API_KEY).correct_error(text)
381
+ t = Corrector.truncation(res) # 잘리지 않았으면 None
382
+ if t:
383
+ rest = t.dropped_text(text) # 교정되지 않은 뒷부분
384
+ ```
385
+
386
+ 뒷부분까지 처리하려면 `dropped_text()` 로 받은 나머지를 다시 요청하면 됩니다. `taglist()` 는
387
+ 문장 목록 요청이라 `t.dropped_begin_sentence_index` 번째 문장부터 처리되지 않았고, 그보다 앞
388
+ 문장은 모두 처리됩니다(응답의 문장 수는 요청과 같고, 처리되지 않은 문장은 빈 문장으로 채워집니다).
389
+
390
+ ### 긴 문서는 세션으로 나눠 보내기
391
+
392
+ 교정은 긴 글을 세션(`OpenSession`, `CloseSession`)을 열고 문단 단위로 5,000자 이하씩 나눠 보내세요(세션은 맞춤법 교정에만 있고 형태소 분석에는 없습니다). 세션 안의 요청들은 따로 부르는 `CorrectError` 가 아니라 한 문서로 이어진 것으로 처리되어, 사용자 사전과 옵션이 문단마다 같게 적용되고 앞 문단에서 두 번 이상 나온 사전에 없는 낱말을 뒤 문단에서 오타로 보지 않습니다. 짧은 문단 요청은 서버가 한 번에 쓰는 메모리와 시간이 작아 긴 한 요청보다 안정되게 처리되며, 이는 서버 처리 부담에 관한 설명이고 요금이 달라진다는 뜻은 아닙니다. 5,000자 기준은 세션 안의 각 요청에도 똑같이 걸리고, 바뀔 수 있으니 `truncation` 필드로 판단하세요.
393
+
394
+ bareunpy 에서는 `corrector.open_session()` 으로 열고 `session.close()` 로 닫습니다(`with` 문이 알아서 닫습니다). 사용자 사전과 교정 설정은 세션을 열 때 정하고 닫을 때까지 바뀌지 않습니다. 세션은 마지막 호출 뒤 10분이 지나거나 열린 지 1시간이 지나면 서버가 닫고, 키당 동시에 열 수 있는 수에 상한이 있으니 끝나면 닫습니다.
395
+
396
+ ```python
397
+ from bareunpy import Corrector
398
+
399
+ corrector = Corrector(API_KEY)
400
+ text = "..." # 아주 긴 문서
401
+
402
+ revised = []
403
+ with corrector.open_session(custom_dicts=["my_dict"]) as session:
404
+ while text:
405
+ res = session.correct_error(text)
406
+ revised.append(res.revised)
407
+ t = Corrector.truncation(res) # 잘리지 않았으면 None
408
+ text = t.dropped_text(text) if t else "" # 교정되지 않은 뒷부분을 이어서 보냄
409
+ print("".join(revised))
410
+ ```
411
+
412
+ 위 예시는 서버가 잘라 알려 주는 뒷부분을 이어 보냅니다. 문서를 직접 문단 단위(5,000자 이하)로 나눠 호출해도 됩니다. 단발 호출(`session.correct_error`)로 앞 답을 받은 뒤
413
+ 뒤 호출 때문에 앞 답이 달라졌는지는 `session.events()` 로 확인합니다(`session_revision` 이 올랐으면
414
+ 미등록 단어가 새로 확정된 것입니다). 스트리밍(`session.correct_error_stream`)은 같은 정보를
415
+ `session_correction` 응답으로 보내 주고, 되돌릴 구간(`reverted`)의 교정을 취소하면 됩니다. 세션이
416
+ 만료되거나 서버가 모르면 `NOT_FOUND` 오류가 나니, 세션을 다시 열고 필요한 앞부분부터 다시 보냅니다.
417
+
345
418
  ---
346
419
 
347
420
  ## 사용자 사전 (Custom Dictionary)
@@ -8,6 +8,18 @@
8
8
 
9
9
  ## 변경사항
10
10
 
11
+ ### 2.2.0
12
+
13
+ - **교정 세션 지원**: 긴 문서를 여러 번에 나눠 교정할 때 `corrector.open_session()` 으로 세션을 엽니다. 서버가 같은 문서임을 알고 동작해, 앞 호출에서 두 번 이상 나온 미등록 단어를 뒤 호출에서 고치지 않습니다.
14
+ - `RevisionSession`: `correct_error()`, `correct_error_stream()`, `events()`, `close()`, `with` 문 지원
15
+ - 서버가 세션을 지원해야 합니다(바른 3.3.1 이상).
16
+ - **긴 글 요청의 잘림(truncation) 응답 지원**: 바른 엔진 자체에는 글자 수 제약이 없지만 클라우드 서비스(`api.bareun.ai`)는 용량 때문에 요청 한 번에 5,000자까지 처리하고, 넘으면 앞부분만 처리한 뒤 버린 부분을 응답으로 알립니다. 이제 이 정보를 읽을 수 있습니다.
17
+ - `Tagged` / `Tokenized`: `is_truncated()`, `truncation()`, `dropped_text()`
18
+ - `Corrector`: `Corrector.is_truncated(res)`, `Corrector.truncation(res)`, `print_results()` 가 안내 문구를 함께 출력
19
+ - `TruncationInfo`: 요청 글 전체·처리한·버린 글자 수, 버린 구간의 시작 위치, 안내 문구, 글자 중간에서 잘랐는지
20
+ - 새 메서드만 더했습니다. **기존 코드의 동작은 그대로**이고, 잘리지 않은 응답에는 정보가 없습니다(`None`).
21
+ - 서버 쪽에서 긴 요청 자르기를 지원해야 정보가 옵니다. 지원하지 않는 서버는 길면 거절하거나 그대로 처리합니다(`None`).
22
+
11
23
  ### 2.1.0
12
24
 
13
25
  - **동형이의어 의미 구분(WSD) API 추가 — 베타**: 표기·품사가 같은데 뜻이 다른 단어(`다리`(橋)/`다리`(脚))를 문맥으로 구분합니다.
@@ -302,6 +314,70 @@ for res in corrector.correct_error_stream("영수 도 줄기가 얇어서 시들
302
314
  print("취소:", res.cancelled.thinking_id)
303
315
  ```
304
316
 
317
+ ### 긴 글 처리와 잘림 확인
318
+
319
+ 바른 엔진 자체에는 글자 수 제약이 없지만, 클라우드 서비스(`api.bareun.ai`)는 용량 때문에 요청 한 번에 처리하는 양을 **5,000자**로 둡니다. 5,000자를 넘는 글은 거절하지 않고 앞부분만 처리하며(문장 끝, 공백 순으로 끊을 자리를 찾아 최대 500자 짧게), 버린 부분을 응답의 `truncation` 필드로 알립니다. 형태소 분석·토크나이징·맞춤법 교정 모두 같습니다. 긴 글은 5,000자 이하씩 나눠 보내세요(교정은 아래 세션을 쓰면 좋습니다). 이 기준은 운영 상황에 따라 바뀔 수 있으니 숫자를 코드에 박지 말고 `truncation` 의 `processed_chars`·`dropped_chars` 로 판단하세요.
320
+
321
+ 글자 수는 한글 한 글자, 영문 한 자, 공백, 줄바꿈이 각각 한 글자입니다. 지금 기준으로 5,000자까지는 전부 처리되고 5,001자부터 잘립니다. 자체 서버(설치형)는 기본으로 제한이 없고 설정으로 기준을 둘 수 있습니다.
322
+
323
+ 응답 좌표(`begin_offset` 등)는 잘려도 요청 글의 처음 기준 그대로입니다. 잘렸는지는 응답으로 확인합니다.
324
+
325
+ ```python
326
+ from bareunpy import Corrector, Tagger, Tokenizer
327
+
328
+ text = "..." # 5,001자 이상의 긴 글
329
+
330
+ tagged = Tagger(API_KEY).tag(text)
331
+ if tagged.is_truncated():
332
+ t = tagged.truncation()
333
+ print(t.original_chars) # 요청 글 전체 글자 수
334
+ print(t.processed_chars) # 처리한 글자 수
335
+ print(t.dropped_chars) # 버린 글자 수
336
+ print(t.message) # 서버 안내 문구
337
+ print(t.cut_mid_word) # True 면 글자 중간에서 잘라 마지막 어절을 믿기 어려움
338
+ rest = tagged.dropped_text() # 처리되지 않은 뒷부분 원문
339
+
340
+ # 토크나이저도 같습니다: Tokenizer(API_KEY).tokenize(text).truncation()
341
+
342
+ # 교정기는 응답을 넘깁니다. 스트리밍이면 first 응답을 넘깁니다.
343
+ res = Corrector(API_KEY).correct_error(text)
344
+ t = Corrector.truncation(res) # 잘리지 않았으면 None
345
+ if t:
346
+ rest = t.dropped_text(text) # 교정되지 않은 뒷부분
347
+ ```
348
+
349
+ 뒷부분까지 처리하려면 `dropped_text()` 로 받은 나머지를 다시 요청하면 됩니다. `taglist()` 는
350
+ 문장 목록 요청이라 `t.dropped_begin_sentence_index` 번째 문장부터 처리되지 않았고, 그보다 앞
351
+ 문장은 모두 처리됩니다(응답의 문장 수는 요청과 같고, 처리되지 않은 문장은 빈 문장으로 채워집니다).
352
+
353
+ ### 긴 문서는 세션으로 나눠 보내기
354
+
355
+ 교정은 긴 글을 세션(`OpenSession`, `CloseSession`)을 열고 문단 단위로 5,000자 이하씩 나눠 보내세요(세션은 맞춤법 교정에만 있고 형태소 분석에는 없습니다). 세션 안의 요청들은 따로 부르는 `CorrectError` 가 아니라 한 문서로 이어진 것으로 처리되어, 사용자 사전과 옵션이 문단마다 같게 적용되고 앞 문단에서 두 번 이상 나온 사전에 없는 낱말을 뒤 문단에서 오타로 보지 않습니다. 짧은 문단 요청은 서버가 한 번에 쓰는 메모리와 시간이 작아 긴 한 요청보다 안정되게 처리되며, 이는 서버 처리 부담에 관한 설명이고 요금이 달라진다는 뜻은 아닙니다. 5,000자 기준은 세션 안의 각 요청에도 똑같이 걸리고, 바뀔 수 있으니 `truncation` 필드로 판단하세요.
356
+
357
+ bareunpy 에서는 `corrector.open_session()` 으로 열고 `session.close()` 로 닫습니다(`with` 문이 알아서 닫습니다). 사용자 사전과 교정 설정은 세션을 열 때 정하고 닫을 때까지 바뀌지 않습니다. 세션은 마지막 호출 뒤 10분이 지나거나 열린 지 1시간이 지나면 서버가 닫고, 키당 동시에 열 수 있는 수에 상한이 있으니 끝나면 닫습니다.
358
+
359
+ ```python
360
+ from bareunpy import Corrector
361
+
362
+ corrector = Corrector(API_KEY)
363
+ text = "..." # 아주 긴 문서
364
+
365
+ revised = []
366
+ with corrector.open_session(custom_dicts=["my_dict"]) as session:
367
+ while text:
368
+ res = session.correct_error(text)
369
+ revised.append(res.revised)
370
+ t = Corrector.truncation(res) # 잘리지 않았으면 None
371
+ text = t.dropped_text(text) if t else "" # 교정되지 않은 뒷부분을 이어서 보냄
372
+ print("".join(revised))
373
+ ```
374
+
375
+ 위 예시는 서버가 잘라 알려 주는 뒷부분을 이어 보냅니다. 문서를 직접 문단 단위(5,000자 이하)로 나눠 호출해도 됩니다. 단발 호출(`session.correct_error`)로 앞 답을 받은 뒤
376
+ 뒤 호출 때문에 앞 답이 달라졌는지는 `session.events()` 로 확인합니다(`session_revision` 이 올랐으면
377
+ 미등록 단어가 새로 확정된 것입니다). 스트리밍(`session.correct_error_stream`)은 같은 정보를
378
+ `session_correction` 응답으로 보내 주고, 되돌릴 구간(`reverted`)의 교정을 취소하면 됩니다. 세션이
379
+ 만료되거나 서버가 모르면 `NOT_FOUND` 오류가 나니, 세션을 다시 열고 필요한 앞부분부터 다시 보냅니다.
380
+
305
381
  ---
306
382
 
307
383
  ## 사용자 사전 (Custom Dictionary)
@@ -31,6 +31,12 @@ Tagged
31
31
  SenseInfo
32
32
  동형이의어 의미 구분(WSD, 베타) 결과 한 건
33
33
  `from bareunpy import SenseInfo`
34
+ TruncationInfo
35
+ 긴 요청이 앞부분만 처리됐을 때의 정보(처리·버린 글자 수, 안내 문구)
36
+ `from bareunpy import TruncationInfo`
37
+ RevisionSession
38
+ 긴 문서를 나눠 교정할 때 쓰는 교정 세션(`corrector.open_session()`)
39
+ `from bareunpy import RevisionSession`
34
40
  CustomDict
35
41
  Custom dictionary for Korean.
36
42
  `from bareunpy import CustomDict`
@@ -55,6 +61,8 @@ import os
55
61
  from bareunpy._tagger import Tagger, Tagged, SenseInfo
56
62
  from bareunpy._tokenizer import Tokenizer, Tokenized
57
63
  from bareunpy._corrector import Corrector
64
+ from bareunpy._truncation import TruncationInfo
65
+ from bareunpy._session import RevisionSession
58
66
  from bareunpy._custom_dict import CustomDict
59
67
  from bareunpy._custom_dict_client import CustomDictionaryServiceClient
60
68
  from bareunpy._lang_service_client import BareunLanguageServiceClient
@@ -8,6 +8,8 @@ import bareunpy.bareun.revision_service_pb2 as pb
8
8
  import bareunpy.bareun.lang_common_pb2 as lpb
9
9
  from ._revision_service_client import BareunRevisionServiceClient
10
10
  from bareunpy._tagger import _resolve_port
11
+ from bareunpy._truncation import TruncationInfo, truncation_of
12
+ from ._session import RevisionSession
11
13
 
12
14
 
13
15
  class Corrector:
@@ -136,10 +138,56 @@ class Corrector:
136
138
 
137
139
  return self.client.stream_correct_error(request)
138
140
 
141
+ def open_session(self, custom_dicts: Optional[List[str]] = None,
142
+ config: Union[pb.RevisionConfig, None] = None) -> RevisionSession:
143
+ """교정 세션을 엽니다. 긴 문서를 여러 번에 나눠 교정할 때 씁니다.
144
+
145
+ 세션 안의 호출은 같은 문서로 취급되어, 앞 호출에서 두 번 이상 나온 미등록 단어를 뒤 호출에서
146
+ 고치지 않습니다. 사용자 사전과 설정은 여기서 한 번 정하고 세션이 닫힐 때까지 바뀌지 않습니다.
147
+
148
+ .. code-block:: python
149
+ >>> with corrector.open_session() as session:
150
+ ... res = session.correct_error(part)
151
+
152
+ Args:
153
+ custom_dicts (List[str]): 사용자 사전의 이름 목록
154
+ config (Union[pb.RevisionConfig, None]): 교정 설정
155
+
156
+ Returns:
157
+ RevisionSession: 열린 세션(``with`` 문으로 쓰면 끝날 때 닫는다)
158
+ """
159
+ request = pb.OpenSessionRequest()
160
+ if custom_dicts:
161
+ request.custom_dict_names.extend(custom_dicts)
162
+ if config is not None:
163
+ request.config.CopyFrom(config)
164
+ return RevisionSession(self.client, self.client.open_session(request))
165
+
139
166
  def close(self) -> None:
140
- """내부 세션을 닫습니다(선택)."""
167
+ """내부 세션을 닫습니다(선택). 교정 세션은 :meth:`RevisionSession.close` 로 따로 닫습니다."""
141
168
  self.client.close()
142
169
 
170
+ @staticmethod
171
+ def is_truncated(res: Union[pb.CorrectErrorResponse, pb.StreamFirstCorrectError]) -> bool:
172
+ """요청 글이 길어 앞부분만 교정됐으면 True.
173
+
174
+ 서버는 기준(클라우드 서비스는 현재 5,000자, 바뀔 수 있음)을 넘는 글을 거절하지 않고 앞부분만 교정합니다.
175
+ 스트리밍이면 ``first`` 응답(``res.first``)을 넘깁니다.
176
+ """
177
+ return truncation_of(res) is not None
178
+
179
+ @staticmethod
180
+ def truncation(res: Union[pb.CorrectErrorResponse, pb.StreamFirstCorrectError]) -> Optional[TruncationInfo]:
181
+ """잘림 정보(처리한 글자 수, 버린 글자 수, 안내 문구 등). 잘리지 않았으면 None.
182
+
183
+ .. code-block:: python
184
+ >>> res = corrector.correct_error(very_long_text)
185
+ >>> t = Corrector.truncation(res)
186
+ >>> if t:
187
+ ... rest = t.dropped_text(very_long_text) # 교정되지 않은 뒷부분
188
+ """
189
+ return truncation_of(res)
190
+
143
191
  def print_results(self, res: pb.CorrectErrorResponse, out: IO = stdout) -> None:
144
192
  """
145
193
  교정 결과를 출력
@@ -151,6 +199,10 @@ class Corrector:
151
199
  print(f'원문: {res.origin}', file=out)
152
200
  print(f'교정: {res.revised}', file=out)
153
201
 
202
+ t = truncation_of(res)
203
+ if t is not None:
204
+ print(f'[주의] {t.message}', file=out)
205
+
154
206
  print("\n=== 교정된 문장들 ===", file=out)
155
207
 
156
208
  for sent in res.revised_sentences:
@@ -90,3 +90,45 @@ class BareunRevisionServiceClient:
90
90
  yield resp
91
91
  except ConnectError as e:
92
92
  self._handle_connect_error(e)
93
+
94
+ def open_session(self, request: pb.OpenSessionRequest) -> pb.OpenSessionResponse:
95
+ """교정 세션을 엽니다(단발 unary 호출).
96
+
97
+ Args:
98
+ request (pb.OpenSessionRequest): 세션을 열 때 정할 사용자 사전과 교정 설정
99
+
100
+ Returns:
101
+ pb.OpenSessionResponse: 세션 ID 와 수명(유휴·최대 시간)
102
+ """
103
+ try:
104
+ return self.stub.open_session(request, headers=self.metadata)
105
+ except ConnectError as e:
106
+ self._handle_connect_error(e)
107
+
108
+ def close_session(self, request: pb.CloseSessionRequest) -> pb.CloseSessionResponse:
109
+ """교정 세션을 닫습니다(단발 unary 호출).
110
+
111
+ Args:
112
+ request (pb.CloseSessionRequest): 닫을 세션 ID
113
+
114
+ Returns:
115
+ pb.CloseSessionResponse: 닫힌 시점의 세션 개정 번호
116
+ """
117
+ try:
118
+ return self.stub.close_session(request, headers=self.metadata)
119
+ except ConnectError as e:
120
+ self._handle_connect_error(e)
121
+
122
+ def get_session_events(self, request: pb.GetSessionEventsRequest) -> pb.GetSessionEventsResponse:
123
+ """세션의 변경 사건(미등록 단어 확정 등)을 가져옵니다(단발 unary 호출).
124
+
125
+ Args:
126
+ request (pb.GetSessionEventsRequest): 세션 ID 와 이 번호보다 큰 개정만 받을 기준
127
+
128
+ Returns:
129
+ pb.GetSessionEventsResponse: 지금의 세션 개정 번호와 사건 목록
130
+ """
131
+ try:
132
+ return self.stub.get_session_events(request, headers=self.metadata)
133
+ except ConnectError as e:
134
+ self._handle_connect_error(e)
@@ -0,0 +1,108 @@
1
+ # -*- coding: utf-8 -*-
2
+ """긴 문서를 여러 번에 나눠 교정할 때 쓰는 교정 세션.
3
+
4
+ 세션을 열면 서버가 같은 문서임을 알고 동작합니다. 앞 호출에서 두 번 이상 나온 미등록 단어는
5
+ 알려진 말로 확정해 뒤 호출에서 고치지 않습니다. 사용자 사전과 교정 설정은 세션을 열 때 한 번
6
+ 정하고 닫을 때까지 바뀌지 않습니다. 세션은 서버에 영구 저장되지 않고, 마지막 호출 뒤 10분이
7
+ 지나거나 열린 지 1시간이 지나면 서버가 닫습니다.
8
+ """
9
+
10
+ from typing import Iterator, List, Optional
11
+
12
+ import bareunpy.bareun.revision_service_pb2 as pb
13
+ import bareunpy.bareun.lang_common_pb2 as lpb
14
+ from ._revision_service_client import BareunRevisionServiceClient
15
+
16
+
17
+ class RevisionSession:
18
+ """열려 있는 교정 세션 하나.
19
+
20
+ :meth:`Corrector.open_session` 으로 만듭니다. ``with`` 문으로 쓰면 블록이 끝날 때 닫습니다.
21
+
22
+ .. code-block:: python
23
+ >>> with corrector.open_session() as session:
24
+ ... first = session.correct_error(part1)
25
+ ... second = session.correct_error(part2)
26
+
27
+ Attributes:
28
+ session_id (str): 서버가 정한 세션 ID(UUID).
29
+ session_revision (int): 세션을 열 때의 개정 번호(처음은 0). 최신 값은 :meth:`events` 로 본다.
30
+ idle_timeout_seconds (int): 마지막 호출 뒤 이 시간이 지나면 닫힌다.
31
+ max_lifetime_seconds (int): 열린 지 이 시간이 지나면 호출 중이어도 닫힌다.
32
+ """
33
+
34
+ def __init__(self, client: BareunRevisionServiceClient, opened: pb.OpenSessionResponse):
35
+ self._client = client
36
+ self.session_id = opened.session_id
37
+ self.session_revision = opened.session_revision
38
+ self.idle_timeout_seconds = opened.idle_timeout_seconds
39
+ self.max_lifetime_seconds = opened.max_lifetime_seconds
40
+
41
+ def correct_error(self, content: str) -> pb.CorrectErrorResponse:
42
+ """세션 안에서 맞춤법을 교정합니다(단발 호출).
43
+
44
+ 사용자 사전과 설정은 세션을 열 때 정한 값을 씁니다. 글이 서버 기준보다 길면 앞부분만
45
+ 교정되니, 응답의 :meth:`Corrector.truncation` 으로 확인하고 ``dropped_text`` 로 이어 보냅니다.
46
+
47
+ Args:
48
+ content (str): 교정을 요청할 글
49
+
50
+ Returns:
51
+ pb.CorrectErrorResponse: 교정 결과
52
+ """
53
+ request = pb.CorrectErrorRequest(
54
+ document=lpb.Document(content=content, language="ko_KR"),
55
+ encoding_type=lpb.EncodingType.UTF32,
56
+ session_id=self.session_id,
57
+ )
58
+ return self._client.correct_error(request)
59
+
60
+ def correct_error_stream(self, content: str, req_id: int = 0) -> Iterator[pb.StreamCorrectErrorResponse]:
61
+ """세션 안에서 맞춤법을 실시간(server-streaming)으로 교정합니다.
62
+
63
+ 같은 호출 안에서 먼저 나온 미등록 단어는 아직 몰랐을 때의 규칙이 이미 고쳤을 수 있어,
64
+ 서버가 첫 응답 뒤에 ``session_correction`` 응답으로 되돌릴 구간을 알려 줍니다.
65
+
66
+ Args:
67
+ content (str): 교정을 요청할 글
68
+ req_id (int): 요청 식별자. 0(기본값)이면 서버가 생성합니다.
69
+
70
+ Yields:
71
+ pb.StreamCorrectErrorResponse: first / progress / post / cancelled / session_correction 중 하나
72
+ """
73
+ request = pb.StreamCorrectErrorRequest(
74
+ document=lpb.Document(content=content, language="ko_KR"),
75
+ encoding_type=lpb.EncodingType.UTF32,
76
+ session_id=self.session_id,
77
+ )
78
+ if req_id:
79
+ request.req_id = req_id
80
+ return self._client.stream_correct_error(request)
81
+
82
+ def events(self, since_revision: int = 0) -> pb.GetSessionEventsResponse:
83
+ """세션의 변경 사건을 가져옵니다.
84
+
85
+ 단발 호출로 앞 응답을 받은 뒤, 뒤 호출 때문에 세션이 바뀌었는지(미등록 단어가 확정됐는지)
86
+ 알아볼 때 씁니다. ``session_revision`` 이 응답의 값보다 올랐으면 앞 호출의 답이 달라졌을 수 있습니다.
87
+
88
+ Args:
89
+ since_revision (int): 이 번호보다 큰 개정의 사건만 받는다. 0 이면 처음부터.
90
+
91
+ Returns:
92
+ pb.GetSessionEventsResponse: 지금의 세션 개정 번호와 사건 목록(개정 번호 순)
93
+ """
94
+ return self._client.get_session_events(
95
+ pb.GetSessionEventsRequest(session_id=self.session_id, since_revision=since_revision))
96
+
97
+ def close(self) -> pb.CloseSessionResponse:
98
+ """세션을 닫고 서버가 쥔 상태를 정리합니다. 닫으면 동시 세션 수 상한을 바로 돌려받습니다.
99
+
100
+ 호출하지 않아도 서버가 알아서 닫습니다. 이미 닫혔거나 만료된 세션이면 서버 오류가 납니다.
101
+ """
102
+ return self._client.close_session(pb.CloseSessionRequest(session_id=self.session_id))
103
+
104
+ def __enter__(self) -> "RevisionSession":
105
+ return self
106
+
107
+ def __exit__(self, exc_type, exc, tb) -> None:
108
+ self.close()
@@ -7,6 +7,7 @@ from typing import IO, List, NamedTuple, Optional, Union
7
7
  from google.protobuf.json_format import MessageToDict
8
8
  from bareunpy._custom_dict import CustomDict
9
9
  from bareunpy._lang_service_client import BareunLanguageServiceClient
10
+ from bareunpy._truncation import TruncationMixin
10
11
  from bareunpy.bareun.language_service_pb2 import AnalyzeSyntaxResponse, AnalyzeSyntaxListResponse, Morpheme, Sentence, Token
11
12
 
12
13
 
@@ -60,10 +61,13 @@ def _resolve_port(host: str, port: Optional[int]) -> int:
60
61
  else:
61
62
  return 5656
62
63
 
63
- class Tagged:
64
+ class Tagged(TruncationMixin):
64
65
  """
65
66
  Tagged result.
66
67
  It has various output manipulations.
68
+
69
+ 요청 글이 서버 기준(클라우드 서비스는 현재 5,000자, 바뀔 수 있음)보다 길면 앞부분만 분석됩니다. 이때
70
+ :meth:`is_truncated`, :meth:`truncation`, :meth:`dropped_text` 로 처리 범위를 확인합니다.
67
71
  """
68
72
 
69
73
  def __init__(self, phrase: Union[str, List[str]], res: Union[AnalyzeSyntaxResponse, AnalyzeSyntaxListResponse]):
@@ -7,11 +7,15 @@ from google.protobuf.json_format import MessageToDict
7
7
  from bareunpy._lang_service_client import BareunLanguageServiceClient
8
8
  from bareunpy.bareun.language_service_pb2 import TokenizeResponse, Segment, SegmentSentence, SegmentToken
9
9
  from bareunpy._tagger import _resolve_port
10
+ from bareunpy._truncation import TruncationMixin
10
11
 
11
- class Tokenized:
12
+ class Tokenized(TruncationMixin):
12
13
  """
13
14
  Tokenized result.
14
15
  It has various output manipulations.
16
+
17
+ 요청 글이 서버 기준(클라우드 서비스는 현재 5,000자, 바뀔 수 있음)보다 길면 앞부분만 처리됩니다. 이때
18
+ :meth:`is_truncated`, :meth:`truncation`, :meth:`dropped_text` 로 처리 범위를 확인합니다.
15
19
  """
16
20
 
17
21
  def __init__(self, phrase: str, res: TokenizeResponse):
@@ -0,0 +1,122 @@
1
+ # -*- coding: utf-8 -*-
2
+ """긴 요청이 잘렸을 때(truncation)의 응답 정보를 읽는 도구.
3
+
4
+ 서버는 요청 글이 기준(클라우드 서비스는 현재 5,000자, 바뀔 수 있음)을 넘으면 거절하지 않고 앞부분(5,000자 안쪽)만
5
+ 처리한 뒤, 응답의 ``truncation`` 필드로 버린 부분을 알립니다. 잘리지 않은 응답에는 이 필드가
6
+ 없고, 이 정보를 모르는 옛 버전의 클라이언트도 그대로 동작합니다.
7
+
8
+ 이 모듈은 그 필드를 :class:`TruncationInfo` 로 바꿔 줍니다. ``Tagged``·``Tokenized`` 와
9
+ ``Corrector`` 가 같은 도구를 씁니다.
10
+ """
11
+
12
+ from typing import Any, List, NamedTuple, Optional, Union
13
+
14
+
15
+ class TruncationInfo(NamedTuple):
16
+ """긴 요청이 앞부분만 처리됐을 때의 정보.
17
+
18
+ 글자 수는 유니코드 코드 포인트(한글 한 글자, 영문 한 자, 공백, 줄바꿈이 각각 한 글자)로 셉니다.
19
+ bareunpy 는 요청을 항상 UTF32 로 보내므로 ``dropped_begin_offset`` 도 파이썬 문자열의 글자
20
+ 위치와 같습니다(``content[dropped_begin_offset:]`` 가 버린 부분).
21
+
22
+ Attributes:
23
+ original_chars (int): 요청 글 전체의 글자 수.
24
+ processed_chars (int): 처리한 글자 수(앞부분).
25
+ dropped_chars (int): 처리하지 않고 버린 글자 수.
26
+ dropped_begin_offset (int): 버린 구간이 시작하는 글자 위치. 문장 목록(``taglist``)
27
+ 요청이면 ``dropped_begin_sentence_index`` 번째 문장 안의 위치다.
28
+ message (str): 서버가 준 안내 문구(한국어, 괄호 안에 영어).
29
+ cut_mid_word (bool): 문장 끝이나 공백을 찾지 못해 글자 중간에서 잘랐으면 True.
30
+ 마지막 어절의 분석·교정은 믿기 어렵다.
31
+ dropped_begin_sentence_index (Optional[int]): 문장 목록 요청(``taglist``)에서만 값이
32
+ 있다. 처리하지 않은 부분이 시작하는 문장의 번호(0부터). 그 뒤 문장은 모두 처리되지
33
+ 않았다. 다른 요청은 None.
34
+ """
35
+
36
+ original_chars: int
37
+ processed_chars: int
38
+ dropped_chars: int
39
+ dropped_begin_offset: int
40
+ message: str
41
+ cut_mid_word: bool
42
+ dropped_begin_sentence_index: Optional[int] = None
43
+
44
+ def dropped_text(self, content: Union[str, List[str]]) -> str:
45
+ """요청에 쓴 원문에서 처리되지 않은 부분을 돌려줍니다.
46
+
47
+ 긴 글을 나눠 다시 요청할 때 이어서 보낼 나머지입니다.
48
+
49
+ Args:
50
+ content: 요청에 쓴 원문. 문장 목록(``taglist``)이면 그 목록 그대로.
51
+
52
+ Returns:
53
+ 처리되지 않은 뒷부분. 문장 목록이면 문장 사이를 줄바꿈으로 이어 붙인다.
54
+ """
55
+ if isinstance(content, str):
56
+ return content[self.dropped_begin_offset:]
57
+ index = self.dropped_begin_sentence_index or 0
58
+ if index >= len(content):
59
+ return ""
60
+ head = content[index][self.dropped_begin_offset:]
61
+ return "\n".join([head] + list(content[index + 1:]))
62
+
63
+
64
+ def truncation_of(msg: Any) -> Optional[TruncationInfo]:
65
+ """응답 메시지에서 잘림 정보를 꺼냅니다. 잘리지 않았으면 None.
66
+
67
+ ``truncation`` 은 proto3 ``optional`` 메시지 필드라, 잘리지 않은 응답에는 필드 자체가
68
+ 없습니다. 그래서 값 비교가 아니라 ``HasField`` 로 존재를 확인합니다.
69
+
70
+ Args:
71
+ msg: ``truncation`` 필드를 가진 응답(분석·토크나이즈·교정·스트림 첫 응답).
72
+ 필드가 없는 메시지(스트림의 진행·확정 응답 등)면 None.
73
+ """
74
+ descriptor = getattr(msg, "DESCRIPTOR", None)
75
+ if descriptor is None or "truncation" not in descriptor.fields_by_name:
76
+ return None
77
+ if not msg.HasField("truncation"):
78
+ return None
79
+ t = msg.truncation
80
+ index = None
81
+ if "dropped_begin_sentence_index" in descriptor.fields_by_name \
82
+ and msg.HasField("dropped_begin_sentence_index"):
83
+ index = msg.dropped_begin_sentence_index
84
+ return TruncationInfo(
85
+ original_chars=t.original_chars,
86
+ processed_chars=t.processed_chars,
87
+ dropped_chars=t.dropped_chars,
88
+ dropped_begin_offset=t.dropped_begin_offset,
89
+ message=t.message,
90
+ cut_mid_word=t.cut_mid_word,
91
+ dropped_begin_sentence_index=index,
92
+ )
93
+
94
+
95
+ class TruncationMixin:
96
+ """응답 래퍼(``Tagged``·``Tokenized``)에 잘림 정보 조회를 더합니다.
97
+
98
+ 쓰는 쪽은 응답 메시지를 ``self.r``, 요청 원문을 ``self.phrase`` 로 가져야 한다.
99
+ """
100
+
101
+ r: Any
102
+ phrase: Union[str, List[str]]
103
+
104
+ def is_truncated(self) -> bool:
105
+ """요청 글이 길어 앞부분만 처리됐으면 True."""
106
+ return truncation_of(self.r) is not None
107
+
108
+ def truncation(self) -> Optional[TruncationInfo]:
109
+ """잘림 정보. 잘리지 않았으면 None.
110
+
111
+ .. code-block:: python
112
+ >>> tagged = tagger.tag(very_long_text)
113
+ >>> t = tagged.truncation()
114
+ >>> if t:
115
+ ... print(t.processed_chars, t.dropped_chars, t.message)
116
+ """
117
+ return truncation_of(self.r)
118
+
119
+ def dropped_text(self) -> str:
120
+ """처리되지 않은 뒷부분의 원문. 잘리지 않았으면 빈 문자열."""
121
+ t = truncation_of(self.r)
122
+ return "" if t is None else t.dropped_text(self.phrase)
@@ -1,4 +1,4 @@
1
1
 
2
- version = "2.1.0"
2
+ version = "2.2.0"
3
3
  bareun_version = "3.1.0"
4
4