eptx 1.0.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.
- eptx-1.0.0/.gitignore +24 -0
- eptx-1.0.0/LICENSE +21 -0
- eptx-1.0.0/PKG-INFO +76 -0
- eptx-1.0.0/README.md +58 -0
- eptx-1.0.0/pyproject.toml +28 -0
- eptx-1.0.0/src/eptx/__init__.py +8 -0
- eptx-1.0.0/src/eptx/_client.py +336 -0
- eptx-1.0.0/src/eptx/errors.py +36 -0
- eptx-1.0.0/src/eptx/py.typed +0 -0
- eptx-1.0.0/tests/test_against_dev.py +106 -0
eptx-1.0.0/.gitignore
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Logs
|
|
2
|
+
logs
|
|
3
|
+
*.log
|
|
4
|
+
npm-debug.log*
|
|
5
|
+
yarn-debug.log*
|
|
6
|
+
yarn-error.log*
|
|
7
|
+
pnpm-debug.log*
|
|
8
|
+
lerna-debug.log*
|
|
9
|
+
|
|
10
|
+
node_modules
|
|
11
|
+
dist
|
|
12
|
+
dist-ssr
|
|
13
|
+
*.local
|
|
14
|
+
|
|
15
|
+
# Editor directories and files
|
|
16
|
+
.vscode/*
|
|
17
|
+
!.vscode/extensions.json
|
|
18
|
+
.idea
|
|
19
|
+
.DS_Store
|
|
20
|
+
*.suo
|
|
21
|
+
*.ntvs*
|
|
22
|
+
*.njsproj
|
|
23
|
+
*.sln
|
|
24
|
+
*.sw?
|
eptx-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 1001771280 Ontario Ltd. (Eptx)
|
|
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.
|
eptx-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: eptx
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python client for the Eptx API: background removal, captions, noise removal and text to speech, on private hardware.
|
|
5
|
+
Project-URL: Homepage, https://eptx.space
|
|
6
|
+
Project-URL: Documentation, https://eptx.space/developers
|
|
7
|
+
Author-email: Eptx <contact@eptx.space>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai,background removal,eptx,image api,remove background,remove.bg
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Requires-Dist: httpx>=0.27
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# eptx
|
|
20
|
+
|
|
21
|
+
Official Python client for the [Eptx API](https://eptx.space/developers): background removal, captions, noise removal and text to speech, processed on Eptx's own hardware. Files are never used for training and are deleted after 24 hours.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install eptx
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from eptx import Eptx
|
|
29
|
+
|
|
30
|
+
client = Eptx() # reads EPTX_API_KEY (create one at https://eptx.space/developers)
|
|
31
|
+
cutout = client.remove_background("photo.jpg")
|
|
32
|
+
cutout.save("photo-cutout.png") # PNG with transparency
|
|
33
|
+
print(cutout.width, cutout.height, cutout.credits_charged)
|
|
34
|
+
|
|
35
|
+
# options mirror remove.bg
|
|
36
|
+
client.remove_background("product.jpg", format="webp", crop=True, crop_margin="5%")
|
|
37
|
+
client.remove_background(url="https://example.com/shoe.jpg", bg_color="ffffff", format="jpg")
|
|
38
|
+
|
|
39
|
+
print(client.account().balance_credits) # 1 credit = $0.001
|
|
40
|
+
for r in client.recent(): # results from the last 24 hours
|
|
41
|
+
print(r.result_id, r.tool, r.created_at)
|
|
42
|
+
client.download(cutout.result_id).save("again.png")
|
|
43
|
+
|
|
44
|
+
# audio
|
|
45
|
+
t = client.transcribe("interview.mp4", language="en") # .text, .segments
|
|
46
|
+
client.transcribe("interview.mp4", output_format="srt").save("interview.srt")
|
|
47
|
+
client.remove_noise("podcast_raw.wav", output_format="wav").save("podcast_clean.wav")
|
|
48
|
+
print([v.id for v in client.voices()])
|
|
49
|
+
client.text_to_speech("Your order ships on Thursday.", voice="juniper").save("speech.m4a")
|
|
50
|
+
```
|
|
51
|
+
Voice cloning is website-only for now.
|
|
52
|
+
|
|
53
|
+
## Errors
|
|
54
|
+
|
|
55
|
+
Every error is an `eptx.EptxError` with `.status` and `.detail` (the server says what to fix). Failed calls are
|
|
56
|
+
never charged.
|
|
57
|
+
|
|
58
|
+
| Exception | When |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `AuthenticationError` | missing, wrong or revoked key |
|
|
61
|
+
| `InsufficientCreditsError` | the balance doesn't cover the call |
|
|
62
|
+
| `InvalidRequestError` | bad parameter or file |
|
|
63
|
+
| `RateLimitError` | over your plan's rate or parallel-job limit (`.retry_after`) |
|
|
64
|
+
| `ServiceUnavailableError` | busy or briefly down (`.retry_after`) |
|
|
65
|
+
| `APIConnectionError` | network problem |
|
|
66
|
+
|
|
67
|
+
The client retries rate limits, busy answers and network errors (`max_retries=3`, honouring `Retry-After`). Each call
|
|
68
|
+
carries a job id: if the connection drops after the server started, the retry picks up that job's result instead of
|
|
69
|
+
paying again.
|
|
70
|
+
|
|
71
|
+
## AI agents
|
|
72
|
+
|
|
73
|
+
Using Claude Code, Codex, Antigravity or Cursor? Connect the Eptx MCP server instead (no key needed, you sign in):
|
|
74
|
+
see [eptx.space/developers#mcp](https://eptx.space/developers#mcp).
|
|
75
|
+
|
|
76
|
+
MIT licensed.
|
eptx-1.0.0/README.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# eptx
|
|
2
|
+
|
|
3
|
+
Official Python client for the [Eptx API](https://eptx.space/developers): background removal, captions, noise removal and text to speech, processed on Eptx's own hardware. Files are never used for training and are deleted after 24 hours.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install eptx
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from eptx import Eptx
|
|
11
|
+
|
|
12
|
+
client = Eptx() # reads EPTX_API_KEY (create one at https://eptx.space/developers)
|
|
13
|
+
cutout = client.remove_background("photo.jpg")
|
|
14
|
+
cutout.save("photo-cutout.png") # PNG with transparency
|
|
15
|
+
print(cutout.width, cutout.height, cutout.credits_charged)
|
|
16
|
+
|
|
17
|
+
# options mirror remove.bg
|
|
18
|
+
client.remove_background("product.jpg", format="webp", crop=True, crop_margin="5%")
|
|
19
|
+
client.remove_background(url="https://example.com/shoe.jpg", bg_color="ffffff", format="jpg")
|
|
20
|
+
|
|
21
|
+
print(client.account().balance_credits) # 1 credit = $0.001
|
|
22
|
+
for r in client.recent(): # results from the last 24 hours
|
|
23
|
+
print(r.result_id, r.tool, r.created_at)
|
|
24
|
+
client.download(cutout.result_id).save("again.png")
|
|
25
|
+
|
|
26
|
+
# audio
|
|
27
|
+
t = client.transcribe("interview.mp4", language="en") # .text, .segments
|
|
28
|
+
client.transcribe("interview.mp4", output_format="srt").save("interview.srt")
|
|
29
|
+
client.remove_noise("podcast_raw.wav", output_format="wav").save("podcast_clean.wav")
|
|
30
|
+
print([v.id for v in client.voices()])
|
|
31
|
+
client.text_to_speech("Your order ships on Thursday.", voice="juniper").save("speech.m4a")
|
|
32
|
+
```
|
|
33
|
+
Voice cloning is website-only for now.
|
|
34
|
+
|
|
35
|
+
## Errors
|
|
36
|
+
|
|
37
|
+
Every error is an `eptx.EptxError` with `.status` and `.detail` (the server says what to fix). Failed calls are
|
|
38
|
+
never charged.
|
|
39
|
+
|
|
40
|
+
| Exception | When |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `AuthenticationError` | missing, wrong or revoked key |
|
|
43
|
+
| `InsufficientCreditsError` | the balance doesn't cover the call |
|
|
44
|
+
| `InvalidRequestError` | bad parameter or file |
|
|
45
|
+
| `RateLimitError` | over your plan's rate or parallel-job limit (`.retry_after`) |
|
|
46
|
+
| `ServiceUnavailableError` | busy or briefly down (`.retry_after`) |
|
|
47
|
+
| `APIConnectionError` | network problem |
|
|
48
|
+
|
|
49
|
+
The client retries rate limits, busy answers and network errors (`max_retries=3`, honouring `Retry-After`). Each call
|
|
50
|
+
carries a job id: if the connection drops after the server started, the retry picks up that job's result instead of
|
|
51
|
+
paying again.
|
|
52
|
+
|
|
53
|
+
## AI agents
|
|
54
|
+
|
|
55
|
+
Using Claude Code, Codex, Antigravity or Cursor? Connect the Eptx MCP server instead (no key needed, you sign in):
|
|
56
|
+
see [eptx.space/developers#mcp](https://eptx.space/developers#mcp).
|
|
57
|
+
|
|
58
|
+
MIT licensed.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "eptx"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Official Python client for the Eptx API: background removal, captions, noise removal and text to speech, on private hardware."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "Eptx", email = "contact@eptx.space" }]
|
|
14
|
+
keywords = ["eptx", "background removal", "remove background", "remove.bg", "image api", "ai"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Multimedia :: Graphics",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["httpx>=0.27"]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://eptx.space"
|
|
25
|
+
Documentation = "https://eptx.space/developers"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.wheel]
|
|
28
|
+
packages = ["src/eptx"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Official Python client for the Eptx API: photo and audio AI on private hardware. https://eptx.space/developers"""
|
|
2
|
+
from ._client import Account, AudioResult, Eptx, ImageResult, RecentResult, SubjectBox, Transcript, Voice, __version__
|
|
3
|
+
from .errors import (APIConnectionError, AuthenticationError, EptxError, InsufficientCreditsError, InvalidRequestError,
|
|
4
|
+
RateLimitError, ServiceUnavailableError)
|
|
5
|
+
|
|
6
|
+
__all__ = ["Eptx", "ImageResult", "AudioResult", "Transcript", "Voice", "Account", "RecentResult", "SubjectBox", "EptxError", "AuthenticationError",
|
|
7
|
+
"InsufficientCreditsError", "InvalidRequestError", "RateLimitError", "ServiceUnavailableError",
|
|
8
|
+
"APIConnectionError", "__version__"]
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import secrets
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import IO, Union
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from .errors import (APIConnectionError, AuthenticationError, EptxError, InsufficientCreditsError, InvalidRequestError,
|
|
13
|
+
RateLimitError, ServiceUnavailableError)
|
|
14
|
+
|
|
15
|
+
__version__ = "1.0.0"
|
|
16
|
+
DEFAULT_BASE_URL = "https://api.eptx.space"
|
|
17
|
+
ImageInput = Union[str, os.PathLike, bytes, bytearray, IO[bytes]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class SubjectBox:
|
|
22
|
+
left: int
|
|
23
|
+
top: int
|
|
24
|
+
width: int
|
|
25
|
+
height: int
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class ImageResult:
|
|
30
|
+
"""A finished image. `data` is the file's bytes; `save()` writes it. `result_id` lets you download it again for
|
|
31
|
+
24 hours (`client.download(result_id)`). `credits_charged` is None when the result was recovered after a dropped
|
|
32
|
+
connection (it was charged once, by the original request)."""
|
|
33
|
+
data: bytes
|
|
34
|
+
mime: str
|
|
35
|
+
width: int | None = None
|
|
36
|
+
height: int | None = None
|
|
37
|
+
credits_charged: int | None = None
|
|
38
|
+
result_id: str | None = None
|
|
39
|
+
subject_box: SubjectBox | None = None
|
|
40
|
+
recovered: bool = False
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def extension(self) -> str:
|
|
44
|
+
return {"image/png": "png", "image/webp": "webp", "image/jpeg": "jpg"}.get(self.mime, "bin")
|
|
45
|
+
|
|
46
|
+
def save(self, path: str | os.PathLike) -> Path:
|
|
47
|
+
p = Path(path)
|
|
48
|
+
p.write_bytes(self.data)
|
|
49
|
+
return p
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class AudioResult:
|
|
54
|
+
"""A finished audio file (voiceover or cleaned audio). `save()` writes it; `result_id` downloads it again for 24 h."""
|
|
55
|
+
data: bytes
|
|
56
|
+
mime: str
|
|
57
|
+
result_id: str | None = None
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def extension(self) -> str:
|
|
61
|
+
return {"audio/mp4": "m4a", "audio/mpeg": "mp3", "audio/ogg": "ogg", "audio/wav": "wav", "audio/x-wav": "wav",
|
|
62
|
+
"audio/flac": "flac"}.get(self.mime, "bin")
|
|
63
|
+
|
|
64
|
+
def save(self, path: str | os.PathLike) -> Path:
|
|
65
|
+
p = Path(path)
|
|
66
|
+
p.write_bytes(self.data)
|
|
67
|
+
return p
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class Transcript:
|
|
72
|
+
"""`text` and `segments` (start, end, text, words) for json; `subtitles` for srt/vtt."""
|
|
73
|
+
text: str | None
|
|
74
|
+
language: str | None
|
|
75
|
+
segments: list
|
|
76
|
+
subtitles: str | None = None
|
|
77
|
+
result_id: str | None = None
|
|
78
|
+
|
|
79
|
+
def save(self, path: str | os.PathLike) -> Path:
|
|
80
|
+
p = Path(path)
|
|
81
|
+
p.write_text(self.subtitles if self.subtitles is not None else (self.text or ""), encoding="utf-8")
|
|
82
|
+
return p
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Voice:
|
|
87
|
+
id: str
|
|
88
|
+
language: str
|
|
89
|
+
accent: str | None
|
|
90
|
+
gender: str
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class Account:
|
|
95
|
+
balance_credits: int
|
|
96
|
+
subscription_credits: int
|
|
97
|
+
purchased_credits: int
|
|
98
|
+
plan: str | None
|
|
99
|
+
team_role: str | None
|
|
100
|
+
requests_per_minute: int
|
|
101
|
+
parallel_jobs: int
|
|
102
|
+
tools: list[dict] = field(default_factory=list)
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def balance_usd(self) -> float:
|
|
106
|
+
return self.balance_credits / 1000
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class RecentResult:
|
|
111
|
+
result_id: str
|
|
112
|
+
tool: str
|
|
113
|
+
mime: str
|
|
114
|
+
bytes: int
|
|
115
|
+
created_at: str
|
|
116
|
+
expires_at: str
|
|
117
|
+
via_api: bool
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
_ERRORS = {400: InvalidRequestError, 401: AuthenticationError, 402: InsufficientCreditsError, 403: AuthenticationError,
|
|
121
|
+
404: InvalidRequestError, 413: InvalidRequestError, 422: InvalidRequestError, 429: RateLimitError,
|
|
122
|
+
502: ServiceUnavailableError, 503: ServiceUnavailableError, 504: ServiceUnavailableError}
|
|
123
|
+
_RETRY_STATUS = {429, 502, 503, 504}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _retry_after(r: httpx.Response) -> float | None:
|
|
127
|
+
try:
|
|
128
|
+
return float(r.headers.get("retry-after"))
|
|
129
|
+
except (TypeError, ValueError):
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _raise_for(r: httpx.Response) -> None:
|
|
134
|
+
if r.status_code < 400:
|
|
135
|
+
return
|
|
136
|
+
detail = r.text[:500] or r.reason_phrase
|
|
137
|
+
try:
|
|
138
|
+
body = r.json()
|
|
139
|
+
if isinstance(body, dict):
|
|
140
|
+
if isinstance(body.get("detail"), str):
|
|
141
|
+
detail = body["detail"]
|
|
142
|
+
elif isinstance(body.get("errors"), list) and body["errors"]:
|
|
143
|
+
detail = body["errors"][0].get("title") or detail
|
|
144
|
+
except ValueError:
|
|
145
|
+
pass
|
|
146
|
+
raise _ERRORS.get(r.status_code, EptxError)(detail, r.status_code, _retry_after(r))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _read_image(image: ImageInput) -> tuple[str, bytes]:
|
|
150
|
+
if isinstance(image, (bytes, bytearray)):
|
|
151
|
+
return "image", bytes(image)
|
|
152
|
+
if isinstance(image, (str, os.PathLike)):
|
|
153
|
+
if isinstance(image, str) and image.startswith(("http://", "https://")):
|
|
154
|
+
raise InvalidRequestError("For a URL use remove_background(url=...), not a path.")
|
|
155
|
+
p = Path(image)
|
|
156
|
+
return p.name, p.read_bytes()
|
|
157
|
+
if hasattr(image, "read"):
|
|
158
|
+
return Path(getattr(image, "name", "image")).name, image.read()
|
|
159
|
+
raise InvalidRequestError("image must be a file path, bytes or a binary file object.")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class Eptx:
|
|
163
|
+
"""Client for the Eptx API (https://eptx.space/developers).
|
|
164
|
+
|
|
165
|
+
from eptx import Eptx
|
|
166
|
+
client = Eptx() # reads EPTX_API_KEY
|
|
167
|
+
client.remove_background("photo.jpg").save("cutout.png")
|
|
168
|
+
|
|
169
|
+
Retries 429/502/503/504 and network errors (honouring Retry-After) up to `max_retries` times. Every call carries
|
|
170
|
+
a job id, so if the connection drops after the server started, the retry first looks for that job's result
|
|
171
|
+
(kept 24 h) instead of paying again.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def __init__(self, api_key: str | None = None, *, base_url: str | None = None, timeout: float = 120.0,
|
|
175
|
+
max_retries: int = 3, http_client: httpx.Client | None = None):
|
|
176
|
+
self.api_key = api_key or os.environ.get("EPTX_API_KEY")
|
|
177
|
+
if not self.api_key:
|
|
178
|
+
raise AuthenticationError("No API key. Pass api_key=... or set EPTX_API_KEY. Create one at https://eptx.space/developers.")
|
|
179
|
+
self.base_url = (base_url or os.environ.get("EPTX_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
180
|
+
self.max_retries = max_retries
|
|
181
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
182
|
+
self._headers = {"Authorization": f"Bearer {self.api_key}", "User-Agent": f"eptx-python/{__version__}"}
|
|
183
|
+
|
|
184
|
+
# -- plumbing
|
|
185
|
+
def close(self) -> None:
|
|
186
|
+
self._http.close()
|
|
187
|
+
|
|
188
|
+
def __enter__(self) -> "Eptx":
|
|
189
|
+
return self
|
|
190
|
+
|
|
191
|
+
def __exit__(self, *exc) -> None:
|
|
192
|
+
self.close()
|
|
193
|
+
|
|
194
|
+
def _request(self, method: str, path: str, *, job: str | None = None, **kw) -> httpx.Response:
|
|
195
|
+
headers = dict(self._headers)
|
|
196
|
+
if job:
|
|
197
|
+
headers["X-Client-Job"] = job
|
|
198
|
+
attempt = 0
|
|
199
|
+
if kw.get("timeout") is None:
|
|
200
|
+
kw.pop("timeout", None)
|
|
201
|
+
while True:
|
|
202
|
+
try:
|
|
203
|
+
r = self._http.request(method, self.base_url + path, headers=headers, **kw)
|
|
204
|
+
except (httpx.TimeoutException, httpx.NetworkError) as e:
|
|
205
|
+
if attempt >= self.max_retries:
|
|
206
|
+
raise APIConnectionError(f"Could not reach Eptx: {type(e).__name__}") from e
|
|
207
|
+
if job:
|
|
208
|
+
found = self._find_job(job)
|
|
209
|
+
if found is not None:
|
|
210
|
+
return found
|
|
211
|
+
time.sleep(min(2 ** attempt, 20))
|
|
212
|
+
attempt += 1
|
|
213
|
+
continue
|
|
214
|
+
if r.status_code in _RETRY_STATUS and attempt < self.max_retries:
|
|
215
|
+
time.sleep(min(_retry_after(r) or 2 ** attempt, 60))
|
|
216
|
+
attempt += 1
|
|
217
|
+
continue
|
|
218
|
+
_raise_for(r)
|
|
219
|
+
return r
|
|
220
|
+
|
|
221
|
+
def _find_job(self, job: str) -> httpx.Response | None:
|
|
222
|
+
"""After a dropped connection: the result of this job if the server finished it (no second charge)."""
|
|
223
|
+
try:
|
|
224
|
+
items = self._http.get(self.base_url + "/api/recent", headers=self._headers).json().get("items", [])
|
|
225
|
+
hit = next((i for i in items if (i.get("meta") or {}).get("job") == job), None)
|
|
226
|
+
if not hit:
|
|
227
|
+
return None
|
|
228
|
+
r = self._http.get(f"{self.base_url}/api/recent/{hit['id']}/file", headers=self._headers)
|
|
229
|
+
if r.status_code != 200:
|
|
230
|
+
return None
|
|
231
|
+
r.headers["X-Result-Id"] = hit["id"]
|
|
232
|
+
r.headers["X-Eptx-Recovered"] = "1"
|
|
233
|
+
return r
|
|
234
|
+
except Exception: # noqa: BLE001 -- recovery is best effort; the normal retry follows
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
# -- tools
|
|
238
|
+
def remove_background(self, image: ImageInput | None = None, *, url: str | None = None, size: str | None = None,
|
|
239
|
+
format: str | None = None, bg_color: str | None = None, crop: bool | None = None,
|
|
240
|
+
crop_margin: str | None = None, channels: str | None = None) -> ImageResult:
|
|
241
|
+
"""Removes the background of a photo. Give a path, bytes or a file object, or url= for a public image.
|
|
242
|
+
|
|
243
|
+
size: auto (original, default) | full | hd (4 MP) | medium (1.5 MP) | preview (0.25 MP)
|
|
244
|
+
format: auto (PNG with transparency) | png | webp | jpg ; bg_color: hex like "81d4fa" or a colour name
|
|
245
|
+
crop: crop to the subject ; crop_margin: "30px" or "10%" ; channels: rgba | alpha (mask only)
|
|
246
|
+
"""
|
|
247
|
+
if (image is None) == (url is None):
|
|
248
|
+
raise InvalidRequestError("Give exactly one of image or url.")
|
|
249
|
+
opts = {k: v for k, v in {"size": size, "format": format, "bg_color": bg_color, "crop_margin": crop_margin,
|
|
250
|
+
"channels": channels}.items() if v is not None}
|
|
251
|
+
if crop is not None:
|
|
252
|
+
opts["crop"] = "true" if crop else "false"
|
|
253
|
+
job = secrets.token_hex(16)
|
|
254
|
+
if url is not None:
|
|
255
|
+
r = self._request("POST", "/v1.0/removebg", job=job, data={**opts, "image_url": url})
|
|
256
|
+
else:
|
|
257
|
+
name, data = _read_image(image)
|
|
258
|
+
r = self._request("POST", "/api/image/remove-bg", job=job, data=opts, files={"image": (name, data)})
|
|
259
|
+
h = r.headers
|
|
260
|
+
box = None
|
|
261
|
+
if h.get("x-foreground-width"):
|
|
262
|
+
box = SubjectBox(*(int(h.get(f"x-foreground-{k}", 0)) for k in ("left", "top", "width", "height")))
|
|
263
|
+
recovered = h.get("x-eptx-recovered") == "1"
|
|
264
|
+
num = lambda k: int(h[k]) if h.get(k, "").isdigit() else None # noqa: E731
|
|
265
|
+
return ImageResult(data=r.content, mime=h.get("content-type", "application/octet-stream").split(";")[0],
|
|
266
|
+
width=num("x-width"), height=num("x-height"),
|
|
267
|
+
credits_charged=None if recovered else num("x-credits-charged"),
|
|
268
|
+
result_id=h.get("x-result-id"), subject_box=box, recovered=recovered)
|
|
269
|
+
|
|
270
|
+
# -- audio
|
|
271
|
+
def _audio_call(self, path: str, data: dict, files: dict | None = None, timeout: float = 600.0) -> httpx.Response:
|
|
272
|
+
return self._request("POST", path, job=secrets.token_hex(16), data={k: v for k, v in data.items() if v is not None},
|
|
273
|
+
files=files, timeout=timeout)
|
|
274
|
+
|
|
275
|
+
def transcribe(self, audio: ImageInput, *, language: str | None = None, output_format: str = "json",
|
|
276
|
+
align: bool = True) -> Transcript:
|
|
277
|
+
"""Speech to text from an audio or video file (up to 95 MB per request).
|
|
278
|
+
|
|
279
|
+
output_format: json (text + segments with word timings, default) | srt | vtt (subtitles in `.subtitles`)
|
|
280
|
+
language: ISO code to skip detection, e.g. "en". align=False is slightly faster, segment timing only.
|
|
281
|
+
"""
|
|
282
|
+
name, data = _read_image(audio)
|
|
283
|
+
r = self._audio_call("/api/audio/transcribe", {"language": language, "output_format": output_format,
|
|
284
|
+
"align": "true" if align else "false"}, {"file": (name, data)})
|
|
285
|
+
rid = r.headers.get("x-result-id")
|
|
286
|
+
if output_format in ("srt", "vtt"):
|
|
287
|
+
return Transcript(text=None, language=language, segments=[], subtitles=r.text, result_id=rid)
|
|
288
|
+
d = r.json()
|
|
289
|
+
segs = d.get("segments") or []
|
|
290
|
+
text = d.get("text") or " ".join((s.get("text") or "").strip() for s in segs).strip()
|
|
291
|
+
return Transcript(text=text, language=d.get("language"), segments=segs, subtitles=None, result_id=rid)
|
|
292
|
+
|
|
293
|
+
def remove_noise(self, audio: ImageInput, *, strength_limit_db: float | None = None,
|
|
294
|
+
output_format: str = "aac") -> AudioResult:
|
|
295
|
+
"""Removes hiss, hum, wind and room noise from speech. strength_limit_db caps the reduction (20 keeps some room
|
|
296
|
+
tone, 10 is subtle; omit to remove everything). output_format: aac (M4A, default) | mp3 | opus | wav."""
|
|
297
|
+
name, data = _read_image(audio)
|
|
298
|
+
r = self._audio_call("/api/audio/denoise", {"atten_lim_db": strength_limit_db, "output_format": output_format},
|
|
299
|
+
{"file": (name, data)})
|
|
300
|
+
return AudioResult(data=r.content, mime=r.headers.get("content-type", "").split(";")[0], result_id=r.headers.get("x-result-id"))
|
|
301
|
+
|
|
302
|
+
def text_to_speech(self, text: str, *, voice: str | None = None, language: str | None = None, speed: float | None = None,
|
|
303
|
+
pitch_semitones: float | None = None, output_format: str = "aac") -> AudioResult:
|
|
304
|
+
"""A voiceover with a named voice (see voices()). Up to 2,000 characters, billed per character. speed 0.5-2.0
|
|
305
|
+
changes duration without changing pitch; pitch_semitones -6..6. Voice cloning is website-only."""
|
|
306
|
+
r = self._audio_call("/api/audio/tts", {"text": text, "speaker": voice, "language_id": language, "speed_factor": speed,
|
|
307
|
+
"pitch_semitones": pitch_semitones, "output_format": output_format}, timeout=300.0)
|
|
308
|
+
return AudioResult(data=r.content, mime=r.headers.get("content-type", "").split(";")[0], result_id=r.headers.get("x-result-id"))
|
|
309
|
+
|
|
310
|
+
def voices(self) -> list[Voice]:
|
|
311
|
+
"""The named voices for text_to_speech: id, native language, accent, gender."""
|
|
312
|
+
d = self._request("GET", "/api/tts/voices").json()
|
|
313
|
+
return [Voice(**v) for v in d.get("voices", [])]
|
|
314
|
+
|
|
315
|
+
def account(self) -> Account:
|
|
316
|
+
"""Balance (in credits; 1 credit = $0.001), plan, rate limits and the open tools with their prices."""
|
|
317
|
+
d = self._request("GET", "/api/account").json()
|
|
318
|
+
return Account(balance_credits=d["balance_credits"], subscription_credits=d["subscription_credits"],
|
|
319
|
+
purchased_credits=d["purchased_credits"], plan=d.get("plan"), team_role=d.get("team_role"),
|
|
320
|
+
requests_per_minute=d["limits"]["requests_per_minute"], parallel_jobs=d["limits"]["parallel_jobs"],
|
|
321
|
+
tools=d.get("tools", []))
|
|
322
|
+
|
|
323
|
+
def recent(self) -> list[RecentResult]:
|
|
324
|
+
"""Everything you made in the last 24 hours (site and API), newest first."""
|
|
325
|
+
items = self._request("GET", "/api/recent").json().get("items", [])
|
|
326
|
+
return [RecentResult(result_id=i["id"], tool=i["tool"], mime=i["mime"], bytes=i["bytes"], created_at=i["created_at"],
|
|
327
|
+
expires_at=i["expires_at"], via_api=bool(i.get("via_api"))) for i in items]
|
|
328
|
+
|
|
329
|
+
def download(self, result_id: str) -> ImageResult:
|
|
330
|
+
"""A result from the last 24 hours, by its result_id."""
|
|
331
|
+
r = self._request("GET", f"/api/recent/{result_id}/file")
|
|
332
|
+
return ImageResult(data=r.content, mime=r.headers.get("content-type", "").split(";")[0], result_id=result_id)
|
|
333
|
+
|
|
334
|
+
def __repr__(self) -> str:
|
|
335
|
+
return f"Eptx(base_url={self.base_url!r})"
|
|
336
|
+
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Errors raised by the Eptx client. Every one carries the HTTP status and the server's message, which says what to fix."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class EptxError(Exception):
|
|
6
|
+
"""Base class. `status` is the HTTP status (None for network errors), `detail` the server's message."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, detail: str, status: int | None = None, retry_after: float | None = None):
|
|
9
|
+
super().__init__(f"{detail} (HTTP {status})" if status else detail)
|
|
10
|
+
self.detail = detail
|
|
11
|
+
self.status = status
|
|
12
|
+
self.retry_after = retry_after
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AuthenticationError(EptxError):
|
|
16
|
+
"""401/403: missing, wrong or revoked API key. Create one at https://eptx.space/developers."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class InsufficientCreditsError(EptxError):
|
|
20
|
+
"""402: the balance doesn't cover the call. Nothing was charged. Top up at https://eptx.space/pricing."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InvalidRequestError(EptxError):
|
|
24
|
+
"""400/413/422: a bad parameter or file. Nothing was charged; the message names the problem."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RateLimitError(EptxError):
|
|
28
|
+
"""429: too many requests or parallel jobs for your plan. `retry_after` is in seconds."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ServiceUnavailableError(EptxError):
|
|
32
|
+
"""503 (and 502/504): busy or briefly down. Nothing was charged; retry after `retry_after` seconds."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class APIConnectionError(EptxError):
|
|
36
|
+
"""The request didn't reach Eptx or the answer didn't come back (network, timeout)."""
|
|
File without changes
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Runs the INSTALLED eptx package against a running dev server. Needs EPTX_BASE_URL, EPTX_API_KEY (paid, 5,000
|
|
2
|
+
credits), EPTX_POOR_KEY (0 credits), EPTX_TEST_PHOTO and a way to read the balance: the harness
|
|
3
|
+
(EptxSpaceServerStuff/test_sdks.py) sets all of them and deletes the accounts after."""
|
|
4
|
+
import io
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from PIL import Image
|
|
10
|
+
|
|
11
|
+
import eptx
|
|
12
|
+
from eptx import Eptx
|
|
13
|
+
|
|
14
|
+
results = []
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def check(name, cond, detail=""):
|
|
18
|
+
results.append(bool(cond))
|
|
19
|
+
print(("PASS " if cond else "FAIL ") + "[py] " + name + (f" [{str(detail)[:250]}]" if detail and not cond else ""))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
PHOTO = os.environ["EPTX_TEST_PHOTO"]
|
|
23
|
+
c = Eptx(max_retries=1)
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
Eptx(api_key="epx_live_nope").account()
|
|
27
|
+
check("bad key -> AuthenticationError", False)
|
|
28
|
+
except eptx.AuthenticationError as e:
|
|
29
|
+
check("bad key -> AuthenticationError", e.status == 401)
|
|
30
|
+
|
|
31
|
+
acc = c.account()
|
|
32
|
+
b0 = acc.balance_credits
|
|
33
|
+
check("account(): balance, plan, limits, priced tools", b0 == 5000 and acc.requests_per_minute > 0 and acc.tools
|
|
34
|
+
and acc.tools[0]["credits"] == 20, acc)
|
|
35
|
+
|
|
36
|
+
r = c.remove_background(PHOTO)
|
|
37
|
+
im = Image.open(io.BytesIO(r.data))
|
|
38
|
+
check("remove_background(path): RGBA PNG at full size, 20 credits, result id, subject box",
|
|
39
|
+
r.mime == "image/png" and im.mode == "RGBA" and (r.width, r.height) == im.size and r.credits_charged == 20
|
|
40
|
+
and r.result_id and r.subject_box and r.subject_box.width > 0, r)
|
|
41
|
+
p = r.save(os.path.join(os.environ.get("TMP", "."), "eptx-sdk-py.png"))
|
|
42
|
+
check("save() writes the file", p.exists() and p.stat().st_size == len(r.data))
|
|
43
|
+
|
|
44
|
+
r2 = c.remove_background(open(PHOTO, "rb"), format="webp", size="preview", crop=True, crop_margin="5%")
|
|
45
|
+
check("file object + webp/preview/crop", r2.mime == "image/webp" and r2.width * r2.height <= 260_000, (r2.mime, r2.width, r2.height))
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
c.remove_background(PHOTO, format="gif")
|
|
49
|
+
check("bad option -> InvalidRequestError", False)
|
|
50
|
+
except eptx.InvalidRequestError as e:
|
|
51
|
+
check("bad option -> InvalidRequestError naming it", "format" in e.detail, e.detail)
|
|
52
|
+
try:
|
|
53
|
+
c.remove_background(url="http://127.0.0.1:8001/health")
|
|
54
|
+
check("private url -> InvalidRequestError", False)
|
|
55
|
+
except eptx.InvalidRequestError as e:
|
|
56
|
+
check("url= to a private address -> InvalidRequestError (SSRF guard)", e.status == 400, e.detail)
|
|
57
|
+
check("failed calls charged nothing", c.account().balance_credits == b0 - 40)
|
|
58
|
+
|
|
59
|
+
ids = [x.result_id for x in c.recent()]
|
|
60
|
+
check("recent(): both results listed", r.result_id in ids and r2.result_id in ids)
|
|
61
|
+
check("download(result_id): same bytes", c.download(r.result_id).data == r.data)
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
Eptx(api_key=os.environ["EPTX_POOR_KEY"], max_retries=0).remove_background(PHOTO)
|
|
65
|
+
check("no credits -> InsufficientCreditsError", False)
|
|
66
|
+
except eptx.InsufficientCreditsError as e:
|
|
67
|
+
check("no credits -> InsufficientCreditsError", e.status == 402, e.detail)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class DropAfterSend(httpx.BaseTransport):
|
|
71
|
+
"""Forwards the first remove-bg request to the server, then pretends the answer never came back."""
|
|
72
|
+
def __init__(self):
|
|
73
|
+
self.real, self.dropped = httpx.HTTPTransport(), False
|
|
74
|
+
|
|
75
|
+
def handle_request(self, request):
|
|
76
|
+
resp = self.real.handle_request(request)
|
|
77
|
+
if request.url.path == "/api/image/remove-bg" and not self.dropped:
|
|
78
|
+
resp.read()
|
|
79
|
+
self.dropped = True
|
|
80
|
+
raise httpx.ReadTimeout("simulated drop", request=request)
|
|
81
|
+
return resp
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
b1 = c.account().balance_credits
|
|
85
|
+
flaky = Eptx(max_retries=2, http_client=httpx.Client(transport=DropAfterSend(), timeout=120))
|
|
86
|
+
r3 = flaky.remove_background(PHOTO, size="preview")
|
|
87
|
+
check("dropped connection after the job ran: result recovered, charged ONCE",
|
|
88
|
+
r3.recovered and r3.data[:4] == b"\x89PNG" and c.account().balance_credits == b1 - 20, (r3.recovered, b1, c.account().balance_credits))
|
|
89
|
+
|
|
90
|
+
# audio tools (owner 2026-11-27)
|
|
91
|
+
vs = c.voices()
|
|
92
|
+
check("voices(): the named voices with language + gender", len(vs) >= 20 and all(v.language and v.gender for v in vs), vs[:2])
|
|
93
|
+
ba = c.account().balance_credits
|
|
94
|
+
check("account(): lists the 4 open tools with units", {t["name"] for t in c.account().tools} >= {"remove_background", "transcribe_audio", "remove_noise", "text_to_speech"})
|
|
95
|
+
vo = c.text_to_speech("Hello from Eptx. Your order ships on Thursday.", voice="juniper", language="en")
|
|
96
|
+
check("text_to_speech(): an M4A voiceover", vo.mime == "audio/mp4" and vo.data[4:8] == b"ftyp" and vo.result_id, (vo.mime, len(vo.data)))
|
|
97
|
+
nz = c.remove_noise(vo.data, output_format="wav")
|
|
98
|
+
check("remove_noise(bytes, wav): a WAV back", nz.data[:4] == b"RIFF" and nz.extension == "wav", (nz.mime, nz.data[:4]))
|
|
99
|
+
tr = c.transcribe(vo.data, language="en")
|
|
100
|
+
check("transcribe(): the words come back", "thursday" in (tr.text or "").lower() and tr.segments, tr.text)
|
|
101
|
+
sr = c.transcribe(vo.data, output_format="srt")
|
|
102
|
+
check("transcribe(srt): subtitles", "-->" in (sr.subtitles or ""), (sr.subtitles or "")[:80])
|
|
103
|
+
check("audio calls were charged (API rates)", 0 < ba - c.account().balance_credits < 200, ba - c.account().balance_credits)
|
|
104
|
+
|
|
105
|
+
print(f"[py] {sum(results)}/{len(results)} passed")
|
|
106
|
+
sys.exit(0 if all(results) else 1)
|