speechtrace 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- speechtrace/__init__.py +4 -0
- speechtrace/__main__.py +5 -0
- speechtrace/batch.py +219 -0
- speechtrace/cli.py +160 -0
- speechtrace/config.py +98 -0
- speechtrace/mcp_server.py +115 -0
- speechtrace/tools.py +271 -0
- speechtrace-0.1.0.dist-info/METADATA +85 -0
- speechtrace-0.1.0.dist-info/RECORD +12 -0
- speechtrace-0.1.0.dist-info/WHEEL +4 -0
- speechtrace-0.1.0.dist-info/entry_points.txt +2 -0
- speechtrace-0.1.0.dist-info/licenses/LICENSE +21 -0
speechtrace/__init__.py
ADDED
speechtrace/__main__.py
ADDED
speechtrace/batch.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Transcribe a folder of recordings through the Speechtrace API, and save the transcripts next to
|
|
3
|
+
each other in an output folder. Safe to stop and run again: finished files are skipped, and files
|
|
4
|
+
already sent are picked up where they left off.
|
|
5
|
+
|
|
6
|
+
The easiest way to run this is the speechtrace command-line tool, which also signs you in and buys
|
|
7
|
+
hours: `uvx speechtrace login --email you@example.com`, then `uvx speechtrace transcribe ./recordings`.
|
|
8
|
+
This file works on its own too:
|
|
9
|
+
|
|
10
|
+
pip install requests
|
|
11
|
+
export SPEECHTRACE_API_KEY=tx_... # from your dashboard (TX_API_KEY also works)
|
|
12
|
+
python bulk-transcribe.py ./recordings --out ./transcripts --formats txt,srt,json
|
|
13
|
+
|
|
14
|
+
Open source (MIT). Needs Python 3.9+ and the requests package. This file is also the speechtrace
|
|
15
|
+
package's batch module (speechtrace/batch.py): keep the two identical."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import mimetypes
|
|
22
|
+
import os
|
|
23
|
+
import sys
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
import requests
|
|
31
|
+
|
|
32
|
+
EXTENSIONS = {".mp3", ".m4a", ".wav", ".flac", ".ogg", ".opus", ".aac", ".wma", ".webm", ".mp4", ".mov", ".mkv",
|
|
33
|
+
".avi", ".m4v", ".amr", ".aif", ".aiff"}
|
|
34
|
+
FORMATS = ("txt", "srt", "vtt", "json")
|
|
35
|
+
STATE = ".bulk-transcribe.json"
|
|
36
|
+
DEFAULT_API = "https://speechtraceai.com"
|
|
37
|
+
OUT_OF_HOURS = 4 # exit code: files weren't sent because the account is out of audio hours
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ApiError(Exception):
|
|
41
|
+
def __init__(self, status: int, message: str) -> None:
|
|
42
|
+
super().__init__(f"HTTP {status}: {message}")
|
|
43
|
+
self.status = status
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Client:
|
|
47
|
+
def __init__(self, base: str, key: str = "", session: Any = None, user_agent: str = "bulk-transcribe") -> None:
|
|
48
|
+
self.base = base.rstrip("/")
|
|
49
|
+
self.s = session or requests.Session()
|
|
50
|
+
self.s.headers["User-Agent"] = user_agent
|
|
51
|
+
if key:
|
|
52
|
+
self.s.headers["Authorization"] = f"Bearer {key}"
|
|
53
|
+
else:
|
|
54
|
+
self.s.headers.pop("Authorization", None)
|
|
55
|
+
|
|
56
|
+
def _call(self, method: str, path: str, retry: bool = True, **kw: Any) -> Any:
|
|
57
|
+
tries = 5 if retry else 1
|
|
58
|
+
for attempt in range(tries):
|
|
59
|
+
try:
|
|
60
|
+
r = self.s.request(method, self.base + path, timeout=120, **kw)
|
|
61
|
+
except requests.RequestException:
|
|
62
|
+
if attempt == tries - 1:
|
|
63
|
+
raise
|
|
64
|
+
time.sleep(2 ** attempt)
|
|
65
|
+
continue
|
|
66
|
+
if r.status_code >= 500 and attempt < tries - 1:
|
|
67
|
+
time.sleep(2 ** attempt)
|
|
68
|
+
continue
|
|
69
|
+
if r.status_code >= 400:
|
|
70
|
+
try:
|
|
71
|
+
msg = r.json().get("error") or r.text
|
|
72
|
+
except ValueError:
|
|
73
|
+
msg = r.text
|
|
74
|
+
raise ApiError(r.status_code, str(msg)[:300])
|
|
75
|
+
return r
|
|
76
|
+
raise RuntimeError("unreachable")
|
|
77
|
+
|
|
78
|
+
def submit(self, path: Path, speakers: bool) -> str:
|
|
79
|
+
ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
|
80
|
+
up = self._call("POST", "/v1/uploads", json={"filename": path.name, "size_bytes": path.stat().st_size,
|
|
81
|
+
"content_type": ctype}).json()
|
|
82
|
+
with open(path, "rb") as f:
|
|
83
|
+
put = self.s.put(up["put_url"], data=f, headers={"Content-Type": ctype, "Authorization": None},
|
|
84
|
+
timeout=3600)
|
|
85
|
+
if put.status_code >= 300:
|
|
86
|
+
raise ApiError(put.status_code, "upload failed")
|
|
87
|
+
job = self._call("POST", "/v1/transcriptions", json={"upload_id": up["upload_id"], "speakers": speakers})
|
|
88
|
+
return job.json()["id"]
|
|
89
|
+
|
|
90
|
+
def status(self, job_id: str) -> dict[str, Any]:
|
|
91
|
+
return self._call("GET", f"/v1/transcriptions/{job_id}").json()
|
|
92
|
+
|
|
93
|
+
def result(self, job_id: str, fmt: str) -> bytes:
|
|
94
|
+
return self._call("GET", f"/v1/transcriptions/{job_id}/result", params={"format": fmt}).content
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def find_files(paths: list[str]) -> list[tuple[Path, Path]]:
|
|
98
|
+
"""(file, its path relative to the folder given) for every audio or video file, sorted."""
|
|
99
|
+
out = []
|
|
100
|
+
for p in map(Path, paths):
|
|
101
|
+
if p.is_dir():
|
|
102
|
+
out += [(f, f.relative_to(p)) for f in sorted(p.rglob("*")) if f.is_file()
|
|
103
|
+
and f.suffix.lower() in EXTENSIONS and not f.name.startswith(".")]
|
|
104
|
+
elif p.is_file():
|
|
105
|
+
out.append((p, Path(p.name)))
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def load_state(out: Path) -> dict[str, dict[str, Any]]:
|
|
110
|
+
try:
|
|
111
|
+
return json.loads((out / STATE).read_text())
|
|
112
|
+
except (OSError, ValueError):
|
|
113
|
+
return {}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def save_state(out: Path, state: dict[str, dict[str, Any]]) -> None:
|
|
117
|
+
tmp = out / (STATE + ".tmp")
|
|
118
|
+
tmp.write_text(json.dumps(state, indent=1))
|
|
119
|
+
tmp.replace(out / STATE)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def run(client: Client, paths: list[str], out: Path, formats: list[str], speakers: bool = True, parallel: int = 4,
|
|
123
|
+
poll_s: float = 10.0, log=print, wait: bool = True, stop: Any = None) -> dict[str, int]:
|
|
124
|
+
"""Send every file not sent yet, then (if wait) collect transcripts until all are done or failed, or
|
|
125
|
+
`stop` (a threading.Event) is set. The counts include "not_sent": files held back because the account
|
|
126
|
+
ran out of audio hours."""
|
|
127
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
128
|
+
state = load_state(out)
|
|
129
|
+
files = find_files(paths)
|
|
130
|
+
todo = [(f, rel) for f, rel in files if state.get(str(rel), {}).get("status") not in ("done", "sent", "failed")]
|
|
131
|
+
log(f"{len(files)} files; {len(files) - len(todo)} already sent or done; sending {len(todo)}")
|
|
132
|
+
out_of_hours = threading.Event()
|
|
133
|
+
not_sent = 0
|
|
134
|
+
|
|
135
|
+
def send(f: Path, rel: Path) -> tuple[Path, str | None, str | None]:
|
|
136
|
+
if out_of_hours.is_set() or (stop is not None and stop.is_set()):
|
|
137
|
+
return rel, None, "402"
|
|
138
|
+
try:
|
|
139
|
+
return rel, client.submit(f, speakers), None
|
|
140
|
+
except ApiError as exc:
|
|
141
|
+
return rel, None, str(exc) if exc.status != 402 else "402"
|
|
142
|
+
|
|
143
|
+
with ThreadPoolExecutor(max_workers=max(1, parallel)) as pool:
|
|
144
|
+
futures = [pool.submit(send, f, rel) for f, rel in todo]
|
|
145
|
+
for fut in as_completed(futures):
|
|
146
|
+
rel, job_id, err = fut.result()
|
|
147
|
+
if err == "402":
|
|
148
|
+
if not out_of_hours.is_set():
|
|
149
|
+
log(" out of audio hours: the rest aren't sent")
|
|
150
|
+
out_of_hours.set()
|
|
151
|
+
not_sent += 1
|
|
152
|
+
continue
|
|
153
|
+
if err:
|
|
154
|
+
state[str(rel)] = {"status": "error", "error": err}
|
|
155
|
+
log(f" {rel}: couldn't send ({err})")
|
|
156
|
+
else:
|
|
157
|
+
state[str(rel)] = {"status": "sent", "id": job_id}
|
|
158
|
+
save_state(out, state)
|
|
159
|
+
|
|
160
|
+
pending = {rel: s["id"] for rel, s in state.items() if s.get("status") == "sent"} if wait else {}
|
|
161
|
+
while pending and not (stop is not None and stop.is_set()):
|
|
162
|
+
for rel, job_id in list(pending.items()):
|
|
163
|
+
try:
|
|
164
|
+
st = client.status(job_id)
|
|
165
|
+
except ApiError as exc:
|
|
166
|
+
if exc.status == 404:
|
|
167
|
+
state[rel] = {"status": "error", "error": "no longer on the server"}
|
|
168
|
+
pending.pop(rel)
|
|
169
|
+
continue
|
|
170
|
+
if st["status"] == "done":
|
|
171
|
+
base = out / Path(rel).with_suffix("")
|
|
172
|
+
base.parent.mkdir(parents=True, exist_ok=True)
|
|
173
|
+
for fmt in formats:
|
|
174
|
+
(base.parent / f"{base.name}.{fmt}").write_bytes(client.result(job_id, fmt))
|
|
175
|
+
state[rel] = {"status": "done", "id": job_id, "seconds": st.get("audio_seconds")}
|
|
176
|
+
pending.pop(rel)
|
|
177
|
+
log(f" done: {rel}")
|
|
178
|
+
elif st["status"] in ("failed", "deleted"):
|
|
179
|
+
state[rel] = {"status": "failed", "id": job_id, "error": st.get("error") or st["status"]}
|
|
180
|
+
pending.pop(rel)
|
|
181
|
+
log(f" failed: {rel}: {st.get('error')}")
|
|
182
|
+
save_state(out, state)
|
|
183
|
+
if pending:
|
|
184
|
+
time.sleep(poll_s)
|
|
185
|
+
counts: dict[str, int] = {}
|
|
186
|
+
for s in state.values():
|
|
187
|
+
counts[s["status"]] = counts.get(s["status"], 0) + 1
|
|
188
|
+
if not_sent:
|
|
189
|
+
counts["not_sent"] = not_sent
|
|
190
|
+
log("finished: " + ", ".join(f"{n} {k}" for k, n in sorted(counts.items())))
|
|
191
|
+
return counts
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def main(argv: list[str] | None = None) -> int:
|
|
195
|
+
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
196
|
+
p.add_argument("paths", nargs="+", help="audio/video files or folders (searched recursively)")
|
|
197
|
+
p.add_argument("--out", default="transcripts", help="where to save transcripts (default ./transcripts)")
|
|
198
|
+
p.add_argument("--formats", default="txt,srt,json", help=f"any of {','.join(FORMATS)}")
|
|
199
|
+
p.add_argument("--no-speakers", action="store_true", help="don't label speakers")
|
|
200
|
+
p.add_argument("--parallel", type=int, default=4, help="uploads at once")
|
|
201
|
+
p.add_argument("--api", default=os.environ.get("SPEECHTRACE_API_URL") or os.environ.get("TX_API_URL")
|
|
202
|
+
or DEFAULT_API, help=f"the API's address (or SPEECHTRACE_API_URL; default {DEFAULT_API})")
|
|
203
|
+
a = p.parse_args(argv)
|
|
204
|
+
key = os.environ.get("SPEECHTRACE_API_KEY") or os.environ.get("TX_API_KEY", "")
|
|
205
|
+
formats = [f.strip() for f in a.formats.split(",") if f.strip()]
|
|
206
|
+
if not key:
|
|
207
|
+
p.error("set SPEECHTRACE_API_KEY (an API key from your dashboard)")
|
|
208
|
+
if any(f not in FORMATS for f in formats):
|
|
209
|
+
p.error(f"--formats: any of {', '.join(FORMATS)}")
|
|
210
|
+
counts = run(Client(a.api, key), a.paths, Path(a.out), formats, not a.no_speakers, a.parallel)
|
|
211
|
+
if counts.get("not_sent"):
|
|
212
|
+
print(f"{counts['not_sent']} files weren't sent: the account is out of audio hours. Top up on your dashboard "
|
|
213
|
+
"(or run `uvx speechtrace buy 10`), then run this again.")
|
|
214
|
+
return OUT_OF_HOURS
|
|
215
|
+
return 1 if counts.get("failed") or counts.get("error") else 0
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
if __name__ == "__main__":
|
|
219
|
+
sys.exit(main())
|
speechtrace/cli.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""speechtrace: transcribe audio and video files with Speechtrace (https://speechtraceai.com).
|
|
2
|
+
|
|
3
|
+
speechtrace login --email you@example.com we email you a code (new accounts get free hours)
|
|
4
|
+
speechtrace login --code 123456 ...or `login --wait` after clicking Approve in the email
|
|
5
|
+
speechtrace transcribe ~/Recordings transcripts go to ~/Recordings/transcripts
|
|
6
|
+
speechtrace balance hours left
|
|
7
|
+
speechtrace buy 10 a Stripe link to add $10 of hours; `buy --wait` waits for it
|
|
8
|
+
speechtrace mcp run as an MCP server (Claude Desktop, Claude Code, Cursor...)
|
|
9
|
+
|
|
10
|
+
Add --json for one JSON object on stdout (messages go to stderr). Exit codes: 0 done, 1 error or some
|
|
11
|
+
files failed, 2 bad arguments, 3 not signed in, 4 out of audio hours, 5 still waiting."""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from . import __version__, batch, config, tools
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _common(sub: bool) -> argparse.ArgumentParser:
|
|
24
|
+
"""--api and --json, accepted before or after the command (a subcommand's copy has no default, so it
|
|
25
|
+
doesn't overwrite one given before the command)."""
|
|
26
|
+
kw: dict[str, Any] = {"default": argparse.SUPPRESS} if sub else {}
|
|
27
|
+
c = argparse.ArgumentParser(add_help=False)
|
|
28
|
+
c.add_argument("--api", help="the API's address (or SPEECHTRACE_API_URL; default https://speechtraceai.com)", **kw)
|
|
29
|
+
c.add_argument("--json", action="store_true", help="print one JSON object on stdout", **kw)
|
|
30
|
+
return c
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _parser() -> argparse.ArgumentParser:
|
|
34
|
+
common = _common(sub=True)
|
|
35
|
+
p = argparse.ArgumentParser(prog="speechtrace", description=__doc__.split("\n\n")[0],
|
|
36
|
+
parents=[_common(False)], epilog=__doc__.split("\n\n", 1)[1],
|
|
37
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
38
|
+
p.add_argument("--version", action="version", version=f"speechtrace {__version__}")
|
|
39
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
40
|
+
|
|
41
|
+
s = sub.add_parser("login", parents=[common], help="sign in (or sign up) by email")
|
|
42
|
+
s.add_argument("--email", help="start: we email this address a 6-digit code and an Approve link")
|
|
43
|
+
s.add_argument("--code", help="finish with the code from the email")
|
|
44
|
+
s.add_argument("--wait", action="store_true", help="finish once the person clicks Approve in the email")
|
|
45
|
+
s.add_argument("--timeout", type=float, default=600, help="seconds --wait waits (default 600)")
|
|
46
|
+
s.add_argument("--name", default="", help="this program's name, shown in the email (default: detected)")
|
|
47
|
+
|
|
48
|
+
sub.add_parser("logout", parents=[common], help="revoke the saved key and forget it")
|
|
49
|
+
sub.add_parser("balance", parents=[common], help="audio hours left, and the price")
|
|
50
|
+
|
|
51
|
+
s = sub.add_parser("buy", parents=[common], help="a Stripe link to buy audio hours")
|
|
52
|
+
s.add_argument("usd", nargs="?", type=int, help="whole dollars to add")
|
|
53
|
+
s.add_argument("--wait", action="store_true", help="wait until the payment arrives")
|
|
54
|
+
s.add_argument("--timeout", type=float, default=600, help="seconds --wait waits (default 600)")
|
|
55
|
+
|
|
56
|
+
s = sub.add_parser("transcribe", parents=[common], help="transcribe files or folders (safe to run again)")
|
|
57
|
+
s.add_argument("paths", nargs="+", help="audio or video files, or folders (searched recursively)")
|
|
58
|
+
s.add_argument("--out", default="", help="where transcripts go (default: a transcripts folder next to them)")
|
|
59
|
+
s.add_argument("--formats", default="txt,srt,json", help=f"any of {','.join(batch.FORMATS)}")
|
|
60
|
+
s.add_argument("--no-speakers", action="store_true", help="don't label speakers")
|
|
61
|
+
s.add_argument("--parallel", type=int, default=4, help="uploads at once")
|
|
62
|
+
s.add_argument("--no-wait", action="store_true", help="send the files and return; run again to collect")
|
|
63
|
+
|
|
64
|
+
sub.add_parser("mcp", help="run as an MCP server over stdio")
|
|
65
|
+
return p
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _say(msg: str, as_json: bool) -> None:
|
|
69
|
+
print(msg, file=sys.stderr if as_json else sys.stdout, flush=True)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _human(cmd: str, out: dict[str, Any]) -> str:
|
|
73
|
+
st = out.get("status")
|
|
74
|
+
if cmd == "login" and st == "code_sent":
|
|
75
|
+
return (f"{out['message_for_user']}\nThen run `speechtrace login --code <code>`, or `speechtrace login --wait`"
|
|
76
|
+
" once they've clicked Approve.")
|
|
77
|
+
if st == "pending":
|
|
78
|
+
return out["message_for_user"]
|
|
79
|
+
if st == "signed_in":
|
|
80
|
+
extra = " New account:" if out["new_account"] else ""
|
|
81
|
+
return (f"Signed in as {out['email']}.{extra} {out['balance_hours']:g} audio hours left. "
|
|
82
|
+
f"Key saved to {out['key_saved_to']}.")
|
|
83
|
+
if st == "signed_out":
|
|
84
|
+
return "Signed out: the key is revoked and forgotten. " + out.get("note", "")
|
|
85
|
+
if cmd == "balance":
|
|
86
|
+
return (f"{out['email']}: {out['balance_hours']:g} audio hours left ({out['free_hours']:g} free, "
|
|
87
|
+
f"{out['paid_hours']:g} bought). ${out['price_per_hour_usd']:.2f} per audio hour; top-ups "
|
|
88
|
+
f"${out['min_topup_usd']:g} to ${out['max_topup_usd']:,.0f}.")
|
|
89
|
+
if st == "link_ready":
|
|
90
|
+
return f"{out['message_for_user']}\nThen run `speechtrace buy --wait`."
|
|
91
|
+
if st == "paid":
|
|
92
|
+
return f"Payment arrived: +{out['hours_added']:g} hours. {out['balance_hours']:g} audio hours left."
|
|
93
|
+
if st == "waiting":
|
|
94
|
+
return out["message_for_user"]
|
|
95
|
+
if cmd == "transcribe":
|
|
96
|
+
lines = [f"{len(out['done'])} of {out['files_total']} done; transcripts in {out['out_dir']}"]
|
|
97
|
+
lines += [f"failed: {f['file']}: {f['error']}" for f in out["failed"]]
|
|
98
|
+
if out.get("next_step"):
|
|
99
|
+
lines.append(out["next_step"])
|
|
100
|
+
return "\n".join(lines)
|
|
101
|
+
return json.dumps(out)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def main(argv: list[str] | None = None, session: Any = None) -> int:
|
|
105
|
+
a = _parser().parse_args(argv)
|
|
106
|
+
if a.cmd == "mcp":
|
|
107
|
+
from .mcp_server import run_server # the MCP SDK loads only for this command
|
|
108
|
+
run_server(a.api)
|
|
109
|
+
return 0
|
|
110
|
+
api, as_json = config.api_url(a.api), a.json
|
|
111
|
+
try:
|
|
112
|
+
out, code = _run(a, api, as_json, session)
|
|
113
|
+
except tools.Problem as exc:
|
|
114
|
+
out, code = {"status": "error", "error": str(exc)}, exc.code
|
|
115
|
+
if not as_json:
|
|
116
|
+
print(str(exc), file=sys.stderr)
|
|
117
|
+
return code
|
|
118
|
+
if as_json:
|
|
119
|
+
print(json.dumps(out))
|
|
120
|
+
elif out.get("status") != "error":
|
|
121
|
+
print(_human(a.cmd, out))
|
|
122
|
+
return code
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _run(a: argparse.Namespace, api: str, as_json: bool, session: Any) -> tuple[dict[str, Any], int]:
|
|
126
|
+
if a.cmd == "login":
|
|
127
|
+
if a.email:
|
|
128
|
+
out = tools.sign_in_start(api, a.email, a.name, session)
|
|
129
|
+
if not as_json and not a.code and not a.wait and sys.stdin.isatty():
|
|
130
|
+
print(_human("login", out))
|
|
131
|
+
code = input("Code from the email (or press Enter after clicking Approve): ").strip()
|
|
132
|
+
out = tools.sign_in_finish(api, code, 0 if code else a.timeout, session)
|
|
133
|
+
return out, 0 if out["status"] == "signed_in" else tools.WAITING
|
|
134
|
+
if not (a.code or a.wait):
|
|
135
|
+
return out, 0
|
|
136
|
+
if not (a.code or a.wait):
|
|
137
|
+
raise tools.Problem("use --email to start, then --code or --wait to finish", 2)
|
|
138
|
+
out = tools.sign_in_finish(api, a.code or "", 0 if a.code else a.timeout, session)
|
|
139
|
+
return out, 0 if out["status"] == "signed_in" else tools.WAITING
|
|
140
|
+
if a.cmd == "logout":
|
|
141
|
+
return tools.sign_out(api, session), 0
|
|
142
|
+
if a.cmd == "balance":
|
|
143
|
+
return tools.account(api, session), 0
|
|
144
|
+
if a.cmd == "buy":
|
|
145
|
+
if a.usd is not None:
|
|
146
|
+
out = tools.buy(api, a.usd, session)
|
|
147
|
+
if not a.wait:
|
|
148
|
+
return out, 0
|
|
149
|
+
_say(_human("buy", out), as_json)
|
|
150
|
+
elif not a.wait:
|
|
151
|
+
raise tools.Problem("say how many dollars, e.g. `speechtrace buy 10`, or use --wait", 2)
|
|
152
|
+
out = tools.wait_for_payment(api, a.timeout, session)
|
|
153
|
+
return out, 0 if out["status"] == "paid" else tools.WAITING
|
|
154
|
+
if a.cmd == "transcribe":
|
|
155
|
+
formats = [f.strip() for f in a.formats.split(",") if f.strip()]
|
|
156
|
+
out = tools.transcribe(api, a.paths, a.out, formats, not a.no_speakers, a.parallel, wait=not a.no_wait,
|
|
157
|
+
session=session, log=lambda m: _say(m, as_json))
|
|
158
|
+
code = {"out_of_hours": tools.OUT_OF_HOURS, "failed": 1}.get(out["status"], 0)
|
|
159
|
+
return out, 1 if code == 0 and out["failed"] else code
|
|
160
|
+
raise tools.Problem(f"unknown command {a.cmd}", 2)
|
speechtrace/config.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Where the API is, and which key to use: the environment first, then the config file.
|
|
2
|
+
|
|
3
|
+
The config file (config.json in the user's config folder, readable only by them) keeps the key for each
|
|
4
|
+
API address, plus a sign-in or checkout that's still waiting. The key is never printed."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .batch import DEFAULT_API
|
|
14
|
+
|
|
15
|
+
KEY_VARS = ("SPEECHTRACE_API_KEY", "TX_API_KEY")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def config_dir() -> Path:
|
|
19
|
+
if os.environ.get("SPEECHTRACE_CONFIG_DIR"):
|
|
20
|
+
return Path(os.environ["SPEECHTRACE_CONFIG_DIR"])
|
|
21
|
+
if os.name == "nt" and os.environ.get("APPDATA"):
|
|
22
|
+
return Path(os.environ["APPDATA"]) / "speechtrace"
|
|
23
|
+
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "speechtrace"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def config_path() -> Path:
|
|
27
|
+
return config_dir() / "config.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load() -> dict[str, Any]:
|
|
31
|
+
try:
|
|
32
|
+
data = json.loads(config_path().read_text())
|
|
33
|
+
return data if isinstance(data, dict) else {}
|
|
34
|
+
except (OSError, ValueError):
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def save(data: dict[str, Any]) -> None:
|
|
39
|
+
"""Written atomically, readable only by the user (0600, in a 0700 folder)."""
|
|
40
|
+
folder = config_dir()
|
|
41
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
try:
|
|
43
|
+
os.chmod(folder, 0o700)
|
|
44
|
+
except OSError:
|
|
45
|
+
pass
|
|
46
|
+
tmp = folder / f".config.{os.getpid()}.tmp"
|
|
47
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
48
|
+
with os.fdopen(fd, "w") as f:
|
|
49
|
+
json.dump(data, f, indent=1)
|
|
50
|
+
os.replace(tmp, config_path())
|
|
51
|
+
try:
|
|
52
|
+
os.chmod(config_path(), 0o600)
|
|
53
|
+
except OSError:
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def api_url(flag: str | None = None) -> str:
|
|
58
|
+
return (flag or os.environ.get("SPEECHTRACE_API_URL") or os.environ.get("TX_API_URL") or DEFAULT_API).rstrip("/")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def api_key(api: str) -> tuple[str, str]:
|
|
62
|
+
"""(key, where it came from), or ("", "") when not signed in."""
|
|
63
|
+
for var in KEY_VARS:
|
|
64
|
+
if os.environ.get(var):
|
|
65
|
+
return os.environ[var], var
|
|
66
|
+
entry = load().get("accounts", {}).get(api) or {}
|
|
67
|
+
return (entry.get("api_key", ""), str(config_path())) if entry.get("api_key") else ("", "")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def signed_in_email(api: str) -> str:
|
|
71
|
+
return (load().get("accounts", {}).get(api) or {}).get("email", "")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def remember(api: str, key: str, email: str) -> None:
|
|
75
|
+
data = load()
|
|
76
|
+
data.setdefault("accounts", {})[api] = {"api_key": key, "email": email}
|
|
77
|
+
save(data)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def forget(api: str) -> None:
|
|
81
|
+
data = load()
|
|
82
|
+
data.get("accounts", {}).pop(api, None)
|
|
83
|
+
save(data)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def pending(name: str, api: str) -> dict[str, Any]:
|
|
87
|
+
"""A sign-in or checkout still waiting for this API address ({} if none)."""
|
|
88
|
+
item = load().get(f"pending_{name}") or {}
|
|
89
|
+
return item if item.get("api") == api else {}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def set_pending(name: str, api: str, value: dict[str, Any] | None) -> None:
|
|
93
|
+
data = load()
|
|
94
|
+
if value is None:
|
|
95
|
+
data.pop(f"pending_{name}", None)
|
|
96
|
+
else:
|
|
97
|
+
data[f"pending_{name}"] = {"api": api, **value}
|
|
98
|
+
save(data)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""The MCP server (`speechtrace mcp`, over stdio): sign in by email, transcribe local files, check the
|
|
2
|
+
balance and buy hours, for AI apps that can't run commands themselves (Claude Desktop) or prefer tools.
|
|
3
|
+
|
|
4
|
+
stdout carries the protocol, so nothing here prints: the batch log is collected in memory and errors go
|
|
5
|
+
back to the model as ToolError messages that say what to do next. No result contains the API key."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
import anyio
|
|
13
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
14
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
15
|
+
|
|
16
|
+
from . import __version__, config, tools
|
|
17
|
+
|
|
18
|
+
INSTRUCTIONS = """Speechtrace turns English audio and video into text: transcripts with punctuation, word \
|
|
19
|
+
timestamps and speaker labels (txt, srt, vtt, json).
|
|
20
|
+
|
|
21
|
+
1. If a tool says you aren't signed in, ask the person for their email address and call sign_in_start. Pass \
|
|
22
|
+
its message_for_user on to them: they either tell you a 6-digit code (call sign_in_finish with it) or click \
|
|
23
|
+
Approve in the email and type the number you gave them (call sign_in_finish with wait_seconds).
|
|
24
|
+
2. Call transcribe with absolute paths. If its status is "working", call it again with the same arguments \
|
|
25
|
+
until it is "done"; finished files are skipped.
|
|
26
|
+
3. If transcribe returns "out_of_hours", ask the person how many dollars to add, call buy_credit, give them \
|
|
27
|
+
the link (only they pay, on Stripe's page; never ask for card details), then call account with \
|
|
28
|
+
wait_for_payment_seconds, and call transcribe again.
|
|
29
|
+
Using Speechtrace means the person agrees to its terms and privacy policy (speechtraceai.com/terms, /privacy)."""
|
|
30
|
+
|
|
31
|
+
Format = Literal["txt", "srt", "vtt", "json"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _client_name(ctx: Context | None) -> str:
|
|
35
|
+
"""The app's name from the MCP handshake (e.g. "claude-ai", "cursor-vscode"), if it gave one."""
|
|
36
|
+
for path in (("session", "client_info", "name"), ("session", "client_params", "clientInfo", "name"),
|
|
37
|
+
("session", "client_params", "client_info", "name")):
|
|
38
|
+
obj: Any = ctx
|
|
39
|
+
try:
|
|
40
|
+
for attr in path:
|
|
41
|
+
obj = getattr(obj, attr)
|
|
42
|
+
except Exception: # noqa: BLE001 - not available in this SDK version or connection
|
|
43
|
+
continue
|
|
44
|
+
if isinstance(obj, str) and obj:
|
|
45
|
+
return obj[:40]
|
|
46
|
+
return "an MCP app"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def build(api_flag: str | None = None, session: Any = None) -> MCPServer:
|
|
50
|
+
api = config.api_url(api_flag)
|
|
51
|
+
runs = tools.Runs()
|
|
52
|
+
server = MCPServer("speechtrace", title="Speechtrace", version=__version__, instructions=INSTRUCTIONS,
|
|
53
|
+
website_url="https://speechtraceai.com")
|
|
54
|
+
|
|
55
|
+
async def off_loop(fn: Any, *args: Any) -> dict[str, Any]:
|
|
56
|
+
try:
|
|
57
|
+
return await anyio.to_thread.run_sync(lambda: fn(*args))
|
|
58
|
+
except tools.Problem as exc:
|
|
59
|
+
raise ToolError(str(exc)) from exc
|
|
60
|
+
|
|
61
|
+
@server.tool()
|
|
62
|
+
async def sign_in_start(email: str, switch_account: bool = False, ctx: Context | None = None) -> dict[str, Any]:
|
|
63
|
+
"""Sign in or sign up by email: Speechtrace emails the person a 6-digit code and an Approve link.
|
|
64
|
+
New accounts get free hours. Pass message_for_user on to the person, then call sign_in_finish."""
|
|
65
|
+
current = config.signed_in_email(api)
|
|
66
|
+
if current and not switch_account:
|
|
67
|
+
return {"status": "already_signed_in", "email": current,
|
|
68
|
+
"next_step": "Call sign_in_start with switch_account=true to sign in as someone else."}
|
|
69
|
+
return await off_loop(tools.sign_in_start, api, email, _client_name(ctx), session)
|
|
70
|
+
|
|
71
|
+
@server.tool()
|
|
72
|
+
async def sign_in_finish(code: str = "", wait_seconds: int = 0) -> dict[str, Any]:
|
|
73
|
+
"""Finish signing in with the 6-digit code from the email, or (no code) after the person clicked
|
|
74
|
+
Approve: waits up to wait_seconds (max 60) for that. The key is stored locally, never returned."""
|
|
75
|
+
return await off_loop(tools.sign_in_finish, api, code, min(max(wait_seconds, 0), 60), session)
|
|
76
|
+
|
|
77
|
+
@server.tool()
|
|
78
|
+
async def account(wait_for_payment_seconds: int = 0) -> dict[str, Any]:
|
|
79
|
+
"""Audio hours left and the price. With wait_for_payment_seconds (max 60), first waits for the
|
|
80
|
+
payment from the last buy_credit link to arrive."""
|
|
81
|
+
if wait_for_payment_seconds > 0:
|
|
82
|
+
paid = await off_loop(tools.wait_for_payment, api, min(wait_for_payment_seconds, 60), session)
|
|
83
|
+
if paid["status"] != "paid":
|
|
84
|
+
return paid
|
|
85
|
+
return await off_loop(tools.account, api, session)
|
|
86
|
+
|
|
87
|
+
@server.tool()
|
|
88
|
+
async def buy_credit(usd: int) -> dict[str, Any]:
|
|
89
|
+
"""A Stripe link for the person to buy audio hours (whole dollars; see account for the range). Only
|
|
90
|
+
they pay, on Stripe's page. Afterwards call account with wait_for_payment_seconds."""
|
|
91
|
+
return await off_loop(tools.buy, api, usd, session)
|
|
92
|
+
|
|
93
|
+
@server.tool()
|
|
94
|
+
async def transcribe(paths: list[str], out_dir: str = "", formats: list[Format] | None = None,
|
|
95
|
+
speakers: bool = True, wait_seconds: int = 45, include_text: bool = True) -> dict[str, Any]:
|
|
96
|
+
"""Transcribe local audio or video files or folders (absolute paths; folders are searched). Transcripts
|
|
97
|
+
are saved next to them in a "transcripts" folder (or out_dir). Waits up to wait_seconds (max 300);
|
|
98
|
+
if the status is "working", call again with the same arguments. With include_text, the text of
|
|
99
|
+
finished transcripts comes back too (up to about 20,000 characters)."""
|
|
100
|
+
if not paths:
|
|
101
|
+
raise ToolError("give at least one file or folder")
|
|
102
|
+
return await off_loop(runs.transcribe, api, paths, out_dir, list(formats or ["txt", "srt", "json"]),
|
|
103
|
+
speakers, min(max(wait_seconds, 0), 300), include_text, session)
|
|
104
|
+
|
|
105
|
+
@server.tool()
|
|
106
|
+
async def sign_out() -> dict[str, Any]:
|
|
107
|
+
"""Revoke this computer's Speechtrace key and forget it."""
|
|
108
|
+
return await off_loop(tools.sign_out, api, session)
|
|
109
|
+
|
|
110
|
+
return server
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def run_server(api_flag: str | None = None) -> None:
|
|
114
|
+
print(f"speechtrace {__version__} MCP server on stdio", file=sys.stderr)
|
|
115
|
+
build(api_flag).run("stdio")
|
speechtrace/tools.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""What the command line and the MCP server do: sign in by email, check the balance, buy hours, transcribe.
|
|
2
|
+
Each returns a plain dict (the --json output and the MCP tools' results), and raises Problem with the next
|
|
3
|
+
step when something needs doing first. No result ever contains the API key."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from . import __version__, batch, config
|
|
15
|
+
|
|
16
|
+
NOT_SIGNED_IN = 3
|
|
17
|
+
OUT_OF_HOURS = batch.OUT_OF_HOURS
|
|
18
|
+
WAITING = 5
|
|
19
|
+
TEXT_LIMIT = 20_000 # characters of transcript text returned to chat apps
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Problem(Exception):
|
|
23
|
+
def __init__(self, message: str, code: int = 1) -> None:
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
self.code = code
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def client(api: str, key: str = "", session: Any = None) -> batch.Client:
|
|
29
|
+
return batch.Client(api, key, session, user_agent=f"speechtrace/{__version__}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def keyed(api: str, session: Any = None) -> batch.Client:
|
|
33
|
+
key, _ = config.api_key(api)
|
|
34
|
+
if not key:
|
|
35
|
+
raise Problem("Not signed in. Ask the person for their email address and run "
|
|
36
|
+
"`speechtrace login --email them@example.com` (or the sign_in_start tool).", NOT_SIGNED_IN)
|
|
37
|
+
return client(api, key, session)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def call(c: batch.Client, method: str, path: str, **kw: Any) -> Any:
|
|
41
|
+
try:
|
|
42
|
+
return c._call(method, path, **kw)
|
|
43
|
+
except batch.ApiError as exc:
|
|
44
|
+
if exc.status == 401:
|
|
45
|
+
raise Problem("The saved API key doesn't work any more (revoked?). Sign in again with "
|
|
46
|
+
"`speechtrace login --email …`.", NOT_SIGNED_IN) from exc
|
|
47
|
+
raise Problem(str(exc).split(": ", 1)[-1]) from exc
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def default_client_name() -> str:
|
|
51
|
+
env = os.environ
|
|
52
|
+
if env.get("CLAUDECODE") or env.get("CLAUDE_CODE_ENTRYPOINT"):
|
|
53
|
+
return "Claude Code"
|
|
54
|
+
if any(k.startswith("CURSOR_") for k in env):
|
|
55
|
+
return "Cursor"
|
|
56
|
+
if any(k.startswith("CODEX_") for k in env):
|
|
57
|
+
return "Codex"
|
|
58
|
+
return "speechtrace CLI"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---------------------------------------------------------------- sign-in
|
|
62
|
+
|
|
63
|
+
def sign_in_start(api: str, email: str, client_name: str = "", session: Any = None) -> dict[str, Any]:
|
|
64
|
+
"""Email the person a 6-digit code and an Approve link; remember the request for sign_in_finish."""
|
|
65
|
+
r = call(client(api, session=session), "POST", "/v1/auth/email", retry=False,
|
|
66
|
+
json={"email": email, "client_name": client_name or default_client_name()})
|
|
67
|
+
body = r.json()
|
|
68
|
+
config.set_pending("signin", api, {"request_token": body["request_token"], "email": body["email"],
|
|
69
|
+
"match_number": body["match_number"],
|
|
70
|
+
"expires_at": time.time() + body["expires_in"]})
|
|
71
|
+
n = body["match_number"]
|
|
72
|
+
return {"status": "code_sent", "email": body["email"], "match_number": n,
|
|
73
|
+
"expires_in_minutes": body["expires_in"] // 60,
|
|
74
|
+
"message_for_user": f"I've asked Speechtrace to email {body['email']}. Tell me the 6-digit code from "
|
|
75
|
+
f"that email, or click Approve in it and enter {n}.",
|
|
76
|
+
"next_step": "speechtrace login --code <code> or, after they click Approve: speechtrace login --wait"}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sign_in_finish(api: str, code: str = "", wait_seconds: float = 0, session: Any = None,
|
|
80
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
81
|
+
clock: Callable[[], float] = time.time) -> dict[str, Any]:
|
|
82
|
+
"""Finish with the code, or (without one) check whether the person approved, waiting up to wait_seconds.
|
|
83
|
+
The key is saved to the config file, never returned."""
|
|
84
|
+
pend = config.pending("signin", api)
|
|
85
|
+
if not pend:
|
|
86
|
+
raise Problem("No sign-in is waiting. Start one with `speechtrace login --email …`.")
|
|
87
|
+
c, until = client(api, session=session), clock() + max(0.0, wait_seconds)
|
|
88
|
+
while True:
|
|
89
|
+
try:
|
|
90
|
+
r = c._call("POST", "/v1/auth/email/complete",
|
|
91
|
+
json={"request_token": pend["request_token"], "code": code or ""})
|
|
92
|
+
except batch.ApiError as exc:
|
|
93
|
+
msg = str(exc).split(": ", 1)[-1]
|
|
94
|
+
if exc.status in (404, 410, 429) and not (exc.status == 429 and "Approve" in msg):
|
|
95
|
+
config.set_pending("signin", api, None)
|
|
96
|
+
raise Problem(f"{msg}." if not msg.endswith(".") else msg) from exc
|
|
97
|
+
body = r.json()
|
|
98
|
+
if r.status_code == 200:
|
|
99
|
+
config.remember(api, body["api_key"], body["email"])
|
|
100
|
+
config.set_pending("signin", api, None)
|
|
101
|
+
return {"status": "signed_in", "email": body["email"], "new_account": body["new_account"],
|
|
102
|
+
"balance_hours": body["balance_hours"], "price_per_hour_usd": body["price_per_hour_usd"],
|
|
103
|
+
"key_saved_to": str(config.config_path())}
|
|
104
|
+
if code or clock() >= until:
|
|
105
|
+
return {"status": "pending", "email": pend["email"], "match_number": pend["match_number"],
|
|
106
|
+
"message_for_user": f"Waiting for you to click Approve in the email and enter "
|
|
107
|
+
f"{pend['match_number']} (or tell me the 6-digit code).",
|
|
108
|
+
"next_step": "speechtrace login --wait or speechtrace login --code <code>"}
|
|
109
|
+
sleep(min(body.get("poll_interval", 5), max(0.5, until - clock())))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def sign_out(api: str, session: Any = None) -> dict[str, Any]:
|
|
113
|
+
key, source = config.api_key(api)
|
|
114
|
+
if key:
|
|
115
|
+
try:
|
|
116
|
+
client(api, key, session)._call("DELETE", "/v1/auth/key")
|
|
117
|
+
except batch.ApiError:
|
|
118
|
+
pass # already revoked: forget it anyway
|
|
119
|
+
if source == str(config.config_path()):
|
|
120
|
+
config.forget(api)
|
|
121
|
+
return {"status": "signed_out", "note": "" if source in ("", str(config.config_path()))
|
|
122
|
+
else f"The key in {source} still works; unset that variable to stop using it."}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ---------------------------------------------------------------- account and buying hours
|
|
126
|
+
|
|
127
|
+
def account(api: str, session: Any = None) -> dict[str, Any]:
|
|
128
|
+
a = call(keyed(api, session), "GET", "/v1/account").json()
|
|
129
|
+
return {"email": a["email"], "balance_hours": a["balance_hours"], "free_hours": a["free_hours"],
|
|
130
|
+
"paid_hours": a["paid_hours"], "price_per_hour_usd": a["price_per_hour_usd"],
|
|
131
|
+
"min_topup_usd": a["min_topup_usd"], "max_topup_usd": a["max_topup_usd"],
|
|
132
|
+
"payments_enabled": a["payments_enabled"]}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def buy(api: str, usd: int, session: Any = None) -> dict[str, Any]:
|
|
136
|
+
out = call(keyed(api, session), "POST", "/v1/billing/checkout", json={"usd": usd}).json()
|
|
137
|
+
config.set_pending("checkout", api, {"created_at": out["created_at"], "usd": out["usd"]})
|
|
138
|
+
return {"status": "link_ready", "url": out["url"], "usd": out["usd"], "hours": out["hours"],
|
|
139
|
+
"message_for_user": f"To add ${out['usd']:g} (about {out['hours']:,.0f} audio hours), pay here on "
|
|
140
|
+
f"Stripe's page: {out['url']}",
|
|
141
|
+
"next_step": "speechtrace buy --wait (returns once the hours have arrived)"}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def wait_for_payment(api: str, timeout: float = 600, session: Any = None, sleep: Callable[[float], None] = time.sleep,
|
|
145
|
+
clock: Callable[[], float] = time.time, every: float = 5) -> dict[str, Any]:
|
|
146
|
+
c = keyed(api, session)
|
|
147
|
+
since = config.pending("checkout", api).get("created_at", clock() - 3600) - 5
|
|
148
|
+
until = clock() + max(0.0, timeout)
|
|
149
|
+
while True:
|
|
150
|
+
new = [p for p in call(c, "GET", "/v1/billing/payments").json()["data"] if p["at"] >= since]
|
|
151
|
+
if new:
|
|
152
|
+
config.set_pending("checkout", api, None)
|
|
153
|
+
acc = account(api, session)
|
|
154
|
+
return {"status": "paid", "usd": new[0]["usd"], "hours_added": new[0]["hours"],
|
|
155
|
+
"balance_hours": acc["balance_hours"]}
|
|
156
|
+
if clock() >= until:
|
|
157
|
+
return {"status": "waiting", "message_for_user": "I haven't seen the payment yet. Once you've paid on "
|
|
158
|
+
"Stripe's page, the hours arrive within seconds.",
|
|
159
|
+
"next_step": "speechtrace buy --wait"}
|
|
160
|
+
sleep(min(every, max(0.5, until - clock())))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# ---------------------------------------------------------------- transcribing
|
|
164
|
+
|
|
165
|
+
def default_out(paths: list[str]) -> Path:
|
|
166
|
+
first = Path(paths[0]).expanduser().resolve()
|
|
167
|
+
return (first if first.is_dir() else first.parent) / "transcripts"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def summary(api: str, paths: list[str], out: Path, counts: dict[str, int] | None, running: bool,
|
|
171
|
+
include_text: bool = False, session: Any = None) -> dict[str, Any]:
|
|
172
|
+
"""Where every file stands, from the folder's progress file."""
|
|
173
|
+
state = batch.load_state(out)
|
|
174
|
+
files = batch.find_files([str(Path(p).expanduser()) for p in paths])
|
|
175
|
+
done, pending, failed, unsent, budget = [], [], [], [], TEXT_LIMIT
|
|
176
|
+
for f, rel in files:
|
|
177
|
+
s = state.get(str(rel), {})
|
|
178
|
+
if s.get("status") == "done":
|
|
179
|
+
stem = out / Path(rel).with_suffix("")
|
|
180
|
+
item: dict[str, Any] = {"file": str(f), "outputs": sorted(str(p) for p in stem.parent.glob(f"{stem.name}.*")
|
|
181
|
+
if p.suffix in (".txt", ".srt", ".vtt", ".json"))}
|
|
182
|
+
txt = stem.parent / f"{stem.name}.txt"
|
|
183
|
+
if include_text and budget > 0 and txt.exists():
|
|
184
|
+
text = txt.read_text(errors="replace")
|
|
185
|
+
item["text"] = text[:budget] + ("…" if len(text) > budget else "")
|
|
186
|
+
budget -= len(item["text"])
|
|
187
|
+
done.append(item)
|
|
188
|
+
elif s.get("status") == "sent":
|
|
189
|
+
pending.append(str(f))
|
|
190
|
+
elif s.get("status") in ("failed", "error"):
|
|
191
|
+
failed.append({"file": str(f), "error": s.get("error", "")})
|
|
192
|
+
else:
|
|
193
|
+
unsent.append(str(f))
|
|
194
|
+
not_sent = (counts or {}).get("not_sent", 0)
|
|
195
|
+
status = "working" if running else "out_of_hours" if not_sent else "failed" if failed and not done else "done"
|
|
196
|
+
out_dict: dict[str, Any] = {"status": status, "out_dir": str(out), "files_total": len(files),
|
|
197
|
+
"done": done, "pending": pending, "failed": failed}
|
|
198
|
+
if status == "out_of_hours":
|
|
199
|
+
out_dict["not_sent"] = len(unsent)
|
|
200
|
+
try:
|
|
201
|
+
price = account(api, session)["price_per_hour_usd"]
|
|
202
|
+
per10 = f" ($10 buys about {10 / price:,.0f} audio hours)" if price else ""
|
|
203
|
+
except Problem:
|
|
204
|
+
per10 = ""
|
|
205
|
+
out_dict["next_step"] = (f"Out of audio hours: {len(unsent)} files weren't sent. Ask the person how much to add"
|
|
206
|
+
f"{per10}, run `speechtrace buy <dollars>`, give them the link, run "
|
|
207
|
+
"`speechtrace buy --wait`, then run this same transcribe again.")
|
|
208
|
+
elif status == "working" or pending:
|
|
209
|
+
out_dict["next_step"] = "Run the same transcribe again to collect the rest (finished files are skipped)."
|
|
210
|
+
return out_dict
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def transcribe(api: str, paths: list[str], out_dir: str = "", formats: list[str] | None = None,
|
|
214
|
+
speakers: bool = True, parallel: int = 4, wait: bool = True, include_text: bool = False,
|
|
215
|
+
session: Any = None, log: Callable[[str], None] = print, poll_s: float = 10.0) -> dict[str, Any]:
|
|
216
|
+
"""Send every file not sent yet and (if wait) collect all transcripts. Safe to run again."""
|
|
217
|
+
c = keyed(api, session)
|
|
218
|
+
formats = formats or ["txt", "srt", "json"]
|
|
219
|
+
bad = [f for f in formats if f not in batch.FORMATS]
|
|
220
|
+
if bad:
|
|
221
|
+
raise Problem(f"unknown format {bad[0]!r}: use any of {', '.join(batch.FORMATS)}", 2)
|
|
222
|
+
paths = [str(Path(p).expanduser()) for p in paths]
|
|
223
|
+
missing = [p for p in paths if not Path(p).exists()]
|
|
224
|
+
if missing:
|
|
225
|
+
raise Problem(f"not found: {missing[0]}", 2)
|
|
226
|
+
out = Path(out_dir).expanduser().resolve() if out_dir else default_out(paths)
|
|
227
|
+
if not batch.find_files(paths):
|
|
228
|
+
raise Problem(f"no audio or video files in {', '.join(paths)} (looked for "
|
|
229
|
+
f"{', '.join(sorted(batch.EXTENSIONS))})", 2)
|
|
230
|
+
run_formats = formats if "txt" in formats or not include_text else [*formats, "txt"]
|
|
231
|
+
counts = batch.run(c, paths, out, run_formats, speakers, parallel, poll_s=poll_s, log=log, wait=wait)
|
|
232
|
+
return summary(api, paths, out, counts, False, include_text, session)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class Runs:
|
|
236
|
+
"""Transcriptions running in the background for the MCP server: one per output folder. Calling again
|
|
237
|
+
with the same folder attaches to the run in progress."""
|
|
238
|
+
|
|
239
|
+
def __init__(self) -> None:
|
|
240
|
+
self.lock = threading.Lock()
|
|
241
|
+
self.runs: dict[str, dict[str, Any]] = {}
|
|
242
|
+
|
|
243
|
+
def transcribe(self, api: str, paths: list[str], out_dir: str, formats: list[str], speakers: bool,
|
|
244
|
+
wait_seconds: float, include_text: bool, session: Any = None) -> dict[str, Any]:
|
|
245
|
+
keyed(api, session) # not signed in: say so now, not from the background
|
|
246
|
+
paths = [str(Path(p).expanduser()) for p in paths]
|
|
247
|
+
out = Path(out_dir).expanduser().resolve() if out_dir else default_out(paths)
|
|
248
|
+
with self.lock:
|
|
249
|
+
run = self.runs.get(str(out))
|
|
250
|
+
if run is None or not run["thread"].is_alive():
|
|
251
|
+
run = {"result": None, "error": None, "log": []}
|
|
252
|
+
|
|
253
|
+
def work(run: dict[str, Any] = run) -> None:
|
|
254
|
+
try:
|
|
255
|
+
run["result"] = transcribe(api, paths, str(out), formats, speakers, include_text=False,
|
|
256
|
+
session=session, log=run["log"].append)
|
|
257
|
+
except Problem as exc:
|
|
258
|
+
run["error"] = exc
|
|
259
|
+
except Exception as exc: # noqa: BLE001 - reported to the model, not raised in a thread
|
|
260
|
+
run["error"] = Problem(f"{type(exc).__name__}: {exc}")
|
|
261
|
+
|
|
262
|
+
run["thread"] = threading.Thread(target=work, daemon=True)
|
|
263
|
+
self.runs[str(out)] = run
|
|
264
|
+
run["thread"].start()
|
|
265
|
+
run["thread"].join(timeout=max(0.0, wait_seconds))
|
|
266
|
+
if run["error"] is not None:
|
|
267
|
+
raise run["error"]
|
|
268
|
+
counts = None
|
|
269
|
+
if run["result"] is not None:
|
|
270
|
+
counts = {"not_sent": run["result"].get("not_sent", 0)} if run["result"]["status"] == "out_of_hours" else {}
|
|
271
|
+
return summary(api, paths, out, counts, run["thread"].is_alive(), include_text, session)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: speechtrace
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Transcribe audio and video files with Speechtrace: punctuation, word timestamps and speaker labels. A command-line tool and an MCP server for AI assistants.
|
|
5
|
+
Project-URL: Homepage, https://speechtraceai.com
|
|
6
|
+
Project-URL: Documentation, https://speechtraceai.com/ai-assistants
|
|
7
|
+
Project-URL: Instructions for AI assistants, https://speechtraceai.com/llms.txt
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai-assistant,audio,mcp,speech-to-text,subtitles,transcription
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Requires-Dist: mcp<3,>=2.3
|
|
17
|
+
Requires-Dist: requests<3,>=2.31
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# speechtrace
|
|
21
|
+
|
|
22
|
+
Transcribe audio and video files with [Speechtrace](https://speechtraceai.com): English transcripts with
|
|
23
|
+
punctuation, word timestamps and speaker labels, as plain text, SRT, WebVTT or JSON. New accounts get free hours,
|
|
24
|
+
no card needed.
|
|
25
|
+
|
|
26
|
+
It's a command-line tool, and an MCP server for AI assistants. Use it yourself, or tell your assistant:
|
|
27
|
+
|
|
28
|
+
> Use speechtraceai.com to transcribe the audio files in ~/Recordings. Instructions for AI assistants:
|
|
29
|
+
> https://speechtraceai.com/llms.txt
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
With [uv](https://docs.astral.sh/uv/) installed, nothing else to install:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uvx speechtrace login --email you@example.com # we email you a 6-digit code
|
|
37
|
+
uvx speechtrace login --code 123456 # ...or `login --wait` after clicking Approve in the email
|
|
38
|
+
uvx speechtrace transcribe ~/Recordings # transcripts go to ~/Recordings/transcripts
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Without uv: `pipx run speechtrace …`, or `pip install speechtrace` and then `speechtrace …`.
|
|
42
|
+
|
|
43
|
+
## Commands
|
|
44
|
+
|
|
45
|
+
| Command | What it does |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `login --email E` | Start signing in (or signing up): we email a code and an Approve link |
|
|
48
|
+
| `login --code C` / `login --wait` | Finish with the code, or once you've clicked Approve |
|
|
49
|
+
| `transcribe PATHS…` | Transcribe files or folders. Safe to stop and run again: finished files are skipped |
|
|
50
|
+
| `balance` | Audio hours left, and the price |
|
|
51
|
+
| `buy USD` / `buy --wait` | A Stripe link to buy hours; `--wait` returns once they've arrived |
|
|
52
|
+
| `logout` | Revoke this computer's key and forget it |
|
|
53
|
+
| `mcp` | Run as an MCP server over stdio |
|
|
54
|
+
|
|
55
|
+
`transcribe` options: `--out DIR`, `--formats txt,srt,vtt,json`, `--no-speakers`, `--parallel N`, and
|
|
56
|
+
`--no-wait` (send everything and return; run again to collect).
|
|
57
|
+
|
|
58
|
+
Every command takes `--json` (one JSON object on stdout) and `--api URL`. Exit codes: 0 done, 1 error or some
|
|
59
|
+
files failed, 2 bad arguments, 3 not signed in, 4 out of audio hours, 5 still waiting.
|
|
60
|
+
|
|
61
|
+
The API key is saved in your user config folder (`~/.config/speechtrace/config.json`, readable only by you).
|
|
62
|
+
`SPEECHTRACE_API_KEY` overrides it; `SPEECHTRACE_CONFIG_DIR` moves it.
|
|
63
|
+
|
|
64
|
+
## As an MCP server
|
|
65
|
+
|
|
66
|
+
Tools: `sign_in_start`, `sign_in_finish`, `transcribe`, `account`, `buy_credit`, `sign_out`.
|
|
67
|
+
|
|
68
|
+
- **Claude Code:** `claude mcp add --scope user speechtrace -- uvx speechtrace@latest mcp`
|
|
69
|
+
- **Claude Desktop or Cursor** (their MCP config file):
|
|
70
|
+
```json
|
|
71
|
+
{"mcpServers": {"speechtrace": {"command": "uvx", "args": ["speechtrace@latest", "mcp"]}}}
|
|
72
|
+
```
|
|
73
|
+
If Claude Desktop can't find `uvx`, use its full path (`which uvx`).
|
|
74
|
+
- **Codex:** `codex mcp add speechtrace -- uvx speechtrace@latest mcp`
|
|
75
|
+
|
|
76
|
+
## Safety
|
|
77
|
+
|
|
78
|
+
- Signing in needs the code or the Approve button from your own inbox. Approving also asks for the 2-digit
|
|
79
|
+
number your assistant shows, so nobody else's program can sign in as you.
|
|
80
|
+
- Only you can pay: buying hours gives you a link to Stripe's checkout page. Your assistant never sees card
|
|
81
|
+
details.
|
|
82
|
+
- See and revoke keys on your [dashboard](https://speechtraceai.com/app).
|
|
83
|
+
|
|
84
|
+
Using Speechtrace means you agree to its [terms](https://speechtraceai.com/terms) and
|
|
85
|
+
[privacy policy](https://speechtraceai.com/privacy). The tool is open source (MIT).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
speechtrace/__init__.py,sha256=sHXk1ro17oA7iqyWsPIvQ2UgQw007pQQrcLTCgJWwLg,193
|
|
2
|
+
speechtrace/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
speechtrace/batch.py,sha256=ciOAdYO3atQwxgT_VA7z_9SVP_OQ1v-MvBZe9iv2FoM,9965
|
|
4
|
+
speechtrace/cli.py,sha256=3LX5rl443kYSMmcV8-mRgWV1oOwibTrfivwQNpFMDro,8520
|
|
5
|
+
speechtrace/config.py,sha256=x50CV19lAZIatowiC3sG5TEFyJm5j8h957ddH9vk_-U,3041
|
|
6
|
+
speechtrace/mcp_server.py,sha256=ofJLk7iUNLoziBMLB_jlytcg3a_mjFpWGAXrvVaKBeI,6189
|
|
7
|
+
speechtrace/tools.py,sha256=KHfyVjJuJFyQQZ2txAJ0_FZ2jtN7K5u6MCSHU-RoFeI,14389
|
|
8
|
+
speechtrace-0.1.0.dist-info/METADATA,sha256=8dvQEgFIGO2GUyR6XeXXSyV1c7_oe3sIKHZcYbaQg2k,4037
|
|
9
|
+
speechtrace-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
speechtrace-0.1.0.dist-info/entry_points.txt,sha256=nlQqtfu_g_6hZ13798is0Y-0gZ8SSS4MeKu8m4QAutw,53
|
|
11
|
+
speechtrace-0.1.0.dist-info/licenses/LICENSE,sha256=HNDH-WNGfeMcPOhPLFe2C0WbhQD1anVtqueGXcZpSEE,1068
|
|
12
|
+
speechtrace-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Speechtrace
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|