olign 1.1.4__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.
- olign/__init__.py +32 -0
- olign/__main__.py +7 -0
- olign/cli.py +197 -0
- olign/client.py +204 -0
- olign/errors.py +82 -0
- olign/py.typed +0 -0
- olign/result.py +327 -0
- olign-1.1.4.dist-info/METADATA +108 -0
- olign-1.1.4.dist-info/RECORD +13 -0
- olign-1.1.4.dist-info/WHEEL +5 -0
- olign-1.1.4.dist-info/entry_points.txt +2 -0
- olign-1.1.4.dist-info/licenses/LICENSE +202 -0
- olign-1.1.4.dist-info/top_level.txt +1 -0
olign/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Olign, the forced alignment API from Olewave, in Python.
|
|
2
|
+
|
|
3
|
+
import olign
|
|
4
|
+
|
|
5
|
+
client = olign.Client() # reads OLIGN_KEY
|
|
6
|
+
result = client.align("talk.mp3", transcript="what is better a fruit or hamburger")
|
|
7
|
+
for w in result.words:
|
|
8
|
+
print(w.word, w.begin, w.end)
|
|
9
|
+
result.to_textgrid("talk.TextGrid")
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "1.1.4"
|
|
13
|
+
|
|
14
|
+
from .client import Client # noqa: E402
|
|
15
|
+
from .errors import ( # noqa: E402
|
|
16
|
+
APIError,
|
|
17
|
+
AudioTooLargeError,
|
|
18
|
+
AuthenticationError,
|
|
19
|
+
ConnectionFailedError,
|
|
20
|
+
JobFailedError,
|
|
21
|
+
OlignError,
|
|
22
|
+
PaymentRequiredError,
|
|
23
|
+
UsageLimitError,
|
|
24
|
+
)
|
|
25
|
+
from .result import Pause, Phone, Phrase, Result, Word # noqa: E402
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"Client", "Result", "Word", "Phone", "Pause", "Phrase",
|
|
29
|
+
"OlignError", "APIError", "AuthenticationError", "PaymentRequiredError", "AudioTooLargeError",
|
|
30
|
+
"UsageLimitError", "JobFailedError", "ConnectionFailedError",
|
|
31
|
+
"__version__",
|
|
32
|
+
]
|
olign/__main__.py
ADDED
olign/cli.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""The ``olign`` command.
|
|
2
|
+
|
|
3
|
+
olign align talk.mp3 --textgrid # writes talk.TextGrid
|
|
4
|
+
olign align talk.mp3 --transcript talk.txt --srt --vtt
|
|
5
|
+
olign export talk.json --csv words.csv # from a saved result, no upload
|
|
6
|
+
olign get 6abb52b92239acba --srt # a job you stopped waiting for
|
|
7
|
+
|
|
8
|
+
Progress goes to stderr and a short summary to stdout.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import pathlib
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from typing import List, Optional
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .client import Client
|
|
21
|
+
from .errors import OlignError
|
|
22
|
+
from .result import Result
|
|
23
|
+
|
|
24
|
+
# flag -> (file suffix, Result method)
|
|
25
|
+
FORMATS = {
|
|
26
|
+
"textgrid": (".TextGrid", "to_textgrid"),
|
|
27
|
+
"srt": (".srt", "to_srt"),
|
|
28
|
+
"vtt": (".vtt", "to_vtt"),
|
|
29
|
+
"csv": (".csv", "to_csv"),
|
|
30
|
+
"json": (".json", "to_json"),
|
|
31
|
+
}
|
|
32
|
+
AUTO = "\0auto"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
36
|
+
ap = argparse.ArgumentParser(
|
|
37
|
+
prog="olign", description="Word and phone timings for English speech, from the Olign API.",
|
|
38
|
+
epilog="Set OLIGN_KEY to your API key (https://tycho.olewave.com > Profile > API keys).")
|
|
39
|
+
ap.add_argument("--version", action="version", version=f"olign {__version__}")
|
|
40
|
+
sub = ap.add_subparsers(dest="command", metavar="COMMAND")
|
|
41
|
+
|
|
42
|
+
al = sub.add_parser("align", help="align a recording and save the timings",
|
|
43
|
+
description="Upload a recording, wait for the job and save the timings. "
|
|
44
|
+
"A flag given without a file name writes AUDIO's name with the "
|
|
45
|
+
"format's extension in the current directory. With no output "
|
|
46
|
+
"flag the result is saved as JSON.")
|
|
47
|
+
al.add_argument("audio", type=pathlib.Path, help="the recording (wav, mp3, m4a, flac, ogg/opus or webm)")
|
|
48
|
+
al.add_argument("--transcript", "-t", type=pathlib.Path, metavar="FILE",
|
|
49
|
+
help="UTF-8 text of what is said. Without it, olign transcribes the audio first")
|
|
50
|
+
al.add_argument("--word-edges", choices=("phonetic", "audible"),
|
|
51
|
+
help="phonetic (the default) or audible: words start and end where a listener hears "
|
|
52
|
+
"them, as dubbing and subtitles need (clean recordings)")
|
|
53
|
+
al.add_argument("--align-untranscribed", action="store_true",
|
|
54
|
+
help="also align the speech the transcript leaves out (fillers, repeats)")
|
|
55
|
+
_add_outputs(al, with_json=True)
|
|
56
|
+
al.add_argument("--api", metavar="URL", help="API base URL (default $OLIGN_API_URL, else the public API)")
|
|
57
|
+
al.add_argument("--every", type=float, default=5.0, metavar="SECONDS", help="poll interval (default 5)")
|
|
58
|
+
al.add_argument("--quiet", "-q", action="store_true", help="no progress on stderr")
|
|
59
|
+
|
|
60
|
+
gt = sub.add_parser("get", help="wait for a job you already submitted and save it",
|
|
61
|
+
description="Fetch a job by its id, wait until it is done and save it. "
|
|
62
|
+
"Useful after you stop 'olign align' while it waits. "
|
|
63
|
+
"With no output flag the result is saved as JSON.")
|
|
64
|
+
gt.add_argument("job_id", help="the id 'olign align' printed")
|
|
65
|
+
_add_outputs(gt, with_json=True)
|
|
66
|
+
gt.add_argument("--api", metavar="URL", help="API base URL (default $OLIGN_API_URL, else the public API)")
|
|
67
|
+
gt.add_argument("--every", type=float, default=5.0, metavar="SECONDS", help="poll interval (default 5)")
|
|
68
|
+
gt.add_argument("--quiet", "-q", action="store_true", help="no progress on stderr")
|
|
69
|
+
|
|
70
|
+
ex = sub.add_parser("export", help="convert a saved JSON result, without calling the API",
|
|
71
|
+
description="Write subtitles, a TextGrid or a CSV from a result saved by "
|
|
72
|
+
"'olign align --json'.")
|
|
73
|
+
ex.add_argument("result", type=pathlib.Path, help="a JSON result saved by olign")
|
|
74
|
+
_add_outputs(ex, with_json=False)
|
|
75
|
+
return ap
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _add_outputs(p: argparse.ArgumentParser, with_json: bool) -> None:
|
|
79
|
+
help_ = {"textgrid": "Praat TextGrid, a words, a phones and a pauses tier",
|
|
80
|
+
"srt": "SubRip subtitles", "vtt": "WebVTT subtitles with a timestamp on every word",
|
|
81
|
+
"csv": "one row per word", "json": "the full result, readable by 'olign export'"}
|
|
82
|
+
for name in FORMATS:
|
|
83
|
+
if name == "json" and not with_json:
|
|
84
|
+
continue
|
|
85
|
+
p.add_argument(f"--{name}", nargs="?", const=AUTO, metavar="FILE", type=str, help=help_[name])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def outputs(args: argparse.Namespace, stem: str) -> List[tuple]:
|
|
89
|
+
"""[(path, method name)] for every format flag that was given."""
|
|
90
|
+
out = []
|
|
91
|
+
for name, (suffix, method) in FORMATS.items():
|
|
92
|
+
value = getattr(args, name, None)
|
|
93
|
+
if value is not None:
|
|
94
|
+
out.append((pathlib.Path(stem + suffix) if value == AUTO else pathlib.Path(value), method))
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
99
|
+
ap = build_parser()
|
|
100
|
+
args = ap.parse_args(argv)
|
|
101
|
+
if not args.command:
|
|
102
|
+
ap.print_help(sys.stderr)
|
|
103
|
+
return 2
|
|
104
|
+
run = {"align": run_align, "get": run_get, "export": run_export}[args.command]
|
|
105
|
+
try:
|
|
106
|
+
return run(args)
|
|
107
|
+
except OlignError as e:
|
|
108
|
+
print(f"olign: error: {e}", file=sys.stderr)
|
|
109
|
+
return 1
|
|
110
|
+
except KeyboardInterrupt:
|
|
111
|
+
print(file=sys.stderr)
|
|
112
|
+
return 130
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _say(args: argparse.Namespace):
|
|
116
|
+
return (lambda *_: None) if args.quiet else (lambda m: print(f"olign: {m}", file=sys.stderr, flush=True))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def run_align(args: argparse.Namespace) -> int:
|
|
120
|
+
say = _say(args)
|
|
121
|
+
for f in (args.audio, args.transcript):
|
|
122
|
+
if f is not None and not f.is_file():
|
|
123
|
+
raise OlignError(f"no such file: {f}")
|
|
124
|
+
targets = outputs(args, args.audio.stem) or [(pathlib.Path(args.audio.stem + ".json"), "to_json")]
|
|
125
|
+
|
|
126
|
+
client = Client(base_url=args.api, poll_interval=args.every)
|
|
127
|
+
size = args.audio.stat().st_size / 1e6
|
|
128
|
+
say(f"uploading {args.audio.name} ({size:.1f} MB)"
|
|
129
|
+
+ ("" if args.transcript else ", no transcript, so olign transcribes it first"))
|
|
130
|
+
t0 = time.monotonic()
|
|
131
|
+
job = client.align(args.audio, transcript=args.transcript, poll=False, word_edges=args.word_edges,
|
|
132
|
+
align_untranscribed=args.align_untranscribed)
|
|
133
|
+
say(f"job {job.job_id} {job.state}")
|
|
134
|
+
return _wait_and_save(client, job.job_id, job.state, args, targets, args.audio.name, t0)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def run_get(args: argparse.Namespace) -> int:
|
|
138
|
+
client = Client(base_url=args.api, poll_interval=args.every)
|
|
139
|
+
targets = outputs(args, args.job_id) or [(pathlib.Path(args.job_id + ".json"), "to_json")]
|
|
140
|
+
return _wait_and_save(client, args.job_id, "", args, targets, args.job_id, time.monotonic())
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _wait_and_save(client: Client, job_id: str, state: str, args: argparse.Namespace, targets: List[tuple],
|
|
144
|
+
name: str, t0: float) -> int:
|
|
145
|
+
say = _say(args)
|
|
146
|
+
seen = [state]
|
|
147
|
+
|
|
148
|
+
def progress(r: Result) -> None:
|
|
149
|
+
line = r.state + (f" {r.progress:.0%}" if r.progress is not None and r.state == "running" else "")
|
|
150
|
+
if line != seen[0]:
|
|
151
|
+
say(line)
|
|
152
|
+
seen[0] = line
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
result = client.wait(job_id, on_progress=progress)
|
|
156
|
+
except KeyboardInterrupt:
|
|
157
|
+
print(f"\nolign: stopped waiting. Job {job_id} keeps running, and "
|
|
158
|
+
f"'olign get {job_id}' saves it later.", file=sys.stderr)
|
|
159
|
+
return 130
|
|
160
|
+
say(f"done in {time.monotonic() - t0:.0f} s")
|
|
161
|
+
_summary(result, name)
|
|
162
|
+
_write(result, targets)
|
|
163
|
+
return 0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def run_export(args: argparse.Namespace) -> int:
|
|
167
|
+
if not args.result.is_file():
|
|
168
|
+
raise OlignError(f"no such file: {args.result}")
|
|
169
|
+
try:
|
|
170
|
+
result = Result.load(args.result)
|
|
171
|
+
except (ValueError, KeyError, TypeError) as e:
|
|
172
|
+
raise OlignError(f"{args.result} is not an olign result: {e}") from None
|
|
173
|
+
targets = outputs(args, args.result.stem)
|
|
174
|
+
if not targets:
|
|
175
|
+
raise OlignError("name an output with --textgrid, --srt, --vtt or --csv")
|
|
176
|
+
_summary(result, args.result.name)
|
|
177
|
+
_write(result, targets)
|
|
178
|
+
return 0
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _summary(r: Result, name: str) -> None:
|
|
182
|
+
timed = sum(1 for _ in r.timed_words())
|
|
183
|
+
source = {"client": "aligned to your transcript", "asr": "transcribed by olign"}.get(
|
|
184
|
+
r.transcript_source or "", "aligned")
|
|
185
|
+
length = f"{r.audio_seconds:.2f} s of audio, " if r.audio_seconds is not None else ""
|
|
186
|
+
pauses = f", {len(r.pauses)} pauses, {len(r.phrases)} phrases" if r.pauses or r.phrases else ""
|
|
187
|
+
print(f"{name}: {length}{timed} words {source}{pauses}")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _write(r: Result, targets: List[tuple]) -> None:
|
|
191
|
+
for path, method in targets:
|
|
192
|
+
getattr(r, method)(path)
|
|
193
|
+
print(f"wrote {path}")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
if __name__ == "__main__":
|
|
197
|
+
sys.exit(main())
|
olign/client.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""The olign API v1 client: submit a recording, poll the job, get a Result.
|
|
2
|
+
|
|
3
|
+
Standard library only, so ``pip install olign`` pulls in nothing else.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import pathlib
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
import uuid
|
|
15
|
+
from typing import Callable, List, Optional, Tuple, Union
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .errors import BY_STATUS, APIError, ConnectionFailedError, JobFailedError, OlignError, UsageLimitError
|
|
19
|
+
from .result import PathLike, Result
|
|
20
|
+
|
|
21
|
+
API = "https://api.olewave.com/olign/v1"
|
|
22
|
+
# Cloudflare fronts the API and turns away some library defaults (HTTP 403,
|
|
23
|
+
# "error code: 1010" for Python-urllib), so the client names itself.
|
|
24
|
+
USER_AGENT = f"olign-python/{__version__}"
|
|
25
|
+
|
|
26
|
+
Transcript = Union[str, bytes, "os.PathLike[str]", None]
|
|
27
|
+
Progress = Callable[[Result], None]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Client:
|
|
31
|
+
"""A client for the olign API v1.
|
|
32
|
+
|
|
33
|
+
``api_key`` defaults to the ``OLIGN_KEY`` environment variable and
|
|
34
|
+
``base_url`` to ``OLIGN_API_URL``, then to the public API.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None,
|
|
38
|
+
poll_interval: float = 5.0, timeout: float = 300.0):
|
|
39
|
+
key = api_key or os.environ.get("OLIGN_KEY")
|
|
40
|
+
if not key:
|
|
41
|
+
raise OlignError("no API key: set OLIGN_KEY, or pass Client(api_key=...). "
|
|
42
|
+
"Create one under Profile > API keys on https://tycho.olewave.com")
|
|
43
|
+
self.api_key = key
|
|
44
|
+
self.base_url = (base_url or os.environ.get("OLIGN_API_URL") or API).rstrip("/")
|
|
45
|
+
self.poll_interval = poll_interval
|
|
46
|
+
self.timeout = timeout
|
|
47
|
+
|
|
48
|
+
def __repr__(self) -> str:
|
|
49
|
+
return f"Client(base_url={self.base_url!r})"
|
|
50
|
+
|
|
51
|
+
# -- the three calls -----------------------------------------------------
|
|
52
|
+
|
|
53
|
+
def align(self, audio_path: PathLike, transcript: Transcript = None, poll: bool = True,
|
|
54
|
+
on_progress: Optional[Progress] = None, *, word_edges: Optional[str] = None,
|
|
55
|
+
align_untranscribed: bool = False) -> Result:
|
|
56
|
+
"""Align a recording and return its words.
|
|
57
|
+
|
|
58
|
+
``transcript`` is optional. Pass the text as a ``str``, or a
|
|
59
|
+
``pathlib.Path`` to a UTF-8 text file. Without it, olign transcribes
|
|
60
|
+
the audio first, then aligns. With ``poll=False`` the call returns as
|
|
61
|
+
soon as the job is accepted, and :meth:`wait` finishes it.
|
|
62
|
+
|
|
63
|
+
``word_edges`` is ``"phonetic"`` (the API's default) or ``"audible"``:
|
|
64
|
+
words then start and end where a listener hears them, as dubbing and
|
|
65
|
+
subtitles need (the silence before a p, t, k, b, d or g stays outside
|
|
66
|
+
its word; for clean recordings). ``align_untranscribed=True`` also
|
|
67
|
+
aligns the speech your transcript leaves out; those words come back
|
|
68
|
+
with ``untranscribed`` set.
|
|
69
|
+
"""
|
|
70
|
+
job = self.submit(audio_path, transcript, word_edges=word_edges,
|
|
71
|
+
align_untranscribed=align_untranscribed)
|
|
72
|
+
if on_progress:
|
|
73
|
+
on_progress(job)
|
|
74
|
+
return self.wait(job.job_id, on_progress=on_progress) if poll else job
|
|
75
|
+
|
|
76
|
+
def submit(self, audio_path: PathLike, transcript: Transcript = None, *,
|
|
77
|
+
word_edges: Optional[str] = None, align_untranscribed: bool = False) -> Result:
|
|
78
|
+
"""Upload the audio and return the accepted job, still queued.
|
|
79
|
+
Takes the options of :meth:`align`."""
|
|
80
|
+
if word_edges not in (None, "phonetic", "audible"):
|
|
81
|
+
raise ValueError(f"word_edges must be 'phonetic' or 'audible', not {word_edges!r}")
|
|
82
|
+
audio = pathlib.Path(audio_path)
|
|
83
|
+
fields: List[Tuple[str, Optional[str], bytes]] = [("audio", audio.name, audio.read_bytes())]
|
|
84
|
+
if transcript is not None:
|
|
85
|
+
fields.append(("transcript", "transcript.txt", _transcript_bytes(transcript)))
|
|
86
|
+
if word_edges:
|
|
87
|
+
fields.append(("word_edges", None, word_edges.encode()))
|
|
88
|
+
if align_untranscribed:
|
|
89
|
+
fields.append(("align_untranscribed", None, b"1"))
|
|
90
|
+
body, ctype = _multipart(fields)
|
|
91
|
+
d, headers = self._call("POST", self.base_url, body, ctype)
|
|
92
|
+
if not d.get("job_id"):
|
|
93
|
+
raise APIError(f"the API accepted the upload but sent no job_id: {str(d)[:200]}")
|
|
94
|
+
d.setdefault("state", "queued")
|
|
95
|
+
return Result.from_dict(d, headers)
|
|
96
|
+
|
|
97
|
+
def get(self, job_id: str) -> Result:
|
|
98
|
+
"""One look at a job: queued, running, done or failed."""
|
|
99
|
+
d, headers = self._call("GET", f"{self.base_url}/{job_id}")
|
|
100
|
+
d.setdefault("job_id", job_id)
|
|
101
|
+
return Result.from_dict(d, headers)
|
|
102
|
+
|
|
103
|
+
def wait(self, job_id: str, on_progress: Optional[Progress] = None) -> Result:
|
|
104
|
+
"""Poll a job until it is done. Raises :class:`JobFailedError` if it fails."""
|
|
105
|
+
misses = 0
|
|
106
|
+
while True:
|
|
107
|
+
try:
|
|
108
|
+
r = self.get(job_id)
|
|
109
|
+
misses = 0
|
|
110
|
+
except (ConnectionFailedError, APIError) as e:
|
|
111
|
+
# A long job outlives a brief network or gateway hiccup.
|
|
112
|
+
transient = isinstance(e, ConnectionFailedError) or (e.status or 0) >= 500
|
|
113
|
+
misses += 1
|
|
114
|
+
if not transient or misses > 3:
|
|
115
|
+
raise
|
|
116
|
+
time.sleep(self.poll_interval * misses)
|
|
117
|
+
continue
|
|
118
|
+
if on_progress:
|
|
119
|
+
on_progress(r)
|
|
120
|
+
if r.state == "done":
|
|
121
|
+
return r
|
|
122
|
+
if r.state == "failed":
|
|
123
|
+
raise JobFailedError(job_id, r.error)
|
|
124
|
+
time.sleep(self.poll_interval)
|
|
125
|
+
|
|
126
|
+
# -- HTTP ----------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
def _call(self, method: str, url: str, body: Optional[bytes] = None,
|
|
129
|
+
ctype: Optional[str] = None) -> Tuple[dict, dict]:
|
|
130
|
+
headers = {"X-API-Key": self.api_key, "User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
131
|
+
if ctype:
|
|
132
|
+
headers["Content-Type"] = ctype
|
|
133
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
134
|
+
try:
|
|
135
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
136
|
+
return _json(r.read()), dict(r.headers.items())
|
|
137
|
+
except urllib.error.HTTPError as e:
|
|
138
|
+
raise _http_error(e) from None
|
|
139
|
+
except (urllib.error.URLError, OSError) as e:
|
|
140
|
+
reason = getattr(e, "reason", e)
|
|
141
|
+
raise ConnectionFailedError(f"could not reach {url}: {reason}") from None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _http_error(e: urllib.error.HTTPError) -> OlignError:
|
|
145
|
+
raw = e.read()
|
|
146
|
+
body = _json(raw, strict=False)
|
|
147
|
+
message = _message(body) or raw.decode("utf-8", "replace").strip()[:300] or (e.reason or "")
|
|
148
|
+
cls = BY_STATUS.get(e.code, APIError)
|
|
149
|
+
if cls is UsageLimitError:
|
|
150
|
+
retry = e.headers.get("Retry-After") if e.headers else None
|
|
151
|
+
try:
|
|
152
|
+
retry_after = float(retry) if retry else None
|
|
153
|
+
except ValueError:
|
|
154
|
+
retry_after = None
|
|
155
|
+
return UsageLimitError(message, e.code, body, retry_after=retry_after)
|
|
156
|
+
return cls(message, e.code, body)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _message(body: dict) -> str:
|
|
160
|
+
"""The API's own words: FastAPI puts them in ``detail``, other layers in
|
|
161
|
+
``error`` or ``message``."""
|
|
162
|
+
for key in ("detail", "error", "message"):
|
|
163
|
+
v = body.get(key)
|
|
164
|
+
if isinstance(v, str) and v:
|
|
165
|
+
return v
|
|
166
|
+
if isinstance(v, list) and v: # validation errors: a list of {"msg": ...}
|
|
167
|
+
return "; ".join(str(x.get("msg", x)) if isinstance(x, dict) else str(x) for x in v)
|
|
168
|
+
return ""
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _json(raw: bytes, strict: bool = True) -> dict:
|
|
172
|
+
try:
|
|
173
|
+
d = json.loads(raw or b"{}")
|
|
174
|
+
except ValueError:
|
|
175
|
+
if strict:
|
|
176
|
+
raise APIError(f"the API sent something that is not JSON: {raw[:200]!r}") from None
|
|
177
|
+
return {}
|
|
178
|
+
return d if isinstance(d, dict) else {}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _transcript_bytes(t: Transcript) -> bytes:
|
|
182
|
+
if isinstance(t, bytes):
|
|
183
|
+
return t
|
|
184
|
+
if isinstance(t, str):
|
|
185
|
+
return t.encode("utf-8")
|
|
186
|
+
return pathlib.Path(t).read_bytes()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _multipart(fields: List[Tuple[str, Optional[str], bytes]]) -> Tuple[bytes, str]:
|
|
190
|
+
"""A multipart/form-data body with a known length: the API refuses chunked
|
|
191
|
+
uploads. A field without a filename is a plain form value."""
|
|
192
|
+
boundary = uuid.uuid4().hex
|
|
193
|
+
body = bytearray()
|
|
194
|
+
for name, filename, data in fields:
|
|
195
|
+
if filename is None:
|
|
196
|
+
body += f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'.encode()
|
|
197
|
+
body += data + b"\r\n"
|
|
198
|
+
continue
|
|
199
|
+
filename = filename.replace('"', "_").replace("\r", "_").replace("\n", "_")
|
|
200
|
+
body += (f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; '
|
|
201
|
+
f'filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()
|
|
202
|
+
body += data + b"\r\n"
|
|
203
|
+
body += f"--{boundary}--\r\n".encode()
|
|
204
|
+
return bytes(body), f"multipart/form-data; boundary={boundary}"
|
olign/errors.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Exceptions raised by the olign client.
|
|
2
|
+
|
|
3
|
+
Every error the API returns becomes an :class:`OlignError` subclass whose
|
|
4
|
+
message starts with the HTTP status and the API's own words, then says what
|
|
5
|
+
you can do about it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
DASHBOARD = "https://tycho.olewave.com"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class OlignError(Exception):
|
|
16
|
+
"""Base class. ``status`` is the HTTP status, or None for errors that are
|
|
17
|
+
not HTTP answers (a failed job, an unreachable server)."""
|
|
18
|
+
|
|
19
|
+
hint = ""
|
|
20
|
+
|
|
21
|
+
def __init__(self, message: str, status: Optional[int] = None, body: Optional[dict] = None):
|
|
22
|
+
self.status = status
|
|
23
|
+
self.api_message = message
|
|
24
|
+
self.body = body or {}
|
|
25
|
+
text = f"HTTP {status}: {message}" if status else message
|
|
26
|
+
if self.hint:
|
|
27
|
+
text += f" ({self.hint})"
|
|
28
|
+
super().__init__(text)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class APIError(OlignError):
|
|
32
|
+
"""Any HTTP error without a more specific class below."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthenticationError(OlignError):
|
|
36
|
+
"""401. The API key is missing, wrong or revoked."""
|
|
37
|
+
|
|
38
|
+
hint = f"check OLIGN_KEY, or create a key under Profile > API keys on {DASHBOARD}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PaymentRequiredError(OlignError):
|
|
42
|
+
"""402. Your balance does not cover this recording."""
|
|
43
|
+
|
|
44
|
+
hint = f"add a card or buy more minutes under Billing on {DASHBOARD}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class AudioTooLargeError(OlignError):
|
|
48
|
+
"""413. The upload is over the size limit, or the audio is over 3 hours."""
|
|
49
|
+
|
|
50
|
+
hint = "split the recording, or compress it with ffmpeg -i in.wav -ac 1 -c:a libopus -b:a 32k out.ogg"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class UsageLimitError(OlignError):
|
|
54
|
+
"""429. Your own monthly limit is reached. ``retry_after`` is the number of
|
|
55
|
+
seconds until it resets, when the API says."""
|
|
56
|
+
|
|
57
|
+
hint = f"raise or remove the limit under Settings on {DASHBOARD}"
|
|
58
|
+
|
|
59
|
+
def __init__(self, message: str, status: Optional[int] = None, body: Optional[dict] = None,
|
|
60
|
+
retry_after: Optional[float] = None):
|
|
61
|
+
self.retry_after = retry_after
|
|
62
|
+
super().__init__(message, status, body)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class JobFailedError(OlignError):
|
|
66
|
+
"""The job was accepted but ended in the ``failed`` state."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, job_id: str, reason: Optional[str] = None):
|
|
69
|
+
self.job_id = job_id
|
|
70
|
+
super().__init__(f"job {job_id} failed: {reason or 'the API gave no reason'}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ConnectionFailedError(OlignError):
|
|
74
|
+
"""The API could not be reached."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
BY_STATUS = {
|
|
78
|
+
401: AuthenticationError,
|
|
79
|
+
402: PaymentRequiredError,
|
|
80
|
+
413: AudioTooLargeError,
|
|
81
|
+
429: UsageLimitError,
|
|
82
|
+
}
|
olign/py.typed
ADDED
|
File without changes
|
olign/result.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""An alignment result, and the files you can make from it.
|
|
2
|
+
|
|
3
|
+
Times are seconds from the start of the audio. Scores are 0 to 100, or None
|
|
4
|
+
when the API does not send them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import csv
|
|
10
|
+
import io
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import pathlib
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Iterator, List, Optional, Union
|
|
16
|
+
|
|
17
|
+
PathLike = Union[str, "os.PathLike[str]"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Phone:
|
|
22
|
+
ph: str
|
|
23
|
+
begin: float
|
|
24
|
+
end: float
|
|
25
|
+
score: Optional[float] = None
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def from_dict(cls, d: dict) -> "Phone":
|
|
29
|
+
return cls(ph=d["ph"], begin=float(d["begin"]), end=float(d["end"]), score=d.get("score"))
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict:
|
|
32
|
+
out: dict = {"ph": self.ph, "begin": self.begin, "end": self.end}
|
|
33
|
+
if self.score is not None:
|
|
34
|
+
out["score"] = self.score
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Word:
|
|
40
|
+
word: str
|
|
41
|
+
begin: float
|
|
42
|
+
end: float
|
|
43
|
+
score: Optional[float] = None
|
|
44
|
+
phones: List[Phone] = field(default_factory=list)
|
|
45
|
+
spoken: bool = True
|
|
46
|
+
annotation: bool = False
|
|
47
|
+
untranscribed: bool = False # heard but not in your transcript (align_untranscribed=True)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_dict(cls, d: dict) -> "Word":
|
|
51
|
+
return cls(word=d["word"], begin=float(d["begin"]), end=float(d["end"]), score=d.get("score"),
|
|
52
|
+
phones=[Phone.from_dict(p) for p in d.get("phones") or []],
|
|
53
|
+
spoken=bool(d.get("spoken", True)), annotation=bool(d.get("annotation", False)),
|
|
54
|
+
untranscribed=bool(d.get("untranscribed", False)))
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> dict:
|
|
57
|
+
out: dict = {"word": self.word, "begin": self.begin, "end": self.end}
|
|
58
|
+
if self.score is not None:
|
|
59
|
+
out["score"] = self.score
|
|
60
|
+
out["phones"] = [p.to_dict() for p in self.phones]
|
|
61
|
+
if not self.spoken:
|
|
62
|
+
out["spoken"] = False
|
|
63
|
+
if self.annotation:
|
|
64
|
+
out["annotation"] = True
|
|
65
|
+
if self.untranscribed:
|
|
66
|
+
out["untranscribed"] = True
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def timed(self) -> bool:
|
|
71
|
+
"""True for a spoken word with a duration: one that belongs on a timeline."""
|
|
72
|
+
return self.spoken and not self.annotation and self.end > self.begin
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class Pause:
|
|
77
|
+
"""A stretch of 0.05 s or more that no word covers: silence, a breath, a noise."""
|
|
78
|
+
begin: float
|
|
79
|
+
end: float
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def seconds(self) -> float:
|
|
83
|
+
return self.end - self.begin
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def from_dict(cls, d: dict) -> "Pause":
|
|
87
|
+
return cls(begin=float(d["begin"]), end=float(d["end"]))
|
|
88
|
+
|
|
89
|
+
def to_dict(self) -> dict:
|
|
90
|
+
return {"begin": self.begin, "end": self.end}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class Phrase:
|
|
95
|
+
"""Words between pauses of 0.1 s or more. ``first`` and ``last`` are
|
|
96
|
+
positions in :attr:`Result.words`, both included."""
|
|
97
|
+
begin: float
|
|
98
|
+
end: float
|
|
99
|
+
first: int
|
|
100
|
+
last: int
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def from_dict(cls, d: dict) -> "Phrase":
|
|
104
|
+
first, last = d["words"]
|
|
105
|
+
return cls(begin=float(d["begin"]), end=float(d["end"]), first=int(first), last=int(last))
|
|
106
|
+
|
|
107
|
+
def to_dict(self) -> dict:
|
|
108
|
+
return {"begin": self.begin, "end": self.end, "words": [self.first, self.last]}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass
|
|
112
|
+
class Result:
|
|
113
|
+
"""One olign job. ``words`` is empty until ``state`` is ``done``."""
|
|
114
|
+
|
|
115
|
+
job_id: Optional[str] = None
|
|
116
|
+
state: str = "done"
|
|
117
|
+
audio_seconds: Optional[float] = None
|
|
118
|
+
transcript_source: Optional[str] = None
|
|
119
|
+
words: List[Word] = field(default_factory=list)
|
|
120
|
+
pauses: List[Pause] = field(default_factory=list)
|
|
121
|
+
phrases: List[Phrase] = field(default_factory=list)
|
|
122
|
+
progress: Optional[float] = None
|
|
123
|
+
error: Optional[str] = None
|
|
124
|
+
api_version: Optional[str] = None
|
|
125
|
+
olign_version: Optional[str] = None
|
|
126
|
+
|
|
127
|
+
# -- reading -------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def from_dict(cls, d: dict, headers: Optional[dict] = None) -> "Result":
|
|
131
|
+
"""Build a Result from a job status response, or from what
|
|
132
|
+
:meth:`to_json` or the API saved. Fields the client does not use are
|
|
133
|
+
ignored."""
|
|
134
|
+
h = {k.lower(): v for k, v in (headers or {}).items()}
|
|
135
|
+
saved = {k.lower(): v for k, v in (d.get("_versions") or {}).items()}
|
|
136
|
+
result = d.get("result") or {}
|
|
137
|
+
progress = d.get("progress")
|
|
138
|
+
return cls(
|
|
139
|
+
job_id=d.get("job_id"),
|
|
140
|
+
state=d.get("state", "done"),
|
|
141
|
+
audio_seconds=None if d.get("audio_seconds") is None else float(d["audio_seconds"]),
|
|
142
|
+
transcript_source=d.get("transcript_source"),
|
|
143
|
+
words=[Word.from_dict(w) for w in result.get("words") or []],
|
|
144
|
+
pauses=[Pause.from_dict(p) for p in result.get("pauses") or []],
|
|
145
|
+
phrases=[Phrase.from_dict(p) for p in result.get("phrases") or []],
|
|
146
|
+
progress=None if progress is None else float(progress),
|
|
147
|
+
error=d.get("error"),
|
|
148
|
+
api_version=h.get("x-olign-api-version") or saved.get("x-olign-api-version"),
|
|
149
|
+
olign_version=h.get("x-olign-version") or saved.get("x-olign-version"),
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def load(cls, path: PathLike) -> "Result":
|
|
154
|
+
"""Read a result saved as JSON."""
|
|
155
|
+
return cls.from_dict(json.loads(pathlib.Path(path).read_text(encoding="utf-8")))
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def done(self) -> bool:
|
|
159
|
+
return self.state == "done"
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def text(self) -> str:
|
|
163
|
+
"""The spoken words, joined by spaces."""
|
|
164
|
+
return " ".join(w.word for w in self.words if w.spoken and not w.annotation)
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def duration(self) -> float:
|
|
168
|
+
"""The audio length, or the end of the last word when it is unknown."""
|
|
169
|
+
if self.audio_seconds is not None:
|
|
170
|
+
return self.audio_seconds
|
|
171
|
+
return max((w.end for w in self.words), default=0.0)
|
|
172
|
+
|
|
173
|
+
def timed_words(self) -> Iterator[Word]:
|
|
174
|
+
return (w for w in self.words if w.timed)
|
|
175
|
+
|
|
176
|
+
def phrase_words(self, phrase: Phrase) -> List[Word]:
|
|
177
|
+
"""The words of one of :attr:`phrases`."""
|
|
178
|
+
return self.words[phrase.first:phrase.last + 1]
|
|
179
|
+
|
|
180
|
+
# -- writing -------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
def to_json(self, path: Optional[PathLike] = None, indent: int = 1) -> str:
|
|
183
|
+
"""The job's public fields and its words, in the API's own shape, so
|
|
184
|
+
:meth:`load` reads it back."""
|
|
185
|
+
d: dict = {"job_id": self.job_id, "state": self.state, "audio_seconds": self.audio_seconds,
|
|
186
|
+
"transcript_source": self.transcript_source,
|
|
187
|
+
"result": {"words": [w.to_dict() for w in self.words],
|
|
188
|
+
"pauses": [p.to_dict() for p in self.pauses],
|
|
189
|
+
"phrases": [p.to_dict() for p in self.phrases]}}
|
|
190
|
+
if self.error:
|
|
191
|
+
d["error"] = self.error
|
|
192
|
+
versions = {k: v for k, v in (("X-Olign-Api-Version", self.api_version),
|
|
193
|
+
("X-Olign-Version", self.olign_version)) if v}
|
|
194
|
+
if versions:
|
|
195
|
+
d["_versions"] = versions
|
|
196
|
+
return _out(json.dumps(d, indent=indent, ensure_ascii=False) + "\n", path)
|
|
197
|
+
|
|
198
|
+
def to_csv(self, path: Optional[PathLike] = None, phones: bool = False) -> str:
|
|
199
|
+
"""One row per word. With ``phones=True``, one row per phone."""
|
|
200
|
+
buf = io.StringIO()
|
|
201
|
+
out = csv.writer(buf, lineterminator="\n")
|
|
202
|
+
if phones:
|
|
203
|
+
out.writerow(["word_index", "word", "phone", "begin", "end", "score"])
|
|
204
|
+
for i, w in enumerate(self.words):
|
|
205
|
+
for p in w.phones:
|
|
206
|
+
out.writerow([i, w.word, p.ph, _num(p.begin), _num(p.end), _opt(p.score)])
|
|
207
|
+
else:
|
|
208
|
+
out.writerow(["index", "word", "begin", "end", "score", "spoken"])
|
|
209
|
+
for i, w in enumerate(self.words):
|
|
210
|
+
out.writerow([i, w.word, _num(w.begin), _num(w.end), _opt(w.score), str(w.spoken).lower()])
|
|
211
|
+
return _out(buf.getvalue(), path)
|
|
212
|
+
|
|
213
|
+
def to_textgrid(self, path: Optional[PathLike] = None) -> str:
|
|
214
|
+
"""A Praat TextGrid with a words, a phones and a pauses tier. The
|
|
215
|
+
gaps between intervals become empty ones, as Praat requires."""
|
|
216
|
+
xmax = self.duration
|
|
217
|
+
words = list(self.timed_words())
|
|
218
|
+
tiers = {
|
|
219
|
+
"words": [(w.begin, w.end, w.word) for w in words],
|
|
220
|
+
"phones": [(p.begin, p.end, p.ph) for w in words for p in w.phones if p.end > p.begin],
|
|
221
|
+
"pauses": [(p.begin, p.end, "pause") for p in self.pauses if p.end > p.begin],
|
|
222
|
+
}
|
|
223
|
+
lines = ['File type = "ooTextFile"', 'Object class = "TextGrid"', "",
|
|
224
|
+
"xmin = 0", f"xmax = {_num(xmax)}", "tiers? <exists>", f"size = {len(tiers)}", "item []:"]
|
|
225
|
+
for n, (name, spans) in enumerate(tiers.items(), 1):
|
|
226
|
+
iv = _fill(spans, xmax)
|
|
227
|
+
lines += [f" item [{n}]:", ' class = "IntervalTier"', f' name = "{name}"',
|
|
228
|
+
" xmin = 0", f" xmax = {_num(xmax)}", f" intervals: size = {len(iv)}"]
|
|
229
|
+
for k, (b, e, label) in enumerate(iv, 1):
|
|
230
|
+
text = label.replace('"', '""')
|
|
231
|
+
lines += [f" intervals [{k}]:", f" xmin = {_num(b)}",
|
|
232
|
+
f" xmax = {_num(e)}", f' text = "{text}"']
|
|
233
|
+
return _out("\n".join(lines) + "\n", path)
|
|
234
|
+
|
|
235
|
+
def cues(self, max_chars: int = 42, max_duration: float = 6.0, max_gap: float = 0.6,
|
|
236
|
+
max_words: Optional[int] = None) -> List[List[Word]]:
|
|
237
|
+
"""Group the spoken words into subtitle cues. A new cue starts after a
|
|
238
|
+
pause longer than ``max_gap`` seconds, after a word that ends a
|
|
239
|
+
sentence, or when the cue would grow past ``max_chars`` characters,
|
|
240
|
+
``max_duration`` seconds or ``max_words`` words. ``max_words=1``
|
|
241
|
+
gives one cue per word."""
|
|
242
|
+
cues: List[List[Word]] = []
|
|
243
|
+
cur: List[Word] = []
|
|
244
|
+
for w in self.timed_words():
|
|
245
|
+
if cur:
|
|
246
|
+
chars = sum(len(x.word) + 1 for x in cur) + len(w.word)
|
|
247
|
+
if (w.begin - cur[-1].end > max_gap or cur[-1].word.rstrip("\"')").endswith((".", "?", "!"))
|
|
248
|
+
or chars > max_chars or w.end - cur[0].begin > max_duration
|
|
249
|
+
or (max_words and len(cur) >= max_words)):
|
|
250
|
+
cues.append(cur)
|
|
251
|
+
cur = []
|
|
252
|
+
cur.append(w)
|
|
253
|
+
if cur:
|
|
254
|
+
cues.append(cur)
|
|
255
|
+
return cues
|
|
256
|
+
|
|
257
|
+
def to_srt(self, path: Optional[PathLike] = None, **cue_options: Any) -> str:
|
|
258
|
+
"""SubRip subtitles. Each cue starts when its first word starts and
|
|
259
|
+
ends when its last word ends. Takes the options of :meth:`cues`."""
|
|
260
|
+
blocks = []
|
|
261
|
+
for n, cue in enumerate(self.cues(**cue_options), 1):
|
|
262
|
+
text = " ".join(w.word for w in cue)
|
|
263
|
+
blocks.append(f"{n}\n{_clock(cue[0].begin, ',')} --> {_clock(cue[-1].end, ',')}\n{text}\n")
|
|
264
|
+
return _out("\n".join(blocks), path)
|
|
265
|
+
|
|
266
|
+
def to_vtt(self, path: Optional[PathLike] = None, word_timing: bool = True, **cue_options: Any) -> str:
|
|
267
|
+
"""WebVTT subtitles. With ``word_timing`` (the default), every word
|
|
268
|
+
after the first in a cue carries its start time as a WebVTT timestamp
|
|
269
|
+
tag, so players that support it highlight each word as it is said.
|
|
270
|
+
Takes the options of :meth:`cues`."""
|
|
271
|
+
blocks = ["WEBVTT\n"]
|
|
272
|
+
for cue in self.cues(**cue_options):
|
|
273
|
+
parts = [_vtt_escape(cue[0].word)]
|
|
274
|
+
last = cue[0].begin
|
|
275
|
+
for w in cue[1:]:
|
|
276
|
+
tag = ""
|
|
277
|
+
if word_timing and w.begin > last: # WebVTT wants each tag later than the one before
|
|
278
|
+
tag, last = f"<{_clock(w.begin, '.')}>", w.begin
|
|
279
|
+
parts.append(tag + _vtt_escape(w.word))
|
|
280
|
+
blocks.append(f"{_clock(cue[0].begin, '.')} --> {_clock(cue[-1].end, '.')}\n{' '.join(parts)}\n")
|
|
281
|
+
return _out("\n".join(blocks), path)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _fill(spans, xmax: float):
|
|
285
|
+
"""Sort the spans, clip overlaps and fill every gap with an empty interval."""
|
|
286
|
+
out, t = [], 0.0
|
|
287
|
+
for b, e, label in sorted(spans):
|
|
288
|
+
b, e = max(b, t), min(e, xmax)
|
|
289
|
+
if e <= b:
|
|
290
|
+
continue
|
|
291
|
+
if b > t:
|
|
292
|
+
out.append((t, b, ""))
|
|
293
|
+
out.append((b, e, label))
|
|
294
|
+
t = e
|
|
295
|
+
if t < xmax:
|
|
296
|
+
out.append((t, xmax, ""))
|
|
297
|
+
return out
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _num(x: float) -> str:
|
|
301
|
+
s = f"{x:.6f}".rstrip("0").rstrip(".")
|
|
302
|
+
return s if s not in ("", "-0") else "0"
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _opt(x: Optional[float]) -> str:
|
|
306
|
+
return "" if x is None else _num(float(x))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _clock(seconds: float, sep: str) -> str:
|
|
310
|
+
ms = max(0, round(seconds * 1000))
|
|
311
|
+
h, ms = divmod(ms, 3_600_000)
|
|
312
|
+
m, ms = divmod(ms, 60_000)
|
|
313
|
+
s, ms = divmod(ms, 1000)
|
|
314
|
+
return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _vtt_escape(text: str) -> str:
|
|
318
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _out(text: str, path: Optional[PathLike]) -> str:
|
|
322
|
+
if path is not None:
|
|
323
|
+
p = pathlib.Path(path)
|
|
324
|
+
if p.parent != pathlib.Path("."):
|
|
325
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
326
|
+
p.write_text(text, encoding="utf-8")
|
|
327
|
+
return text
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: olign
|
|
3
|
+
Version: 1.1.4
|
|
4
|
+
Summary: Word and phone timestamps for English speech, from the Olign forced alignment API
|
|
5
|
+
Author-email: "Olewave, LLC" <info@olewave.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://olewave.com
|
|
8
|
+
Project-URL: Documentation, https://github.com/olewave/olign-client#readme
|
|
9
|
+
Project-URL: Source, https://github.com/olewave/olign-client
|
|
10
|
+
Project-URL: Benchmark, https://github.com/olewave/fa-bench
|
|
11
|
+
Keywords: forced alignment,word timestamps,speech,TextGrid,Praat,subtitles,SRT,WebVTT
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# olign
|
|
27
|
+
|
|
28
|
+
`olign` is the Python package and command line for Olign, the forced alignment
|
|
29
|
+
API from Olewave. You send English speech, with its transcript if you have one.
|
|
30
|
+
Olign tells you where every word and every phone starts and ends, in seconds.
|
|
31
|
+
Without a transcript, Olign transcribes the audio first and then aligns it.
|
|
32
|
+
|
|
33
|
+
Each result also lists the pauses between the words and the phrases they
|
|
34
|
+
form, and `word_edges="audible"` times words the way a listener hears them, for
|
|
35
|
+
dubbing and subtitles.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
The package runs on Python 3.9 or later and needs nothing beyond the standard
|
|
40
|
+
library.
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install olign
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The package's version is the Olign release it was made with: Olign, its API
|
|
47
|
+
and this package share one version number.
|
|
48
|
+
|
|
49
|
+
Sign up at [tycho.olewave.com](https://tycho.olewave.com/#signup). No invitation
|
|
50
|
+
code is needed, and a new account starts with 300 free credits. Save a card under
|
|
51
|
+
**Billing** for 3,000 more: 1,000 minutes of audio at the launch promotion's price.
|
|
52
|
+
Saving it charges nothing. Then create an API
|
|
53
|
+
key under **Profile → API keys** and put it in `OLIGN_KEY`.
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
export OLIGN_KEY=gvk_your_key
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Command line
|
|
60
|
+
|
|
61
|
+
One line uploads a recording and writes a Praat TextGrid with a words, a
|
|
62
|
+
phones and a pauses tier.
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
olign align talk.mp3 --transcript talk.txt --textgrid
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Leave out `--transcript` and Olign transcribes the audio first. Swap
|
|
69
|
+
`--textgrid` for `--srt` or `--vtt` to get subtitles instead.
|
|
70
|
+
|
|
71
|
+
## Python
|
|
72
|
+
|
|
73
|
+
`olign.Client` submits the job and polls it until the words are ready. This
|
|
74
|
+
example aligns
|
|
75
|
+
[short1.wav](https://github.com/olewave/olign-client/blob/main/examples/short1.wav),
|
|
76
|
+
a 4.5-second clip from the repo.
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import olign
|
|
80
|
+
|
|
81
|
+
client = olign.Client() # reads OLIGN_KEY
|
|
82
|
+
result = client.align("short1.wav", transcript="what is better a fruit or hamburger")
|
|
83
|
+
|
|
84
|
+
for w in result.words:
|
|
85
|
+
print(f"{w.word:<10} {w.begin:5.2f} {w.end:5.2f}")
|
|
86
|
+
|
|
87
|
+
result.to_srt("short1.srt")
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Each line is a word with its start and end in seconds. Here are the first
|
|
91
|
+
three.
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
what 0.47 0.75
|
|
95
|
+
is 0.84 1.13
|
|
96
|
+
better 1.21 1.89
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Pricing
|
|
100
|
+
|
|
101
|
+
You pay in prepaid credits, and 1,000 credits cost $1. A minute of audio is 3 credits
|
|
102
|
+
during the launch promotion ($0.18 an hour) and 3.5 after it ($0.21 an hour).
|
|
103
|
+
Saving a card adds 3,000 free credits, and credits never expire.
|
|
104
|
+
|
|
105
|
+
## Learn more
|
|
106
|
+
|
|
107
|
+
The documentation, the source and more examples are on
|
|
108
|
+
[GitHub](https://github.com/olewave/olign-client).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
olign/__init__.py,sha256=hANqdyiGBl7F9b12vh8lYNYEEFxbmFJUfztfM9dj4TU,946
|
|
2
|
+
olign/__main__.py,sha256=Ey84c70OZB0_1hP_XxZklzqIJndLWXjhrONYHS4QbCU,75
|
|
3
|
+
olign/cli.py,sha256=WXaalTy7t1qb7sIt5tbUB6iZ-RFpYbLg32ZZO3W8Wwo,8759
|
|
4
|
+
olign/client.py,sha256=5-2-WFWuBGdFnPVWa5yEM6hPOrvzKTLfBd3pkKoM3HA,8918
|
|
5
|
+
olign/errors.py,sha256=4rDM3CntbTFEv6oeVM1tAkedZ5p-UrUPar-tQ1MXGno,2524
|
|
6
|
+
olign/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
olign/result.py,sha256=e9hwmrYTn2BOYvaOUoIA9-8T5yZv_khzDjjMAtE5JWE,13176
|
|
8
|
+
olign-1.1.4.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
9
|
+
olign-1.1.4.dist-info/METADATA,sha256=dGCP3YaSaKQWezh6cZKYU84bG3BNClg60Fvsd62GiWs,3579
|
|
10
|
+
olign-1.1.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
olign-1.1.4.dist-info/entry_points.txt,sha256=lwuuWiewjfXXEZw1JQm_bMYYVXvK_lpRcgOvWQVzC08,41
|
|
12
|
+
olign-1.1.4.dist-info/top_level.txt,sha256=IwVhDG81P0ZahIUTkqITOq3DgTFmX38IvIG5g800NDc,6
|
|
13
|
+
olign-1.1.4.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
olign
|