medsplain 0.1.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.
Potentially problematic release.
This version of medsplain might be problematic. Click here for more details.
- medsplain/__init__.py +44 -0
- medsplain/client.py +222 -0
- medsplain/exceptions.py +98 -0
- medsplain/models.py +55 -0
- medsplain/py.typed +0 -0
- medsplain-0.1.0.dist-info/METADATA +156 -0
- medsplain-0.1.0.dist-info/RECORD +9 -0
- medsplain-0.1.0.dist-info/WHEEL +4 -0
- medsplain-0.1.0.dist-info/licenses/LICENSE +21 -0
medsplain/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Medsplain TX — official Python client.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
from medsplain import Medsplain
|
|
6
|
+
|
|
7
|
+
client = Medsplain(api_key="mds_live_...")
|
|
8
|
+
result = client.translate("Patient presents with acute myocardial infarction.")
|
|
9
|
+
print(result.simplified_text)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from .client import Medsplain
|
|
15
|
+
from .exceptions import (
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
APIStatusError,
|
|
18
|
+
AuthenticationError,
|
|
19
|
+
BadRequestError,
|
|
20
|
+
MedsplainError,
|
|
21
|
+
NotFoundError,
|
|
22
|
+
PermissionDeniedError,
|
|
23
|
+
RateLimitError,
|
|
24
|
+
ServerError,
|
|
25
|
+
)
|
|
26
|
+
from .models import HealthStatus, TranslationResult
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Medsplain",
|
|
32
|
+
"TranslationResult",
|
|
33
|
+
"HealthStatus",
|
|
34
|
+
"MedsplainError",
|
|
35
|
+
"APIConnectionError",
|
|
36
|
+
"APIStatusError",
|
|
37
|
+
"BadRequestError",
|
|
38
|
+
"AuthenticationError",
|
|
39
|
+
"PermissionDeniedError",
|
|
40
|
+
"NotFoundError",
|
|
41
|
+
"RateLimitError",
|
|
42
|
+
"ServerError",
|
|
43
|
+
"__version__",
|
|
44
|
+
]
|
medsplain/client.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Synchronous client for the Medsplain TX API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from .exceptions import (
|
|
13
|
+
APIConnectionError,
|
|
14
|
+
APIStatusError,
|
|
15
|
+
MedsplainError,
|
|
16
|
+
RateLimitError,
|
|
17
|
+
ServerError,
|
|
18
|
+
exception_for_status,
|
|
19
|
+
)
|
|
20
|
+
from .models import HealthStatus, TranslationResult
|
|
21
|
+
|
|
22
|
+
__all__ = ["Medsplain"]
|
|
23
|
+
|
|
24
|
+
DEFAULT_BASE_URL = "http://localhost:8000"
|
|
25
|
+
DEFAULT_TIMEOUT = 30.0
|
|
26
|
+
DEFAULT_MAX_RETRIES = 2
|
|
27
|
+
TEXT_CHAR_LIMIT = 5000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Medsplain:
|
|
31
|
+
"""Client for the Medsplain TX medical text simplification API.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
api_key: Your ``mds_live_`` API key. Falls back to the ``MEDSPLAIN_API_KEY``
|
|
35
|
+
environment variable when omitted.
|
|
36
|
+
base_url: API root (without the ``/v1`` prefix). Falls back to
|
|
37
|
+
``MEDSPLAIN_BASE_URL`` then to ``http://localhost:8000``.
|
|
38
|
+
timeout: Per-request timeout in seconds.
|
|
39
|
+
max_retries: How many times to retry on connection errors, 429s, and 5xx.
|
|
40
|
+
transport: Optional ``httpx`` transport — primarily for testing.
|
|
41
|
+
|
|
42
|
+
Example:
|
|
43
|
+
>>> from medsplain import Medsplain
|
|
44
|
+
>>> client = Medsplain(api_key="mds_live_...")
|
|
45
|
+
>>> result = client.translate("Patient presents with acute myocardial infarction.")
|
|
46
|
+
>>> print(result.simplified_text)
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
api_key: Optional[str] = None,
|
|
52
|
+
*,
|
|
53
|
+
base_url: Optional[str] = None,
|
|
54
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
55
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
56
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
api_key = api_key or os.getenv("MEDSPLAIN_API_KEY")
|
|
59
|
+
if not api_key:
|
|
60
|
+
raise MedsplainError(
|
|
61
|
+
"An API key is required. Pass api_key=... or set the "
|
|
62
|
+
"MEDSPLAIN_API_KEY environment variable."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
self.api_key = api_key
|
|
66
|
+
self.base_url = (base_url or os.getenv("MEDSPLAIN_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
67
|
+
self.max_retries = max(0, max_retries)
|
|
68
|
+
|
|
69
|
+
self._client = httpx.Client(
|
|
70
|
+
base_url=self.base_url,
|
|
71
|
+
timeout=timeout,
|
|
72
|
+
transport=transport,
|
|
73
|
+
headers={
|
|
74
|
+
"x-api-key": self.api_key,
|
|
75
|
+
"Accept": "application/json",
|
|
76
|
+
"User-Agent": "medsplain-python/0.1.0",
|
|
77
|
+
},
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
# ── Context manager ──────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
def __enter__(self) -> "Medsplain":
|
|
83
|
+
return self
|
|
84
|
+
|
|
85
|
+
def __exit__(
|
|
86
|
+
self,
|
|
87
|
+
exc_type: Optional[type[BaseException]],
|
|
88
|
+
exc: Optional[BaseException],
|
|
89
|
+
tb: Optional[TracebackType],
|
|
90
|
+
) -> None:
|
|
91
|
+
self.close()
|
|
92
|
+
|
|
93
|
+
def close(self) -> None:
|
|
94
|
+
"""Close the underlying HTTP connection pool."""
|
|
95
|
+
self._client.close()
|
|
96
|
+
|
|
97
|
+
# ── Public API ───────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
def translate(self, text: str, *, model: Optional[str] = None) -> TranslationResult:
|
|
100
|
+
"""Simplify medical text into plain language (Claude-backed ``/v1/translate``).
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
text: The medical text to simplify (max 5000 characters).
|
|
104
|
+
model: Optional model hint. The server currently selects the model, so this
|
|
105
|
+
is forwarded but may be ignored.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
A :class:`~medsplain.models.TranslationResult`.
|
|
109
|
+
|
|
110
|
+
Raises:
|
|
111
|
+
ValueError: If ``text`` is empty or exceeds the character limit.
|
|
112
|
+
AuthenticationError, RateLimitError, PermissionDeniedError, ...: on API errors.
|
|
113
|
+
"""
|
|
114
|
+
return self._translate("/v1/translate", text, model)
|
|
115
|
+
|
|
116
|
+
def translate_gemini(self, text: str, *, model: Optional[str] = None) -> TranslationResult:
|
|
117
|
+
"""Same as :meth:`translate` but backed by Gemini (``/v1/translate_test_gemini``)."""
|
|
118
|
+
return self._translate("/v1/translate_test_gemini", text, model)
|
|
119
|
+
|
|
120
|
+
def health_check(self) -> HealthStatus:
|
|
121
|
+
"""Check that the API is reachable and healthy (``GET /health-check``)."""
|
|
122
|
+
data = self._request("GET", "/health-check")
|
|
123
|
+
return HealthStatus.from_response(data)
|
|
124
|
+
|
|
125
|
+
# ── Internals ──────────────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
def _translate(self, path: str, text: str, model: Optional[str]) -> TranslationResult:
|
|
128
|
+
if not text or not text.strip():
|
|
129
|
+
raise ValueError("text must be a non-empty string.")
|
|
130
|
+
if len(text) > TEXT_CHAR_LIMIT:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"text exceeds the {TEXT_CHAR_LIMIT}-character limit (got {len(text)})."
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
form: Dict[str, Any] = {"raw_text": text, "is_guest": "false"}
|
|
136
|
+
if model:
|
|
137
|
+
form["model"] = model
|
|
138
|
+
|
|
139
|
+
data = self._request("POST", path, data=form)
|
|
140
|
+
return TranslationResult.from_response(data)
|
|
141
|
+
|
|
142
|
+
def _request(self, method: str, path: str, *, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
143
|
+
last_exc: Optional[Exception] = None
|
|
144
|
+
|
|
145
|
+
for attempt in range(self.max_retries + 1):
|
|
146
|
+
try:
|
|
147
|
+
response = self._client.request(method, path, data=data)
|
|
148
|
+
except httpx.HTTPError as exc:
|
|
149
|
+
last_exc = APIConnectionError(f"Failed to reach Medsplain API: {exc}")
|
|
150
|
+
if attempt < self.max_retries:
|
|
151
|
+
time.sleep(self._backoff(attempt))
|
|
152
|
+
continue
|
|
153
|
+
raise last_exc from exc
|
|
154
|
+
|
|
155
|
+
if response.is_success:
|
|
156
|
+
return self._parse_json(response)
|
|
157
|
+
|
|
158
|
+
error = self._build_status_error(response)
|
|
159
|
+
should_retry = (
|
|
160
|
+
attempt < self.max_retries
|
|
161
|
+
and isinstance(error, (RateLimitError, ServerError))
|
|
162
|
+
)
|
|
163
|
+
if should_retry:
|
|
164
|
+
time.sleep(error.retry_after or self._backoff(attempt))
|
|
165
|
+
last_exc = error
|
|
166
|
+
continue
|
|
167
|
+
raise error
|
|
168
|
+
|
|
169
|
+
# Only reachable if every attempt raised a retryable connection error.
|
|
170
|
+
assert last_exc is not None
|
|
171
|
+
raise last_exc
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def _backoff(attempt: int) -> float:
|
|
175
|
+
"""Exponential backoff: 0.5s, 1s, 2s, ... capped at 8s."""
|
|
176
|
+
return min(0.5 * (2 ** attempt), 8.0)
|
|
177
|
+
|
|
178
|
+
@staticmethod
|
|
179
|
+
def _parse_json(response: httpx.Response) -> Dict[str, Any]:
|
|
180
|
+
try:
|
|
181
|
+
return response.json()
|
|
182
|
+
except ValueError as exc:
|
|
183
|
+
raise MedsplainError(
|
|
184
|
+
f"Expected a JSON response but got: {response.text[:200]!r}"
|
|
185
|
+
) from exc
|
|
186
|
+
|
|
187
|
+
@staticmethod
|
|
188
|
+
def _build_status_error(response: httpx.Response) -> APIStatusError:
|
|
189
|
+
status_code = response.status_code
|
|
190
|
+
message = response.reason_phrase or "Request failed"
|
|
191
|
+
code: Optional[str] = None
|
|
192
|
+
retry_after: Optional[int] = None
|
|
193
|
+
body: Any = response.text
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
body = response.json()
|
|
197
|
+
except ValueError:
|
|
198
|
+
body = response.text
|
|
199
|
+
|
|
200
|
+
# The API wraps errors as {"detail": {"status", "code", "message", "retry_after"}}.
|
|
201
|
+
if isinstance(body, dict):
|
|
202
|
+
detail = body.get("detail", body)
|
|
203
|
+
if isinstance(detail, dict):
|
|
204
|
+
message = detail.get("message") or message
|
|
205
|
+
code = detail.get("code")
|
|
206
|
+
retry_after = detail.get("retry_after")
|
|
207
|
+
elif isinstance(detail, str):
|
|
208
|
+
message = detail
|
|
209
|
+
|
|
210
|
+
if retry_after is None:
|
|
211
|
+
header = response.headers.get("Retry-After")
|
|
212
|
+
if header and header.isdigit():
|
|
213
|
+
retry_after = int(header)
|
|
214
|
+
|
|
215
|
+
exc_cls = exception_for_status(status_code)
|
|
216
|
+
return exc_cls(
|
|
217
|
+
message,
|
|
218
|
+
status_code=status_code,
|
|
219
|
+
code=code,
|
|
220
|
+
retry_after=retry_after,
|
|
221
|
+
body=body,
|
|
222
|
+
)
|
medsplain/exceptions.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Exception hierarchy for the Medsplain SDK.
|
|
2
|
+
|
|
3
|
+
All errors raised by the SDK inherit from :class:`MedsplainError`, so callers can
|
|
4
|
+
catch everything with a single ``except MedsplainError``. HTTP error responses raise
|
|
5
|
+
a subclass of :class:`APIStatusError` chosen by status code.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MedsplainError(Exception):
|
|
14
|
+
"""Base class for every error raised by the SDK."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class APIConnectionError(MedsplainError):
|
|
18
|
+
"""The request never reached the server (DNS failure, timeout, connection reset)."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class APIStatusError(MedsplainError):
|
|
22
|
+
"""The server returned a non-2xx HTTP status.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
status_code: The HTTP status code (e.g. 401, 429, 500).
|
|
26
|
+
message: Human-readable error message extracted from the response body.
|
|
27
|
+
code: Machine-readable error code from the API (e.g. ``RATE_LIMIT_EXCEEDED``),
|
|
28
|
+
or ``None`` if the response did not include one.
|
|
29
|
+
retry_after: Seconds to wait before retrying, if the API provided it.
|
|
30
|
+
body: The parsed response body (``dict``) or raw text, for debugging.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
message: str,
|
|
36
|
+
*,
|
|
37
|
+
status_code: int,
|
|
38
|
+
code: Optional[str] = None,
|
|
39
|
+
retry_after: Optional[int] = None,
|
|
40
|
+
body: Any = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
super().__init__(message)
|
|
43
|
+
self.message = message
|
|
44
|
+
self.status_code = status_code
|
|
45
|
+
self.code = code
|
|
46
|
+
self.retry_after = retry_after
|
|
47
|
+
self.body = body
|
|
48
|
+
|
|
49
|
+
def __str__(self) -> str:
|
|
50
|
+
prefix = f"[{self.status_code}"
|
|
51
|
+
prefix += f" {self.code}]" if self.code else "]"
|
|
52
|
+
return f"{prefix} {self.message}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BadRequestError(APIStatusError):
|
|
56
|
+
"""400 — the request was malformed or input validation failed."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AuthenticationError(APIStatusError):
|
|
60
|
+
"""401 — the API key is missing, invalid, expired, or revoked."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PermissionDeniedError(APIStatusError):
|
|
64
|
+
"""403 — authenticated, but the organization has no active plan/subscription."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class NotFoundError(APIStatusError):
|
|
68
|
+
"""404 — the requested resource does not exist."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class RateLimitError(APIStatusError):
|
|
72
|
+
"""429 — too many requests, or the organization's token quota is exhausted.
|
|
73
|
+
|
|
74
|
+
Inspect :attr:`code` to distinguish ``RATE_LIMIT_EXCEEDED`` (transient, retry after
|
|
75
|
+
:attr:`retry_after` seconds) from ``TOKEN_QUOTA_EXCEEDED`` (plan limit reached).
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ServerError(APIStatusError):
|
|
80
|
+
"""5xx — something went wrong on the Medsplain side."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
_STATUS_TO_EXCEPTION = {
|
|
84
|
+
400: BadRequestError,
|
|
85
|
+
401: AuthenticationError,
|
|
86
|
+
403: PermissionDeniedError,
|
|
87
|
+
404: NotFoundError,
|
|
88
|
+
429: RateLimitError,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def exception_for_status(status_code: int) -> type[APIStatusError]:
|
|
93
|
+
"""Return the most specific :class:`APIStatusError` subclass for a status code."""
|
|
94
|
+
if status_code in _STATUS_TO_EXCEPTION:
|
|
95
|
+
return _STATUS_TO_EXCEPTION[status_code]
|
|
96
|
+
if status_code >= 500:
|
|
97
|
+
return ServerError
|
|
98
|
+
return APIStatusError
|
medsplain/models.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Typed response models returned by the Medsplain client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Dict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class TranslationResult:
|
|
11
|
+
"""Result of a text simplification call.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
original_text: The cleaned input text the server processed.
|
|
15
|
+
simplified_text: The plain-language simplification (the API field
|
|
16
|
+
``simplified_preview``).
|
|
17
|
+
source_chars: Character count of the input.
|
|
18
|
+
output_chars: Character count of the simplified output.
|
|
19
|
+
is_medical_text: Whether the input was detected as medical content.
|
|
20
|
+
is_conversation: Whether the input was detected as conversational.
|
|
21
|
+
raw: The full, unmodified response payload.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
original_text: str
|
|
25
|
+
simplified_text: str
|
|
26
|
+
source_chars: int
|
|
27
|
+
output_chars: int
|
|
28
|
+
is_medical_text: bool
|
|
29
|
+
is_conversation: bool
|
|
30
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False)
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_response(cls, data: Dict[str, Any]) -> "TranslationResult":
|
|
34
|
+
return cls(
|
|
35
|
+
original_text=data.get("original_text", ""),
|
|
36
|
+
simplified_text=data.get("simplified_preview", ""),
|
|
37
|
+
source_chars=data.get("source_chars", 0),
|
|
38
|
+
output_chars=data.get("output_chars", 0),
|
|
39
|
+
is_medical_text=bool(data.get("is_medical_text", False)),
|
|
40
|
+
is_conversation=bool(data.get("is_conversation", False)),
|
|
41
|
+
raw=data,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class HealthStatus:
|
|
47
|
+
"""Result of a health-check call."""
|
|
48
|
+
|
|
49
|
+
ok: bool
|
|
50
|
+
time: str
|
|
51
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False)
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_response(cls, data: Dict[str, Any]) -> "HealthStatus":
|
|
55
|
+
return cls(ok=bool(data.get("ok", False)), time=data.get("time", ""), raw=data)
|
medsplain/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: medsplain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the Medsplain TX medical text simplification API
|
|
5
|
+
Project-URL: Homepage, https://github.com/medsplain/medsplain-python
|
|
6
|
+
Project-URL: Documentation, https://github.com/medsplain/medsplain-python#readme
|
|
7
|
+
Project-URL: Issues, https://github.com/medsplain/medsplain-python/issues
|
|
8
|
+
Author: Medsplain TX
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: api,client,medical,medsplain,sdk,text-simplification
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Healthcare Industry
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Requires-Dist: httpx>=0.24
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build>=1.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: mypy>=1.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
|
29
|
+
Requires-Dist: twine>=4.0; extra == 'dev'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# Medsplain TX — Python SDK
|
|
33
|
+
|
|
34
|
+
Official Python client for the **Medsplain TX** medical text simplification API. Send
|
|
35
|
+
clinical / medical text and get back a plain-language explanation.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install medsplain
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
> Until this is published to PyPI, install from source — see [Local development](#local-development).
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from medsplain import Medsplain
|
|
49
|
+
|
|
50
|
+
client = Medsplain(api_key="mds_live_...")
|
|
51
|
+
|
|
52
|
+
result = client.translate("Patient presents with acute myocardial infarction.")
|
|
53
|
+
print(result.simplified_text)
|
|
54
|
+
print(f"{result.source_chars} chars in, {result.output_chars} chars out")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The client is a context manager, which closes the connection pool for you:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
with Medsplain(api_key="mds_live_...") as client:
|
|
61
|
+
result = client.translate("CBC shows leukocytosis with left shift.")
|
|
62
|
+
print(result.simplified_text)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Configuration
|
|
66
|
+
|
|
67
|
+
| Argument | Env var | Default | Notes |
|
|
68
|
+
| ------------- | -------------------- | ------------------------ | -------------------------------------------------- |
|
|
69
|
+
| `api_key` | `MEDSPLAIN_API_KEY` | — | Required. Your `mds_live_` key. |
|
|
70
|
+
| `base_url` | `MEDSPLAIN_BASE_URL` | `http://localhost:8000` | API root, **without** the `/v1` prefix. |
|
|
71
|
+
| `timeout` | — | `30.0` | Per-request timeout in seconds. |
|
|
72
|
+
| `max_retries` | — | `2` | Retries on connection errors, `429`, and `5xx`. |
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import os
|
|
76
|
+
client = Medsplain(
|
|
77
|
+
api_key=os.environ["MEDSPLAIN_API_KEY"],
|
|
78
|
+
base_url="https://your-medsplain-host.example.com",
|
|
79
|
+
timeout=60.0,
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## API
|
|
84
|
+
|
|
85
|
+
### `translate(text, *, model=None) -> TranslationResult`
|
|
86
|
+
Simplify medical text using the Claude-backed endpoint (`POST /v1/translate`).
|
|
87
|
+
`text` must be non-empty and at most **5000 characters**.
|
|
88
|
+
|
|
89
|
+
### `translate_gemini(text, *, model=None) -> TranslationResult`
|
|
90
|
+
Same contract, backed by Gemini (`POST /v1/translate_test_gemini`).
|
|
91
|
+
|
|
92
|
+
### `health_check() -> HealthStatus`
|
|
93
|
+
Verify the API is reachable (`GET /health-check`).
|
|
94
|
+
|
|
95
|
+
### `TranslationResult`
|
|
96
|
+
| Field | Type | Description |
|
|
97
|
+
| ----------------- | ------ | ------------------------------------------------- |
|
|
98
|
+
| `original_text` | `str` | Cleaned input text the server processed. |
|
|
99
|
+
| `simplified_text` | `str` | The plain-language simplification. |
|
|
100
|
+
| `source_chars` | `int` | Character count of the input. |
|
|
101
|
+
| `output_chars` | `int` | Character count of the output. |
|
|
102
|
+
| `is_medical_text` | `bool` | Whether the input was detected as medical. |
|
|
103
|
+
| `is_conversation` | `bool` | Whether the input was detected as conversational. |
|
|
104
|
+
| `raw` | `dict` | Full, unmodified response payload. |
|
|
105
|
+
|
|
106
|
+
## Error handling
|
|
107
|
+
|
|
108
|
+
Every error inherits from `MedsplainError`. HTTP failures raise an `APIStatusError`
|
|
109
|
+
subclass chosen by status code:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from medsplain import (
|
|
113
|
+
Medsplain, AuthenticationError, RateLimitError,
|
|
114
|
+
PermissionDeniedError, APIStatusError,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
client = Medsplain(api_key="mds_live_...")
|
|
118
|
+
try:
|
|
119
|
+
result = client.translate("...")
|
|
120
|
+
except AuthenticationError:
|
|
121
|
+
... # 401 — key missing/invalid/expired/revoked
|
|
122
|
+
except RateLimitError as e:
|
|
123
|
+
print("retry after", e.retry_after) # 429 — rate limit or token quota
|
|
124
|
+
except PermissionDeniedError:
|
|
125
|
+
... # 403 — no active plan / subscription
|
|
126
|
+
except APIStatusError as e:
|
|
127
|
+
print(e.status_code, e.code, e.message)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
| Exception | Status | Meaning |
|
|
131
|
+
| ----------------------- | ------ | ------------------------------------------------ |
|
|
132
|
+
| `BadRequestError` | 400 | Malformed request / validation error. |
|
|
133
|
+
| `AuthenticationError` | 401 | API key missing, invalid, expired, or revoked. |
|
|
134
|
+
| `PermissionDeniedError` | 403 | No active plan or subscription. |
|
|
135
|
+
| `NotFoundError` | 404 | Resource not found. |
|
|
136
|
+
| `RateLimitError` | 429 | Rate limit hit or token quota exhausted. |
|
|
137
|
+
| `ServerError` | 5xx | Server-side failure. |
|
|
138
|
+
| `APIConnectionError` | — | The request never reached the server. |
|
|
139
|
+
|
|
140
|
+
## Local development
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
cd sdk
|
|
144
|
+
python -m venv .venv
|
|
145
|
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
146
|
+
pip install -e ".[dev]"
|
|
147
|
+
|
|
148
|
+
pytest # run tests
|
|
149
|
+
ruff check . # lint
|
|
150
|
+
mypy src/ # type-check
|
|
151
|
+
python -m build # build wheel + sdist into dist/
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
medsplain/__init__.py,sha256=964Lg_w4vpTP3g4VLXqyUCZd5rdfZavABxGkPD0zPIo,936
|
|
2
|
+
medsplain/client.py,sha256=YhsKnwZ_Vl1eRlgYxszl5bVX_Gxn1Owpj4xSXMDbJUo,8197
|
|
3
|
+
medsplain/exceptions.py,sha256=pkvOzXxiJp2zKjfu3XEfe3aAOIc_jqWNxeSZxlNfOBQ,3070
|
|
4
|
+
medsplain/models.py,sha256=ER9e7tqTTccPLVx8GqghZd6H4berVdjI74IaIPjfuD0,1840
|
|
5
|
+
medsplain/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
medsplain-0.1.0.dist-info/METADATA,sha256=k7RjARHmdRuI3TXBIcJmtAyOn7qL_IRGTOdWM2bSQ1s,6259
|
|
7
|
+
medsplain-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
8
|
+
medsplain-0.1.0.dist-info/licenses/LICENSE,sha256=RDklkT1kP0x48XMGF-QFyM5i_UpKnfEF4n4HC2oZ_-g,1069
|
|
9
|
+
medsplain-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Medsplain TX
|
|
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.
|