moneytools-transcripts 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.
- moneytools_transcripts-0.1.0/.gitignore +6 -0
- moneytools_transcripts-0.1.0/LICENSE +21 -0
- moneytools_transcripts-0.1.0/PKG-INFO +95 -0
- moneytools_transcripts-0.1.0/README.md +79 -0
- moneytools_transcripts-0.1.0/pyproject.toml +28 -0
- moneytools_transcripts-0.1.0/src/moneytools_transcripts/__init__.py +388 -0
- moneytools_transcripts-0.1.0/src/moneytools_transcripts/__main__.py +2 -0
- moneytools_transcripts-0.1.0/src/moneytools_transcripts/cli.py +127 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MoneyTools
|
|
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.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: moneytools-transcripts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pay-per-file transcription over x402 (USDC on Base): official MoneyTools Transcripts client with a dTelecom-compatible file API and CLI mt-transcribe, plus a pay-per-call MoneyTools Settle client. No prepaid credits.
|
|
5
|
+
Project-URL: Homepage, https://speech.moneytools.dev/migrate/dtelecom
|
|
6
|
+
Project-URL: Documentation, https://speech.moneytools.dev/llms.txt
|
|
7
|
+
Author-email: MoneyTools <support@moneytools.dev>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,base,dtelecom,speech-to-text,srt,transcription,usdc,x402
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: eth-account>=0.13
|
|
13
|
+
Requires-Dist: requests>=2.31
|
|
14
|
+
Requires-Dist: x402[evm,requests]<3,>=2.27
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# moneytools-transcripts
|
|
18
|
+
|
|
19
|
+
Pay-per-file speech-to-text for [MoneyTools Transcripts](https://speech.moneytools.dev), over [x402](https://www.x402.org) (USDC on Base).
|
|
20
|
+
|
|
21
|
+
- **$0.005 per started audio minute**, no prepaid credits
|
|
22
|
+
- Same REST shape as dTelecom's `POST /v1/transcriptions/jobs` + poll
|
|
23
|
+
- Uses the official `x402` Python client (`x402[requests,evm]`) to answer HTTP 402 automatically
|
|
24
|
+
- CLI: `mt-transcribe meeting.mp3`
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install moneytools-transcripts
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import os
|
|
36
|
+
from eth_account import Account
|
|
37
|
+
from moneytools_transcripts import TranscriptsClient
|
|
38
|
+
|
|
39
|
+
account = Account.from_key(os.environ["X402_PRIVATE_KEY"]) # Base wallet with a little USDC
|
|
40
|
+
tc = TranscriptsClient(account) # https://speech.moneytools.dev, Base mainnet
|
|
41
|
+
|
|
42
|
+
job = tc.transcribe_file("meeting.mp3", language="en", idempotency_key="meeting-42")
|
|
43
|
+
done = tc.wait_for_job(job["id"])
|
|
44
|
+
print(done["result"]["text"])
|
|
45
|
+
print(tc.get_job(job["id"], fmt="srt"))
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
A public `https` media URL:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
job = tc.transcribe_url("https://example.com/meeting.mp3", wait=True)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Unpaid price check (no signature):
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
quote = tc.quote_file("meeting.mp3")
|
|
58
|
+
print(quote["amountUsd"], quote["startedMinutes"])
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Spend cap: `TranscriptsClient(account, max_usd_per_request=0.05)`.
|
|
62
|
+
|
|
63
|
+
## Settle (agent spend controls, pay-per-call)
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from moneytools_transcripts import SettleClient
|
|
67
|
+
settle = SettleClient(account) # or api_key="mts_..."; default cap 0.05 USDC per call
|
|
68
|
+
settle.spend_check(payer=account.address, amount_usd="0.40", host="api.example.com")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## CLI
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
export X402_PRIVATE_KEY=0x... # never pass this on a shared command line if you can avoid it
|
|
75
|
+
mt-transcribe meeting.mp3
|
|
76
|
+
mt-transcribe --format srt meeting.mp3 > meeting.srt
|
|
77
|
+
mt-transcribe --url https://example.com/episode.mp3
|
|
78
|
+
mt-transcribe --quote meeting.mp3 # HTTP 402 only; no key required
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Drop-in names (dTelecom file transcription)
|
|
82
|
+
|
|
83
|
+
`create_file_transcription`, `get_file_transcription`, and `delete_file_transcription` match the public file-transcription surface of `@dtelecom/x402-client` / the dTelecom gateway (snake_case). There is no `buy_credits` — pay the 402 per file instead.
|
|
84
|
+
|
|
85
|
+
Migration notes: https://speech.moneytools.dev/migrate/dtelecom
|
|
86
|
+
|
|
87
|
+
Hosted raw examples (also not prepaid):
|
|
88
|
+
|
|
89
|
+
- https://speech.moneytools.dev/examples/transcribe.py
|
|
90
|
+
- https://speech.moneytools.dev/examples/x402_sign.py
|
|
91
|
+
- https://speech.moneytools.dev/examples/transcribe.ts
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# moneytools-transcripts
|
|
2
|
+
|
|
3
|
+
Pay-per-file speech-to-text for [MoneyTools Transcripts](https://speech.moneytools.dev), over [x402](https://www.x402.org) (USDC on Base).
|
|
4
|
+
|
|
5
|
+
- **$0.005 per started audio minute**, no prepaid credits
|
|
6
|
+
- Same REST shape as dTelecom's `POST /v1/transcriptions/jobs` + poll
|
|
7
|
+
- Uses the official `x402` Python client (`x402[requests,evm]`) to answer HTTP 402 automatically
|
|
8
|
+
- CLI: `mt-transcribe meeting.mp3`
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install moneytools-transcripts
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import os
|
|
20
|
+
from eth_account import Account
|
|
21
|
+
from moneytools_transcripts import TranscriptsClient
|
|
22
|
+
|
|
23
|
+
account = Account.from_key(os.environ["X402_PRIVATE_KEY"]) # Base wallet with a little USDC
|
|
24
|
+
tc = TranscriptsClient(account) # https://speech.moneytools.dev, Base mainnet
|
|
25
|
+
|
|
26
|
+
job = tc.transcribe_file("meeting.mp3", language="en", idempotency_key="meeting-42")
|
|
27
|
+
done = tc.wait_for_job(job["id"])
|
|
28
|
+
print(done["result"]["text"])
|
|
29
|
+
print(tc.get_job(job["id"], fmt="srt"))
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
A public `https` media URL:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
job = tc.transcribe_url("https://example.com/meeting.mp3", wait=True)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Unpaid price check (no signature):
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
quote = tc.quote_file("meeting.mp3")
|
|
42
|
+
print(quote["amountUsd"], quote["startedMinutes"])
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Spend cap: `TranscriptsClient(account, max_usd_per_request=0.05)`.
|
|
46
|
+
|
|
47
|
+
## Settle (agent spend controls, pay-per-call)
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from moneytools_transcripts import SettleClient
|
|
51
|
+
settle = SettleClient(account) # or api_key="mts_..."; default cap 0.05 USDC per call
|
|
52
|
+
settle.spend_check(payer=account.address, amount_usd="0.40", host="api.example.com")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## CLI
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
export X402_PRIVATE_KEY=0x... # never pass this on a shared command line if you can avoid it
|
|
59
|
+
mt-transcribe meeting.mp3
|
|
60
|
+
mt-transcribe --format srt meeting.mp3 > meeting.srt
|
|
61
|
+
mt-transcribe --url https://example.com/episode.mp3
|
|
62
|
+
mt-transcribe --quote meeting.mp3 # HTTP 402 only; no key required
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Drop-in names (dTelecom file transcription)
|
|
66
|
+
|
|
67
|
+
`create_file_transcription`, `get_file_transcription`, and `delete_file_transcription` match the public file-transcription surface of `@dtelecom/x402-client` / the dTelecom gateway (snake_case). There is no `buy_credits` — pay the 402 per file instead.
|
|
68
|
+
|
|
69
|
+
Migration notes: https://speech.moneytools.dev/migrate/dtelecom
|
|
70
|
+
|
|
71
|
+
Hosted raw examples (also not prepaid):
|
|
72
|
+
|
|
73
|
+
- https://speech.moneytools.dev/examples/transcribe.py
|
|
74
|
+
- https://speech.moneytools.dev/examples/x402_sign.py
|
|
75
|
+
- https://speech.moneytools.dev/examples/transcribe.ts
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
MIT
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "moneytools-transcripts"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Pay-per-file transcription over x402 (USDC on Base): official MoneyTools Transcripts client with a dTelecom-compatible file API and CLI mt-transcribe, plus a pay-per-call MoneyTools Settle client. No prepaid credits."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "MoneyTools", email = "support@moneytools.dev" }]
|
|
13
|
+
keywords = ["x402", "transcription", "speech-to-text", "srt", "usdc", "base", "dtelecom", "agents"]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"x402[requests,evm]>=2.27,<3",
|
|
16
|
+
"eth-account>=0.13",
|
|
17
|
+
"requests>=2.31",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://speech.moneytools.dev/migrate/dtelecom"
|
|
22
|
+
Documentation = "https://speech.moneytools.dev/llms.txt"
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
mt-transcribe = "moneytools_transcripts.cli:main"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.sdist]
|
|
28
|
+
include = ["src/moneytools_transcripts", "README.md", "LICENSE"]
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""moneytools-transcripts: pay-per-file transcription over x402 (USDC on Base).
|
|
2
|
+
|
|
3
|
+
Official client for MoneyTools Transcripts (https://speech.moneytools.dev).
|
|
4
|
+
Same REST shape as dTelecom's POST /v1/transcriptions/jobs, but there are no
|
|
5
|
+
prepaid credits: each file is paid once via x402 ($0.005 per started minute).
|
|
6
|
+
|
|
7
|
+
from eth_account import Account
|
|
8
|
+
from moneytools_transcripts import TranscriptsClient
|
|
9
|
+
|
|
10
|
+
tc = TranscriptsClient(Account.from_key(os.environ["X402_PRIVATE_KEY"]))
|
|
11
|
+
job = tc.transcribe_file("meeting.mp3", language="en")
|
|
12
|
+
done = tc.wait_for_job(job["id"])
|
|
13
|
+
print(done["result"]["text"])
|
|
14
|
+
|
|
15
|
+
Primary API: transcribe_file, transcribe_url, get_job (plus wait_for_job, delete_job, quote_file).
|
|
16
|
+
Drop-in aliases: create_file_transcription, get_file_transcription, delete_file_transcription.
|
|
17
|
+
Also: SettleClient for MoneyTools Settle pay-per-call endpoints (spend caps, checks, verify, log).
|
|
18
|
+
CLI: ``mt-transcribe meeting.mp3`` (or ``mt-transcribe --quote meeting.mp3`` to price without paying).
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
import time
|
|
24
|
+
import uuid
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, BinaryIO, Optional, Union, Mapping
|
|
27
|
+
|
|
28
|
+
import requests
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"TRANSCRIPTS_URL",
|
|
32
|
+
"SETTLE_URL",
|
|
33
|
+
"BASE_MAINNET",
|
|
34
|
+
"BASE_SEPOLIA",
|
|
35
|
+
"PRICE_PER_STARTED_MINUTE_USD",
|
|
36
|
+
"USDC_BASE",
|
|
37
|
+
"USDC_BASE_SEPOLIA",
|
|
38
|
+
"TranscriptsClient",
|
|
39
|
+
"TranscriptsGateway",
|
|
40
|
+
"TranscriptsError",
|
|
41
|
+
"SettleClient",
|
|
42
|
+
"paying_session",
|
|
43
|
+
"wallet_auth_headers",
|
|
44
|
+
"quote_from_accepts",
|
|
45
|
+
]
|
|
46
|
+
__version__ = "0.1.0"
|
|
47
|
+
|
|
48
|
+
TRANSCRIPTS_URL = "https://speech.moneytools.dev"
|
|
49
|
+
SETTLE_URL = "https://settle.moneytools.dev"
|
|
50
|
+
BASE_MAINNET = "eip155:8453"
|
|
51
|
+
BASE_SEPOLIA = "eip155:84532"
|
|
52
|
+
PRICE_PER_STARTED_MINUTE_USD = "0.005"
|
|
53
|
+
USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
|
|
54
|
+
USDC_BASE_SEPOLIA = "0x036CbD53842c5426634e7929541eC878d3C0E5e4"
|
|
55
|
+
|
|
56
|
+
FileInput = Union[str, Path, BinaryIO, bytes, bytearray]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class TranscriptsError(Exception):
|
|
60
|
+
def __init__(self, message: str, status: int, body: Any = None):
|
|
61
|
+
super().__init__(message)
|
|
62
|
+
self.status = status
|
|
63
|
+
self.body = body
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def paying_session(account, max_usd_per_request: float = 1.0, network: str = BASE_MAINNET) -> requests.Session:
|
|
67
|
+
"""requests.Session that answers HTTP 402 automatically (x402 v2 exact, USDC), capped per request."""
|
|
68
|
+
from x402 import x402ClientSync
|
|
69
|
+
from x402.http.clients import x402_requests
|
|
70
|
+
from x402.mechanisms.evm.exact import register_exact_evm_client
|
|
71
|
+
|
|
72
|
+
cap = int(round(float(max_usd_per_request) * 1_000_000))
|
|
73
|
+
|
|
74
|
+
def policy(_version, reqs):
|
|
75
|
+
out = []
|
|
76
|
+
for r in reqs:
|
|
77
|
+
amt = getattr(r, "amount", None) or getattr(r, "max_amount_required", None) or (
|
|
78
|
+
r.get("amount") if isinstance(r, dict) else None
|
|
79
|
+
)
|
|
80
|
+
net = getattr(r, "network", None) or (r.get("network") if isinstance(r, dict) else None)
|
|
81
|
+
if net == network and amt is not None and int(amt) <= cap:
|
|
82
|
+
out.append(r)
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
client = x402ClientSync()
|
|
86
|
+
asset = USDC_BASE_SEPOLIA if network == BASE_SEPOLIA else USDC_BASE
|
|
87
|
+
if hasattr(client, "set_spend_controls"):
|
|
88
|
+
client.set_spend_controls({
|
|
89
|
+
"max_amount_per_payment": f"${float(max_usd_per_request)}",
|
|
90
|
+
"allowed_assets": [{"network": network, "asset": asset, "max_amount_per_payment": str(cap)}],
|
|
91
|
+
})
|
|
92
|
+
# Some versions accept networks= as a string, others as a list.
|
|
93
|
+
try:
|
|
94
|
+
register_exact_evm_client(client, account, networks=[network], policies=[policy])
|
|
95
|
+
except TypeError:
|
|
96
|
+
register_exact_evm_client(client, account, networks=network, policies=[policy])
|
|
97
|
+
return x402_requests(client)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def wallet_auth_headers(account, method: str, path: str) -> dict:
|
|
101
|
+
"""dTelecom-style wallet auth (EIP-191 over 'METHOD\\nPATH\\nTIMESTAMP'); accepted from the wallet that paid the job."""
|
|
102
|
+
from eth_account.messages import encode_defunct
|
|
103
|
+
|
|
104
|
+
ts = str(int(time.time()))
|
|
105
|
+
msg = f"{method.upper()}\n{path.split('?')[0]}\n{ts}"
|
|
106
|
+
sig = account.sign_message(encode_defunct(text=msg)).signature.hex()
|
|
107
|
+
if not sig.startswith("0x"):
|
|
108
|
+
sig = "0x" + sig
|
|
109
|
+
return {
|
|
110
|
+
"Authorization": f"evm:{sig}",
|
|
111
|
+
"X-Wallet-Address": account.address,
|
|
112
|
+
"X-Wallet-Chain": "evm",
|
|
113
|
+
"X-Timestamp": ts,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def quote_from_accepts(body: Mapping[str, Any]) -> dict:
|
|
118
|
+
acc = (body.get("accepts") or [{}])[0] or {}
|
|
119
|
+
atomic = str(acc.get("amount") or acc.get("maxAmountRequired") or "0")
|
|
120
|
+
usd = f"{int(atomic) / 1_000_000:.6f}".rstrip("0").rstrip(".")
|
|
121
|
+
q = body.get("quote")
|
|
122
|
+
q = q if isinstance(q, dict) else {}
|
|
123
|
+
unit = int(round(float(PRICE_PER_STARTED_MINUTE_USD) * 1_000_000)) or 5000
|
|
124
|
+
return {
|
|
125
|
+
"startedMinutes": q.get("startedMinutes") or max(1, round(int(atomic) / unit) or 1),
|
|
126
|
+
"amountAtomic": atomic,
|
|
127
|
+
"amountUsd": q.get("amountUsd") or usd,
|
|
128
|
+
"pricePerStartedMinuteUsd": q.get("pricePerStartedMinuteUsd") or PRICE_PER_STARTED_MINUTE_USD,
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _json(res: requests.Response) -> Any:
|
|
133
|
+
try:
|
|
134
|
+
body = res.json()
|
|
135
|
+
except ValueError:
|
|
136
|
+
body = {"error": res.text[:300]}
|
|
137
|
+
if res.status_code >= 400 and res.status_code != 402:
|
|
138
|
+
raise TranscriptsError(str(body.get("message") or body.get("error") or f"HTTP {res.status_code}"), res.status_code, body)
|
|
139
|
+
return body
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _read_file(file: FileInput) -> tuple[bytes, str]:
|
|
143
|
+
if isinstance(file, (bytes, bytearray)):
|
|
144
|
+
return bytes(file), "audio.media"
|
|
145
|
+
if isinstance(file, (str, Path)):
|
|
146
|
+
path = Path(file)
|
|
147
|
+
return path.read_bytes(), path.name
|
|
148
|
+
name = getattr(file, "name", "audio.media")
|
|
149
|
+
if not isinstance(name, str):
|
|
150
|
+
name = "audio.media"
|
|
151
|
+
else:
|
|
152
|
+
name = os.path.basename(name)
|
|
153
|
+
return file.read(), name
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class TranscriptsClient:
|
|
157
|
+
"""MoneyTools Transcripts client. Methods mirror dTelecom file transcription (snake_case) plus transcribe_file/url/get_job."""
|
|
158
|
+
|
|
159
|
+
def __init__(
|
|
160
|
+
self,
|
|
161
|
+
account,
|
|
162
|
+
base_url: str = TRANSCRIPTS_URL,
|
|
163
|
+
max_usd_per_request: float = 1.0,
|
|
164
|
+
network: str = BASE_MAINNET,
|
|
165
|
+
session: Optional[requests.Session] = None,
|
|
166
|
+
):
|
|
167
|
+
if account is None:
|
|
168
|
+
raise ValueError("account (EVM) is required")
|
|
169
|
+
self.account = account
|
|
170
|
+
self.base_url = base_url.rstrip("/")
|
|
171
|
+
self.network = network
|
|
172
|
+
self.pay = session or paying_session(account, max_usd_per_request, network=network)
|
|
173
|
+
self.http = requests.Session()
|
|
174
|
+
self._tokens: dict[str, str] = {}
|
|
175
|
+
|
|
176
|
+
def _submit(self, res: requests.Response) -> dict:
|
|
177
|
+
body = _json(res)
|
|
178
|
+
if res.status_code not in (200, 202):
|
|
179
|
+
raise TranscriptsError(str(body.get("message") or body.get("error") or f"HTTP {res.status_code}"), res.status_code, body)
|
|
180
|
+
if body.get("job_token"):
|
|
181
|
+
self._tokens[body["id"]] = body["job_token"]
|
|
182
|
+
return body
|
|
183
|
+
|
|
184
|
+
def quote_file(
|
|
185
|
+
self,
|
|
186
|
+
file: FileInput,
|
|
187
|
+
filename: Optional[str] = None,
|
|
188
|
+
language: Optional[str] = None,
|
|
189
|
+
idempotency_key: Optional[str] = None,
|
|
190
|
+
) -> dict:
|
|
191
|
+
"""Unpaid quote (HTTP 402). Does not sign or retry."""
|
|
192
|
+
data, default_name = _read_file(file)
|
|
193
|
+
fields: dict[str, str] = {}
|
|
194
|
+
if language is not None:
|
|
195
|
+
fields["language"] = language
|
|
196
|
+
headers = {}
|
|
197
|
+
if idempotency_key:
|
|
198
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
199
|
+
res = self.http.post(
|
|
200
|
+
f"{self.base_url}/v1/transcriptions/jobs",
|
|
201
|
+
headers=headers,
|
|
202
|
+
files={"file": (filename or default_name, data, "application/octet-stream")},
|
|
203
|
+
data=fields,
|
|
204
|
+
)
|
|
205
|
+
body = _json(res)
|
|
206
|
+
if res.status_code != 402:
|
|
207
|
+
raise TranscriptsError(f"expected 402, got HTTP {res.status_code}", res.status_code, body)
|
|
208
|
+
quote = body.get("quote") or quote_from_accepts(body)
|
|
209
|
+
return {**quote, "job": body, "status": body.get("status"), "id": body.get("id")}
|
|
210
|
+
|
|
211
|
+
def quote_url(self, url: str, language: Optional[str] = None) -> dict:
|
|
212
|
+
body_in: dict[str, Any] = {"url": url}
|
|
213
|
+
if language:
|
|
214
|
+
body_in["language"] = language
|
|
215
|
+
res = self.http.post(f"{self.base_url}/v1/transcriptions/jobs", json=body_in)
|
|
216
|
+
body = _json(res)
|
|
217
|
+
if res.status_code != 402:
|
|
218
|
+
raise TranscriptsError(f"expected 402, got HTTP {res.status_code}", res.status_code, body)
|
|
219
|
+
quote = body.get("quote") or quote_from_accepts(body)
|
|
220
|
+
return {**quote, "job": body, "status": body.get("status"), "id": body.get("id")}
|
|
221
|
+
|
|
222
|
+
def transcribe_file(
|
|
223
|
+
self,
|
|
224
|
+
file: FileInput,
|
|
225
|
+
filename: Optional[str] = None,
|
|
226
|
+
language: Optional[str] = None,
|
|
227
|
+
diarize: Optional[bool] = None,
|
|
228
|
+
summary: bool = False,
|
|
229
|
+
webhook: Optional[str] = None,
|
|
230
|
+
idempotency_key: Optional[str] = None,
|
|
231
|
+
wait: bool = False,
|
|
232
|
+
interval: float = 5.0,
|
|
233
|
+
timeout: float = 3 * 3600,
|
|
234
|
+
) -> dict:
|
|
235
|
+
data, default_name = _read_file(file)
|
|
236
|
+
job = self.create_file_transcription(
|
|
237
|
+
data,
|
|
238
|
+
idempotency_key=idempotency_key or f"file-{uuid.uuid4()}",
|
|
239
|
+
filename=filename or default_name,
|
|
240
|
+
language=language,
|
|
241
|
+
diarize=diarize,
|
|
242
|
+
summary=summary,
|
|
243
|
+
webhook=webhook,
|
|
244
|
+
)
|
|
245
|
+
if wait:
|
|
246
|
+
return self.wait_for_job(job["id"], interval=interval, timeout=timeout)
|
|
247
|
+
return job
|
|
248
|
+
|
|
249
|
+
def transcribe_url(
|
|
250
|
+
self,
|
|
251
|
+
url: str,
|
|
252
|
+
language: Optional[str] = None,
|
|
253
|
+
diarize: Optional[bool] = None,
|
|
254
|
+
summary: bool = False,
|
|
255
|
+
webhook: Optional[str] = None,
|
|
256
|
+
wait: bool = False,
|
|
257
|
+
interval: float = 5.0,
|
|
258
|
+
timeout: float = 3 * 3600,
|
|
259
|
+
) -> dict:
|
|
260
|
+
body: dict[str, Any] = {"url": url}
|
|
261
|
+
if language is not None:
|
|
262
|
+
body["language"] = language
|
|
263
|
+
if diarize is not None:
|
|
264
|
+
body["diarize"] = diarize
|
|
265
|
+
if summary:
|
|
266
|
+
body["summary"] = True
|
|
267
|
+
if webhook:
|
|
268
|
+
body["webhook"] = webhook
|
|
269
|
+
job = self._submit(self.pay.post(f"{self.base_url}/v1/transcriptions/jobs", json=body))
|
|
270
|
+
if wait:
|
|
271
|
+
return self.wait_for_job(job["id"], interval=interval, timeout=timeout)
|
|
272
|
+
return job
|
|
273
|
+
|
|
274
|
+
def get_job(self, job_id: str, fmt: str = "json") -> Any:
|
|
275
|
+
if fmt and fmt != "json":
|
|
276
|
+
return self.get_file_transcription_text(job_id, fmt)
|
|
277
|
+
return self.get_file_transcription(job_id)
|
|
278
|
+
|
|
279
|
+
def wait_for_job(self, job_id: str, interval: float = 5.0, timeout: float = 3 * 3600) -> dict:
|
|
280
|
+
return self.wait_for_file_transcription(job_id, interval=interval, timeout=timeout)
|
|
281
|
+
|
|
282
|
+
def delete_job(self, job_id: str) -> dict:
|
|
283
|
+
return self.delete_file_transcription(job_id)
|
|
284
|
+
|
|
285
|
+
# ---- dTelecom drop-in (snake_case file-transcription surface) ----
|
|
286
|
+
|
|
287
|
+
def create_file_transcription(
|
|
288
|
+
self,
|
|
289
|
+
file: Union[BinaryIO, bytes, bytearray],
|
|
290
|
+
idempotency_key: str,
|
|
291
|
+
filename: str = "audio.media",
|
|
292
|
+
language: Optional[str] = None,
|
|
293
|
+
diarize: Optional[bool] = None,
|
|
294
|
+
summary: bool = False,
|
|
295
|
+
webhook: Optional[str] = None,
|
|
296
|
+
) -> dict:
|
|
297
|
+
"""POST multipart file → HTTP 402 with the exact price → paid automatically → {id, status: running, job_token, ...}."""
|
|
298
|
+
data = file if isinstance(file, (bytes, bytearray)) else file.read()
|
|
299
|
+
fields: dict[str, str] = {}
|
|
300
|
+
if language is not None:
|
|
301
|
+
fields["language"] = language
|
|
302
|
+
if diarize is not None:
|
|
303
|
+
fields["diarize"] = "true" if diarize else "false"
|
|
304
|
+
if summary:
|
|
305
|
+
fields["summary"] = "true"
|
|
306
|
+
if webhook:
|
|
307
|
+
fields["webhook"] = webhook
|
|
308
|
+
return self._submit(
|
|
309
|
+
self.pay.post(
|
|
310
|
+
f"{self.base_url}/v1/transcriptions/jobs",
|
|
311
|
+
headers={"Idempotency-Key": idempotency_key},
|
|
312
|
+
files={"file": (filename, data, "application/octet-stream")},
|
|
313
|
+
data=fields,
|
|
314
|
+
)
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
def _auth(self, method: str, path: str, job_id: str) -> dict:
|
|
318
|
+
t = self._tokens.get(job_id)
|
|
319
|
+
return {"Authorization": f"Bearer {t}"} if t else wallet_auth_headers(self.account, method, path)
|
|
320
|
+
|
|
321
|
+
def get_file_transcription(self, job_id: str) -> dict:
|
|
322
|
+
path = f"/v1/transcriptions/jobs/{job_id}"
|
|
323
|
+
return _json(self.http.get(self.base_url + path, headers=self._auth("GET", path, job_id)))
|
|
324
|
+
|
|
325
|
+
def get_file_transcription_text(self, job_id: str, fmt: str = "srt") -> str:
|
|
326
|
+
path = f"/v1/transcriptions/jobs/{job_id}"
|
|
327
|
+
res = self.http.get(f"{self.base_url}{path}?format={fmt}", headers=self._auth("GET", path, job_id))
|
|
328
|
+
if res.status_code >= 400:
|
|
329
|
+
raise TranscriptsError(res.text[:300], res.status_code)
|
|
330
|
+
return res.text
|
|
331
|
+
|
|
332
|
+
def delete_file_transcription(self, job_id: str) -> dict:
|
|
333
|
+
path = f"/v1/transcriptions/jobs/{job_id}"
|
|
334
|
+
out = _json(self.http.delete(self.base_url + path, headers=self._auth("DELETE", path, job_id)))
|
|
335
|
+
self._tokens.pop(job_id, None)
|
|
336
|
+
return out
|
|
337
|
+
|
|
338
|
+
def wait_for_file_transcription(self, job_id: str, interval: float = 5.0, timeout: float = 3 * 3600) -> dict:
|
|
339
|
+
end = time.time() + timeout
|
|
340
|
+
while True:
|
|
341
|
+
j = self.get_file_transcription(job_id)
|
|
342
|
+
if j.get("status") in ("completed", "failed", "cancelled", "deleted"):
|
|
343
|
+
return j
|
|
344
|
+
if time.time() > end:
|
|
345
|
+
raise TranscriptsError(f"timed out waiting for {job_id}", 408, j)
|
|
346
|
+
time.sleep(interval)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# Alias used in migration docs.
|
|
350
|
+
TranscriptsGateway = TranscriptsClient
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class SettleClient:
|
|
354
|
+
"""MoneyTools Settle pay-per-call endpoints (0.002-0.003 USDC/call via x402) or an mts_ API key. Default cap 0.05 USDC per call."""
|
|
355
|
+
|
|
356
|
+
def __init__(self, account=None, api_key: Optional[str] = None, base_url: str = SETTLE_URL,
|
|
357
|
+
max_usd_per_request: float = 0.05, network: str = BASE_MAINNET, session: Optional[requests.Session] = None):
|
|
358
|
+
if account is None and api_key is None:
|
|
359
|
+
raise ValueError("account (pay per call) or api_key is required")
|
|
360
|
+
self.base_url = base_url.rstrip("/")
|
|
361
|
+
self.api_key = api_key
|
|
362
|
+
self.s = session or (paying_session(account, max_usd_per_request, network=network) if api_key is None else requests.Session())
|
|
363
|
+
|
|
364
|
+
def _post(self, path: str, body: dict) -> dict:
|
|
365
|
+
h = {"X-API-Key": self.api_key} if self.api_key else {}
|
|
366
|
+
res = self.s.post(self.base_url + path, json={k: v for k, v in body.items() if v is not None}, headers=h)
|
|
367
|
+
out = _json(res)
|
|
368
|
+
if res.status_code == 402: # payment not made (e.g. above the cap): surface it, never treat as success
|
|
369
|
+
raise TranscriptsError(str(out.get("message") or out.get("error") or "HTTP 402"), 402, out)
|
|
370
|
+
return out
|
|
371
|
+
|
|
372
|
+
def spend_check(self, payer: str, amount_usd: Optional[str] = None, payment_required: Any = None, host: Optional[str] = None,
|
|
373
|
+
pay_to: Optional[str] = None, session_id: Optional[str] = None) -> dict:
|
|
374
|
+
return self._post("/v1/spend/check", {"payer": payer, "amountUsd": amount_usd, "paymentRequired": payment_required, "host": host, "payTo": pay_to, "sessionId": session_id})
|
|
375
|
+
|
|
376
|
+
def spend_cap_set(self, payer: str, per_call_usd: Optional[str] = None, per_day_usd: Optional[str] = None,
|
|
377
|
+
per_session_usd: Optional[str] = None, allow_hosts: Optional[list] = None) -> dict:
|
|
378
|
+
return self._post("/v1/spend/cap", {"payer": payer, "perCallUsd": per_call_usd, "perDayUsd": per_day_usd, "perSessionUsd": per_session_usd, "allowHosts": allow_hosts})
|
|
379
|
+
|
|
380
|
+
def spend_record(self, payer: str, amount_usd: Optional[str] = None, status: str = "settled", tx: Optional[str] = None,
|
|
381
|
+
host: Optional[str] = None, ref: Optional[str] = None) -> dict:
|
|
382
|
+
return self._post("/v1/spend/record", {"payer": payer, "amountUsd": amount_usd, "status": status, "tx": tx, "host": host, "ref": ref})
|
|
383
|
+
|
|
384
|
+
def spend_log(self, payer: str, days: int = 7, limit: Optional[int] = None) -> dict:
|
|
385
|
+
return self._post("/v1/spend/log", {"payer": payer, "days": days, "limit": limit})
|
|
386
|
+
|
|
387
|
+
def verify(self, tx: Optional[str] = None, payer: Optional[str] = None, nonce: Optional[str] = None, payment_payload: Any = None) -> dict:
|
|
388
|
+
return self._post("/v1/verify", {"tx": tx, "payer": payer, "nonce": nonce, "paymentPayload": payment_payload})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""CLI: mt-transcribe file.mp3
|
|
2
|
+
|
|
3
|
+
Environment:
|
|
4
|
+
X402_PRIVATE_KEY Hex private key of a Base wallet that holds USDC (required to pay).
|
|
5
|
+
Never printed. Prefer the environment variable over --private-key.
|
|
6
|
+
|
|
7
|
+
TRANSCRIPTS_BASE Override API host (default https://speech.moneytools.dev).
|
|
8
|
+
|
|
9
|
+
Examples:
|
|
10
|
+
mt-transcribe --quote meeting.mp3 # unpaid 402, print the exact price, do not sign
|
|
11
|
+
mt-transcribe meeting.mp3 # pay, wait, print transcript text
|
|
12
|
+
mt-transcribe --format srt meeting.mp3 > meeting.srt
|
|
13
|
+
mt-transcribe --url https://host/ep.mp3
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
from typing import Optional
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _load_account(explicit: Optional[str]):
|
|
25
|
+
raw = explicit or os.environ.get("X402_PRIVATE_KEY") or os.environ.get("PRIVATE_KEY")
|
|
26
|
+
if not raw:
|
|
27
|
+
return None
|
|
28
|
+
raw = raw.strip()
|
|
29
|
+
if not raw.startswith("0x"):
|
|
30
|
+
raw = "0x" + raw
|
|
31
|
+
from eth_account import Account
|
|
32
|
+
|
|
33
|
+
return Account.from_key(raw)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(argv: Optional[list[str]] = None) -> int:
|
|
37
|
+
p = argparse.ArgumentParser(
|
|
38
|
+
prog="mt-transcribe",
|
|
39
|
+
description="Transcribe an audio file with MoneyTools Transcripts (x402, $0.005 per started minute on Base USDC). No prepaid credits.",
|
|
40
|
+
)
|
|
41
|
+
p.add_argument("file", nargs="?", help="Local audio/video file (mp3, wav, m4a, mp4, webm, ogg, flac)")
|
|
42
|
+
p.add_argument("--url", help="Public https media URL instead of a local file")
|
|
43
|
+
p.add_argument("--quote", action="store_true", help="Show the exact unpaid 402 price and exit (no signature, no key needed)")
|
|
44
|
+
p.add_argument("--language", help="Language hint (default: auto-detect)")
|
|
45
|
+
p.add_argument("--format", dest="fmt", choices=("json", "srt", "vtt", "txt"), default="txt", help="Output format after completion (default: txt)")
|
|
46
|
+
p.add_argument("--base-url", default=os.environ.get("TRANSCRIPTS_BASE", "https://speech.moneytools.dev"))
|
|
47
|
+
p.add_argument("--max-usd", type=float, default=float(os.environ.get("MAX_USD", "1.0")), help="Refuse to sign a quote above this many USDC (default 1.00)")
|
|
48
|
+
p.add_argument("--idempotency-key", help="Reuse when retrying the same file")
|
|
49
|
+
p.add_argument("--no-wait", action="store_true", help="Print the running job JSON and exit (do not poll)")
|
|
50
|
+
p.add_argument("--network", default="eip155:8453", help="CAIP-2 network the wallet will pay on (default Base mainnet)")
|
|
51
|
+
p.add_argument("--private-key", default=None, help="Hex key (prefer X402_PRIVATE_KEY). Never logged.")
|
|
52
|
+
args = p.parse_args(argv)
|
|
53
|
+
|
|
54
|
+
if not args.file and not args.url:
|
|
55
|
+
p.error("provide a file path or --url")
|
|
56
|
+
|
|
57
|
+
from moneytools_transcripts import TranscriptsClient, TranscriptsError
|
|
58
|
+
|
|
59
|
+
if args.quote:
|
|
60
|
+
# Unpaid path: a throwaway account is enough because quote_* never signs.
|
|
61
|
+
from eth_account import Account
|
|
62
|
+
|
|
63
|
+
tc = TranscriptsClient(Account.create(), base_url=args.base_url, network=args.network)
|
|
64
|
+
try:
|
|
65
|
+
if args.url:
|
|
66
|
+
q = tc.quote_url(args.url, language=args.language)
|
|
67
|
+
else:
|
|
68
|
+
q = tc.quote_file(args.file, language=args.language, idempotency_key=args.idempotency_key)
|
|
69
|
+
except TranscriptsError as e:
|
|
70
|
+
print(f"quote failed: HTTP {e.status}: {e}", file=sys.stderr)
|
|
71
|
+
return 2
|
|
72
|
+
print(f"duration_seconds\t{(q.get('job') or {}).get('duration_seconds')}")
|
|
73
|
+
print(f"started_minutes\t{q.get('startedMinutes')}")
|
|
74
|
+
print(f"amount_usd\t{q.get('amountUsd')}")
|
|
75
|
+
print(f"amount_atomic\t{q.get('amountAtomic')}")
|
|
76
|
+
print(f"price_per_started_minute_usd\t{q.get('pricePerStartedMinuteUsd')}")
|
|
77
|
+
if q.get("id"):
|
|
78
|
+
print(f"job_id\t{q['id']}")
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
account = _load_account(args.private_key)
|
|
82
|
+
if account is None:
|
|
83
|
+
print("set X402_PRIVATE_KEY (a Base wallet with USDC) to pay, or use --quote to only print the price", file=sys.stderr)
|
|
84
|
+
return 2
|
|
85
|
+
|
|
86
|
+
tc = TranscriptsClient(account, base_url=args.base_url, max_usd_per_request=args.max_usd, network=args.network)
|
|
87
|
+
try:
|
|
88
|
+
if args.url:
|
|
89
|
+
job = tc.transcribe_url(args.url, language=args.language, wait=not args.no_wait)
|
|
90
|
+
else:
|
|
91
|
+
job = tc.transcribe_file(
|
|
92
|
+
args.file,
|
|
93
|
+
language=args.language,
|
|
94
|
+
idempotency_key=args.idempotency_key,
|
|
95
|
+
wait=not args.no_wait,
|
|
96
|
+
)
|
|
97
|
+
except TranscriptsError as e:
|
|
98
|
+
print(f"transcribe failed: HTTP {e.status}: {e}", file=sys.stderr)
|
|
99
|
+
return 2
|
|
100
|
+
|
|
101
|
+
if args.no_wait:
|
|
102
|
+
json.dump(job, sys.stdout, indent=2)
|
|
103
|
+
sys.stdout.write("\n")
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
if args.fmt == "json":
|
|
107
|
+
json.dump(job, sys.stdout, indent=2)
|
|
108
|
+
sys.stdout.write("\n")
|
|
109
|
+
return 0 if job.get("status") == "completed" else 1
|
|
110
|
+
|
|
111
|
+
if job.get("status") != "completed":
|
|
112
|
+
print(f"job {job.get('id')} ended with status {job.get('status')}: {job.get('error')}", file=sys.stderr)
|
|
113
|
+
return 1
|
|
114
|
+
|
|
115
|
+
if args.fmt == "txt":
|
|
116
|
+
sys.stdout.write((job.get("result") or {}).get("text") or "")
|
|
117
|
+
if not str((job.get("result") or {}).get("text") or "").endswith("\n"):
|
|
118
|
+
sys.stdout.write("\n")
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
text = tc.get_job(job["id"], fmt=args.fmt)
|
|
122
|
+
sys.stdout.write(text if isinstance(text, str) else json.dumps(text, indent=2) + "\n")
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
raise SystemExit(main())
|