bareun-baropy 3.4.1__py3-none-win_amd64.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,130 @@
1
+ Metadata-Version: 2.1
2
+ Name: bareun-baropy
3
+ Version: 3.4.1
4
+ Summary: Bareun Korean morphological analyzer as a Python package (server binary included)
5
+ Home-page: https://bareun.ai/
6
+ License: Proprietary. See https://bareun.ai/en/service
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+
10
+ # bareun-baropy
11
+
12
+ **Bareun Korean morphological analyzer as a Python package.**
13
+ 한국어 형태소 분석기 [바른(Bareun)](https://bareun.ai/)을 `pip install` 한 번으로 쓰는 파이썬 패키지입니다.
14
+
15
+ The analysis server binary is bundled in the wheel, so there is nothing else to install and no server to run.
16
+ The package starts the server for you, analyzes text, and shuts it down when you are done.
17
+ This release covers **morphological analysis only** (no spelling correction API).
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install bareun-baropy
23
+ ```
24
+
25
+ - Python 3.10 or later.
26
+ - Platforms (CPU only):
27
+ - Linux x86_64 (glibc 2.28+) and Linux aarch64 (glibc 2.34+)
28
+ - macOS on Apple silicon (arm64, signed and notarized)
29
+ - Windows x64 (tested) and Windows ARM64 (built for ARM64 but not yet tested on real hardware; please report problems)
30
+ - The package version follows the Bareun release it ships. `3.4.x` contains the Bareun 3.4.0 server (3.4.1 only fixes the package description).
31
+
32
+ ## Quick start
33
+
34
+ An API key is required. Get one at <https://bareun.ai/>. It is registered automatically on the first call.
35
+ Pass it as `api_key=` or set the `BAREUN_API_KEY` environment variable.
36
+
37
+ ```python
38
+ import baropy
39
+
40
+ with baropy.Bareun(api_key="koba-...") as b: # or: export BAREUN_API_KEY=koba-...
41
+ res = b.analyze("나는 책을 읽었다.")
42
+ print(res.morphemes.pairs()) # [('나', 'NP'), ('는', 'JX'), ('책', 'NNG'), ...]
43
+ print(res.morphemes.nouns().texts()) # ['책']
44
+ ```
45
+
46
+ The first call downloads the model into your user cache folder (it is not part of the wheel) and can take a while.
47
+ Later calls start in seconds. `baropy fetch` downloads the model ahead of time.
48
+
49
+ For one-off scripts, module-level functions share a single default object (the key comes from `BAREUN_API_KEY`):
50
+
51
+ ```python
52
+ import baropy
53
+ print(baropy.analyze("바른 형태소 분석기").morphemes.pairs())
54
+ baropy.release() # unload the model when finished
55
+ ```
56
+
57
+ ## Results
58
+
59
+ `analyze()` returns an `Analysis` > `Sentence` > `Token` (eojeol) > `Morpheme` tree. All objects are read-only.
60
+
61
+ ```python
62
+ res = b.analyze("하늘이 맑다. 구름이 없다.")
63
+ for sent in res.sentences:
64
+ for tok in sent.tokens:
65
+ print(tok.text, tok.morphemes.tagged()) # e.g. 하늘이 하늘/NNG 이/JKS
66
+
67
+ res.morphemes.verbs().texts() # filter by part of speech
68
+ res.morphemes.frequency(top=5) # most frequent morphemes: [(text, count), ...]
69
+ ```
70
+
71
+ - `b.analyze(["문장 하나", "문장 둘"])` takes a list; `res.sentences[i]` matches input `i`.
72
+ - `b.analyze(text, sense=True)` adds word sense (WSD) results to each morpheme.
73
+ - `b.tokenize(text)` splits text into eojeol only.
74
+ - `MorphemeSeq` helpers: `texts`, `pairs`, `tagged`, `select`, `where`, `nouns`, `verbs`, `adjectives`, `adverbs`, `tokens`, `stats`, `tag_counts`, `frequency`.
75
+
76
+ ## Custom dictionaries
77
+
78
+ Add your own words by domain name, then use them per call or as defaults.
79
+
80
+ ```python
81
+ b.dicts.put("lab", np=["바른"], cp=["형태소분석기"]) # replaces the whole dictionary "lab"
82
+ b.analyze("바른 형태소분석기", dicts="lab")
83
+ b.default_dicts = ["lab"] # use it on every call
84
+ b.dicts.list() # see what is registered
85
+ b.dicts.remove("lab")
86
+ ```
87
+
88
+ Kinds: `np`, `cp`, `cp_caret` (compound split), `vv`, `va`, `mm`, `mag`, `ic`.
89
+ Names may contain only letters, digits, `_` and `-` (lower-cased).
90
+
91
+ ## Options
92
+
93
+ ```python
94
+ baropy.Bareun(
95
+ api_key=None, # or BAREUN_API_KEY
96
+ idle_timeout=3600.0, # unload the model after this many idle seconds (None: never)
97
+ session_timeout=None, # hard limit for one session
98
+ background=False, # True: leave a detached server running (server mode)
99
+ cache_dir=None, # model and runtime files (default: user cache folder)
100
+ threads=4,
101
+ start_timeout=1800.0, # how long to wait for the first model download
102
+ )
103
+ ```
104
+
105
+ By default the server is a hidden child process bound to `127.0.0.1` on a random port. It is tied to your Python
106
+ process and exits with it. With `background=True` it runs as a detached server on a fixed port instead; in that mode
107
+ anyone on the machine who can reach the port can use the registered key, so use it only on machines you trust.
108
+
109
+ Cache folders: Linux `~/.cache/bareun`, macOS `~/Library/Caches/bareun`, Windows `%LOCALAPPDATA%\bareun\Cache`.
110
+
111
+ ## Command line
112
+
113
+ ```text
114
+ baropy help open the documentation for the installed version
115
+ baropy version print the package version
116
+ baropy fetch download the model ahead of time (key from BAREUN_API_KEY)
117
+ baropy serve run server mode in this terminal (Ctrl-C to stop)
118
+ baropy stop stop a server started in server mode
119
+ baropy register register BAREUN_API_KEY with a running server
120
+ ```
121
+
122
+ ## Errors
123
+
124
+ All errors derive from `baropy.BaropyError`: `AuthError` (key rejected), `ModelFetchError` (model download failed),
125
+ `ServerStartError` (server did not start), `AnalysisError` (the call failed).
126
+
127
+ ## Documentation and license
128
+
129
+ - Documentation: run `baropy help`, or see <https://bareun.ai/>.
130
+ - License: proprietary, see <https://bareun.ai/en/service>. The source repository is private.
@@ -0,0 +1,17 @@
1
+ baropy/__init__.py,sha256=hKDh9UKkmsCotHPSiFY32I0uf4lsJv-vlldDF8Y9cMY,2310
2
+ baropy/_child.py,sha256=qnbx3fJeieJTW1gS-LPzN7NU7cruY01ZkIogQfyTtqo,6974
3
+ baropy/_server.py,sha256=WVEJRbl3AaCQQdXQ9A7r4xpBa3aj-XOnWhH-pwFHvM4,7905
4
+ baropy/cli.py,sha256=ZnNxRQfSrbER9Pv4n-bflu8fS-2p86oPKt7r_BGZ6yY,5893
5
+ baropy/client.py,sha256=D_wnsAcXUJn2Bbea0_fzdFNqlEV3SqUPstNnUsOUFzo,15315
6
+ baropy/customdicts.py,sha256=WjIOIpDle6Lyirdpp_ijeav-yfZ6pdFZsNdqygM01M0,7676
7
+ baropy/errors.py,sha256=q9sa4-5IZHksFfA5m5hqr8zwOYnGtHg14qETEAfHCb0,724
8
+ baropy/paths.py,sha256=_M4F6OoMlVsO2Q0I7XG6WWHCvR6UpRCHMdPWAtI9kn0,3720
9
+ baropy/types.py,sha256=NdQFL1U4WTytpvZun1dAjruUVkrNYnKD6L8bhFsb0cs,15291
10
+ baropy/_bin/bareun.exe,sha256=o6nGpzZatRcWbHMaCv6b7ANfwTimeBy285htLlrJnmM,17525760
11
+ baropy/_bin/onnxruntime.dll,sha256=adjm04eaO0ABzcdMjtnMx-f3maW4RwWXODI0BFGexHE,16149344
12
+ baropy/_bin/onnxruntime_providers_shared.dll,sha256=h_aHjNwfgLOpr6WwyEZjMVAwtJV_W7trZkcFV8svSNg,21856
13
+ bareun_baropy-3.4.1.dist-info/METADATA,sha256=anxWuJxK818M7BOUvDjrAAb3lwKRSLUkirB0gQXQ4DE,5580
14
+ bareun_baropy-3.4.1.dist-info/WHEEL,sha256=dIHs1396cn664DqqLNSKauCJ_TlJqPYGcDpLKENgPaA,95
15
+ bareun_baropy-3.4.1.dist-info/entry_points.txt,sha256=XCbNS_tdMgVdnh-S7ZCfgxrAhGRHwzPPKh3uuO2WE4g,43
16
+ bareun_baropy-3.4.1.dist-info/top_level.txt,sha256=TyFiCBrhSigpkUTbQXK5vHu9rI6UbNLIbjCpIsatmmY,7
17
+ bareun_baropy-3.4.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bareun-make-wheel
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ baropy = baropy.cli:main
@@ -0,0 +1 @@
1
+ baropy
baropy/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """bareun-baropy: 바른 형태소 분석기를 파이썬 패키지로.
2
+
3
+ import baropy
4
+ with baropy.Bareun(api_key="koba-...") as b:
5
+ print(b.analyze("나는 책을 읽었다.").morphemes.pairs())
6
+
7
+ 모듈 함수(analyze, tokenize, release)는 프로세스에 하나뿐인 기본 객체를 쓴다(API 키는 환경변수 BAREUN_API_KEY).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import threading
12
+
13
+ from .client import Bareun
14
+ from .errors import AnalysisError, AuthError, BaropyError, ModelFetchError, ServerStartError
15
+ from .customdicts import Conflict, CustomDicts, DictInfo, UserDict
16
+ from .types import Analysis, Morpheme, MorphemeSeq, SegToken, Sense, Sentence, Span, Stats, Token
17
+
18
+ __version__ = "3.4.1"
19
+ # 이 패키지가 싣고 있는 바른 서버의 정식 버전. 도움말 사이트 주소(/docs/<언어>/<버전>)는 이 값을 쓴다.
20
+ # 패키지 버전만 올린 3.4.1 에도 도움말 사이트는 3.4.0 하나뿐이다.
21
+ BAREUN_VERSION = "3.4.0"
22
+
23
+ __all__ = [
24
+ "Bareun", "analyze", "tokenize", "dicts", "release",
25
+ "Analysis", "Sentence", "Token", "Morpheme", "MorphemeSeq", "Sense", "Span", "Stats", "SegToken",
26
+ "UserDict", "DictInfo", "Conflict", "CustomDicts",
27
+ "BaropyError", "AuthError", "ModelFetchError", "ServerStartError", "AnalysisError",
28
+ "__version__", "BAREUN_VERSION",
29
+ ]
30
+
31
+ _default: Bareun | None = None
32
+ _default_lock = threading.Lock()
33
+
34
+
35
+ def _get_default() -> Bareun:
36
+ """기본 객체를 처음 쓸 때 만든다(키는 환경변수에서 읽는다)."""
37
+ global _default
38
+ with _default_lock:
39
+ if _default is None:
40
+ _default = Bareun()
41
+ return _default
42
+
43
+
44
+ def analyze(text, **kwargs) -> Analysis:
45
+ """기본 객체로 형태소 분석을 한다. 인자는 Bareun.analyze 와 같다."""
46
+ return _get_default().analyze(text, **kwargs)
47
+
48
+
49
+ def dicts() -> CustomDicts:
50
+ """기본 객체의 사용자 사전 관리자."""
51
+ return _get_default().dicts
52
+
53
+
54
+ def tokenize(text: str) -> list[SegToken]:
55
+ """기본 객체로 어절을 나눈다."""
56
+ return _get_default().tokenize(text)
57
+
58
+
59
+ def release() -> None:
60
+ """기본 객체가 올려 둔 모델을 내린다. 기본 객체를 쓴 적이 없으면 아무 일도 안 한다."""
61
+ with _default_lock:
62
+ d = _default
63
+ if d is not None:
64
+ d.release()
baropy/_bin/bareun.exe ADDED
Binary file
Binary file
baropy/_child.py ADDED
@@ -0,0 +1,136 @@
1
+ """숨은 자식 서버 프로세스를 띄우고 관리한다.
2
+
3
+ 부모와 자식은 표준입력 파이프로 묶인다. 부모가 어떤 방식으로 죽든(kill -9 포함) OS 가 파이프를 닫고,
4
+ 자식이 표준입력 EOF 를 보면 스스로 끝난다(서버 쪽 baropychild 패키지). 이 파일은 그 짝이 되는 부모 쪽이다.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import atexit
9
+ import json
10
+ import os
11
+ import secrets
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import time
16
+ from pathlib import Path
17
+ from typing import Sequence
18
+
19
+ from .errors import ServerStartError
20
+
21
+ # 로그 끝부분을 오류 메시지에 싣는 줄 수.
22
+ _LOG_TAIL_LINES = 20
23
+
24
+
25
+ def _tail(path: Path, lines: int = _LOG_TAIL_LINES) -> str:
26
+ """파일 끝 lines 줄을 돌려준다. 파일이 없거나 읽지 못하면 빈 문자열."""
27
+ try:
28
+ return "\n".join(path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:])
29
+ except OSError:
30
+ return ""
31
+
32
+
33
+ class Child:
34
+ """자식 서버 프로세스 하나. start() 로 띄우고 terminate() 로 끝낸다."""
35
+
36
+ def __init__(self, command: Sequence[str], cache_dir: Path, *, idle_timeout: float | None,
37
+ session_timeout: float | None, start_timeout: float) -> None:
38
+ self._command = list(command)
39
+ self._cache_dir = cache_dir
40
+ self._idle = idle_timeout or 0.0
41
+ self._session = session_timeout or 0.0
42
+ self._start_timeout = start_timeout
43
+ self.token = secrets.token_urlsafe(24) # 요청 인증 토큰. 명령줄이 아닌 표준입력으로만 넘긴다.
44
+ self.port = 0
45
+ self._proc: subprocess.Popen | None = None
46
+ self._ready = threading.Event()
47
+ self._ready_error = "" # READY 줄이 깨졌을 때 그 줄. 비어 있지 않으면 시작 실패다
48
+ self._log_path = cache_dir / "logs" / "baropy-child.log"
49
+
50
+ def start(self) -> None:
51
+ """자식을 띄우고 READY 줄이 나올 때까지 기다린다.
52
+
53
+ 첫 실행이면 모델 내려받기 때문에 start_timeout(기본 수십 분)까지 걸릴 수 있다.
54
+ 자식이 먼저 끝나거나 시간이 넘으면 ServerStartError 를 낸다(메시지에 로그 끝부분 포함).
55
+ """
56
+ self._log_path.parent.mkdir(parents=True, exist_ok=True)
57
+ env = dict(os.environ, BAREUN_ROOT=str(self._cache_dir))
58
+ kwargs: dict = {}
59
+ if sys.platform.startswith("win"):
60
+ # 콘솔 창을 띄우지 않고, 부모의 Ctrl-C 가 자식에게 같이 가지 않게 새 프로세스 그룹에 둔다.
61
+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
62
+ else:
63
+ # 새 세션에 두어 터미널 Ctrl-C(SIGINT)가 자식에게 직접 가지 않게 한다. 자식은 EOF 로 끝난다.
64
+ kwargs["start_new_session"] = True
65
+ with open(self._log_path, "ab") as log:
66
+ self._proc = subprocess.Popen(self._command + ["-baropy-child"], stdin=subprocess.PIPE,
67
+ stdout=subprocess.PIPE, stderr=log, env=env,
68
+ cwd=str(self._cache_dir), **kwargs)
69
+ # 프로세스가 비정상 종료하는 경우에도 자식이 남지 않게 인터프리터 종료 때 정리한다.
70
+ atexit.register(self.terminate)
71
+ hello = json.dumps({"token": self.token, "idle_seconds": self._idle, "session_seconds": self._session})
72
+ try:
73
+ assert self._proc.stdin is not None
74
+ self._proc.stdin.write((hello + "\n").encode())
75
+ self._proc.stdin.flush()
76
+ except OSError:
77
+ pass # 자식이 이미 죽었다. 아래 대기에서 ServerStartError 로 보고한다.
78
+ # 서버가 READY 말고도 안내 줄을 찍으므로 표준출력은 끝까지 읽어서 버린다(파이프가 차서 멈추지 않게).
79
+ threading.Thread(target=self._drain, daemon=True, name="baropy-stdout").start()
80
+ self._wait_ready()
81
+
82
+ def _drain(self) -> None:
83
+ """표준출력을 읽어 READY 줄에서 포트를 얻고, 나머지는 버린다. 자식이 끝나 EOF 가 오면 돌아온다."""
84
+ assert self._proc is not None and self._proc.stdout is not None
85
+ for raw in self._proc.stdout:
86
+ line = raw.decode("utf-8", errors="replace").strip()
87
+ if line.startswith("READY ") and not self._ready.is_set():
88
+ try:
89
+ self.port = int(line.split()[1])
90
+ except ValueError:
91
+ # 파싱 실패로 읽기 스레드가 죽으면 시작 대기가 한도까지 이어진다. 바로 실패로 알린다.
92
+ self._ready_error = line
93
+ self._ready.set()
94
+
95
+ def _wait_ready(self) -> None:
96
+ """READY 를 기다린다. 자식이 끝났거나 시간이 넘으면 자식을 정리하고 ServerStartError 를 낸다."""
97
+ assert self._proc is not None
98
+ deadline = time.monotonic() + self._start_timeout
99
+ while not self._ready.wait(0.1):
100
+ if self._proc.poll() is not None:
101
+ # 종료 직전에 READY 를 찍었을 수 있으니 읽기 스레드가 마저 처리할 틈을 준다.
102
+ if self._ready.wait(0.2):
103
+ break
104
+ self.terminate()
105
+ raise ServerStartError(f"자식 서버가 기동 중에 끝났다(종료 코드 {self._proc.returncode}).\n"
106
+ f"{_tail(self._log_path)}")
107
+ if time.monotonic() >= deadline:
108
+ self.terminate()
109
+ raise ServerStartError(f"자식 서버가 {self._start_timeout:.0f}초 안에 준비되지 않았다.\n"
110
+ f"{_tail(self._log_path)}")
111
+ if self._ready_error:
112
+ self.terminate()
113
+ raise ServerStartError(f"자식 서버의 READY 줄을 읽을 수 없다: {self._ready_error!r}\n{_tail(self._log_path)}")
114
+
115
+ def alive(self) -> bool:
116
+ """자식이 아직 살아 있고 READY 를 알렸는지."""
117
+ return self._proc is not None and self._proc.poll() is None and self._ready.is_set()
118
+
119
+ def terminate(self) -> None:
120
+ """자식을 끝낸다. 표준입력을 닫아 정상 종료를 청하고, 5초 안에 안 끝나면 강제로 죽인다. 여러 번 불러도 안전하다."""
121
+ atexit.unregister(self.terminate)
122
+ proc = self._proc
123
+ if proc is None:
124
+ return
125
+ self._ready.clear()
126
+ try:
127
+ assert proc.stdin is not None # PIPE 로 열었으므로 항상 있다
128
+ proc.stdin.close()
129
+ except OSError:
130
+ pass
131
+ try:
132
+ proc.wait(timeout=5)
133
+ except subprocess.TimeoutExpired:
134
+ proc.kill()
135
+ proc.wait()
136
+ # 표준출력은 읽기 스레드가 EOF 를 받으며 정리하므로 여기서 닫지 않는다(다른 스레드가 읽는 중일 수 있다).
baropy/_server.py ADDED
@@ -0,0 +1,188 @@
1
+ """서버 모드: 호출 모드의 자식과 달리 일반 서버로 띄워 여러 프로세스·언어가 같이 쓴다.
2
+
3
+ 서버 모드의 서버는 파이썬 부모와 수명이 묶이지 않는다(표준입력 감시 없음). 대신 pid 파일로 찾아 끝낸다.
4
+ 수신 주소는 기본이 루프백(127.0.0.1)이다.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import signal
10
+ import socket
11
+ import subprocess
12
+ import sys
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Sequence
16
+
17
+ from .errors import AuthError, ServerStartError
18
+ from ._child import _tail
19
+
20
+
21
+ def pid_file(cache_dir: Path, port: int) -> Path:
22
+ """포트별 pid 파일 경로."""
23
+ return cache_dir / "run" / f"server-{port}.pid"
24
+
25
+
26
+ def is_serving(host: str, port: int, timeout: float = 0.5) -> bool:
27
+ """host:port 에 TCP 연결이 되는지(서버가 떠 있는지)."""
28
+ try:
29
+ with socket.create_connection((host, port), timeout=timeout):
30
+ return True
31
+ except OSError:
32
+ return False
33
+
34
+
35
+ def _server_env(cache_dir: Path) -> dict[str, str]:
36
+ """서버가 설치 위치(BAREUN_ROOT)를 캐시 폴더로 알게 하는 환경."""
37
+ return dict(os.environ, BAREUN_ROOT=str(cache_dir))
38
+
39
+
40
+ def start_detached(command: Sequence[str], cache_dir: Path, host: str, port: int, *, timeout: float) -> None:
41
+ """서버를 부모와 떼어 낸 프로세스로 띄우고 포트가 열릴 때까지 기다린다.
42
+
43
+ 표준입력은 닫고 표준출력·오류는 로그 파일로 보낸다. 새 세션(윈도우는 분리된 프로세스)에 두어
44
+ 부모가 끝나거나 터미널이 닫혀도 서버가 남는다. 먼저 끝나거나 timeout 이 지나면 ServerStartError 를 낸다.
45
+ """
46
+ log = cache_dir / "logs" / f"baropy-server-{port}.log"
47
+ log.parent.mkdir(parents=True, exist_ok=True)
48
+ pidp = pid_file(cache_dir, port)
49
+ pidp.parent.mkdir(parents=True, exist_ok=True)
50
+ kwargs: dict = {}
51
+ if sys.platform.startswith("win"):
52
+ kwargs["creationflags"] = (subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
53
+ | subprocess.CREATE_NO_WINDOW)
54
+ else:
55
+ kwargs["start_new_session"] = True
56
+ with open(log, "ab") as lf:
57
+ proc = subprocess.Popen(list(command), stdin=subprocess.DEVNULL, stdout=lf, stderr=lf,
58
+ env=_server_env(cache_dir), cwd=str(cache_dir), **kwargs)
59
+ # pid 만 적으면 나중에 같은 번호를 다른 프로세스가 받았을 때 엉뚱한 프로세스를 죽인다. 실행 파일 이름도 같이 적어 확인한다.
60
+ pidp.write_text(f"{proc.pid}\n{os.path.basename(command[0])}\n", encoding="utf-8")
61
+ deadline = time.monotonic() + timeout
62
+ while not is_serving(host, port):
63
+ if proc.poll() is not None:
64
+ pidp.unlink(missing_ok=True)
65
+ raise ServerStartError(f"서버가 기동 중에 끝났다(종료 코드 {proc.returncode}).\n{_tail(log)}")
66
+ if time.monotonic() >= deadline:
67
+ stop(cache_dir, port)
68
+ raise ServerStartError(f"서버가 {timeout:.0f}초 안에 열리지 않았다.\n{_tail(log)}")
69
+ time.sleep(0.2)
70
+
71
+
72
+ def stop(cache_dir: Path, port: int, *, wait: float = 10.0) -> bool:
73
+ """pid 파일의 서버를 끝낸다. 끝낸 서버가 있으면 True, 기록이 없거나 이미 없으면 False.
74
+
75
+ 먼저 정상 종료 신호(SIGTERM, 윈도우는 TerminateProcess)를 보내고 wait 초 안에 안 끝나면 강제로 죽인다.
76
+ """
77
+ pidp = pid_file(cache_dir, port)
78
+ try:
79
+ lines = pidp.read_text(encoding="utf-8").split()
80
+ pid, name = int(lines[0]), lines[1]
81
+ except (OSError, ValueError, IndexError):
82
+ return False # 기록이 없거나, 이름이 없는 옛 형식이라 같은 프로세스인지 확인할 수 없다
83
+ pidp.unlink(missing_ok=True)
84
+ if not _is_our_process(pid, name):
85
+ return False # pid 가 재사용됐거나 이미 끝났다. 남의 프로세스를 건드리지 않는다
86
+ try:
87
+ os.kill(pid, signal.SIGTERM)
88
+ except OSError:
89
+ return False
90
+ deadline = time.monotonic() + wait
91
+ while time.monotonic() < deadline:
92
+ if not _pid_alive(pid):
93
+ return True
94
+ time.sleep(0.1)
95
+ try:
96
+ os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM))
97
+ except OSError:
98
+ pass
99
+ return True
100
+
101
+
102
+ _UNVERIFIABLE = object() # 프로세스 이름을 알아낼 방법이 없는 플랫폼
103
+
104
+
105
+ def _process_name(pid: int):
106
+ """pid 프로세스의 실행 파일 이름. 없는 프로세스면 None, 알아낼 방법이 없으면 _UNVERIFIABLE.
107
+
108
+ 리눅스는 /proc/<pid>/cmdline 의 첫 항목, mac 같은 /proc 없는 유닉스는 `ps -o comm=`, 윈도우는 알 수 없다.
109
+ """
110
+ try:
111
+ return os.path.basename(Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")[0].decode(errors="replace"))
112
+ except OSError:
113
+ pass
114
+ if Path("/proc").is_dir():
115
+ return None # 리눅스인데 못 읽는다: 이미 끝났거나 남의 프로세스다
116
+ try:
117
+ out = subprocess.run(["ps", "-p", str(pid), "-o", "comm="], capture_output=True, text=True, timeout=5).stdout
118
+ except (OSError, subprocess.SubprocessError):
119
+ return _UNVERIFIABLE
120
+ return os.path.basename(out.strip()) or None
121
+
122
+
123
+ def _is_our_process(pid: int, name: str) -> bool:
124
+ """pid 가 우리가 띄운 서버(실행 파일 이름이 name)인지. 이름을 알아낼 수 없는 플랫폼은 믿는다."""
125
+ found = _process_name(pid)
126
+ return found is _UNVERIFIABLE or found == name
127
+
128
+
129
+ def _pid_alive(pid: int) -> bool:
130
+ """pid 가 살아 있는지. 좀비(끝났지만 수거 전)는 죽은 것으로 본다."""
131
+ try:
132
+ os.kill(pid, 0)
133
+ except OSError:
134
+ return False
135
+ try:
136
+ return Path(f"/proc/{pid}/stat").read_text().split(")")[-1].split()[0] != "Z"
137
+ except OSError:
138
+ return True # /proc 이 없는 플랫폼(mac·windows)은 살아 있다고 본다
139
+
140
+
141
+ def run_foreground(command: Sequence[str], cache_dir: Path) -> int:
142
+ """서버를 이 프로세스에 붙여 띄우고 끝날 때까지 기다린다(`baropy serve`). 종료 코드를 돌려준다.
143
+
144
+ Ctrl-C 를 받으면 서버에 종료를 청하고 5초 안에 안 끝나면 강제로 죽인다.
145
+ """
146
+ proc = subprocess.Popen(list(command), env=_server_env(cache_dir), cwd=str(cache_dir))
147
+ try:
148
+ return proc.wait()
149
+ except KeyboardInterrupt:
150
+ proc.terminate()
151
+ try:
152
+ return proc.wait(timeout=5)
153
+ except subprocess.TimeoutExpired:
154
+ proc.kill()
155
+ return proc.wait()
156
+
157
+
158
+ def interpret_register(status: int, body: bytes) -> None:
159
+ """키 등록 응답을 해석해 실패면 AuthError 를 낸다.
160
+
161
+ 서버의 성공 응답 메시지에는 키 값이 들어 있으므로 어떤 경우에도 응답 본문을 예외 메시지에 싣지 않는다.
162
+ """
163
+ if status == 200:
164
+ return
165
+ if b"Other key" in body:
166
+ raise AuthError("이 캐시 폴더에는 다른 API 키가 이미 등록되어 있다. 다른 cache_dir 를 쓰거나 "
167
+ "캐시 폴더의 var/api-keys.db.pb 를 지운다")
168
+ raise AuthError(f"API 키 등록이 거부됐다(HTTP {status})")
169
+
170
+
171
+ class Remote:
172
+ """서버 모드 서버를 가리키는 핸들. Child 와 같은 모양(port, token, alive, terminate)을 가진다.
173
+
174
+ 서버 모드의 서버는 요청 토큰이 없고(token=None), terminate 는 서버를 끝내지 않는다(여러 프로세스가 같이 쓰므로).
175
+ """
176
+
177
+ token = None
178
+
179
+ def __init__(self, host: str, port: int) -> None:
180
+ self.host = host
181
+ self.port = port
182
+
183
+ def alive(self) -> bool:
184
+ """서버가 열려 있는지."""
185
+ return is_serving(self.host, self.port)
186
+
187
+ def terminate(self) -> None:
188
+ """아무것도 하지 않는다. 서버를 끝내려면 stop() 을 쓴다."""