medisync 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.
- medisync/__init__.py +102 -0
- medisync/_app_auth.py +253 -0
- medisync/_client.py +26 -0
- medisync/_core.py +576 -0
- medisync/_exceptions.py +317 -0
- medisync/_files.py +62 -0
- medisync/_generated/__init__.py +1 -0
- medisync/_generated/connect_types.py +2546 -0
- medisync/_generated/live_types.py +244 -0
- medisync/_generated/operations.py +1542 -0
- medisync/_generated/platform_types.py +788 -0
- medisync/_generated/resources.py +6494 -0
- medisync/_helpers/__init__.py +0 -0
- medisync/_helpers/capabilities.py +168 -0
- medisync/_helpers/follow.py +146 -0
- medisync/_helpers/transcriptions.py +74 -0
- medisync/_live.py +743 -0
- medisync/_models.py +51 -0
- medisync/_operation.py +44 -0
- medisync/_pagination.py +115 -0
- medisync/_types.py +23 -0
- medisync/_version.py +1 -0
- medisync/connect/__init__.py +69 -0
- medisync/py.typed +0 -0
- medisync/types/__init__.py +11 -0
- medisync/types/connect.py +4 -0
- medisync-0.1.0.dist-info/METADATA +174 -0
- medisync-0.1.0.dist-info/RECORD +30 -0
- medisync-0.1.0.dist-info/WHEEL +4 -0
- medisync-0.1.0.dist-info/licenses/LICENSE +202 -0
medisync/__init__.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""The MediSync Python SDK.
|
|
2
|
+
|
|
3
|
+
from medisync import MediSync
|
|
4
|
+
|
|
5
|
+
client = MediSync() # reads MEDISYNC_API_KEY
|
|
6
|
+
models = client.models.list()
|
|
7
|
+
|
|
8
|
+
Everything the API generates is a draft that a clinician reviews and releases.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._app_auth import AppAuthError, AppCredentials, AppTokenSource, AsyncAppTokenSource
|
|
12
|
+
from ._client import AsyncMediSync, MediSync
|
|
13
|
+
from ._core import DEFAULT_BASE_URL, ResponseInfo
|
|
14
|
+
from ._exceptions import (
|
|
15
|
+
AgentOfflineError,
|
|
16
|
+
AlreadyTransferredError,
|
|
17
|
+
APIConnectionError,
|
|
18
|
+
APIError,
|
|
19
|
+
APITimeoutError,
|
|
20
|
+
AuthenticationError,
|
|
21
|
+
CapabilityError,
|
|
22
|
+
ConflictError,
|
|
23
|
+
GatewayTimeoutError,
|
|
24
|
+
InternalServerError,
|
|
25
|
+
InvalidRequestError,
|
|
26
|
+
LicenceRequiredError,
|
|
27
|
+
MediSyncError,
|
|
28
|
+
NotFoundError,
|
|
29
|
+
NotSupportedError,
|
|
30
|
+
OperationNotImplementedError,
|
|
31
|
+
PermissionDeniedError,
|
|
32
|
+
PlanExpiredError,
|
|
33
|
+
PlanStaleError,
|
|
34
|
+
ProductNotEnabledError,
|
|
35
|
+
RateLimitError,
|
|
36
|
+
RequestTooLargeError,
|
|
37
|
+
ServiceUnavailableError,
|
|
38
|
+
TargetError,
|
|
39
|
+
UnverifiedVerbError,
|
|
40
|
+
VerbNotGrantedError,
|
|
41
|
+
)
|
|
42
|
+
from ._files import FileTypes
|
|
43
|
+
from ._generated.operations import API_VERSION, HELPERS, OPERATIONS
|
|
44
|
+
from ._helpers.follow import TransferWaitTimeoutError
|
|
45
|
+
from ._helpers.transcriptions import TranscriptionWaitTimeoutError
|
|
46
|
+
from ._live import AsyncLiveStream, LiveStream, LiveStreamError, StreamReconnecting
|
|
47
|
+
from ._pagination import AsyncCursorPage, AsyncPaginator, SyncCursorPage
|
|
48
|
+
from ._types import NOT_GIVEN, NotGiven
|
|
49
|
+
from ._version import __version__
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"MediSync",
|
|
53
|
+
"AsyncMediSync",
|
|
54
|
+
"DEFAULT_BASE_URL",
|
|
55
|
+
"API_VERSION",
|
|
56
|
+
"OPERATIONS",
|
|
57
|
+
"HELPERS",
|
|
58
|
+
"ResponseInfo",
|
|
59
|
+
"NOT_GIVEN",
|
|
60
|
+
"NotGiven",
|
|
61
|
+
"FileTypes",
|
|
62
|
+
"SyncCursorPage",
|
|
63
|
+
"AsyncCursorPage",
|
|
64
|
+
"AsyncPaginator",
|
|
65
|
+
"LiveStream",
|
|
66
|
+
"AsyncLiveStream",
|
|
67
|
+
"LiveStreamError",
|
|
68
|
+
"StreamReconnecting",
|
|
69
|
+
"AppCredentials",
|
|
70
|
+
"AppTokenSource",
|
|
71
|
+
"AsyncAppTokenSource",
|
|
72
|
+
"AppAuthError",
|
|
73
|
+
"TransferWaitTimeoutError",
|
|
74
|
+
"TranscriptionWaitTimeoutError",
|
|
75
|
+
"MediSyncError",
|
|
76
|
+
"APIError",
|
|
77
|
+
"APIConnectionError",
|
|
78
|
+
"APITimeoutError",
|
|
79
|
+
"InvalidRequestError",
|
|
80
|
+
"AuthenticationError",
|
|
81
|
+
"PermissionDeniedError",
|
|
82
|
+
"ProductNotEnabledError",
|
|
83
|
+
"NotFoundError",
|
|
84
|
+
"ConflictError",
|
|
85
|
+
"AlreadyTransferredError",
|
|
86
|
+
"PlanStaleError",
|
|
87
|
+
"PlanExpiredError",
|
|
88
|
+
"RequestTooLargeError",
|
|
89
|
+
"CapabilityError",
|
|
90
|
+
"NotSupportedError",
|
|
91
|
+
"UnverifiedVerbError",
|
|
92
|
+
"VerbNotGrantedError",
|
|
93
|
+
"LicenceRequiredError",
|
|
94
|
+
"RateLimitError",
|
|
95
|
+
"InternalServerError",
|
|
96
|
+
"OperationNotImplementedError",
|
|
97
|
+
"TargetError",
|
|
98
|
+
"ServiceUnavailableError",
|
|
99
|
+
"AgentOfflineError",
|
|
100
|
+
"GatewayTimeoutError",
|
|
101
|
+
"__version__",
|
|
102
|
+
]
|
medisync/_app_auth.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""App mode of MediSync Connect: a partner app authenticates with its own key pair.
|
|
2
|
+
|
|
3
|
+
The SDK signs a client assertion (RFC 7523, `private_key_jwt`) with the app's private key, trades
|
|
4
|
+
it at Connect's token endpoint for a 15-minute access token, and gets a new one before it expires.
|
|
5
|
+
The private key never leaves the process; MediSync holds only the public key. Signing needs the
|
|
6
|
+
`cryptography` package: `pip install "medisync[app]"`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import base64
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import uuid
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Dict, Optional, Sequence, Tuple, cast
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
from typing_extensions import Literal
|
|
23
|
+
|
|
24
|
+
from ._exceptions import APIConnectionError, MediSyncError
|
|
25
|
+
|
|
26
|
+
__all__ = ["AppCredentials", "AppAuthError", "AppTokenSource", "AsyncAppTokenSource", "client_assertion", "DEFAULT_ISSUER"]
|
|
27
|
+
|
|
28
|
+
DEFAULT_ISSUER = "https://connect.medisync.me"
|
|
29
|
+
ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
|
|
30
|
+
REFRESH_MARGIN = 60.0
|
|
31
|
+
"""A new token this long before the old one expires, in seconds."""
|
|
32
|
+
ASSERTION_SECONDS = 60
|
|
33
|
+
"""An assertion lives one minute; Connect allows five."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class AppCredentials:
|
|
38
|
+
"""The credentials of a MediSync Connect app."""
|
|
39
|
+
|
|
40
|
+
client_id: str
|
|
41
|
+
"""The app id from the console, `app_…`. It is the OAuth client_id."""
|
|
42
|
+
key_id: str
|
|
43
|
+
"""The key id (`kid`) the public key has in the console."""
|
|
44
|
+
private_key: Any
|
|
45
|
+
"""A PKCS8 PEM (`-----BEGIN PRIVATE KEY-----`) or a `cryptography` private key. EC P-256 signs with ES256, Ed25519 with EdDSA."""
|
|
46
|
+
installation_id: Optional[str] = None
|
|
47
|
+
"""Act at one site: the installation id (`ins_…`). Leave it out for an app token (sites.create, lists)."""
|
|
48
|
+
verbs: Sequence[str] = field(default_factory=lambda: ())
|
|
49
|
+
"""Fewer verbs than the installation holds, for this client's token."""
|
|
50
|
+
scopes: Sequence[str] = field(default_factory=lambda: ())
|
|
51
|
+
"""Fewer scopes than the app holds."""
|
|
52
|
+
environment: Optional[Literal["live", "test"]] = None
|
|
53
|
+
"""An app token of an app with a live and a test project names the environment."""
|
|
54
|
+
issuer: str = DEFAULT_ISSUER
|
|
55
|
+
"""The authorization server."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class AppAuthError(MediSyncError):
|
|
59
|
+
"""The token endpoint refused: `error` is the OAuth error code (RFC 6749 5.2)."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, status: int, error: str, description: str) -> None:
|
|
62
|
+
super().__init__(f"{error}: {description}")
|
|
63
|
+
self.status = status
|
|
64
|
+
self.error = error
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _b64url(data: bytes) -> str:
|
|
68
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _signer(private_key: Any) -> Tuple[str, Any]:
|
|
72
|
+
try:
|
|
73
|
+
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
|
|
74
|
+
from cryptography.hazmat.primitives.serialization import load_pem_private_key
|
|
75
|
+
except ImportError as e: # pragma: no cover
|
|
76
|
+
raise MediSyncError('App auth needs the cryptography package: pip install "medisync[app]".') from e
|
|
77
|
+
key = private_key
|
|
78
|
+
if isinstance(private_key, (str, bytes)):
|
|
79
|
+
text = private_key.decode() if isinstance(private_key, bytes) else private_key
|
|
80
|
+
text = text.replace("\\n", "\n")
|
|
81
|
+
if "-----BEGIN PRIVATE KEY-----" not in text:
|
|
82
|
+
raise TypeError("private_key must be a PKCS8 PEM (-----BEGIN PRIVATE KEY-----).")
|
|
83
|
+
key = load_pem_private_key(text.encode(), password=None)
|
|
84
|
+
if isinstance(key, ec.EllipticCurvePrivateKey) and isinstance(key.curve, ec.SECP256R1):
|
|
85
|
+
return "ES256", key
|
|
86
|
+
if isinstance(key, ed25519.Ed25519PrivateKey):
|
|
87
|
+
return "EdDSA", key
|
|
88
|
+
raise TypeError("private_key must be an EC P-256 or an Ed25519 private key.")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def client_assertion(credentials: AppCredentials, audience: str, now: Optional[int] = None) -> str:
|
|
92
|
+
"""A client assertion (RFC 7523 2.2): iss = sub = client_id, aud = the endpoint, one-time jti."""
|
|
93
|
+
from cryptography.hazmat.primitives import hashes
|
|
94
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
95
|
+
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
|
|
96
|
+
|
|
97
|
+
alg, key = _signer(credentials.private_key)
|
|
98
|
+
issued = int(time.time()) if now is None else now
|
|
99
|
+
header = _b64url(json.dumps({"alg": alg, "kid": credentials.key_id, "typ": "JWT"}, separators=(",", ":")).encode())
|
|
100
|
+
payload = _b64url(
|
|
101
|
+
json.dumps(
|
|
102
|
+
{
|
|
103
|
+
"iss": credentials.client_id,
|
|
104
|
+
"sub": credentials.client_id,
|
|
105
|
+
"aud": audience,
|
|
106
|
+
"iat": issued,
|
|
107
|
+
"exp": issued + ASSERTION_SECONDS,
|
|
108
|
+
"jti": str(uuid.uuid4()),
|
|
109
|
+
},
|
|
110
|
+
separators=(",", ":"),
|
|
111
|
+
).encode()
|
|
112
|
+
)
|
|
113
|
+
signing_input = f"{header}.{payload}".encode()
|
|
114
|
+
if alg == "ES256":
|
|
115
|
+
der = key.sign(signing_input, ec.ECDSA(hashes.SHA256()))
|
|
116
|
+
r, s = decode_dss_signature(der)
|
|
117
|
+
signature = r.to_bytes(32, "big") + s.to_bytes(32, "big")
|
|
118
|
+
else:
|
|
119
|
+
signature = key.sign(signing_input)
|
|
120
|
+
return f"{header}.{payload}.{_b64url(signature)}"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class _TokenBase:
|
|
124
|
+
def __init__(self, credentials: AppCredentials) -> None:
|
|
125
|
+
if not re.fullmatch(r"app_[A-Za-z0-9]{8,32}", credentials.client_id):
|
|
126
|
+
raise TypeError("client_id is the app id from the console, app_….")
|
|
127
|
+
self.credentials = credentials
|
|
128
|
+
self.issuer = credentials.issuer.rstrip("/")
|
|
129
|
+
self._token: Optional[Tuple[str, float, Dict[str, Any]]] = None
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def answer(self) -> Optional[Dict[str, Any]]:
|
|
133
|
+
"""The last token answer: installation id and authorization details. None before the first call."""
|
|
134
|
+
return self._token[2] if self._token else None
|
|
135
|
+
|
|
136
|
+
def clear(self) -> None:
|
|
137
|
+
"""Drops the token, so the next call fetches one (after a 401 `invalid_token`)."""
|
|
138
|
+
self._token = None
|
|
139
|
+
|
|
140
|
+
def _fresh(self) -> Optional[str]:
|
|
141
|
+
if self._token and self._token[1] - REFRESH_MARGIN > time.time():
|
|
142
|
+
return self._token[0]
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
def _fields(self) -> Dict[str, str]:
|
|
146
|
+
c = self.credentials
|
|
147
|
+
fields: Dict[str, str] = {"grant_type": "client_credentials"}
|
|
148
|
+
if c.scopes:
|
|
149
|
+
fields["scope"] = " ".join(c.scopes)
|
|
150
|
+
if c.installation_id:
|
|
151
|
+
detail: Dict[str, Any] = {"type": "medisync_connect", "installation_id": c.installation_id}
|
|
152
|
+
if c.verbs:
|
|
153
|
+
detail["verbs"] = [{"verb": v, "roles": []} for v in c.verbs]
|
|
154
|
+
fields["authorization_details"] = json.dumps([detail])
|
|
155
|
+
elif c.environment:
|
|
156
|
+
fields["environment"] = c.environment
|
|
157
|
+
return fields
|
|
158
|
+
|
|
159
|
+
def _form(self, path: str, fields: Dict[str, str]) -> Tuple[str, Dict[str, str]]:
|
|
160
|
+
url = f"{self.issuer}{path}"
|
|
161
|
+
return url, {**fields, "client_assertion_type": ASSERTION_TYPE, "client_assertion": client_assertion(self.credentials, url)}
|
|
162
|
+
|
|
163
|
+
@staticmethod
|
|
164
|
+
def _read(response: httpx.Response) -> Dict[str, Any]:
|
|
165
|
+
text = response.text
|
|
166
|
+
try:
|
|
167
|
+
body: Any = json.loads(text) if text else {}
|
|
168
|
+
except ValueError:
|
|
169
|
+
body = None
|
|
170
|
+
data = cast(Dict[str, Any], body) if isinstance(body, dict) else None
|
|
171
|
+
if not response.is_success:
|
|
172
|
+
error = data.get("error") if data else None
|
|
173
|
+
description = data.get("error_description") if data else None
|
|
174
|
+
raise AppAuthError(
|
|
175
|
+
response.status_code,
|
|
176
|
+
error if isinstance(error, str) else f"http_{response.status_code}",
|
|
177
|
+
description if isinstance(description, str) else text[:200],
|
|
178
|
+
)
|
|
179
|
+
return data or {}
|
|
180
|
+
|
|
181
|
+
def _store(self, answer: Dict[str, Any]) -> str:
|
|
182
|
+
token = answer.get("access_token")
|
|
183
|
+
expires = answer.get("expires_in")
|
|
184
|
+
if not isinstance(token, str) or not isinstance(expires, (int, float)):
|
|
185
|
+
raise AppAuthError(502, "invalid_response", "The token endpoint answered without a token.")
|
|
186
|
+
self._token = (token, time.time() + float(expires), answer)
|
|
187
|
+
return token
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class AppTokenSource(_TokenBase):
|
|
191
|
+
"""Gets and keeps an access token for the synchronous client. Share one between clients."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, credentials: AppCredentials, *, http_client: Optional[httpx.Client] = None) -> None:
|
|
194
|
+
super().__init__(credentials)
|
|
195
|
+
self._http = http_client or httpx.Client()
|
|
196
|
+
self._lock = threading.Lock()
|
|
197
|
+
|
|
198
|
+
def get(self) -> str:
|
|
199
|
+
"""The current token; a new one when it expires within a minute."""
|
|
200
|
+
with self._lock:
|
|
201
|
+
fresh = self._fresh()
|
|
202
|
+
if fresh:
|
|
203
|
+
return fresh
|
|
204
|
+
return self._store(self._post("/oauth/token", self._fields()))
|
|
205
|
+
|
|
206
|
+
def revoke(self) -> None:
|
|
207
|
+
"""Ends the current token at Connect (RFC 7009), for example when the app signs out."""
|
|
208
|
+
current = self._token[0] if self._token else None
|
|
209
|
+
self._token = None
|
|
210
|
+
if current:
|
|
211
|
+
self._post("/oauth/revoke", {"token": current})
|
|
212
|
+
|
|
213
|
+
def _post(self, path: str, fields: Dict[str, str]) -> Dict[str, Any]:
|
|
214
|
+
url, form = self._form(path, fields)
|
|
215
|
+
try:
|
|
216
|
+
response = self._http.post(url, data=form, headers={"accept": "application/json"})
|
|
217
|
+
except httpx.TransportError as e:
|
|
218
|
+
raise APIConnectionError(f"POST {path} failed: {e}") from e
|
|
219
|
+
return self._read(response)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class AsyncAppTokenSource(_TokenBase):
|
|
223
|
+
"""Gets and keeps an access token for the async client. Share one between clients."""
|
|
224
|
+
|
|
225
|
+
def __init__(self, credentials: AppCredentials, *, http_client: Optional[httpx.AsyncClient] = None) -> None:
|
|
226
|
+
super().__init__(credentials)
|
|
227
|
+
self._http = http_client or httpx.AsyncClient()
|
|
228
|
+
self._lock: Optional[asyncio.Lock] = None
|
|
229
|
+
|
|
230
|
+
async def get(self) -> str:
|
|
231
|
+
"""The current token; a new one when it expires within a minute. Calls at the same moment share one request."""
|
|
232
|
+
if self._lock is None:
|
|
233
|
+
self._lock = asyncio.Lock()
|
|
234
|
+
async with self._lock:
|
|
235
|
+
fresh = self._fresh()
|
|
236
|
+
if fresh:
|
|
237
|
+
return fresh
|
|
238
|
+
return self._store(await self._post("/oauth/token", self._fields()))
|
|
239
|
+
|
|
240
|
+
async def revoke(self) -> None:
|
|
241
|
+
"""Ends the current token at Connect (RFC 7009)."""
|
|
242
|
+
current = self._token[0] if self._token else None
|
|
243
|
+
self._token = None
|
|
244
|
+
if current:
|
|
245
|
+
await self._post("/oauth/revoke", {"token": current})
|
|
246
|
+
|
|
247
|
+
async def _post(self, path: str, fields: Dict[str, str]) -> Dict[str, Any]:
|
|
248
|
+
url, form = self._form(path, fields)
|
|
249
|
+
try:
|
|
250
|
+
response = await self._http.post(url, data=form, headers={"accept": "application/json"})
|
|
251
|
+
except httpx.TransportError as e:
|
|
252
|
+
raise APIConnectionError(f"POST {path} failed: {e}") from e
|
|
253
|
+
return self._read(response)
|
medisync/_client.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ._generated.resources import AsyncMediSyncResources, MediSyncResources
|
|
4
|
+
|
|
5
|
+
__all__ = ["MediSync", "AsyncMediSync"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MediSync(MediSyncResources):
|
|
9
|
+
"""The MediSync API client: speech, notes and letters, ICD-10-GM coding, decisions, account
|
|
10
|
+
reads and MediSync Connect. One method per API operation, named after the operation:
|
|
11
|
+
|
|
12
|
+
client = MediSync() # reads MEDISYNC_API_KEY
|
|
13
|
+
note = client.notes.create(...)
|
|
14
|
+
transfer = client.connect.transfers.create(plan_id=plan.id, release=release)
|
|
15
|
+
|
|
16
|
+
Arguments: `api_key` (default: MEDISYNC_API_KEY), `connect_app` (MediSync Connect app
|
|
17
|
+
credentials), `base_url` (default: MEDISYNC_BASE_URL, else https://api.medisync.me),
|
|
18
|
+
`version` (the MediSync-Version header), `timeout` (seconds per attempt, default 120),
|
|
19
|
+
`max_retries` (default 2), `default_headers`, `http_client` and `on_response`.
|
|
20
|
+
|
|
21
|
+
Everything the API generates is a draft that a clinician reviews and releases.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AsyncMediSync(AsyncMediSyncResources):
|
|
26
|
+
"""The asyncio form of `MediSync`. Takes the same arguments."""
|