playscan 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.
- playscan/__init__.py +24 -0
- playscan/_client.py +245 -0
- playscan/_errors.py +51 -0
- playscan/_types.py +62 -0
- playscan/cli.py +82 -0
- playscan/py.typed +0 -0
- playscan-0.1.0.dist-info/METADATA +154 -0
- playscan-0.1.0.dist-info/RECORD +11 -0
- playscan-0.1.0.dist-info/WHEEL +4 -0
- playscan-0.1.0.dist-info/entry_points.txt +2 -0
- playscan-0.1.0.dist-info/licenses/LICENSE +21 -0
playscan/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""PlayScan: turn photos and PDFs of printed sheet music into MusicXML or MIDI.
|
|
2
|
+
|
|
3
|
+
Quickstart::
|
|
4
|
+
|
|
5
|
+
from playscan import PlayScan
|
|
6
|
+
result = PlayScan().scan("page1.jpg") # key from PLAYSCAN_API_KEY
|
|
7
|
+
result.save() # writes score.musicxml
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from ._client import FORMATS, PlayScan, __version__
|
|
11
|
+
from ._errors import PlayScanError, ScanFailedError, ScanTimeoutError
|
|
12
|
+
from ._types import Result, Scan, ScanStatus
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"FORMATS",
|
|
16
|
+
"PlayScan",
|
|
17
|
+
"PlayScanError",
|
|
18
|
+
"Result",
|
|
19
|
+
"Scan",
|
|
20
|
+
"ScanFailedError",
|
|
21
|
+
"ScanStatus",
|
|
22
|
+
"ScanTimeoutError",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
playscan/_client.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""HTTP client for the PlayScan API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
|
|
12
|
+
from ._errors import PlayScanError, ScanFailedError, ScanTimeoutError
|
|
13
|
+
from ._types import Result, Scan, ScanStatus
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
|
|
17
|
+
DEFAULT_BASE_URL = "https://api.playscan.app"
|
|
18
|
+
FORMATS = ("musicxml", "mxl", "midi", "zip")
|
|
19
|
+
_FALLBACK_NAMES = {"musicxml": "score.musicxml", "mxl": "score.mxl", "midi": "score.mid", "zip": "result.zip"}
|
|
20
|
+
|
|
21
|
+
FileInput = Union[str, "os.PathLike[str]", bytes, bytearray, IO[bytes]]
|
|
22
|
+
"""A path, raw bytes, or a binary file object."""
|
|
23
|
+
Files = Union[FileInput, Sequence[FileInput]]
|
|
24
|
+
ProgressCallback = Callable[[ScanStatus], None]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _int_or_none(value: Optional[str]) -> Optional[int]:
|
|
28
|
+
try:
|
|
29
|
+
return int(value) if value is not None else None
|
|
30
|
+
except ValueError:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _read_files(files: Files) -> List[Tuple[str, Tuple[str, bytes, str]]]:
|
|
35
|
+
"""Read every input into memory up front so a retried request can resend it."""
|
|
36
|
+
single = isinstance(files, (str, os.PathLike, bytes, bytearray)) or hasattr(files, "read")
|
|
37
|
+
items: Sequence[Any] = [files] if single else list(files) # type: ignore[arg-type]
|
|
38
|
+
if not items:
|
|
39
|
+
raise ValueError("files must contain at least one file")
|
|
40
|
+
parts = []
|
|
41
|
+
for i, item in enumerate(items, 1):
|
|
42
|
+
name = f"page{i}"
|
|
43
|
+
if isinstance(item, (str, os.PathLike)):
|
|
44
|
+
name = os.path.basename(os.fspath(item))
|
|
45
|
+
with open(item, "rb") as f:
|
|
46
|
+
data = f.read()
|
|
47
|
+
elif isinstance(item, (bytes, bytearray)):
|
|
48
|
+
data = bytes(item)
|
|
49
|
+
elif hasattr(item, "read"):
|
|
50
|
+
data = item.read()
|
|
51
|
+
if isinstance(getattr(item, "name", None), str):
|
|
52
|
+
name = os.path.basename(item.name)
|
|
53
|
+
else:
|
|
54
|
+
raise TypeError(f"unsupported file input: {type(item).__name__}")
|
|
55
|
+
if not isinstance(data, bytes):
|
|
56
|
+
raise TypeError("file objects must be opened in binary mode")
|
|
57
|
+
parts.append(("files", (name or f"page{i}", data, "application/octet-stream")))
|
|
58
|
+
return parts
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _status_from(data: Dict[str, Any]) -> ScanStatus:
|
|
62
|
+
return ScanStatus(
|
|
63
|
+
id=data["id"],
|
|
64
|
+
status=data["status"],
|
|
65
|
+
progress=data.get("progress") or 0,
|
|
66
|
+
pages=data.get("pages"),
|
|
67
|
+
charged_pages=data.get("chargedPages"),
|
|
68
|
+
error=data.get("error"),
|
|
69
|
+
queue_position=data.get("queuePosition"),
|
|
70
|
+
eta_seconds=data.get("etaSeconds"),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class PlayScan:
|
|
75
|
+
"""Client for the PlayScan API.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
api_key: Your ``ps_live_...`` key. Defaults to the ``PLAYSCAN_API_KEY`` environment variable.
|
|
79
|
+
base_url: API base URL. Defaults to ``PLAYSCAN_BASE_URL`` or ``https://api.playscan.app``.
|
|
80
|
+
timeout: Per-request HTTP timeout in seconds.
|
|
81
|
+
max_retries: How many times to retry ``rate_limited`` (429) and ``busy`` (503) responses.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
api_key: Optional[str] = None,
|
|
87
|
+
*,
|
|
88
|
+
base_url: Optional[str] = None,
|
|
89
|
+
timeout: float = 120,
|
|
90
|
+
max_retries: int = 5,
|
|
91
|
+
) -> None:
|
|
92
|
+
key = api_key or os.environ.get("PLAYSCAN_API_KEY")
|
|
93
|
+
if not key:
|
|
94
|
+
raise PlayScanError(
|
|
95
|
+
0, "missing_api_key", "No API key. Pass api_key= or set PLAYSCAN_API_KEY (get one at https://developer.playscan.app)."
|
|
96
|
+
)
|
|
97
|
+
self.base_url = (base_url or os.environ.get("PLAYSCAN_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
98
|
+
self.timeout = timeout
|
|
99
|
+
self.max_retries = max_retries
|
|
100
|
+
self._session = requests.Session()
|
|
101
|
+
self._session.headers.update({"Authorization": f"Bearer {key}", "User-Agent": f"playscan-python/{__version__}"})
|
|
102
|
+
|
|
103
|
+
def close(self) -> None:
|
|
104
|
+
"""Close the underlying HTTP session."""
|
|
105
|
+
self._session.close()
|
|
106
|
+
|
|
107
|
+
def __enter__(self) -> "PlayScan":
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
def __exit__(self, *exc: object) -> None:
|
|
111
|
+
self.close()
|
|
112
|
+
|
|
113
|
+
# -- low level -------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> requests.Response:
|
|
116
|
+
attempt = 0
|
|
117
|
+
while True:
|
|
118
|
+
try:
|
|
119
|
+
resp = self._session.request(method, self.base_url + path, timeout=self.timeout, **kwargs)
|
|
120
|
+
except requests.RequestException as e:
|
|
121
|
+
raise PlayScanError(0, "network_error", str(e)) from e
|
|
122
|
+
if resp.status_code < 400:
|
|
123
|
+
return resp
|
|
124
|
+
err = self._error_from(resp)
|
|
125
|
+
retryable = (resp.status_code == 429 and err.code == "rate_limited") or (
|
|
126
|
+
resp.status_code == 503 and err.code == "busy"
|
|
127
|
+
)
|
|
128
|
+
if not retryable or attempt >= self.max_retries:
|
|
129
|
+
raise err
|
|
130
|
+
attempt += 1
|
|
131
|
+
time.sleep(min(err.retry_after if err.retry_after is not None else 2.0, 60.0))
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def _error_from(resp: requests.Response) -> PlayScanError:
|
|
135
|
+
retry_after: Optional[float] = None
|
|
136
|
+
header = resp.headers.get("Retry-After")
|
|
137
|
+
if header is not None:
|
|
138
|
+
try:
|
|
139
|
+
retry_after = float(header)
|
|
140
|
+
except ValueError:
|
|
141
|
+
pass
|
|
142
|
+
try:
|
|
143
|
+
body = resp.json()
|
|
144
|
+
except ValueError:
|
|
145
|
+
body = None
|
|
146
|
+
if isinstance(body, dict) and isinstance(body.get("code"), str):
|
|
147
|
+
if retry_after is None and isinstance(body.get("retryAfter"), (int, float)):
|
|
148
|
+
retry_after = float(body["retryAfter"])
|
|
149
|
+
return PlayScanError(resp.status_code, body["code"], str(body.get("message", "")), retry_after, body)
|
|
150
|
+
return PlayScanError(resp.status_code, "http_error", resp.text[:200], retry_after, body)
|
|
151
|
+
|
|
152
|
+
# -- API methods -----------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
def create_scan(self, files: Files, page_range: Optional[Tuple[int, int]] = None) -> Scan:
|
|
155
|
+
"""Upload images (JPEG/PNG/TIFF) or one PDF and start a scan. Returns immediately.
|
|
156
|
+
|
|
157
|
+
``page_range`` is ``(first, last)`` (1-based, inclusive) and applies to PDFs.
|
|
158
|
+
Sending identical files and options again returns the same scan with ``deduplicated=True``.
|
|
159
|
+
"""
|
|
160
|
+
data: Dict[str, str] = {}
|
|
161
|
+
if page_range is not None:
|
|
162
|
+
first, last = (int(page_range[0]), int(page_range[1]))
|
|
163
|
+
if not 1 <= first <= last:
|
|
164
|
+
raise ValueError("page_range must be (first, last) with 1 <= first <= last")
|
|
165
|
+
data["options"] = json.dumps({"pageRange": [first, last]})
|
|
166
|
+
body = self._request("POST", "/v1/scans", files=_read_files(files), data=data).json()
|
|
167
|
+
return Scan(id=body["id"], status=body["status"], pages=body.get("pages", 0), deduplicated=bool(body.get("deduplicated")))
|
|
168
|
+
|
|
169
|
+
def get_scan(self, scan_id: str) -> ScanStatus:
|
|
170
|
+
"""Return the current status of a scan."""
|
|
171
|
+
return _status_from(self._request("GET", f"/v1/scans/{scan_id}").json())
|
|
172
|
+
|
|
173
|
+
def wait(
|
|
174
|
+
self,
|
|
175
|
+
scan_id: str,
|
|
176
|
+
poll_interval: float = 2.0,
|
|
177
|
+
wait_timeout: Optional[float] = 600,
|
|
178
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
179
|
+
) -> ScanStatus:
|
|
180
|
+
"""Poll until the scan is ``done`` and return its final status.
|
|
181
|
+
|
|
182
|
+
Raises:
|
|
183
|
+
ScanFailedError: the scan ended as ``failed`` or ``canceled``.
|
|
184
|
+
ScanTimeoutError: ``wait_timeout`` seconds passed (the scan keeps running on the server).
|
|
185
|
+
"""
|
|
186
|
+
deadline = None if wait_timeout is None else time.monotonic() + wait_timeout
|
|
187
|
+
while True:
|
|
188
|
+
status = self.get_scan(scan_id)
|
|
189
|
+
if on_progress is not None:
|
|
190
|
+
on_progress(status)
|
|
191
|
+
if status.status == "done":
|
|
192
|
+
return status
|
|
193
|
+
if status.status in ("failed", "canceled"):
|
|
194
|
+
code = status.error or status.status
|
|
195
|
+
raise ScanFailedError(scan_id, code, f"Scan {scan_id} {status.status} ({code}).")
|
|
196
|
+
delay = poll_interval
|
|
197
|
+
if deadline is not None:
|
|
198
|
+
remaining = deadline - time.monotonic()
|
|
199
|
+
if remaining <= 0:
|
|
200
|
+
raise ScanTimeoutError(scan_id, f"Scan {scan_id} did not finish within {wait_timeout} s.")
|
|
201
|
+
delay = min(delay, remaining)
|
|
202
|
+
time.sleep(delay)
|
|
203
|
+
|
|
204
|
+
def _download(self, scan_id: str, format: str) -> requests.Response:
|
|
205
|
+
if format not in FORMATS:
|
|
206
|
+
raise ValueError(f"format must be one of: {', '.join(FORMATS)}")
|
|
207
|
+
return self._request("GET", f"/v1/scans/{scan_id}/result", params={"format": format})
|
|
208
|
+
|
|
209
|
+
def download(self, scan_id: str, format: str = "musicxml") -> bytes:
|
|
210
|
+
"""Download a finished scan as ``musicxml``, ``mxl``, ``midi`` or ``zip``. Free and repeatable for 24 h."""
|
|
211
|
+
return self._download(scan_id, format).content
|
|
212
|
+
|
|
213
|
+
def cancel(self, scan_id: str) -> ScanStatus:
|
|
214
|
+
"""Cancel a scan that is still queued (pages are returned to the balance)."""
|
|
215
|
+
body = self._request("DELETE", f"/v1/scans/{scan_id}").json()
|
|
216
|
+
return ScanStatus(id=body["id"], status=body["status"])
|
|
217
|
+
|
|
218
|
+
def balance(self) -> int:
|
|
219
|
+
"""Return the number of pages left on the account."""
|
|
220
|
+
return int(self._request("GET", "/v1/balance").json()["pages"])
|
|
221
|
+
|
|
222
|
+
def scan(
|
|
223
|
+
self,
|
|
224
|
+
files: Files,
|
|
225
|
+
format: str = "musicxml",
|
|
226
|
+
page_range: Optional[Tuple[int, int]] = None,
|
|
227
|
+
poll_interval: float = 2.0,
|
|
228
|
+
wait_timeout: Optional[float] = 600,
|
|
229
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
230
|
+
) -> Result:
|
|
231
|
+
"""Create a scan, wait for it to finish and download the result in one call."""
|
|
232
|
+
if format not in FORMATS:
|
|
233
|
+
raise ValueError(f"format must be one of: {', '.join(FORMATS)}")
|
|
234
|
+
created = self.create_scan(files, page_range=page_range)
|
|
235
|
+
final = self.wait(created.id, poll_interval=poll_interval, wait_timeout=wait_timeout, on_progress=on_progress)
|
|
236
|
+
resp = self._download(created.id, format)
|
|
237
|
+
return Result(
|
|
238
|
+
content=resp.content,
|
|
239
|
+
format=format,
|
|
240
|
+
# Fixed name per format: the server-sent Content-Disposition name is not trusted for local writes.
|
|
241
|
+
filename=_FALLBACK_NAMES[format],
|
|
242
|
+
scan_id=created.id,
|
|
243
|
+
charged_pages=final.charged_pages,
|
|
244
|
+
balance_pages=_int_or_none(resp.headers.get("X-Balance-Pages")),
|
|
245
|
+
)
|
playscan/_errors.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Exceptions raised by the PlayScan client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PlayScanError(Exception):
|
|
9
|
+
"""An error returned by the PlayScan API (or raised by this client).
|
|
10
|
+
|
|
11
|
+
Attributes:
|
|
12
|
+
status: HTTP status code (0 when no HTTP response was involved).
|
|
13
|
+
code: Machine-readable error code, e.g. ``insufficient_balance``.
|
|
14
|
+
message: Human-readable message.
|
|
15
|
+
retry_after: Seconds the server asked to wait, if given.
|
|
16
|
+
body: Parsed JSON error body (or ``None``).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
status: int,
|
|
22
|
+
code: str,
|
|
23
|
+
message: str,
|
|
24
|
+
retry_after: Optional[float] = None,
|
|
25
|
+
body: Any = None,
|
|
26
|
+
) -> None:
|
|
27
|
+
super().__init__(f"{code}: {message}")
|
|
28
|
+
self.status = status
|
|
29
|
+
self.code = code
|
|
30
|
+
self.message = message
|
|
31
|
+
self.retry_after = retry_after
|
|
32
|
+
self.body = body
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ScanFailedError(PlayScanError):
|
|
36
|
+
"""The scan finished with status ``failed`` or ``canceled``.
|
|
37
|
+
|
|
38
|
+
``code`` is the scan's error code (e.g. ``no_staff_lines``) or ``canceled``.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, scan_id: str, code: str, message: str, body: Any = None) -> None:
|
|
42
|
+
super().__init__(0, code, message, body=body)
|
|
43
|
+
self.scan_id = scan_id
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ScanTimeoutError(PlayScanError):
|
|
47
|
+
"""``wait_timeout`` passed before the scan finished. The scan keeps running on the server."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, scan_id: str, message: str) -> None:
|
|
50
|
+
super().__init__(0, "timeout", message)
|
|
51
|
+
self.scan_id = scan_id
|
playscan/_types.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Data classes returned by the PlayScan client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class Scan:
|
|
12
|
+
"""A newly created scan (response of ``POST /v1/scans``)."""
|
|
13
|
+
|
|
14
|
+
id: str
|
|
15
|
+
status: str
|
|
16
|
+
pages: int
|
|
17
|
+
deduplicated: bool = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ScanStatus:
|
|
22
|
+
"""Current state of a scan (response of ``GET /v1/scans/{id}``).
|
|
23
|
+
|
|
24
|
+
``status`` is one of ``queued``, ``processing``, ``done``, ``failed``, ``canceled``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
id: str
|
|
28
|
+
status: str
|
|
29
|
+
progress: int = 0
|
|
30
|
+
pages: Optional[int] = None
|
|
31
|
+
charged_pages: Optional[int] = None
|
|
32
|
+
error: Optional[str] = None
|
|
33
|
+
queue_position: Optional[int] = None
|
|
34
|
+
eta_seconds: Optional[int] = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class Result:
|
|
39
|
+
"""A downloaded result file."""
|
|
40
|
+
|
|
41
|
+
content: bytes
|
|
42
|
+
format: str
|
|
43
|
+
filename: str
|
|
44
|
+
scan_id: str
|
|
45
|
+
charged_pages: Optional[int] = None
|
|
46
|
+
balance_pages: Optional[int] = None
|
|
47
|
+
|
|
48
|
+
def save(self, path: Union[str, "os.PathLike[str]", None] = None) -> str:
|
|
49
|
+
"""Write ``content`` to ``path`` and return the path written.
|
|
50
|
+
|
|
51
|
+
``path`` defaults to ``filename`` in the current directory. If ``path`` is an existing
|
|
52
|
+
directory, ``filename`` is written inside it. Missing parent directories are created.
|
|
53
|
+
"""
|
|
54
|
+
target = os.fspath(path) if path is not None else self.filename
|
|
55
|
+
if os.path.isdir(target):
|
|
56
|
+
target = os.path.join(target, self.filename)
|
|
57
|
+
parent = os.path.dirname(target)
|
|
58
|
+
if parent:
|
|
59
|
+
os.makedirs(parent, exist_ok=True)
|
|
60
|
+
with open(target, "wb") as f:
|
|
61
|
+
f.write(self.content)
|
|
62
|
+
return target
|
playscan/cli.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Command-line interface: ``playscan scan`` and ``playscan balance``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from typing import List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
from ._client import FORMATS, PlayScan, __version__
|
|
10
|
+
from ._errors import PlayScanError
|
|
11
|
+
from ._types import ScanStatus
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _page_range(value: str) -> Tuple[int, int]:
|
|
15
|
+
first, _, last = value.partition("-")
|
|
16
|
+
try:
|
|
17
|
+
lo, hi = int(first), int(last or first)
|
|
18
|
+
except ValueError:
|
|
19
|
+
raise argparse.ArgumentTypeError("use FIRST-LAST, e.g. 1-3") from None
|
|
20
|
+
if not 1 <= lo <= hi:
|
|
21
|
+
raise argparse.ArgumentTypeError("need 1 <= FIRST <= LAST")
|
|
22
|
+
return lo, hi
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _Progress:
|
|
26
|
+
"""Prints a status line to stderr, skipping lines that repeat the previous one."""
|
|
27
|
+
|
|
28
|
+
def __init__(self) -> None:
|
|
29
|
+
self._last = ""
|
|
30
|
+
|
|
31
|
+
def __call__(self, status: ScanStatus) -> None:
|
|
32
|
+
if status.status == "queued" and status.queue_position is not None:
|
|
33
|
+
line = f"queued (position {status.queue_position})"
|
|
34
|
+
else:
|
|
35
|
+
line = f"{status.status} {status.progress}%"
|
|
36
|
+
if line != self._last:
|
|
37
|
+
print(line, file=sys.stderr)
|
|
38
|
+
self._last = line
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
42
|
+
"""Entry point for the ``playscan`` command. Reads the key from ``PLAYSCAN_API_KEY``."""
|
|
43
|
+
parser = argparse.ArgumentParser(prog="playscan", description="Turn sheet music images or PDFs into MusicXML or MIDI.")
|
|
44
|
+
parser.add_argument("--version", action="version", version=f"playscan {__version__}")
|
|
45
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
46
|
+
scan = sub.add_parser("scan", help="scan files and save the result")
|
|
47
|
+
scan.add_argument("files", nargs="+", metavar="FILE", help="JPEG/PNG/TIFF images (one per page) or one PDF")
|
|
48
|
+
scan.add_argument("-f", "--format", choices=FORMATS, default="musicxml", help="output format (default: musicxml)")
|
|
49
|
+
scan.add_argument("-o", "--output", metavar="OUT", help="output path (default: server filename in current directory)")
|
|
50
|
+
scan.add_argument("--pages", type=_page_range, metavar="FIRST-LAST", help="PDF page range, e.g. 1-3")
|
|
51
|
+
sub.add_parser("balance", help="print pages left on the account")
|
|
52
|
+
args = parser.parse_args(argv)
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
with PlayScan() as client:
|
|
56
|
+
if args.command == "balance":
|
|
57
|
+
print(client.balance())
|
|
58
|
+
else:
|
|
59
|
+
result = client.scan(args.files, format=args.format, page_range=args.pages, on_progress=_Progress())
|
|
60
|
+
try:
|
|
61
|
+
saved = result.save(args.output)
|
|
62
|
+
except OSError as e:
|
|
63
|
+
print(
|
|
64
|
+
f"error io: {e} (scan {result.scan_id} is done; re-run the same command within 24 h"
|
|
65
|
+
" to download it, identical uploads are not charged again)",
|
|
66
|
+
file=sys.stderr,
|
|
67
|
+
)
|
|
68
|
+
return 1
|
|
69
|
+
bal = f", balance {result.balance_pages} pages" if result.balance_pages is not None else ""
|
|
70
|
+
print(f"charged {result.charged_pages or 0} pages{bal}", file=sys.stderr)
|
|
71
|
+
print(saved)
|
|
72
|
+
except PlayScanError as e:
|
|
73
|
+
print(f"error {e.code}: {e.message}", file=sys.stderr)
|
|
74
|
+
return 1
|
|
75
|
+
except OSError as e:
|
|
76
|
+
print(f"error io: {e}", file=sys.stderr)
|
|
77
|
+
return 1
|
|
78
|
+
return 0
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
sys.exit(main())
|
playscan/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: playscan
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the PlayScan API: turn photos and PDFs of printed sheet music into MusicXML or MIDI.
|
|
5
|
+
Project-URL: Homepage, https://developer.playscan.app
|
|
6
|
+
Project-URL: Documentation, https://developer.playscan.app/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/zarifergashev/playscan-api
|
|
8
|
+
Project-URL: Issues, https://github.com/zarifergashev/playscan-api/issues
|
|
9
|
+
Author: PlayScan
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: midi,musicxml,omr,optical-music-recognition,sheet-music
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Conversion
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Requires-Dist: requests>=2.25
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# playscan
|
|
31
|
+
|
|
32
|
+
Python client for the [PlayScan API](https://developer.playscan.app/?ref=pypi): send photos or PDFs of
|
|
33
|
+
printed sheet music, get back MusicXML, compressed MusicXML (`.mxl`) or MIDI.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install playscan
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Requires Python 3.9+. The only dependency is `requests`.
|
|
42
|
+
|
|
43
|
+
## Quickstart
|
|
44
|
+
|
|
45
|
+
Get a key at [developer.playscan.app](https://developer.playscan.app/?ref=pypi) (new accounts get 10 free
|
|
46
|
+
pages once, no card), then:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from playscan import PlayScan
|
|
50
|
+
|
|
51
|
+
result = PlayScan(api_key="ps_live_...").scan("page1.jpg")
|
|
52
|
+
print(result.save()) # score.musicxml
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
If you leave out `api_key`, the client reads `PLAYSCAN_API_KEY` from the environment. Keep the key on
|
|
56
|
+
the server: the API does not accept browser (CORS) requests.
|
|
57
|
+
|
|
58
|
+
More options:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
client = PlayScan() # PLAYSCAN_API_KEY
|
|
62
|
+
|
|
63
|
+
# Several images = several pages of one score, in order.
|
|
64
|
+
result = client.scan(["p1.jpg", "p2.jpg"], format="midi")
|
|
65
|
+
result.save("song.mid")
|
|
66
|
+
|
|
67
|
+
# A PDF, only pages 2-4, with progress output.
|
|
68
|
+
result = client.scan(
|
|
69
|
+
"book.pdf",
|
|
70
|
+
format="mxl",
|
|
71
|
+
page_range=(2, 4),
|
|
72
|
+
on_progress=lambda s: print(s.status, s.progress),
|
|
73
|
+
)
|
|
74
|
+
print(result.charged_pages, "pages charged,", result.balance_pages, "left")
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`files` can be a path, `bytes`, a binary file object, or a list of them.
|
|
78
|
+
|
|
79
|
+
## Command line
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
export PLAYSCAN_API_KEY=ps_live_...
|
|
83
|
+
playscan scan page1.jpg page2.jpg -f midi -o song.mid
|
|
84
|
+
playscan scan book.pdf --pages 1-3 # saves score.musicxml
|
|
85
|
+
playscan balance # pages left
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Progress goes to stderr, the saved path to stdout. On an API error the command prints
|
|
89
|
+
`error <code>: <message>` and exits with code 1.
|
|
90
|
+
|
|
91
|
+
## API
|
|
92
|
+
|
|
93
|
+
| Method | What it does |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `scan(files, format="musicxml", page_range=None, poll_interval=2.0, wait_timeout=600, on_progress=None)` | Create a scan, wait, download. Returns a `Result`. |
|
|
96
|
+
| `create_scan(files, page_range=None)` | Upload and start a scan. Returns `Scan(id, status, pages, deduplicated)`. |
|
|
97
|
+
| `get_scan(id)` | Returns `ScanStatus(id, status, progress, pages, charged_pages, error, queue_position, eta_seconds)`. |
|
|
98
|
+
| `wait(id, poll_interval=2.0, wait_timeout=600, on_progress=None)` | Poll until `done`. Returns the final `ScanStatus`. |
|
|
99
|
+
| `download(id, format="musicxml")` | Result bytes. `format`: `musicxml`, `mxl`, `midi` or `zip`. Free and repeatable. |
|
|
100
|
+
| `cancel(id)` | Cancel a scan that is still queued. |
|
|
101
|
+
| `balance()` | Pages left on the account. |
|
|
102
|
+
|
|
103
|
+
`Result` has `content`, `format`, `filename`, `scan_id`, `charged_pages`, `balance_pages` and
|
|
104
|
+
`save(path=None)`, which writes the file (by default to `filename` in the current directory; a directory
|
|
105
|
+
path gets `filename` inside it, missing folders are created) and returns the path.
|
|
106
|
+
|
|
107
|
+
Constructor: `PlayScan(api_key=None, *, base_url="https://api.playscan.app", timeout=120, max_retries=5)`.
|
|
108
|
+
`base_url` can also come from `PLAYSCAN_BASE_URL`.
|
|
109
|
+
|
|
110
|
+
Uploading the same files with the same options again returns the existing scan
|
|
111
|
+
(`deduplicated=True`) and is not charged again.
|
|
112
|
+
|
|
113
|
+
## Errors
|
|
114
|
+
|
|
115
|
+
API errors and wait errors are `playscan.PlayScanError` with `status`, `code`, `message`, `retry_after` and
|
|
116
|
+
`body`. Invalid arguments (for example an unknown `format` or a bad `page_range`) raise `ValueError` or
|
|
117
|
+
`TypeError`, and a file path that cannot be read raises `OSError`.
|
|
118
|
+
|
|
119
|
+
- `ScanFailedError`: the scan ended as `failed` or `canceled`. `code` is the scan's error code (for
|
|
120
|
+
example `no_staff_lines`) or `canceled`; `scan_id` is attached.
|
|
121
|
+
- `ScanTimeoutError`: `wait_timeout` passed. The scan keeps running on the server; call `wait(e.scan_id)`
|
|
122
|
+
again later.
|
|
123
|
+
|
|
124
|
+
Common codes: `unauthorized` (401), `insufficient_balance` (402), `not_found` (404),
|
|
125
|
+
`unsupported_file` / `too_many_pages` / `upload_too_large` (422), `too_many_active` (429),
|
|
126
|
+
`result_expired` (410). The client retries `rate_limited` (429) and `busy` (503) on its own, waiting the
|
|
127
|
+
`Retry-After` time, up to `max_retries` times. It does not retry `too_many_active`.
|
|
128
|
+
|
|
129
|
+
## Limits
|
|
130
|
+
|
|
131
|
+
- JPEG, PNG or TIFF images, or exactly one PDF; up to 30 pages per scan.
|
|
132
|
+
- 30 MB per file, 60 MB per upload.
|
|
133
|
+
- 2 active scans per account; 10 new scans and 120 requests per minute.
|
|
134
|
+
- Results can be downloaded for 24 hours. Uploaded images are deleted after 24 hours and are not used to
|
|
135
|
+
train models.
|
|
136
|
+
- Printed music only, not handwriting. Recognition is automatic and can make mistakes; check the result.
|
|
137
|
+
|
|
138
|
+
## Pricing
|
|
139
|
+
|
|
140
|
+
Pay per page with one-time packs, no subscription, pages never expire: $10 / 100, $40 / 600,
|
|
141
|
+
$125 / 2,500, $350 / 10,000 pages. Only pages that were read are charged; failed pages go back to your
|
|
142
|
+
balance.
|
|
143
|
+
|
|
144
|
+
## Links
|
|
145
|
+
|
|
146
|
+
- Sign up and get a key: https://developer.playscan.app/?ref=pypi
|
|
147
|
+
- Docs: https://developer.playscan.app/docs?ref=pypi
|
|
148
|
+
- OpenAPI spec: https://developer.playscan.app/openapi.json?ref=pypi
|
|
149
|
+
- Tutorial: https://developer.playscan.app/guides/sheet-music-to-musicxml?ref=pypi
|
|
150
|
+
- Try it in the browser, no account: https://playscan.app/en/try?ref=pypi
|
|
151
|
+
|
|
152
|
+
## License
|
|
153
|
+
|
|
154
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
playscan/__init__.py,sha256=Q89o-ejRebq8mFBcz0GfaLlU_D_UBVv4kaxUNbL6zTc,618
|
|
2
|
+
playscan/_client.py,sha256=hlBeM5EHITNd7cNyi0jvWfSY0ledFxnziIVNJIAyKsY,10488
|
|
3
|
+
playscan/_errors.py,sha256=RlECGfn1TPn779huvQk9XxINanRhtxtvNKPTD7J9K7A,1581
|
|
4
|
+
playscan/_types.py,sha256=nBiMjsHHMIdb7M4t3NIlLi411RFZjqWwAoaUpuvX0a4,1720
|
|
5
|
+
playscan/cli.py,sha256=m6iqinIgb5_1Cq7xPhxmra-O-i9vfrfp54HfaflM84w,3426
|
|
6
|
+
playscan/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
playscan-0.1.0.dist-info/METADATA,sha256=eUxVDKRsrnEMjkfVFep7GVR-HS0maDYPNMN9L3pRuMc,6282
|
|
8
|
+
playscan-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
playscan-0.1.0.dist-info/entry_points.txt,sha256=M8g6Imgx_UUtVTpeAooV5kgm0nuC9_a2XmPM-MzOoN0,47
|
|
10
|
+
playscan-0.1.0.dist-info/licenses/LICENSE,sha256=8eZ1WG2X1VNCfjVB3cIREsR23RQPKxlBistf-PkMNIY,1065
|
|
11
|
+
playscan-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PlayScan
|
|
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.
|