uppercut-tts-worker 0.1.0__tar.gz
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.
- uppercut_tts_worker-0.1.0/.gitignore +10 -0
- uppercut_tts_worker-0.1.0/PKG-INFO +108 -0
- uppercut_tts_worker-0.1.0/README.md +86 -0
- uppercut_tts_worker-0.1.0/pyproject.toml +39 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/__init__.py +27 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/__main__.py +5 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/job.py +107 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/lock.py +111 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/priority.py +60 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/protocol.py +43 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/py.typed +0 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/serve.py +38 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/wav.py +31 -0
- uppercut_tts_worker-0.1.0/src/uppercut_tts_worker/worker.py +103 -0
- uppercut_tts_worker-0.1.0/tests/fake_worker.py +36 -0
- uppercut_tts_worker-0.1.0/tests/test_tts_worker.py +321 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-tts-worker
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The JSON-lines protocol for a resident text-to-speech worker process, a GPU lock that queues, and a resumable job runner. Standard library only; no voice, sample or model is included.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-tts-worker
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Keywords: gpu,json-lines,lock,narration,text-to-speech,tts,worker
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
+
Classifier: Operating System :: POSIX
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# uppercut-tts-worker
|
|
24
|
+
|
|
25
|
+
A text-to-speech model is slow to load and takes the whole GPU, so narration tools start it once as a worker process and send it one sentence at a time. This package is the shared part: the line protocol between the tool and the worker, a lock file that lets only one GPU job run on a machine and queues the others, a job runner that resumes where it stopped, and the worker-side loop for writing a worker. No voice, voice sample, model name or weights are in it: those belong to whoever runs the worker. Standard library only.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install uppercut-tts-worker
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## The protocol
|
|
32
|
+
|
|
33
|
+
One JSON object per line in each direction, over the worker's standard input and output.
|
|
34
|
+
|
|
35
|
+
```text
|
|
36
|
+
worker -> {"ready": true, "device": "cuda:0", "dtype": "float32"} once, when the model is loaded
|
|
37
|
+
tool -> {"text": "...", "output_path": "a.wav", "seed": 12, "settings": {...}, "voice_id": "v1"}
|
|
38
|
+
worker -> {"ok": true, "sample_rate": 24000, "samples": 48000, "wall_s": 1.2}
|
|
39
|
+
worker -> {"ok": false, "error": "RuntimeError: ..."} for a sentence it could not say
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`voice_id` is sent only when there is one. Lines that are not JSON objects, such as a library's log output, are skipped by the reader.
|
|
43
|
+
|
|
44
|
+
## Write a worker
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from uppercut_tts_worker import serve
|
|
48
|
+
|
|
49
|
+
def synthesize(request):
|
|
50
|
+
audio = my_model.say(request["text"], seed=request["seed"], **request["settings"])
|
|
51
|
+
audio.write_wav(request["output_path"])
|
|
52
|
+
return {"sample_rate": audio.rate, "samples": len(audio)}
|
|
53
|
+
|
|
54
|
+
serve(synthesize, ready={"device": "cuda:0", "dtype": "float32"})
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
An exception becomes an `ok: false` response and the loop goes on with the next sentence.
|
|
58
|
+
|
|
59
|
+
## Use a worker
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from uppercut_tts_worker import GpuLock, WorkerProcess, make_request, wav_seconds
|
|
63
|
+
|
|
64
|
+
with GpuLock("runs/.gpu.lock", wait_s=2700, on_wait=print): # queue behind another GPU job
|
|
65
|
+
with WorkerProcess("python", "worker.py", ["--ckpt-dir", "weights"], log_path="worker.log",
|
|
66
|
+
env={"HF_HUB_OFFLINE": "1"}) as worker: # starts it and waits for the ready line
|
|
67
|
+
reply = worker.request(make_request("Hello there.", "hello.wav", seed=7, settings={"language": "English"}))
|
|
68
|
+
if reply["ok"]:
|
|
69
|
+
print(wav_seconds("hello.wav"), "seconds")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Run a job file
|
|
73
|
+
|
|
74
|
+
`uppercut-tts-worker job.json` (or `python -m uppercut_tts_worker job.json`, or `run_job(job)`) generates a list of sentences in one go, on the machine that has the GPU:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{"worker": {"python": "python", "script": "worker.py", "args": ["--ckpt-dir", "weights"], "env": {"HF_HUB_OFFLINE": "1"}},
|
|
78
|
+
"lock": "runs/.gpu.lock", "lock_wait_s": 2700,
|
|
79
|
+
"out_dir": "tts/job1",
|
|
80
|
+
"items": [{"id": "s001", "text": "First sentence.", "seed": 123, "settings": {"language": "English"}, "voice_id": "v1"}]}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Each item is written to `out_dir/<id>.wav` and recorded in `out_dir/results.json` with the SHA-256 of its text and its seed. An item whose WAV exists and whose text and seed still match is skipped, so an interrupted job resumes and an edited sentence is generated again. The lock is taken only when something is left to do. The exit code is 1 if any item failed or the job could not run.
|
|
84
|
+
|
|
85
|
+
## API
|
|
86
|
+
|
|
87
|
+
| Name | What it does |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `make_request(text, output_path, *, seed=None, settings=None, voice_id=None)` | A request object |
|
|
90
|
+
| `read_message(stream)`, `write_message(stream, message)` | One protocol line in or out. `read_message` skips lines that are not JSON objects and returns None at the end |
|
|
91
|
+
| `serve(synthesize, *, ready=None, stdin=None, stdout=None)` | The worker loop |
|
|
92
|
+
| `WorkerProcess(python, script, args=(), *, env=None, log_path=None, cwd=None, raise_priority=False)` | Start a worker (`start()`, `wait_ready()`, `request(r)`, `close()`, or use it as a context manager). Raises `WorkerError` when it does not become ready or exits mid-request. A reply is waited for without a time limit |
|
|
93
|
+
| `GpuLock(path, *, wait_s=0, poll_s=5, on_wait=None)` | The lock file. Context manager, or `acquire()` and `release()`. Raises `LockBusy` |
|
|
94
|
+
| `process_alive(pid)` | Whether a process is running, on Windows and elsewhere |
|
|
95
|
+
| `wav_seconds(path)` | Length of a WAV of any sample format, float files included |
|
|
96
|
+
| `raise_tree_priority(pid)` | Windows only: raise a process and its children to above normal priority, which stops ssh-started processes from running at low clocks. Returns the ids it changed |
|
|
97
|
+
| `run_job(job, *, log, lock_log)`, `main(argv)` | The job runner and its command |
|
|
98
|
+
|
|
99
|
+
## Notes
|
|
100
|
+
|
|
101
|
+
- The lock holds the owner's process id. A lock whose owner has exited is removed and taken; a lock held by a live process is waited for and never deleted. Two machines sharing a network folder do not share a lock: process ids mean nothing across machines.
|
|
102
|
+
- `release()` removes the file only while it still names this process, so a lock that was taken over is left alone.
|
|
103
|
+
- The fake worker in the tests (`tests/fake_worker.py`) is a complete example of a worker built on `serve`.
|
|
104
|
+
- The Windows pieces (`process_alive` and `raise_tree_priority` use the Win32 API) were written from the working scripts they replace but have not been run on Windows by this package's tests.
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# uppercut-tts-worker
|
|
2
|
+
|
|
3
|
+
A text-to-speech model is slow to load and takes the whole GPU, so narration tools start it once as a worker process and send it one sentence at a time. This package is the shared part: the line protocol between the tool and the worker, a lock file that lets only one GPU job run on a machine and queues the others, a job runner that resumes where it stopped, and the worker-side loop for writing a worker. No voice, voice sample, model name or weights are in it: those belong to whoever runs the worker. Standard library only.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install uppercut-tts-worker
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## The protocol
|
|
10
|
+
|
|
11
|
+
One JSON object per line in each direction, over the worker's standard input and output.
|
|
12
|
+
|
|
13
|
+
```text
|
|
14
|
+
worker -> {"ready": true, "device": "cuda:0", "dtype": "float32"} once, when the model is loaded
|
|
15
|
+
tool -> {"text": "...", "output_path": "a.wav", "seed": 12, "settings": {...}, "voice_id": "v1"}
|
|
16
|
+
worker -> {"ok": true, "sample_rate": 24000, "samples": 48000, "wall_s": 1.2}
|
|
17
|
+
worker -> {"ok": false, "error": "RuntimeError: ..."} for a sentence it could not say
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`voice_id` is sent only when there is one. Lines that are not JSON objects, such as a library's log output, are skipped by the reader.
|
|
21
|
+
|
|
22
|
+
## Write a worker
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from uppercut_tts_worker import serve
|
|
26
|
+
|
|
27
|
+
def synthesize(request):
|
|
28
|
+
audio = my_model.say(request["text"], seed=request["seed"], **request["settings"])
|
|
29
|
+
audio.write_wav(request["output_path"])
|
|
30
|
+
return {"sample_rate": audio.rate, "samples": len(audio)}
|
|
31
|
+
|
|
32
|
+
serve(synthesize, ready={"device": "cuda:0", "dtype": "float32"})
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
An exception becomes an `ok: false` response and the loop goes on with the next sentence.
|
|
36
|
+
|
|
37
|
+
## Use a worker
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from uppercut_tts_worker import GpuLock, WorkerProcess, make_request, wav_seconds
|
|
41
|
+
|
|
42
|
+
with GpuLock("runs/.gpu.lock", wait_s=2700, on_wait=print): # queue behind another GPU job
|
|
43
|
+
with WorkerProcess("python", "worker.py", ["--ckpt-dir", "weights"], log_path="worker.log",
|
|
44
|
+
env={"HF_HUB_OFFLINE": "1"}) as worker: # starts it and waits for the ready line
|
|
45
|
+
reply = worker.request(make_request("Hello there.", "hello.wav", seed=7, settings={"language": "English"}))
|
|
46
|
+
if reply["ok"]:
|
|
47
|
+
print(wav_seconds("hello.wav"), "seconds")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Run a job file
|
|
51
|
+
|
|
52
|
+
`uppercut-tts-worker job.json` (or `python -m uppercut_tts_worker job.json`, or `run_job(job)`) generates a list of sentences in one go, on the machine that has the GPU:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{"worker": {"python": "python", "script": "worker.py", "args": ["--ckpt-dir", "weights"], "env": {"HF_HUB_OFFLINE": "1"}},
|
|
56
|
+
"lock": "runs/.gpu.lock", "lock_wait_s": 2700,
|
|
57
|
+
"out_dir": "tts/job1",
|
|
58
|
+
"items": [{"id": "s001", "text": "First sentence.", "seed": 123, "settings": {"language": "English"}, "voice_id": "v1"}]}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Each item is written to `out_dir/<id>.wav` and recorded in `out_dir/results.json` with the SHA-256 of its text and its seed. An item whose WAV exists and whose text and seed still match is skipped, so an interrupted job resumes and an edited sentence is generated again. The lock is taken only when something is left to do. The exit code is 1 if any item failed or the job could not run.
|
|
62
|
+
|
|
63
|
+
## API
|
|
64
|
+
|
|
65
|
+
| Name | What it does |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| `make_request(text, output_path, *, seed=None, settings=None, voice_id=None)` | A request object |
|
|
68
|
+
| `read_message(stream)`, `write_message(stream, message)` | One protocol line in or out. `read_message` skips lines that are not JSON objects and returns None at the end |
|
|
69
|
+
| `serve(synthesize, *, ready=None, stdin=None, stdout=None)` | The worker loop |
|
|
70
|
+
| `WorkerProcess(python, script, args=(), *, env=None, log_path=None, cwd=None, raise_priority=False)` | Start a worker (`start()`, `wait_ready()`, `request(r)`, `close()`, or use it as a context manager). Raises `WorkerError` when it does not become ready or exits mid-request. A reply is waited for without a time limit |
|
|
71
|
+
| `GpuLock(path, *, wait_s=0, poll_s=5, on_wait=None)` | The lock file. Context manager, or `acquire()` and `release()`. Raises `LockBusy` |
|
|
72
|
+
| `process_alive(pid)` | Whether a process is running, on Windows and elsewhere |
|
|
73
|
+
| `wav_seconds(path)` | Length of a WAV of any sample format, float files included |
|
|
74
|
+
| `raise_tree_priority(pid)` | Windows only: raise a process and its children to above normal priority, which stops ssh-started processes from running at low clocks. Returns the ids it changed |
|
|
75
|
+
| `run_job(job, *, log, lock_log)`, `main(argv)` | The job runner and its command |
|
|
76
|
+
|
|
77
|
+
## Notes
|
|
78
|
+
|
|
79
|
+
- The lock holds the owner's process id. A lock whose owner has exited is removed and taken; a lock held by a live process is waited for and never deleted. Two machines sharing a network folder do not share a lock: process ids mean nothing across machines.
|
|
80
|
+
- `release()` removes the file only while it still names this process, so a lock that was taken over is left alone.
|
|
81
|
+
- The fake worker in the tests (`tests/fake_worker.py`) is a complete example of a worker built on `serve`.
|
|
82
|
+
- The Windows pieces (`process_alive` and `raise_tree_priority` use the Win32 API) were written from the working scripts they replace but have not been run on Windows by this package's tests.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-tts-worker"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The JSON-lines protocol for a resident text-to-speech worker process, a GPU lock that queues, and a resumable job runner. Standard library only; no voice, sample or model is included."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
keywords = ["tts", "text-to-speech", "worker", "json-lines", "gpu", "lock", "narration"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: MacOS",
|
|
19
|
+
"Operating System :: Microsoft :: Windows",
|
|
20
|
+
"Operating System :: POSIX",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
uppercut-tts-worker = "uppercut_tts_worker.job:main"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-tts-worker"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/uppercut_tts_worker"]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.sdist]
|
|
39
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""The protocol for a resident text-to-speech worker process, a GPU lock that queues, and a resumable job runner."""
|
|
2
|
+
|
|
3
|
+
from .job import SAFE_ID, main, run_job
|
|
4
|
+
from .lock import GpuLock, LockBusy, process_alive
|
|
5
|
+
from .priority import raise_tree_priority
|
|
6
|
+
from .protocol import make_request, read_message, write_message
|
|
7
|
+
from .serve import serve
|
|
8
|
+
from .wav import wav_seconds
|
|
9
|
+
from .worker import WorkerError, WorkerProcess
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"GpuLock",
|
|
13
|
+
"LockBusy",
|
|
14
|
+
"SAFE_ID",
|
|
15
|
+
"WorkerError",
|
|
16
|
+
"WorkerProcess",
|
|
17
|
+
"main",
|
|
18
|
+
"make_request",
|
|
19
|
+
"process_alive",
|
|
20
|
+
"raise_tree_priority",
|
|
21
|
+
"read_message",
|
|
22
|
+
"run_job",
|
|
23
|
+
"serve",
|
|
24
|
+
"wav_seconds",
|
|
25
|
+
"write_message",
|
|
26
|
+
]
|
|
27
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Run a job file: many sentences through one resident worker, under the GPU lock, resumable."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence
|
|
12
|
+
|
|
13
|
+
from .lock import GpuLock, LockBusy
|
|
14
|
+
from .protocol import make_request
|
|
15
|
+
from .worker import WorkerError, WorkerProcess
|
|
16
|
+
|
|
17
|
+
SAFE_ID = re.compile(r"^[A-Za-z0-9._-]{1,120}$")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _sha(text: str) -> str:
|
|
21
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _save(path: str, data: Dict[str, Any]) -> None:
|
|
25
|
+
tmp = "%s.%d.tmp" % (path, os.getpid())
|
|
26
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
27
|
+
json.dump(data, fh, indent=1)
|
|
28
|
+
os.replace(tmp, path)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def run_job(job: Dict[str, Any], *, log: Callable[[str], None] = lambda line: print(line, flush=True),
|
|
32
|
+
lock_log: Callable[[str], None] = lambda line: print(line, file=sys.stderr, flush=True)) -> int:
|
|
33
|
+
"""Generate every item of the job that is not already done; returns 0, or 1 if any item failed.
|
|
34
|
+
|
|
35
|
+
The job is a dict::
|
|
36
|
+
|
|
37
|
+
{"worker": {"python": "...", "script": "...", "args": [...], "env": {...}},
|
|
38
|
+
"lock": "path/to/.gpu.lock", "lock_wait_s": 2700,
|
|
39
|
+
"out_dir": "path",
|
|
40
|
+
"items": [{"id": "s001", "text": "...", "seed": 123, "settings": {...}, "voice_id": "..."}]}
|
|
41
|
+
|
|
42
|
+
Each item is written to `out_dir/<id>.wav` and recorded in `out_dir/results.json` with the SHA-256 of its
|
|
43
|
+
text and its seed. An item whose WAV exists and whose recorded text hash and seed match is skipped, so an
|
|
44
|
+
interrupted job resumes and an edited sentence is generated again. `settings` defaults to
|
|
45
|
+
`{"language": "English"}`. The lock is taken only when something is left to generate, and the worker's
|
|
46
|
+
standard error goes to `out_dir/worker.log`. Raises LockBusy when the lock stays taken for `lock_wait_s`
|
|
47
|
+
(default 2700) seconds, and WorkerError when the worker cannot start or dies.
|
|
48
|
+
"""
|
|
49
|
+
out = job["out_dir"]
|
|
50
|
+
os.makedirs(out, exist_ok=True)
|
|
51
|
+
items: Sequence[Dict[str, Any]] = job["items"]
|
|
52
|
+
for item in items:
|
|
53
|
+
if not SAFE_ID.match(str(item.get("id", ""))):
|
|
54
|
+
raise ValueError("item id %r is not filename safe" % (item.get("id"),))
|
|
55
|
+
results_path = os.path.join(out, "results.json")
|
|
56
|
+
results: Dict[str, Any] = {}
|
|
57
|
+
if os.path.exists(results_path):
|
|
58
|
+
with open(results_path, encoding="utf-8") as fh:
|
|
59
|
+
results = json.load(fh)
|
|
60
|
+
todo = [it for it in items
|
|
61
|
+
if not (os.path.exists(os.path.join(out, it["id"] + ".wav"))
|
|
62
|
+
and results.get(it["id"], {}).get("text_sha256") == _sha(it["text"])
|
|
63
|
+
and results[it["id"]].get("seed") == it.get("seed"))]
|
|
64
|
+
log("%d/%d items to generate" % (len(todo), len(items)))
|
|
65
|
+
if not todo:
|
|
66
|
+
return 0
|
|
67
|
+
spec = job["worker"]
|
|
68
|
+
with GpuLock(job["lock"], wait_s=float(job.get("lock_wait_s", 2700)), on_wait=lock_log):
|
|
69
|
+
with WorkerProcess(spec["python"], spec["script"], spec.get("args", ()), env=spec.get("env"),
|
|
70
|
+
log_path=os.path.join(out, "worker.log"), raise_priority=True) as worker:
|
|
71
|
+
log("worker ready on %s (%s)" % (worker.ready.get("device"), worker.ready.get("dtype")))
|
|
72
|
+
failed = 0
|
|
73
|
+
for item in todo:
|
|
74
|
+
wav = os.path.join(out, item["id"] + ".wav")
|
|
75
|
+
request = make_request(item["text"], wav, seed=item.get("seed"),
|
|
76
|
+
settings=item.get("settings") or {"language": "English"},
|
|
77
|
+
voice_id=item.get("voice_id"))
|
|
78
|
+
started = time.time()
|
|
79
|
+
response = worker.request(request)
|
|
80
|
+
ok = bool(response.get("ok"))
|
|
81
|
+
failed += not ok
|
|
82
|
+
results[item["id"]] = {"ok": ok, "text_sha256": _sha(item["text"]), "seed": item.get("seed"),
|
|
83
|
+
"sample_rate": response.get("sample_rate"), "samples": response.get("samples"),
|
|
84
|
+
"wall_s": response.get("wall_s"), "error": response.get("error")}
|
|
85
|
+
_save(results_path, results)
|
|
86
|
+
log("[%s] %s %ss %s" % ("ok" if ok else "FAILED", item["id"], round(time.time() - started, 1),
|
|
87
|
+
item["text"][:70]))
|
|
88
|
+
return 1 if failed else 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
92
|
+
"""`uppercut-tts-worker job.json`: run the job; exit 1 if an item failed or the job could not run."""
|
|
93
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
94
|
+
if len(args) != 1 or args[0] in ("-h", "--help"):
|
|
95
|
+
sys.stderr.write((run_job.__doc__ or "") + "\nusage: uppercut-tts-worker job.json\n")
|
|
96
|
+
return 0 if args[:1] in (["-h"], ["--help"]) else 2
|
|
97
|
+
with open(args[0], encoding="utf-8") as fh:
|
|
98
|
+
job = json.load(fh)
|
|
99
|
+
try:
|
|
100
|
+
return run_job(job)
|
|
101
|
+
except (LockBusy, WorkerError) as exc:
|
|
102
|
+
sys.stderr.write("%s\n" % exc)
|
|
103
|
+
return 1
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
sys.exit(main())
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""One GPU job at a time on a machine: a lock file that holds the owner's process id."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import atexit
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
from typing import Callable, Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LockBusy(RuntimeError):
|
|
13
|
+
"""A live process holds the lock and `wait_s` ran out."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def process_alive(pid: int) -> bool:
|
|
17
|
+
"""Is a process with this id running? On Windows a process that has exited but is still open elsewhere is dead."""
|
|
18
|
+
if os.name == "nt":
|
|
19
|
+
import ctypes
|
|
20
|
+
|
|
21
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
22
|
+
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
23
|
+
if not handle:
|
|
24
|
+
return False
|
|
25
|
+
code = ctypes.c_ulong()
|
|
26
|
+
kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
|
|
27
|
+
kernel32.CloseHandle(handle)
|
|
28
|
+
return code.value == 259 # STILL_ACTIVE
|
|
29
|
+
try:
|
|
30
|
+
os.kill(pid, 0)
|
|
31
|
+
except PermissionError:
|
|
32
|
+
return True # it exists; it belongs to someone else
|
|
33
|
+
except OSError:
|
|
34
|
+
return False
|
|
35
|
+
return True
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class GpuLock:
|
|
39
|
+
"""A lock file that names its owner's process id.
|
|
40
|
+
|
|
41
|
+
`acquire()` creates the file exclusively. If it exists, the owner is read: a lock left by a process that
|
|
42
|
+
is gone is removed and taken; a lock held by a live process is waited for, polling every `poll_s` seconds
|
|
43
|
+
for up to `wait_s` seconds (0 means fail at once), and then `LockBusy` is raised. A live lock is never
|
|
44
|
+
deleted. `release()` removes the file only while it still names this process, and runs at exit if the
|
|
45
|
+
lock is still held. Use it as a context manager.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, path: "str | os.PathLike[str]", *, wait_s: float = 0.0, poll_s: float = 5.0,
|
|
49
|
+
on_wait: Optional[Callable[[str], None]] = None,
|
|
50
|
+
sleep: Callable[[float], None] = time.sleep, alive: Callable[[int], bool] = process_alive) -> None:
|
|
51
|
+
self.path = os.fspath(path)
|
|
52
|
+
self.wait_s = wait_s
|
|
53
|
+
self.poll_s = poll_s
|
|
54
|
+
self.on_wait = on_wait
|
|
55
|
+
self._sleep = sleep
|
|
56
|
+
self._alive = alive
|
|
57
|
+
self.held = False
|
|
58
|
+
|
|
59
|
+
def acquire(self) -> "GpuLock":
|
|
60
|
+
os.makedirs(os.path.dirname(os.path.abspath(self.path)), exist_ok=True)
|
|
61
|
+
deadline = time.monotonic() + self.wait_s
|
|
62
|
+
announced = False
|
|
63
|
+
while True:
|
|
64
|
+
try:
|
|
65
|
+
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
66
|
+
except FileExistsError:
|
|
67
|
+
try:
|
|
68
|
+
with open(self.path, encoding="utf-8") as fh:
|
|
69
|
+
owner = fh.read().strip()
|
|
70
|
+
except OSError:
|
|
71
|
+
self._sleep(0.05) # released between our open and our read
|
|
72
|
+
continue
|
|
73
|
+
if owner.isdigit() and not self._alive(int(owner)):
|
|
74
|
+
try:
|
|
75
|
+
os.remove(self.path)
|
|
76
|
+
except OSError:
|
|
77
|
+
pass
|
|
78
|
+
continue
|
|
79
|
+
if time.monotonic() >= deadline:
|
|
80
|
+
waited = "" if not self.wait_s else " after %g s" % self.wait_s
|
|
81
|
+
raise LockBusy("GPU busy: pid %s still holds %s%s. Do not delete a live lock." % (owner or "?", self.path, waited))
|
|
82
|
+
if not announced and self.on_wait:
|
|
83
|
+
self.on_wait("GPU busy: pid %s holds %s; waiting up to %g s" % (owner or "?", self.path, self.wait_s))
|
|
84
|
+
announced = True
|
|
85
|
+
self._sleep(self.poll_s)
|
|
86
|
+
continue
|
|
87
|
+
os.write(fd, str(os.getpid()).encode())
|
|
88
|
+
os.close(fd)
|
|
89
|
+
self.held = True
|
|
90
|
+
atexit.register(self.release)
|
|
91
|
+
if announced and self.on_wait:
|
|
92
|
+
self.on_wait("GPU lock acquired")
|
|
93
|
+
return self
|
|
94
|
+
|
|
95
|
+
def release(self) -> None:
|
|
96
|
+
if not self.held:
|
|
97
|
+
return
|
|
98
|
+
self.held = False
|
|
99
|
+
try:
|
|
100
|
+
with open(self.path, encoding="utf-8") as fh:
|
|
101
|
+
if fh.read().strip() == str(os.getpid()):
|
|
102
|
+
os.remove(self.path)
|
|
103
|
+
except OSError:
|
|
104
|
+
pass
|
|
105
|
+
atexit.unregister(self.release)
|
|
106
|
+
|
|
107
|
+
def __enter__(self) -> "GpuLock":
|
|
108
|
+
return self.acquire()
|
|
109
|
+
|
|
110
|
+
def __exit__(self, *exc: object) -> None:
|
|
111
|
+
self.release()
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Windows only: lift a process tree out of the low-power class that processes started over ssh get."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from typing import List
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def raise_tree_priority(pid: int, *, attempts: int = 20, pause: float = 0.1) -> List[int]:
|
|
11
|
+
"""Set the priority class of `pid` and its descendants to ABOVE_NORMAL; returns the ids it reached.
|
|
12
|
+
|
|
13
|
+
Windows runs a process started from an ssh session at low clocks (EcoQoS); a higher class lifts that. A
|
|
14
|
+
virtual environment's `python.exe` is a launcher whose child is the real interpreter and starts at the
|
|
15
|
+
normal class whatever the launcher got, so the tree is searched up to `attempts` times, `pause` seconds
|
|
16
|
+
apart, until the child exists. Does nothing and returns [] on other systems.
|
|
17
|
+
"""
|
|
18
|
+
if os.name != "nt":
|
|
19
|
+
return []
|
|
20
|
+
import ctypes
|
|
21
|
+
from ctypes import wintypes
|
|
22
|
+
|
|
23
|
+
k = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
24
|
+
|
|
25
|
+
class ProcessEntry(ctypes.Structure):
|
|
26
|
+
_fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD), ("th32ProcessID", wintypes.DWORD),
|
|
27
|
+
("th32DefaultHeapID", ctypes.c_void_p), ("th32ModuleID", wintypes.DWORD),
|
|
28
|
+
("cntThreads", wintypes.DWORD), ("th32ParentProcessID", wintypes.DWORD),
|
|
29
|
+
("pcPriClassBase", ctypes.c_long), ("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_char * 260)]
|
|
30
|
+
|
|
31
|
+
k.CreateToolhelp32Snapshot.restype = ctypes.c_void_p
|
|
32
|
+
k.Process32First.argtypes = k.Process32Next.argtypes = [ctypes.c_void_p, ctypes.POINTER(ProcessEntry)]
|
|
33
|
+
k.OpenProcess.restype = ctypes.c_void_p
|
|
34
|
+
k.SetPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
|
35
|
+
k.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
36
|
+
tree: List[int] = [pid]
|
|
37
|
+
for _ in range(max(1, attempts)):
|
|
38
|
+
snapshot, entry, children = k.CreateToolhelp32Snapshot(2, 0), ProcessEntry(), {}
|
|
39
|
+
entry.dwSize = ctypes.sizeof(ProcessEntry)
|
|
40
|
+
ok = k.Process32First(snapshot, ctypes.byref(entry))
|
|
41
|
+
while ok:
|
|
42
|
+
children.setdefault(entry.th32ParentProcessID, []).append(entry.th32ProcessID)
|
|
43
|
+
ok = k.Process32Next(snapshot, ctypes.byref(entry))
|
|
44
|
+
k.CloseHandle(snapshot)
|
|
45
|
+
tree, todo = [], [pid]
|
|
46
|
+
while todo:
|
|
47
|
+
current = todo.pop()
|
|
48
|
+
tree.append(current)
|
|
49
|
+
todo += children.get(current, [])
|
|
50
|
+
if len(tree) > 1:
|
|
51
|
+
break
|
|
52
|
+
time.sleep(pause)
|
|
53
|
+
reached = []
|
|
54
|
+
for member in tree:
|
|
55
|
+
handle = k.OpenProcess(0x0200, False, member) # PROCESS_SET_INFORMATION
|
|
56
|
+
if handle:
|
|
57
|
+
k.SetPriorityClass(handle, 0x8000) # ABOVE_NORMAL_PRIORITY_CLASS
|
|
58
|
+
k.CloseHandle(handle)
|
|
59
|
+
reached.append(member)
|
|
60
|
+
return reached
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The worker protocol: one JSON object per line in each direction.
|
|
2
|
+
|
|
3
|
+
A worker prints one ready line (`{"ready": true, ...}`) when its model is loaded. Then, for every request line
|
|
4
|
+
on its standard input, it writes one response line on its standard output. Anything else it prints to standard
|
|
5
|
+
output that is not a JSON object is ignored by the reader, so a library's stray log line does not break a job.
|
|
6
|
+
|
|
7
|
+
Request: {"text": str, "output_path": str, "seed": int | null, "settings": {...}, "voice_id": str (optional)}
|
|
8
|
+
Response: {"ok": bool, "sample_rate": int, "samples": int, "wall_s": float, "error": str | null, ...}
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from typing import Any, Dict, Mapping, Optional, TextIO
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def make_request(text: str, output_path: str, *, seed: Optional[int] = None,
|
|
18
|
+
settings: Optional[Mapping[str, Any]] = None, voice_id: Optional[str] = None) -> Dict[str, Any]:
|
|
19
|
+
"""A request object. `voice_id` is left out when empty, so a worker with one fixed voice never sees it."""
|
|
20
|
+
request: Dict[str, Any] = {"text": text, "output_path": output_path, "seed": seed, "settings": dict(settings or {})}
|
|
21
|
+
if voice_id:
|
|
22
|
+
request["voice_id"] = voice_id
|
|
23
|
+
return request
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_message(stream: TextIO) -> Optional[Dict[str, Any]]:
|
|
27
|
+
"""The next JSON object on `stream`, skipping lines that are not one. None at end of stream."""
|
|
28
|
+
while True:
|
|
29
|
+
line = stream.readline()
|
|
30
|
+
if not line:
|
|
31
|
+
return None
|
|
32
|
+
try:
|
|
33
|
+
message = json.loads(line)
|
|
34
|
+
except json.JSONDecodeError:
|
|
35
|
+
continue
|
|
36
|
+
if isinstance(message, dict):
|
|
37
|
+
return message
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def write_message(stream: TextIO, message: Mapping[str, Any]) -> None:
|
|
41
|
+
"""Write one message as a line and flush, so the other side sees it at once."""
|
|
42
|
+
stream.write(json.dumps(message, ensure_ascii=False) + "\n")
|
|
43
|
+
stream.flush()
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The worker side of the protocol: wrap any synthesis function as a worker process."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable, Dict, Mapping, Optional, TextIO
|
|
8
|
+
|
|
9
|
+
from .protocol import read_message, write_message
|
|
10
|
+
|
|
11
|
+
Synthesize = Callable[[Dict[str, Any]], Mapping[str, Any]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def serve(synthesize: Synthesize, *, ready: Optional[Mapping[str, Any]] = None,
|
|
15
|
+
stdin: Optional[TextIO] = None, stdout: Optional[TextIO] = None) -> int:
|
|
16
|
+
"""Run the worker loop: announce readiness, answer each request line, stop at end of input.
|
|
17
|
+
|
|
18
|
+
`synthesize(request)` writes the audio to `request["output_path"]` and returns a dict such as
|
|
19
|
+
`{"sample_rate": 24000, "samples": 48000}`. The loop adds `ok` and `wall_s`. An exception it raises becomes
|
|
20
|
+
`{"ok": false, "error": "<type>: <message>"}` and the loop carries on with the next request, so one bad
|
|
21
|
+
sentence does not end the job. `ready` is merged into the first line (`{"ready": true, ...}`): put the
|
|
22
|
+
device and the data type there. Returns 0.
|
|
23
|
+
"""
|
|
24
|
+
stdin = stdin if stdin is not None else sys.stdin
|
|
25
|
+
stdout = stdout if stdout is not None else sys.stdout
|
|
26
|
+
write_message(stdout, {"ready": True, **(ready or {})})
|
|
27
|
+
while True:
|
|
28
|
+
request = read_message(stdin)
|
|
29
|
+
if request is None:
|
|
30
|
+
return 0
|
|
31
|
+
started = time.time()
|
|
32
|
+
try:
|
|
33
|
+
result = dict(synthesize(request))
|
|
34
|
+
response: Dict[str, Any] = {"ok": True, **result}
|
|
35
|
+
except Exception as exc:
|
|
36
|
+
response = {"ok": False, "error": "%s: %s" % (type(exc).__name__, exc)}
|
|
37
|
+
response.setdefault("wall_s", round(time.time() - started, 3))
|
|
38
|
+
write_message(stdout, response)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""WAV duration, including the float files that the standard library's `wave` module refuses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import struct
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def wav_seconds(path: "str | os.PathLike[str]") -> float:
|
|
10
|
+
"""Length in seconds of a RIFF WAV of any sample format, read from its `fmt ` and `data` chunks.
|
|
11
|
+
|
|
12
|
+
Raises ValueError for a file that has no `fmt ` or `data` chunk.
|
|
13
|
+
"""
|
|
14
|
+
with open(path, "rb") as fh:
|
|
15
|
+
data = fh.read()
|
|
16
|
+
if data[:4] != b"RIFF" or data[8:12] != b"WAVE":
|
|
17
|
+
raise ValueError("not a RIFF WAV file")
|
|
18
|
+
pos, rate, channels, bits, frames = 12, None, None, None, None
|
|
19
|
+
while pos + 8 <= len(data):
|
|
20
|
+
chunk_id, size = data[pos:pos + 4], struct.unpack("<I", data[pos + 4:pos + 8])[0]
|
|
21
|
+
if chunk_id == b"fmt ":
|
|
22
|
+
_, channels, rate, _, _, bits = struct.unpack("<HHIIHH", data[pos + 8:pos + 24])
|
|
23
|
+
elif chunk_id == b"data":
|
|
24
|
+
if not (rate and channels and bits):
|
|
25
|
+
raise ValueError("data chunk before the fmt chunk")
|
|
26
|
+
frames = min(size, len(data) - pos - 8) // (channels * bits // 8)
|
|
27
|
+
break
|
|
28
|
+
pos += 8 + size + (size & 1)
|
|
29
|
+
if frames is None or not rate:
|
|
30
|
+
raise ValueError("no fmt and data chunks")
|
|
31
|
+
return frames / rate
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Start a worker process and talk to it over the protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import atexit
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
from typing import Any, Dict, Mapping, Optional, Sequence
|
|
9
|
+
|
|
10
|
+
from .priority import raise_tree_priority
|
|
11
|
+
from .protocol import read_message, write_message
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class WorkerError(RuntimeError):
|
|
15
|
+
"""The worker did not become ready, or exited while a request was open."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class WorkerProcess:
|
|
19
|
+
"""One resident worker: started once, sent many requests, closed at the end.
|
|
20
|
+
|
|
21
|
+
`python` and `script` start it as `python script *args`. `env` is added to the environment. Its standard
|
|
22
|
+
error goes to `log_path` (appended) when given. With `raise_priority` the process tree is lifted to above
|
|
23
|
+
normal priority on Windows. A reply is waited for without a limit, as the worker may be loading a model.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, python: str, script: str, args: Sequence[str] = (), *, env: Optional[Mapping[str, str]] = None,
|
|
27
|
+
log_path: "str | os.PathLike[str] | None" = None, cwd: Optional[str] = None,
|
|
28
|
+
raise_priority: bool = False) -> None:
|
|
29
|
+
self.argv = [python, script, *args]
|
|
30
|
+
self.env = {**os.environ, **(env or {})}
|
|
31
|
+
self.log_path = os.fspath(log_path) if log_path else None
|
|
32
|
+
self.cwd = cwd
|
|
33
|
+
self.raise_priority = raise_priority
|
|
34
|
+
self.proc: Optional[subprocess.Popen] = None
|
|
35
|
+
self.ready: Dict[str, Any] = {}
|
|
36
|
+
self._log = None
|
|
37
|
+
|
|
38
|
+
def start(self) -> "WorkerProcess":
|
|
39
|
+
self._log = open(self.log_path, "a", encoding="utf-8") if self.log_path else subprocess.DEVNULL
|
|
40
|
+
self.proc = subprocess.Popen(self.argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self._log,
|
|
41
|
+
text=True, encoding="utf-8", env=self.env, cwd=self.cwd)
|
|
42
|
+
if self.raise_priority:
|
|
43
|
+
raise_tree_priority(self.proc.pid)
|
|
44
|
+
atexit.register(self.close)
|
|
45
|
+
return self
|
|
46
|
+
|
|
47
|
+
def _see_log(self) -> str:
|
|
48
|
+
return "; see %s" % self.log_path if self.log_path else ""
|
|
49
|
+
|
|
50
|
+
def wait_ready(self) -> Dict[str, Any]:
|
|
51
|
+
"""Read the ready line; returns it (device, dtype and whatever else the worker reports)."""
|
|
52
|
+
assert self.proc is not None and self.proc.stdout is not None, "start() first"
|
|
53
|
+
message = read_message(self.proc.stdout)
|
|
54
|
+
if not message or not message.get("ready"):
|
|
55
|
+
self.close()
|
|
56
|
+
raise WorkerError("worker did not become ready" + self._see_log())
|
|
57
|
+
self.ready = message
|
|
58
|
+
return message
|
|
59
|
+
|
|
60
|
+
def request(self, request: Mapping[str, Any]) -> Dict[str, Any]:
|
|
61
|
+
"""Send one request and return the worker's response. Raises WorkerError if the worker exits first."""
|
|
62
|
+
assert self.proc is not None and self.proc.stdin is not None and self.proc.stdout is not None, "start() first"
|
|
63
|
+
try:
|
|
64
|
+
write_message(self.proc.stdin, request)
|
|
65
|
+
except (BrokenPipeError, OSError):
|
|
66
|
+
raise WorkerError("worker exited mid-job" + self._see_log())
|
|
67
|
+
response = read_message(self.proc.stdout)
|
|
68
|
+
if response is None:
|
|
69
|
+
raise WorkerError("worker exited mid-job" + self._see_log())
|
|
70
|
+
return response
|
|
71
|
+
|
|
72
|
+
def close(self, grace: float = 5.0) -> None:
|
|
73
|
+
"""Close the worker's input, wait `grace` seconds for it to exit, then terminate it."""
|
|
74
|
+
proc, self.proc = self.proc, None
|
|
75
|
+
if proc is None:
|
|
76
|
+
return
|
|
77
|
+
try:
|
|
78
|
+
if proc.stdin:
|
|
79
|
+
proc.stdin.close()
|
|
80
|
+
except OSError:
|
|
81
|
+
pass
|
|
82
|
+
try:
|
|
83
|
+
proc.wait(timeout=grace)
|
|
84
|
+
except subprocess.TimeoutExpired:
|
|
85
|
+
proc.terminate()
|
|
86
|
+
try:
|
|
87
|
+
proc.wait(timeout=grace)
|
|
88
|
+
except subprocess.TimeoutExpired:
|
|
89
|
+
proc.kill()
|
|
90
|
+
proc.wait()
|
|
91
|
+
if proc.stdout:
|
|
92
|
+
proc.stdout.close()
|
|
93
|
+
if self._log not in (None, subprocess.DEVNULL):
|
|
94
|
+
self._log.close()
|
|
95
|
+
atexit.unregister(self.close)
|
|
96
|
+
|
|
97
|
+
def __enter__(self) -> "WorkerProcess":
|
|
98
|
+
self.start()
|
|
99
|
+
self.wait_ready()
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
def __exit__(self, *exc: object) -> None:
|
|
103
|
+
self.close()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""A fake synthesizer that speaks the worker protocol. It writes a silent float WAV whose length follows the text."""
|
|
2
|
+
import os
|
|
3
|
+
import struct
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from uppercut_tts_worker import serve
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def write_float_wav(path, seconds, rate=24000):
|
|
10
|
+
frames = int(seconds * rate)
|
|
11
|
+
data = struct.pack("<%df" % frames, *([0.0] * frames))
|
|
12
|
+
fmt = struct.pack("<HHIIHH", 3, 1, rate, rate * 4, 4, 32)
|
|
13
|
+
body = b"WAVE" + b"fmt " + struct.pack("<I", 16) + fmt + b"data" + struct.pack("<I", len(data)) + data
|
|
14
|
+
with open(path, "wb") as fh:
|
|
15
|
+
fh.write(b"RIFF" + struct.pack("<I", len(body)) + body)
|
|
16
|
+
return frames, rate
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def synthesize(request):
|
|
20
|
+
text = request["text"]
|
|
21
|
+
if "CRASH" in text:
|
|
22
|
+
os._exit(3)
|
|
23
|
+
if "FAIL" in text:
|
|
24
|
+
raise RuntimeError("cannot say that")
|
|
25
|
+
if "NOISE" in text:
|
|
26
|
+
print("a library log line that is not JSON", flush=True)
|
|
27
|
+
print("[1, 2, 3]", flush=True)
|
|
28
|
+
frames, rate = write_float_wav(request["output_path"], len(text) / 100.0)
|
|
29
|
+
return {"sample_rate": rate, "samples": frames, "echo_voice": request.get("voice_id"),
|
|
30
|
+
"echo_seed": request.get("seed"), "echo_settings": request.get("settings"),
|
|
31
|
+
"env": os.environ.get("FAKE_WORKER_MARK")}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
if __name__ == "__main__":
|
|
35
|
+
mark = sys.argv[1] if len(sys.argv) > 1 else "none"
|
|
36
|
+
sys.exit(serve(synthesize, ready={"device": "fake:0", "dtype": "float32", "mark": mark}))
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import struct
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
from uppercut_tts_worker import (
|
|
13
|
+
GpuLock,
|
|
14
|
+
LockBusy,
|
|
15
|
+
WorkerError,
|
|
16
|
+
WorkerProcess,
|
|
17
|
+
main,
|
|
18
|
+
make_request,
|
|
19
|
+
process_alive,
|
|
20
|
+
raise_tree_priority,
|
|
21
|
+
read_message,
|
|
22
|
+
run_job,
|
|
23
|
+
serve,
|
|
24
|
+
wav_seconds,
|
|
25
|
+
write_message,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
HERE = Path(__file__).resolve().parent
|
|
29
|
+
FAKE = str(HERE / "fake_worker.py")
|
|
30
|
+
PY = sys.executable
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def job_for(tmp_path, items, **extra):
|
|
34
|
+
return {"worker": {"python": PY, "script": FAKE, "args": ["m1"], "env": {"FAKE_WORKER_MARK": "from-env"}},
|
|
35
|
+
"lock": str(tmp_path / "runs" / ".gpu.lock"), "out_dir": str(tmp_path / "out"), "items": items, **extra}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def quiet(job, **kwargs):
|
|
39
|
+
lines = []
|
|
40
|
+
code = run_job(job, log=lines.append, lock_log=lines.append, **kwargs)
|
|
41
|
+
return code, lines
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# protocol ----------------------------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
def test_read_message_skips_noise_and_non_objects():
|
|
47
|
+
stream = io.StringIO('log line\n\n[1, 2]\n"text"\n{"ok": true}\n{broken\n{"second": 2}\n')
|
|
48
|
+
assert read_message(stream) == {"ok": True}
|
|
49
|
+
assert read_message(stream) == {"second": 2}
|
|
50
|
+
assert read_message(stream) is None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_write_message_is_one_line_and_utf8():
|
|
54
|
+
out = io.StringIO()
|
|
55
|
+
write_message(out, {"text": "café"})
|
|
56
|
+
assert out.getvalue() == '{"text": "café"}\n'
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_make_request_leaves_out_an_empty_voice():
|
|
60
|
+
assert make_request("hi", "a.wav") == {"text": "hi", "output_path": "a.wav", "seed": None, "settings": {}}
|
|
61
|
+
assert make_request("hi", "a.wav", seed=5, settings={"language": "English"}, voice_id="v1") == {
|
|
62
|
+
"text": "hi", "output_path": "a.wav", "seed": 5, "settings": {"language": "English"}, "voice_id": "v1"}
|
|
63
|
+
assert "voice_id" not in make_request("hi", "a.wav", voice_id="")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_serve_answers_each_request_and_survives_a_failure():
|
|
67
|
+
stdin = io.StringIO('{"text": "a"}\nnoise\n{"text": "boom"}\n{"text": "c"}\n')
|
|
68
|
+
stdout = io.StringIO()
|
|
69
|
+
|
|
70
|
+
def synth(request):
|
|
71
|
+
if request["text"] == "boom":
|
|
72
|
+
raise ValueError("bad sentence")
|
|
73
|
+
return {"samples": 3}
|
|
74
|
+
|
|
75
|
+
assert serve(synth, ready={"device": "x"}, stdin=stdin, stdout=stdout) == 0
|
|
76
|
+
lines = [json.loads(line) for line in stdout.getvalue().splitlines()]
|
|
77
|
+
assert lines[0] == {"ready": True, "device": "x"}
|
|
78
|
+
assert lines[1]["ok"] is True and lines[1]["samples"] == 3 and "wall_s" in lines[1]
|
|
79
|
+
assert lines[2]["ok"] is False and lines[2]["error"] == "ValueError: bad sentence"
|
|
80
|
+
assert lines[3]["ok"] is True and len(lines) == 4
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# wav ---------------------------------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
def test_wav_seconds_reads_float_and_pcm_files(tmp_path):
|
|
86
|
+
import wave
|
|
87
|
+
|
|
88
|
+
sys.path.insert(0, str(HERE))
|
|
89
|
+
from fake_worker import write_float_wav
|
|
90
|
+
|
|
91
|
+
write_float_wav(str(tmp_path / "f.wav"), 1.5, rate=24000)
|
|
92
|
+
assert wav_seconds(tmp_path / "f.wav") == pytest.approx(1.5)
|
|
93
|
+
with wave.open(str(tmp_path / "p.wav"), "wb") as w:
|
|
94
|
+
w.setnchannels(2), w.setsampwidth(2), w.setframerate(8000)
|
|
95
|
+
w.writeframes(b"\x00\x00" * 2 * 4000)
|
|
96
|
+
assert wav_seconds(tmp_path / "p.wav") == pytest.approx(0.5)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_wav_seconds_skips_odd_sized_chunks_and_rejects_junk(tmp_path):
|
|
100
|
+
fmt = struct.pack("<HHIIHH", 1, 1, 1000, 2000, 2, 16)
|
|
101
|
+
body = (b"WAVE" + b"LIST" + struct.pack("<I", 3) + b"abc" + b"\x00"
|
|
102
|
+
+ b"fmt " + struct.pack("<I", 16) + fmt + b"data" + struct.pack("<I", 2000) + b"\x00" * 2000)
|
|
103
|
+
(tmp_path / "x.wav").write_bytes(b"RIFF" + struct.pack("<I", len(body)) + body)
|
|
104
|
+
assert wav_seconds(tmp_path / "x.wav") == pytest.approx(1.0)
|
|
105
|
+
(tmp_path / "n.wav").write_bytes(b"not a wav at all")
|
|
106
|
+
with pytest.raises(ValueError):
|
|
107
|
+
wav_seconds(tmp_path / "n.wav")
|
|
108
|
+
(tmp_path / "e.wav").write_bytes(b"RIFF\x04\x00\x00\x00WAVE")
|
|
109
|
+
with pytest.raises(ValueError):
|
|
110
|
+
wav_seconds(tmp_path / "e.wav")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# lock --------------------------------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
def test_lock_is_taken_and_released(tmp_path):
|
|
116
|
+
path = tmp_path / "sub" / ".gpu.lock"
|
|
117
|
+
with GpuLock(path) as lock:
|
|
118
|
+
assert path.read_text(encoding="utf-8") == str(os.getpid()) and lock.held
|
|
119
|
+
assert not path.exists()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_a_live_holder_blocks_and_is_never_deleted(tmp_path):
|
|
123
|
+
path = tmp_path / ".gpu.lock"
|
|
124
|
+
path.write_text(str(os.getpid()), encoding="utf-8") # this process is alive
|
|
125
|
+
with pytest.raises(LockBusy, match="GPU busy: pid %d still holds" % os.getpid()):
|
|
126
|
+
GpuLock(path).acquire()
|
|
127
|
+
assert path.read_text(encoding="utf-8") == str(os.getpid())
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def test_a_stale_lock_is_cleared(tmp_path):
|
|
131
|
+
path = tmp_path / ".gpu.lock"
|
|
132
|
+
dead = subprocess.Popen([PY, "-c", "pass"])
|
|
133
|
+
dead.wait()
|
|
134
|
+
path.write_text(str(dead.pid), encoding="utf-8")
|
|
135
|
+
with GpuLock(path):
|
|
136
|
+
assert path.read_text(encoding="utf-8") == str(os.getpid())
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_waiting_for_a_holder_that_lets_go(tmp_path):
|
|
140
|
+
path = tmp_path / ".gpu.lock"
|
|
141
|
+
path.write_text(str(os.getpid()), encoding="utf-8")
|
|
142
|
+
messages, sleeps = [], []
|
|
143
|
+
|
|
144
|
+
def sleep(seconds):
|
|
145
|
+
sleeps.append(seconds)
|
|
146
|
+
path.unlink() # the holder finishes during the first wait
|
|
147
|
+
|
|
148
|
+
with GpuLock(path, wait_s=60, poll_s=5, on_wait=messages.append, sleep=sleep):
|
|
149
|
+
assert path.read_text(encoding="utf-8") == str(os.getpid())
|
|
150
|
+
assert sleeps == [5]
|
|
151
|
+
assert "waiting up to 60 s" in messages[0] and messages[-1] == "GPU lock acquired"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_waiting_gives_up_after_wait_s(tmp_path):
|
|
155
|
+
path = tmp_path / ".gpu.lock"
|
|
156
|
+
path.write_text(str(os.getpid()), encoding="utf-8")
|
|
157
|
+
with pytest.raises(LockBusy, match="after 0.2 s"):
|
|
158
|
+
GpuLock(path, wait_s=0.2, poll_s=0.05).acquire()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_release_leaves_a_lock_that_names_another_process(tmp_path):
|
|
162
|
+
path = tmp_path / ".gpu.lock"
|
|
163
|
+
lock = GpuLock(path).acquire()
|
|
164
|
+
path.write_text("999999", encoding="utf-8")
|
|
165
|
+
lock.release()
|
|
166
|
+
assert path.read_text(encoding="utf-8") == "999999"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def test_a_lock_with_junk_in_it_counts_as_held(tmp_path):
|
|
170
|
+
path = tmp_path / ".gpu.lock"
|
|
171
|
+
path.write_text("not a pid", encoding="utf-8")
|
|
172
|
+
with pytest.raises(LockBusy):
|
|
173
|
+
GpuLock(path).acquire()
|
|
174
|
+
assert path.exists()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_only_one_of_two_threads_gets_the_lock(tmp_path):
|
|
178
|
+
path = tmp_path / ".gpu.lock"
|
|
179
|
+
winners, barrier = [], threading.Barrier(2)
|
|
180
|
+
|
|
181
|
+
def take():
|
|
182
|
+
barrier.wait()
|
|
183
|
+
try:
|
|
184
|
+
GpuLock(path).acquire()
|
|
185
|
+
winners.append(1)
|
|
186
|
+
except LockBusy:
|
|
187
|
+
pass
|
|
188
|
+
|
|
189
|
+
threads = [threading.Thread(target=take) for _ in range(2)]
|
|
190
|
+
[t.start() for t in threads]
|
|
191
|
+
[t.join() for t in threads]
|
|
192
|
+
assert winners == [1]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def test_process_alive():
|
|
196
|
+
assert process_alive(os.getpid())
|
|
197
|
+
dead = subprocess.Popen([PY, "-c", "pass"])
|
|
198
|
+
dead.wait()
|
|
199
|
+
assert not process_alive(dead.pid)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def test_raise_tree_priority_does_nothing_off_windows():
|
|
203
|
+
if os.name != "nt":
|
|
204
|
+
assert raise_tree_priority(os.getpid()) == []
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# worker process ----------------------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
def test_worker_round_trip(tmp_path):
|
|
210
|
+
with WorkerProcess(PY, FAKE, ["m1"], env={"FAKE_WORKER_MARK": "x"}, log_path=tmp_path / "w.log") as worker:
|
|
211
|
+
assert worker.ready["device"] == "fake:0" and worker.ready["mark"] == "m1"
|
|
212
|
+
reply = worker.request(make_request("hello world", str(tmp_path / "a.wav"), seed=7, voice_id="v9"))
|
|
213
|
+
assert reply["ok"] and reply["echo_voice"] == "v9" and reply["echo_seed"] == 7 and reply["env"] == "x"
|
|
214
|
+
assert wav_seconds(tmp_path / "a.wav") == pytest.approx(len("hello world") / 100.0, abs=0.001)
|
|
215
|
+
assert worker.request(make_request("a NOISE b", str(tmp_path / "b.wav")))["ok"] # stray lines are skipped
|
|
216
|
+
failed = worker.request(make_request("FAIL", str(tmp_path / "c.wav")))
|
|
217
|
+
assert failed["ok"] is False and "cannot say that" in failed["error"]
|
|
218
|
+
assert worker.request(make_request("still alive", str(tmp_path / "d.wav")))["ok"]
|
|
219
|
+
assert worker.proc is None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def test_worker_that_never_becomes_ready(tmp_path):
|
|
223
|
+
worker = WorkerProcess(PY, "-c", ["pass"], log_path=tmp_path / "w.log").start()
|
|
224
|
+
with pytest.raises(WorkerError, match="did not become ready; see .*w.log"):
|
|
225
|
+
worker.wait_ready()
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def test_worker_that_dies_mid_request(tmp_path):
|
|
229
|
+
with pytest.raises(WorkerError, match="exited mid-job"):
|
|
230
|
+
with WorkerProcess(PY, FAKE) as worker:
|
|
231
|
+
worker.request(make_request("CRASH", str(tmp_path / "a.wav")))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# job ---------------------------------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
def items(*texts):
|
|
237
|
+
return [{"id": "s%03d" % i, "text": t, "seed": 100 + i, "settings": {"language": "English"}} for i, t in enumerate(texts, 1)]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def test_job_generates_everything_and_releases_the_lock(tmp_path):
|
|
241
|
+
job = job_for(tmp_path, items("one", "two two", "three"))
|
|
242
|
+
code, lines = quiet(job)
|
|
243
|
+
assert code == 0 and lines[0] == "3/3 items to generate"
|
|
244
|
+
assert "worker ready on fake:0 (float32)" in lines[1]
|
|
245
|
+
out = tmp_path / "out"
|
|
246
|
+
assert sorted(p.name for p in out.glob("*.wav")) == ["s001.wav", "s002.wav", "s003.wav"]
|
|
247
|
+
results = json.loads((out / "results.json").read_text(encoding="utf-8"))
|
|
248
|
+
assert results["s002"]["ok"] and results["s002"]["seed"] == 102 and results["s002"]["sample_rate"] == 24000
|
|
249
|
+
assert results["s002"]["text_sha256"] and (out / "worker.log").exists()
|
|
250
|
+
assert not Path(job["lock"]).exists()
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def test_job_resumes_and_redoes_an_edited_sentence_or_seed(tmp_path):
|
|
254
|
+
job = job_for(tmp_path, items("one", "two", "three"))
|
|
255
|
+
quiet(job)
|
|
256
|
+
before = (tmp_path / "out" / "s001.wav").stat().st_mtime_ns
|
|
257
|
+
code, lines = quiet(job)
|
|
258
|
+
assert code == 0 and lines == ["0/3 items to generate"]
|
|
259
|
+
job["items"][1]["text"] = "two, reworded"
|
|
260
|
+
job["items"][2]["seed"] = 999
|
|
261
|
+
code, lines = quiet(job)
|
|
262
|
+
assert lines[0] == "2/3 items to generate"
|
|
263
|
+
assert (tmp_path / "out" / "s001.wav").stat().st_mtime_ns == before
|
|
264
|
+
os.remove(tmp_path / "out" / "s001.wav")
|
|
265
|
+
assert quiet(job)[1][0] == "1/3 items to generate"
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def test_job_with_nothing_to_do_takes_no_lock(tmp_path):
|
|
269
|
+
job = job_for(tmp_path, items("one"))
|
|
270
|
+
quiet(job)
|
|
271
|
+
Path(job["lock"]).write_text(str(os.getpid()), encoding="utf-8") # a live holder
|
|
272
|
+
assert quiet(job)[0] == 0
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def test_job_reports_a_failed_item_and_keeps_going(tmp_path):
|
|
276
|
+
job = job_for(tmp_path, items("fine", "FAIL here", "also fine"))
|
|
277
|
+
code, lines = quiet(job)
|
|
278
|
+
assert code == 1 and any(line.startswith("[FAILED] s002") for line in lines)
|
|
279
|
+
results = json.loads((tmp_path / "out" / "results.json").read_text(encoding="utf-8"))
|
|
280
|
+
assert results["s002"]["ok"] is False and "cannot say that" in results["s002"]["error"]
|
|
281
|
+
assert results["s003"]["ok"] is True and not (tmp_path / "out" / "s002.wav").exists()
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def test_job_waits_for_the_lock_then_runs(tmp_path):
|
|
285
|
+
job = job_for(tmp_path, items("one"), lock_wait_s=0.2)
|
|
286
|
+
Path(job["lock"]).parent.mkdir(parents=True)
|
|
287
|
+
Path(job["lock"]).write_text(str(os.getpid()), encoding="utf-8")
|
|
288
|
+
with pytest.raises(LockBusy):
|
|
289
|
+
run_job(job, log=lambda line: None, lock_log=lambda line: None)
|
|
290
|
+
assert Path(job["lock"]).read_text(encoding="utf-8") == str(os.getpid())
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def test_job_voice_and_settings_reach_the_worker(tmp_path):
|
|
294
|
+
job = job_for(tmp_path, [{"id": "a", "text": "hello", "voice_id": "v2"}, {"id": "b", "text": "hi", "settings": {"language": "French"}}])
|
|
295
|
+
quiet(job)
|
|
296
|
+
assert (tmp_path / "out" / "a.wav").exists() and (tmp_path / "out" / "b.wav").exists()
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def test_job_ids_must_be_filename_safe(tmp_path):
|
|
300
|
+
with pytest.raises(ValueError, match="not filename safe"):
|
|
301
|
+
run_job(job_for(tmp_path, [{"id": "../escape", "text": "x"}]), log=lambda line: None)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def test_command_line(tmp_path, capsys):
|
|
305
|
+
job_file = tmp_path / "job.json"
|
|
306
|
+
job_file.write_text(json.dumps(job_for(tmp_path, items("one", "two"))), encoding="utf-8")
|
|
307
|
+
assert main([str(job_file)]) == 0
|
|
308
|
+
assert "2/2 items to generate" in capsys.readouterr().out
|
|
309
|
+
assert main([]) == 2
|
|
310
|
+
bad = job_for(tmp_path, items("CRASH now"))
|
|
311
|
+
bad["out_dir"] = str(tmp_path / "out2")
|
|
312
|
+
job_file.write_text(json.dumps(bad), encoding="utf-8")
|
|
313
|
+
assert main([str(job_file)]) == 1
|
|
314
|
+
assert "exited mid-job" in capsys.readouterr().err
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def test_module_runs_as_a_command(tmp_path):
|
|
318
|
+
job_file = tmp_path / "job.json"
|
|
319
|
+
job_file.write_text(json.dumps(job_for(tmp_path, items("one"))), encoding="utf-8")
|
|
320
|
+
r = subprocess.run([PY, "-m", "uppercut_tts_worker", str(job_file)], capture_output=True, text=True)
|
|
321
|
+
assert r.returncode == 0 and "1/1 items to generate" in r.stdout
|