sanititext 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.
@@ -0,0 +1,226 @@
1
+ Metadata-Version: 2.3
2
+ Name: sanititext
3
+ Version: 1.0.0
4
+ Summary: Official Python client for SanitiText sub-millisecond edge moderation and username defense API.
5
+ Keywords: moderation,profanity,toxicity,leetspeak,content-moderation,chat-filter,username-defense,safety
6
+ Author: SanitiText Engineering
7
+ Author-email: SanitiText Engineering <engineering@sanititext.com>
8
+ License: MIT
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Communications :: Chat
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Dist: httpx>=0.24.0
24
+ Requires-Python: >=3.9
25
+ Project-URL: Homepage, https://sanititext.com
26
+ Project-URL: Documentation, https://sanititext.com/docs
27
+ Project-URL: Repository, https://github.com/burakkp/sanititext
28
+ Project-URL: Bug Tracker, https://github.com/burakkp/sanititext/issues
29
+ Description-Content-Type: text/markdown
30
+
31
+ # @sanititext Python SDK (`sanititext`)
32
+
33
+ The official Python client for the **[SanitiText](https://sanititext.com)** Edge Moderation Engine. Provides sub-millisecond profanity, toxicity, leetspeak evasion, and handle defense with native Sync and Async support.
34
+
35
+ [![PyPI](https://img.shields.io/pypi/v/sanititext.svg)](https://pypi.org/project/sanititext/)
36
+ [![Python Version](https://img.shields.io/pypi/pyversions/sanititext.svg)](https://pypi.org/project/sanititext/)
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
38
+
39
+ ---
40
+
41
+ ## Features
42
+
43
+ - ⚡ **Sub-Millisecond Edge Latency**: Evaluates text on Cloudflare V8 isolates located within 50ms of 95% of the world's connected population.
44
+ - 🔄 **Sync & Async Interfaces**: Native support for both synchronous code and asynchronous frameworks (`asyncio`, `FastAPI`, `Starlette`, `Quart`, `Django Channels`).
45
+ - 🛡️ **Comprehensive Moderation**: Defends against leetspeak evasion (`s.1.k.i.k`, `f.u.c.k`), Cyrillic/Greek homoglyphs, zero-width spaces, and gamer separators (`_xX_`).
46
+ - 🏷️ **Username Defense Engine**: Validates registration handles against reserved staff roles, toxic compounds, and offensive gamer tags.
47
+ - 📦 **High-Throughput Batching**: Moderates up to 50 chat messages or entries in a single network roundtrip.
48
+ - 🔁 **Automatic Exponential Retries**: Built-in retry handling for rate limits (HTTP 429 honoring `Retry-After`) and transient server errors.
49
+ - 🪶 **Type Safe**: Fully typed with PEP 561 `py.typed` and comprehensive dataclass models.
50
+
51
+ ---
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install sanititext
57
+ ```
58
+
59
+ Or using `uv`:
60
+
61
+ ```bash
62
+ uv add sanititext
63
+ ```
64
+
65
+ ---
66
+
67
+ ## Quickstart
68
+
69
+ ### 1. Synchronous API
70
+
71
+ ```python
72
+ from sanititext import SanitiText
73
+
74
+ # Initialize client (picks up SANITITEXT_API_KEY from environment if omitted)
75
+ client = SanitiText(api_key="st_live_your_api_key_here")
76
+
77
+ # Single message moderation
78
+ result = client.sanitize("What a f.u.c.k.i.n.g great match!", lang="en")
79
+
80
+ if not result.clean:
81
+ print(f"Violation detected! Toxicity Score: {result.metrics.toxicity_score}")
82
+ print(f"Sanitized Text: {result.sanitized_text}")
83
+ for flag in result.flags:
84
+ print(f" - [{flag.category}] {flag.match} -> {flag.canonical} (severity: {flag.severity})")
85
+ else:
86
+ print("Message is safe to post!")
87
+
88
+ client.close()
89
+ ```
90
+
91
+ You can also use a context manager for automatic connection cleanup:
92
+
93
+ ```python
94
+ with SanitiText() as client:
95
+ res = client.sanitize("Tam bir s1k1k vaziyet", lang="tr", mask=True)
96
+ print(res.sanitized_text) # "Tam bir ******* vaziyet"
97
+ ```
98
+
99
+ ---
100
+
101
+ ### 2. Asynchronous API (`FastAPI`, `asyncio`)
102
+
103
+ ```python
104
+ import asyncio
105
+ from sanititext import AsyncSanitiText
106
+
107
+ async def main():
108
+ async with AsyncSanitiText(api_key="st_live_...") as client:
109
+ result = await client.sanitize("You are absolute tr@sh!", lang="en")
110
+ print("Clean:", result.clean)
111
+ print("Latency:", result.execution_time_ms, "ms")
112
+
113
+ asyncio.run(main())
114
+ ```
115
+
116
+ #### FastAPI Example
117
+
118
+ ```python
119
+ from fastapi import FastAPI, HTTPException
120
+ from pydantic import BaseModel
121
+ from sanititext import AsyncSanitiText
122
+
123
+ app = FastAPI()
124
+ moderator = AsyncSanitiText()
125
+
126
+ class ChatIn(BaseModel):
127
+ message: str
128
+
129
+ @app.post("/chat")
130
+ async def post_chat(body: ChatIn):
131
+ res = await moderator.sanitize(body.message, lang="tr", mask=True)
132
+ if not res.clean and res.metrics.toxicity_score > 0.8:
133
+ raise HTTPException(status_code=400, detail="Message violates community standards")
134
+
135
+ return {"message": res.sanitized_text, "clean": res.clean}
136
+ ```
137
+
138
+ ---
139
+
140
+ ### 3. Batch Moderation (Up to 50 items)
141
+
142
+ ```python
143
+ from sanititext import SanitiText, BatchSanitizeItem
144
+
145
+ with SanitiText() as client:
146
+ batch = client.sanitize_batch([
147
+ BatchSanitizeItem(id="msg-1", text="Welcome to the stream!", lang="en"),
148
+ BatchSanitizeItem(id="msg-2", text="Get out of here you f.u.c.k.e.r", lang="en", mask=True),
149
+ BatchSanitizeItem(id="user-3", text="[admin]_official", mode="username"),
150
+ ])
151
+
152
+ print(f"Processed {batch.total_items} items in {batch.total_execution_time_ms}ms")
153
+ for item in batch.results:
154
+ print(f"[{item.id}] Clean: {item.clean} | Text: {item.sanitized_text}")
155
+ ```
156
+
157
+ ---
158
+
159
+ ### 4. Username & Handle Defense
160
+
161
+ ```python
162
+ with SanitiText() as client:
163
+ res = client.is_username_valid(
164
+ "[admin]_head_moderator",
165
+ reserved_words=["admin", "moderator", "staff", "sanititext"],
166
+ )
167
+
168
+ if not res.valid:
169
+ print("Username rejected!")
170
+ print("Rejection reasons:", res.reasons) # ['reserved_handle']
171
+ else:
172
+ print("Username approved for registration.")
173
+ ```
174
+
175
+ ---
176
+
177
+ ## Configuration
178
+
179
+ | Option | Type | Default | Description |
180
+ | :--- | :--- | :--- | :--- |
181
+ | `api_key` | `Optional[str]` | `os.environ["SANITITEXT_API_KEY"]` | Your SanitiText API key. |
182
+ | `base_url` | `str` | `"https://api.sanititext.com"` | Custom API edge URL or local proxy. |
183
+ | `timeout` | `float` | `10.0` | Timeout in seconds. |
184
+ | `max_retries` | `int` | `2` | Max automatic retries on rate limits (429) & 5xx server errors. |
185
+ | `headers` | `Optional[Dict[str, str]]` | `None` | Custom headers to attach to every request. |
186
+
187
+ ---
188
+
189
+ ## Error Handling
190
+
191
+ All SDK exceptions inherit from `SanitiTextError`:
192
+
193
+ ```python
194
+ from sanititext import (
195
+ SanitiText,
196
+ BadRequestError,
197
+ AuthenticationError,
198
+ PayloadTooLargeError,
199
+ RateLimitError,
200
+ TimeoutError,
201
+ SanitiTextError,
202
+ )
203
+
204
+ client = SanitiText()
205
+
206
+ try:
207
+ client.sanitize("sample text")
208
+ except AuthenticationError:
209
+ print("Invalid or missing API key.")
210
+ except RateLimitError as e:
211
+ print(f"Rate limited! Retry after {e.retry_after_seconds}s. Limit: {e.limit}, Remaining: {e.remaining}")
212
+ except BadRequestError as e:
213
+ print(f"Malformed request payload: {e.message}")
214
+ except PayloadTooLargeError:
215
+ print("Batch size exceeded (max 50 items or 250k chars).")
216
+ except TimeoutError:
217
+ print("Edge request timed out.")
218
+ except SanitiTextError as e:
219
+ print(f"Unexpected error (HTTP {e.status_code}): {e.message}")
220
+ ```
221
+
222
+ ---
223
+
224
+ ## License
225
+
226
+ MIT © [SanitiText](https://sanititext.com)
@@ -0,0 +1,196 @@
1
+ # @sanititext Python SDK (`sanititext`)
2
+
3
+ The official Python client for the **[SanitiText](https://sanititext.com)** Edge Moderation Engine. Provides sub-millisecond profanity, toxicity, leetspeak evasion, and handle defense with native Sync and Async support.
4
+
5
+ [![PyPI](https://img.shields.io/pypi/v/sanititext.svg)](https://pypi.org/project/sanititext/)
6
+ [![Python Version](https://img.shields.io/pypi/pyversions/sanititext.svg)](https://pypi.org/project/sanititext/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
8
+
9
+ ---
10
+
11
+ ## Features
12
+
13
+ - ⚡ **Sub-Millisecond Edge Latency**: Evaluates text on Cloudflare V8 isolates located within 50ms of 95% of the world's connected population.
14
+ - 🔄 **Sync & Async Interfaces**: Native support for both synchronous code and asynchronous frameworks (`asyncio`, `FastAPI`, `Starlette`, `Quart`, `Django Channels`).
15
+ - 🛡️ **Comprehensive Moderation**: Defends against leetspeak evasion (`s.1.k.i.k`, `f.u.c.k`), Cyrillic/Greek homoglyphs, zero-width spaces, and gamer separators (`_xX_`).
16
+ - 🏷️ **Username Defense Engine**: Validates registration handles against reserved staff roles, toxic compounds, and offensive gamer tags.
17
+ - 📦 **High-Throughput Batching**: Moderates up to 50 chat messages or entries in a single network roundtrip.
18
+ - 🔁 **Automatic Exponential Retries**: Built-in retry handling for rate limits (HTTP 429 honoring `Retry-After`) and transient server errors.
19
+ - 🪶 **Type Safe**: Fully typed with PEP 561 `py.typed` and comprehensive dataclass models.
20
+
21
+ ---
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install sanititext
27
+ ```
28
+
29
+ Or using `uv`:
30
+
31
+ ```bash
32
+ uv add sanititext
33
+ ```
34
+
35
+ ---
36
+
37
+ ## Quickstart
38
+
39
+ ### 1. Synchronous API
40
+
41
+ ```python
42
+ from sanititext import SanitiText
43
+
44
+ # Initialize client (picks up SANITITEXT_API_KEY from environment if omitted)
45
+ client = SanitiText(api_key="st_live_your_api_key_here")
46
+
47
+ # Single message moderation
48
+ result = client.sanitize("What a f.u.c.k.i.n.g great match!", lang="en")
49
+
50
+ if not result.clean:
51
+ print(f"Violation detected! Toxicity Score: {result.metrics.toxicity_score}")
52
+ print(f"Sanitized Text: {result.sanitized_text}")
53
+ for flag in result.flags:
54
+ print(f" - [{flag.category}] {flag.match} -> {flag.canonical} (severity: {flag.severity})")
55
+ else:
56
+ print("Message is safe to post!")
57
+
58
+ client.close()
59
+ ```
60
+
61
+ You can also use a context manager for automatic connection cleanup:
62
+
63
+ ```python
64
+ with SanitiText() as client:
65
+ res = client.sanitize("Tam bir s1k1k vaziyet", lang="tr", mask=True)
66
+ print(res.sanitized_text) # "Tam bir ******* vaziyet"
67
+ ```
68
+
69
+ ---
70
+
71
+ ### 2. Asynchronous API (`FastAPI`, `asyncio`)
72
+
73
+ ```python
74
+ import asyncio
75
+ from sanititext import AsyncSanitiText
76
+
77
+ async def main():
78
+ async with AsyncSanitiText(api_key="st_live_...") as client:
79
+ result = await client.sanitize("You are absolute tr@sh!", lang="en")
80
+ print("Clean:", result.clean)
81
+ print("Latency:", result.execution_time_ms, "ms")
82
+
83
+ asyncio.run(main())
84
+ ```
85
+
86
+ #### FastAPI Example
87
+
88
+ ```python
89
+ from fastapi import FastAPI, HTTPException
90
+ from pydantic import BaseModel
91
+ from sanititext import AsyncSanitiText
92
+
93
+ app = FastAPI()
94
+ moderator = AsyncSanitiText()
95
+
96
+ class ChatIn(BaseModel):
97
+ message: str
98
+
99
+ @app.post("/chat")
100
+ async def post_chat(body: ChatIn):
101
+ res = await moderator.sanitize(body.message, lang="tr", mask=True)
102
+ if not res.clean and res.metrics.toxicity_score > 0.8:
103
+ raise HTTPException(status_code=400, detail="Message violates community standards")
104
+
105
+ return {"message": res.sanitized_text, "clean": res.clean}
106
+ ```
107
+
108
+ ---
109
+
110
+ ### 3. Batch Moderation (Up to 50 items)
111
+
112
+ ```python
113
+ from sanititext import SanitiText, BatchSanitizeItem
114
+
115
+ with SanitiText() as client:
116
+ batch = client.sanitize_batch([
117
+ BatchSanitizeItem(id="msg-1", text="Welcome to the stream!", lang="en"),
118
+ BatchSanitizeItem(id="msg-2", text="Get out of here you f.u.c.k.e.r", lang="en", mask=True),
119
+ BatchSanitizeItem(id="user-3", text="[admin]_official", mode="username"),
120
+ ])
121
+
122
+ print(f"Processed {batch.total_items} items in {batch.total_execution_time_ms}ms")
123
+ for item in batch.results:
124
+ print(f"[{item.id}] Clean: {item.clean} | Text: {item.sanitized_text}")
125
+ ```
126
+
127
+ ---
128
+
129
+ ### 4. Username & Handle Defense
130
+
131
+ ```python
132
+ with SanitiText() as client:
133
+ res = client.is_username_valid(
134
+ "[admin]_head_moderator",
135
+ reserved_words=["admin", "moderator", "staff", "sanititext"],
136
+ )
137
+
138
+ if not res.valid:
139
+ print("Username rejected!")
140
+ print("Rejection reasons:", res.reasons) # ['reserved_handle']
141
+ else:
142
+ print("Username approved for registration.")
143
+ ```
144
+
145
+ ---
146
+
147
+ ## Configuration
148
+
149
+ | Option | Type | Default | Description |
150
+ | :--- | :--- | :--- | :--- |
151
+ | `api_key` | `Optional[str]` | `os.environ["SANITITEXT_API_KEY"]` | Your SanitiText API key. |
152
+ | `base_url` | `str` | `"https://api.sanititext.com"` | Custom API edge URL or local proxy. |
153
+ | `timeout` | `float` | `10.0` | Timeout in seconds. |
154
+ | `max_retries` | `int` | `2` | Max automatic retries on rate limits (429) & 5xx server errors. |
155
+ | `headers` | `Optional[Dict[str, str]]` | `None` | Custom headers to attach to every request. |
156
+
157
+ ---
158
+
159
+ ## Error Handling
160
+
161
+ All SDK exceptions inherit from `SanitiTextError`:
162
+
163
+ ```python
164
+ from sanititext import (
165
+ SanitiText,
166
+ BadRequestError,
167
+ AuthenticationError,
168
+ PayloadTooLargeError,
169
+ RateLimitError,
170
+ TimeoutError,
171
+ SanitiTextError,
172
+ )
173
+
174
+ client = SanitiText()
175
+
176
+ try:
177
+ client.sanitize("sample text")
178
+ except AuthenticationError:
179
+ print("Invalid or missing API key.")
180
+ except RateLimitError as e:
181
+ print(f"Rate limited! Retry after {e.retry_after_seconds}s. Limit: {e.limit}, Remaining: {e.remaining}")
182
+ except BadRequestError as e:
183
+ print(f"Malformed request payload: {e.message}")
184
+ except PayloadTooLargeError:
185
+ print("Batch size exceeded (max 50 items or 250k chars).")
186
+ except TimeoutError:
187
+ print("Edge request timed out.")
188
+ except SanitiTextError as e:
189
+ print(f"Unexpected error (HTTP {e.status_code}): {e.message}")
190
+ ```
191
+
192
+ ---
193
+
194
+ ## License
195
+
196
+ MIT © [SanitiText](https://sanititext.com)
@@ -0,0 +1,62 @@
1
+ [project]
2
+ name = "sanititext"
3
+ version = "1.0.0"
4
+ description = "Official Python client for SanitiText sub-millisecond edge moderation and username defense API."
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ keywords = [
8
+ "moderation",
9
+ "profanity",
10
+ "toxicity",
11
+ "leetspeak",
12
+ "content-moderation",
13
+ "chat-filter",
14
+ "username-defense",
15
+ "safety",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 5 - Production/Stable",
19
+ "Intended Audience :: Developers",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
28
+ "Topic :: Communications :: Chat",
29
+ "Topic :: Security",
30
+ "Topic :: Software Development :: Libraries :: Python Modules",
31
+ "Typing :: Typed",
32
+ ]
33
+ dependencies = ["httpx>=0.24.0"]
34
+
35
+ [project.license]
36
+ text = "MIT"
37
+
38
+ [[project.authors]]
39
+ name = "SanitiText Engineering"
40
+ email = "engineering@sanititext.com"
41
+
42
+ [project.urls]
43
+ Homepage = "https://sanititext.com"
44
+ Documentation = "https://sanititext.com/docs"
45
+ Repository = "https://github.com/burakkp/sanititext"
46
+ "Bug Tracker" = "https://github.com/burakkp/sanititext/issues"
47
+
48
+ [build-system]
49
+ requires = ["uv_build>=0.10.6,<0.11.0"]
50
+ build-backend = "uv_build"
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ "pytest>=8.0.0",
55
+ "pytest-asyncio>=0.23.0",
56
+ ]
57
+
58
+ [tool.pytest.ini_options]
59
+ minversion = "7.0"
60
+ testpaths = ["tests"]
61
+ asyncio_mode = "auto"
62
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,61 @@
1
+ [project]
2
+ name = "sanititext"
3
+ version = "1.0.0"
4
+ description = "Official Python client for SanitiText sub-millisecond edge moderation and username defense API."
5
+ readme = "README.md"
6
+ license = { text = "MIT" }
7
+ requires-python = ">=3.9"
8
+ authors = [
9
+ { name = "SanitiText Engineering", email = "engineering@sanititext.com" }
10
+ ]
11
+ keywords = [
12
+ "moderation",
13
+ "profanity",
14
+ "toxicity",
15
+ "leetspeak",
16
+ "content-moderation",
17
+ "chat-filter",
18
+ "username-defense",
19
+ "safety",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 5 - Production/Stable",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.9",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Programming Language :: Python :: 3.14",
32
+ "Topic :: Communications :: Chat",
33
+ "Topic :: Security",
34
+ "Topic :: Software Development :: Libraries :: Python Modules",
35
+ "Typing :: Typed",
36
+ ]
37
+ dependencies = [
38
+ "httpx>=0.24.0",
39
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://sanititext.com"
43
+ Documentation = "https://sanititext.com/docs"
44
+ Repository = "https://github.com/burakkp/sanititext"
45
+ "Bug Tracker" = "https://github.com/burakkp/sanititext/issues"
46
+
47
+ [build-system]
48
+ requires = ["uv_build>=0.10.6,<0.11.0"]
49
+ build-backend = "uv_build"
50
+
51
+ [dependency-groups]
52
+ dev = [
53
+ "pytest>=8.0.0",
54
+ "pytest-asyncio>=0.23.0",
55
+ ]
56
+
57
+ [tool.pytest.ini_options]
58
+ minversion = "7.0"
59
+ testpaths = ["tests"]
60
+ asyncio_mode = "auto"
61
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,53 @@
1
+ """
2
+ Official Python client library for SanitiText content moderation API.
3
+ """
4
+ from .client import AsyncSanitiText, SanitiText
5
+ from .errors import (
6
+ AuthenticationError,
7
+ BadRequestError,
8
+ PayloadTooLargeError,
9
+ RateLimitError,
10
+ SanitiTextError,
11
+ TimeoutError,
12
+ )
13
+ from .types import (
14
+ BatchSanitizeItem,
15
+ BatchSanitizeItemResult,
16
+ BatchSanitizeResponse,
17
+ HealthResponse,
18
+ MatchFlag,
19
+ ModerationMode,
20
+ SanitizeMetrics,
21
+ SanitizeResponse,
22
+ SupportedLanguage,
23
+ UsernameValidationResult,
24
+ )
25
+
26
+ # Friendly aliases for cross-SDK consistency
27
+ SanitiTextClient = SanitiText
28
+ AsyncSanitiTextClient = AsyncSanitiText
29
+
30
+ __version__ = "1.0.0"
31
+
32
+ __all__ = [
33
+ "SanitiText",
34
+ "AsyncSanitiText",
35
+ "SanitiTextClient",
36
+ "AsyncSanitiTextClient",
37
+ "SanitiTextError",
38
+ "BadRequestError",
39
+ "AuthenticationError",
40
+ "PayloadTooLargeError",
41
+ "RateLimitError",
42
+ "TimeoutError",
43
+ "SanitizeResponse",
44
+ "MatchFlag",
45
+ "SanitizeMetrics",
46
+ "BatchSanitizeItem",
47
+ "BatchSanitizeItemResult",
48
+ "BatchSanitizeResponse",
49
+ "UsernameValidationResult",
50
+ "HealthResponse",
51
+ "ModerationMode",
52
+ "SupportedLanguage",
53
+ ]
@@ -0,0 +1,464 @@
1
+ """
2
+ Synchronous and Asynchronous SanitiText API Clients.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import os
8
+ import time
9
+ from typing import Any, Dict, List, Optional, Sequence, Union
10
+
11
+ import httpx
12
+
13
+ from .errors import (
14
+ AuthenticationError,
15
+ BadRequestError,
16
+ PayloadTooLargeError,
17
+ RateLimitError,
18
+ SanitiTextError,
19
+ TimeoutError,
20
+ )
21
+ from .types import (
22
+ BatchSanitizeItem,
23
+ BatchSanitizeResponse,
24
+ HealthResponse,
25
+ ModerationMode,
26
+ SanitizeResponse,
27
+ SupportedLanguage,
28
+ UsernameValidationResult,
29
+ )
30
+
31
+ DEFAULT_BASE_URL = "https://api.sanititext.com"
32
+ DEFAULT_TIMEOUT_SECONDS = 10.0
33
+ DEFAULT_MAX_RETRIES = 2
34
+
35
+
36
+ def _resolve_api_key(api_key: Optional[str]) -> Optional[str]:
37
+ if api_key and api_key.strip():
38
+ return api_key.strip()
39
+ env_key = os.environ.get("SANITITEXT_API_KEY")
40
+ if env_key and env_key.strip():
41
+ return env_key.strip()
42
+ return None
43
+
44
+
45
+ def _format_headers(
46
+ api_key: Optional[str],
47
+ custom_headers: Optional[Dict[str, str]] = None,
48
+ ) -> Dict[str, str]:
49
+ headers = {
50
+ "Accept": "application/json",
51
+ "User-Agent": "sanititext-python/1.0.0",
52
+ }
53
+ if custom_headers:
54
+ headers.update(custom_headers)
55
+ if api_key:
56
+ if api_key.lower().startswith("bearer "):
57
+ headers["Authorization"] = api_key
58
+ else:
59
+ headers["Authorization"] = f"Bearer {api_key}"
60
+ return headers
61
+
62
+
63
+ def _map_http_error(response: httpx.Response, attempt: int, max_retries: int) -> None:
64
+ try:
65
+ error_body = response.json()
66
+ except Exception:
67
+ error_body = response.text
68
+
69
+ message = ""
70
+ if isinstance(error_body, dict):
71
+ message = str(error_body.get("error", ""))
72
+ if not message:
73
+ message = response.reason_phrase or f"HTTP {response.status_code}"
74
+
75
+ if response.status_code == 400:
76
+ raise BadRequestError(message, body=error_body)
77
+ if response.status_code == 401:
78
+ raise AuthenticationError(message, body=error_body)
79
+ if response.status_code == 413:
80
+ raise PayloadTooLargeError(message, body=error_body)
81
+ if response.status_code == 429:
82
+ retry_after_str = response.headers.get("Retry-After")
83
+ retry_after = int(retry_after_str) if retry_after_str and retry_after_str.isdigit() else (2**attempt)
84
+ limit_str = response.headers.get("X-RateLimit-Limit")
85
+ rem_str = response.headers.get("X-RateLimit-Remaining")
86
+ limit = int(limit_str) if limit_str and limit_str.isdigit() else None
87
+ remaining = int(rem_str) if rem_str and rem_str.isdigit() else None
88
+ raise RateLimitError(
89
+ message=message,
90
+ retry_after_seconds=retry_after,
91
+ limit=limit,
92
+ remaining=remaining,
93
+ body=error_body,
94
+ )
95
+
96
+ raise SanitiTextError(
97
+ message=message,
98
+ status_code=response.status_code,
99
+ code="HTTP_ERROR",
100
+ body=error_body,
101
+ )
102
+
103
+
104
+ class SanitiText:
105
+ """
106
+ Synchronous client for SanitiText sub-millisecond edge content moderation API.
107
+
108
+ Example:
109
+ ```python
110
+ from sanititext import SanitiText
111
+
112
+ client = SanitiText(api_key="st_live_...")
113
+ result = client.sanitize("What a f.u.c.k.i.n.g great match!")
114
+ print(result.clean, result.sanitized_text)
115
+ ```
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ api_key: Optional[str] = None,
121
+ *,
122
+ base_url: str = DEFAULT_BASE_URL,
123
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
124
+ max_retries: int = DEFAULT_MAX_RETRIES,
125
+ headers: Optional[Dict[str, str]] = None,
126
+ http_client: Optional[httpx.Client] = None,
127
+ ) -> None:
128
+ self.api_key = _resolve_api_key(api_key)
129
+ self.base_url = base_url.rstrip("/")
130
+ self.timeout = timeout
131
+ self.max_retries = max(0, max_retries)
132
+ self._custom_headers = headers
133
+
134
+ if http_client is not None:
135
+ self._client = http_client
136
+ self._owns_client = False
137
+ else:
138
+ self._client = httpx.Client(
139
+ base_url=self.base_url,
140
+ timeout=self.timeout,
141
+ headers=_format_headers(self.api_key, self._custom_headers),
142
+ )
143
+ self._owns_client = True
144
+
145
+ def __enter__(self) -> SanitiText:
146
+ return self
147
+
148
+ def __exit__(self, *args: Any) -> None:
149
+ self.close()
150
+
151
+ def close(self) -> None:
152
+ """Close the underlying HTTP client session."""
153
+ if self._owns_client:
154
+ self._client.close()
155
+
156
+ def sanitize(
157
+ self,
158
+ text: Union[str, Dict[str, Any]],
159
+ *,
160
+ mode: ModerationMode = "chat",
161
+ lang: Union[SupportedLanguage, str] = "tr",
162
+ mask: bool = True,
163
+ mask_char: str = "*",
164
+ reserved_words: Optional[List[str]] = None,
165
+ ) -> SanitizeResponse:
166
+ """
167
+ Evaluate and moderate a single text message or username.
168
+
169
+ Args:
170
+ text: Raw string or dictionary of options.
171
+ mode: 'chat' (general conversation) or 'username' (handle defense).
172
+ lang: Target ISO language code ('tr', 'en', 'nl', 'de', 'es', 'fr').
173
+ mask: Whether to mask prohibited words in sanitized_text.
174
+ mask_char: Character to use when masking (default: '*').
175
+ reserved_words: Custom reserved names or terms for username defense.
176
+
177
+ Returns:
178
+ SanitizeResponse with clean boolean, match flags, metrics, and masked text.
179
+ """
180
+ if isinstance(text, dict):
181
+ payload = text
182
+ else:
183
+ payload: Dict[str, Any] = {
184
+ "text": text,
185
+ "mode": mode,
186
+ "lang": lang,
187
+ "mask": mask,
188
+ "maskChar": mask_char,
189
+ }
190
+ if reserved_words:
191
+ payload["reserved_words"] = reserved_words
192
+
193
+ data = self._request("POST", "/v1/sanitize", json=payload)
194
+ return SanitizeResponse.from_dict(data)
195
+
196
+ def sanitize_batch(
197
+ self,
198
+ items: Sequence[Union[BatchSanitizeItem, Dict[str, Any]]],
199
+ *,
200
+ default_lang: Union[SupportedLanguage, str] = "tr",
201
+ default_mode: ModerationMode = "chat",
202
+ ) -> BatchSanitizeResponse:
203
+ """
204
+ Moderate up to 50 text items in a single edge roundtrip.
205
+
206
+ Args:
207
+ items: Sequence of BatchSanitizeItem or dictionaries.
208
+ default_lang: Fallback language code for items without an explicit lang.
209
+ default_mode: Fallback moderation mode ('chat' or 'username').
210
+
211
+ Returns:
212
+ BatchSanitizeResponse containing item results and total execution latency.
213
+ """
214
+ serialized_items = [
215
+ item.to_dict() if isinstance(item, BatchSanitizeItem) else item for item in items
216
+ ]
217
+ payload = {
218
+ "items": serialized_items,
219
+ "default_lang": default_lang,
220
+ "default_mode": default_mode,
221
+ }
222
+ data = self._request("POST", "/v1/sanitize/batch", json=payload)
223
+ return BatchSanitizeResponse.from_dict(data)
224
+
225
+ def is_username_valid(
226
+ self,
227
+ username: str,
228
+ *,
229
+ reserved_words: Optional[List[str]] = None,
230
+ lang: Union[SupportedLanguage, str] = "tr",
231
+ ) -> UsernameValidationResult:
232
+ """
233
+ Validate whether a vanity handle or clan tag meets safety standards.
234
+
235
+ Args:
236
+ username: The desired handle or gamer tag.
237
+ reserved_words: Additional reserved handles (e.g. ['admin', 'moderator']).
238
+ lang: Primary language dictionary.
239
+
240
+ Returns:
241
+ UsernameValidationResult with valid boolean and explicit rejection reasons.
242
+ """
243
+ res = self.sanitize(
244
+ text=username,
245
+ mode="username",
246
+ lang=lang,
247
+ mask=True,
248
+ reserved_words=reserved_words,
249
+ )
250
+ is_valid = res.valid_username if res.valid_username is not None else res.clean
251
+ return UsernameValidationResult(
252
+ valid=is_valid,
253
+ reasons=res.reasons or [],
254
+ sanitized=res.sanitized_text,
255
+ execution_time_ms=res.execution_time_ms,
256
+ )
257
+
258
+ def health(self) -> HealthResponse:
259
+ """Check edge health and status."""
260
+ data = self._request("GET", "/health")
261
+ return HealthResponse.from_dict(data)
262
+
263
+ def _request(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
264
+ for attempt in range(self.max_retries + 1):
265
+ try:
266
+ response = self._client.request(method, path, **kwargs)
267
+ if response.is_success:
268
+ return response.json()
269
+
270
+ if response.status_code == 429 and attempt < self.max_retries:
271
+ retry_header = response.headers.get("Retry-After")
272
+ backoff = (
273
+ int(retry_header)
274
+ if retry_header and retry_header.isdigit()
275
+ else (2**attempt)
276
+ )
277
+ time.sleep(min(backoff, 10.0))
278
+ continue
279
+
280
+ if response.status_code >= 500 and attempt < self.max_retries:
281
+ time.sleep(0.5 * (2**attempt))
282
+ continue
283
+
284
+ _map_http_error(response, attempt, self.max_retries)
285
+
286
+ except httpx.TimeoutException:
287
+ if attempt < self.max_retries:
288
+ time.sleep(0.5 * (2**attempt))
289
+ continue
290
+ raise TimeoutError(self.timeout)
291
+ except httpx.RequestError as exc:
292
+ if attempt < self.max_retries:
293
+ time.sleep(0.5 * (2**attempt))
294
+ continue
295
+ raise SanitiTextError(f"Network transport error: {exc}", code="NETWORK_ERROR")
296
+
297
+ raise SanitiTextError("Maximum retry attempts exceeded", code="MAX_RETRIES_EXCEEDED")
298
+
299
+
300
+ class AsyncSanitiText:
301
+ """
302
+ Asynchronous client for SanitiText API (asyncio / FastAPI / Starlette / Quart).
303
+
304
+ Example:
305
+ ```python
306
+ import asyncio
307
+ from sanititext import AsyncSanitiText
308
+
309
+ async def main():
310
+ async with AsyncSanitiText(api_key="st_live_...") as client:
311
+ res = await client.sanitize("What a f.u.c.k.i.n.g great match!")
312
+ print(res.clean, res.sanitized_text)
313
+
314
+ asyncio.run(main())
315
+ ```
316
+ """
317
+
318
+ def __init__(
319
+ self,
320
+ api_key: Optional[str] = None,
321
+ *,
322
+ base_url: str = DEFAULT_BASE_URL,
323
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
324
+ max_retries: int = DEFAULT_MAX_RETRIES,
325
+ headers: Optional[Dict[str, str]] = None,
326
+ http_client: Optional[httpx.AsyncClient] = None,
327
+ ) -> None:
328
+ self.api_key = _resolve_api_key(api_key)
329
+ self.base_url = base_url.rstrip("/")
330
+ self.timeout = timeout
331
+ self.max_retries = max(0, max_retries)
332
+ self._custom_headers = headers
333
+
334
+ if http_client is not None:
335
+ self._client = http_client
336
+ self._owns_client = False
337
+ else:
338
+ self._client = httpx.AsyncClient(
339
+ base_url=self.base_url,
340
+ timeout=self.timeout,
341
+ headers=_format_headers(self.api_key, self._custom_headers),
342
+ )
343
+ self._owns_client = True
344
+
345
+ async def __aenter__(self) -> AsyncSanitiText:
346
+ return self
347
+
348
+ async def __aexit__(self, *args: Any) -> None:
349
+ await self.aclose()
350
+
351
+ async def aclose(self) -> None:
352
+ """Close the underlying async HTTP client session."""
353
+ if self._owns_client:
354
+ await self._client.aclose()
355
+
356
+ async def sanitize(
357
+ self,
358
+ text: Union[str, Dict[str, Any]],
359
+ *,
360
+ mode: ModerationMode = "chat",
361
+ lang: Union[SupportedLanguage, str] = "tr",
362
+ mask: bool = True,
363
+ mask_char: str = "*",
364
+ reserved_words: Optional[List[str]] = None,
365
+ ) -> SanitizeResponse:
366
+ """Evaluate and moderate a single text message or username asynchronously."""
367
+ if isinstance(text, dict):
368
+ payload = text
369
+ else:
370
+ payload: Dict[str, Any] = {
371
+ "text": text,
372
+ "mode": mode,
373
+ "lang": lang,
374
+ "mask": mask,
375
+ "maskChar": mask_char,
376
+ }
377
+ if reserved_words:
378
+ payload["reserved_words"] = reserved_words
379
+
380
+ data = await self._request("POST", "/v1/sanitize", json=payload)
381
+ return SanitizeResponse.from_dict(data)
382
+
383
+ async def sanitize_batch(
384
+ self,
385
+ items: Sequence[Union[BatchSanitizeItem, Dict[str, Any]]],
386
+ *,
387
+ default_lang: Union[SupportedLanguage, str] = "tr",
388
+ default_mode: ModerationMode = "chat",
389
+ ) -> BatchSanitizeResponse:
390
+ """Moderate up to 50 text items asynchronously."""
391
+ serialized_items = [
392
+ item.to_dict() if isinstance(item, BatchSanitizeItem) else item for item in items
393
+ ]
394
+ payload = {
395
+ "items": serialized_items,
396
+ "default_lang": default_lang,
397
+ "default_mode": default_mode,
398
+ }
399
+ data = await self._request("POST", "/v1/sanitize/batch", json=payload)
400
+ return BatchSanitizeResponse.from_dict(data)
401
+
402
+ async def is_username_valid(
403
+ self,
404
+ username: str,
405
+ *,
406
+ reserved_words: Optional[List[str]] = None,
407
+ lang: Union[SupportedLanguage, str] = "tr",
408
+ ) -> UsernameValidationResult:
409
+ """Validate handle safety asynchronously."""
410
+ res = await self.sanitize(
411
+ text=username,
412
+ mode="username",
413
+ lang=lang,
414
+ mask=True,
415
+ reserved_words=reserved_words,
416
+ )
417
+ is_valid = res.valid_username if res.valid_username is not None else res.clean
418
+ return UsernameValidationResult(
419
+ valid=is_valid,
420
+ reasons=res.reasons or [],
421
+ sanitized=res.sanitized_text,
422
+ execution_time_ms=res.execution_time_ms,
423
+ )
424
+
425
+ async def health(self) -> HealthResponse:
426
+ """Check edge health asynchronously."""
427
+ data = await self._request("GET", "/health")
428
+ return HealthResponse.from_dict(data)
429
+
430
+ async def _request(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
431
+ for attempt in range(self.max_retries + 1):
432
+ try:
433
+ response = await self._client.request(method, path, **kwargs)
434
+ if response.is_success:
435
+ return response.json()
436
+
437
+ if response.status_code == 429 and attempt < self.max_retries:
438
+ retry_header = response.headers.get("Retry-After")
439
+ backoff = (
440
+ int(retry_header)
441
+ if retry_header and retry_header.isdigit()
442
+ else (2**attempt)
443
+ )
444
+ await asyncio.sleep(min(backoff, 10.0))
445
+ continue
446
+
447
+ if response.status_code >= 500 and attempt < self.max_retries:
448
+ await asyncio.sleep(0.5 * (2**attempt))
449
+ continue
450
+
451
+ _map_http_error(response, attempt, self.max_retries)
452
+
453
+ except httpx.TimeoutException:
454
+ if attempt < self.max_retries:
455
+ await asyncio.sleep(0.5 * (2**attempt))
456
+ continue
457
+ raise TimeoutError(self.timeout)
458
+ except httpx.RequestError as exc:
459
+ if attempt < self.max_retries:
460
+ await asyncio.sleep(0.5 * (2**attempt))
461
+ continue
462
+ raise SanitiTextError(f"Network transport error: {exc}", code="NETWORK_ERROR")
463
+
464
+ raise SanitiTextError("Maximum retry attempts exceeded", code="MAX_RETRIES_EXCEEDED")
@@ -0,0 +1,81 @@
1
+ """
2
+ SanitiText SDK typed exception hierarchy.
3
+ """
4
+ from typing import Any, Optional
5
+
6
+
7
+ class SanitiTextError(Exception):
8
+ """Base exception for all SanitiText SDK errors."""
9
+
10
+ def __init__(
11
+ self,
12
+ message: str,
13
+ status_code: int = 0,
14
+ code: str = "SANITITEXT_ERROR",
15
+ body: Any = None,
16
+ ) -> None:
17
+ super().__init__(message)
18
+ self.message = message
19
+ self.status_code = status_code
20
+ self.code = code
21
+ self.body = body
22
+
23
+ def __repr__(self) -> str:
24
+ return (
25
+ f"{self.__class__.__name__}("
26
+ f"status_code={self.status_code}, code={self.code!r}, message={self.message!r})"
27
+ )
28
+
29
+
30
+ class BadRequestError(SanitiTextError):
31
+ """Raised when an invalid or malformed request payload is sent (HTTP 400)."""
32
+
33
+ def __init__(self, message: str = "Invalid request payload", body: Any = None) -> None:
34
+ super().__init__(message, status_code=400, code="BAD_REQUEST", body=body)
35
+
36
+
37
+ class AuthenticationError(SanitiTextError):
38
+ """Raised when API key authentication fails or is missing (HTTP 401)."""
39
+
40
+ def __init__(self, message: str = "Invalid or missing API key", body: Any = None) -> None:
41
+ super().__init__(message, status_code=401, code="AUTHENTICATION_FAILED", body=body)
42
+
43
+
44
+ class PayloadTooLargeError(SanitiTextError):
45
+ """Raised when request payload exceeds bounds (HTTP 413)."""
46
+
47
+ def __init__(
48
+ self,
49
+ message: str = "Payload exceeds maximum limits (50 items or 250,000 characters)",
50
+ body: Any = None,
51
+ ) -> None:
52
+ super().__init__(message, status_code=413, code="PAYLOAD_TOO_LARGE", body=body)
53
+
54
+
55
+ class RateLimitError(SanitiTextError):
56
+ """Raised when client exceeds rate limit quota (HTTP 429)."""
57
+
58
+ def __init__(
59
+ self,
60
+ message: str = "Rate limit exceeded",
61
+ retry_after_seconds: int = 60,
62
+ limit: Optional[int] = None,
63
+ remaining: Optional[int] = None,
64
+ body: Any = None,
65
+ ) -> None:
66
+ super().__init__(message, status_code=429, code="RATE_LIMIT_EXCEEDED", body=body)
67
+ self.retry_after_seconds = retry_after_seconds
68
+ self.limit = limit
69
+ self.remaining = remaining
70
+
71
+
72
+ class TimeoutError(SanitiTextError):
73
+ """Raised when an API request exceeds the configured timeout."""
74
+
75
+ def __init__(self, timeout_seconds: float) -> None:
76
+ super().__init__(
77
+ f"Request timed out after {timeout_seconds}s",
78
+ status_code=408,
79
+ code="REQUEST_TIMEOUT",
80
+ )
81
+ self.timeout_seconds = timeout_seconds
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,188 @@
1
+ """
2
+ Data models and response types for SanitiText API.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, List, Literal, Optional, Tuple, Union
8
+
9
+ ModerationMode = Literal["chat", "username"]
10
+ SupportedLanguage = Literal["tr", "en", "nl", "de", "es", "fr"]
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class MatchFlag:
15
+ """A specific violation or match found in the evaluated text."""
16
+
17
+ match: str
18
+ canonical: str
19
+ category: str
20
+ severity: int
21
+ technique: str
22
+ range: Tuple[int, int]
23
+
24
+ @classmethod
25
+ def from_dict(cls, data: dict[str, Any]) -> MatchFlag:
26
+ raw_range = data.get("range", [0, 0])
27
+ tuple_range = (int(raw_range[0]), int(raw_range[1])) if len(raw_range) >= 2 else (0, 0)
28
+ return cls(
29
+ match=str(data.get("match", "")),
30
+ canonical=str(data.get("canonical", "")),
31
+ category=str(data.get("category", "")),
32
+ severity=int(data.get("severity", 1)),
33
+ technique=str(data.get("technique", "exact")),
34
+ range=tuple_range,
35
+ )
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class SanitizeMetrics:
40
+ """Toxicity score and confidence metrics."""
41
+
42
+ toxicity_score: float
43
+ confidence: float
44
+
45
+ @classmethod
46
+ def from_dict(cls, data: dict[str, Any]) -> SanitizeMetrics:
47
+ return cls(
48
+ toxicity_score=float(data.get("toxicity_score", 0.0)),
49
+ confidence=float(data.get("confidence", 1.0)),
50
+ )
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class SanitizeResponse:
55
+ """Result of evaluating and sanitizing a single text string or username."""
56
+
57
+ clean: bool
58
+ execution_time_ms: float
59
+ detected_language: str
60
+ sanitized_text: str
61
+ flags: List[MatchFlag] = field(default_factory=list)
62
+ metrics: SanitizeMetrics = field(default_factory=lambda: SanitizeMetrics(0.0, 1.0))
63
+ valid_username: Optional[bool] = None
64
+ reasons: Optional[List[str]] = None
65
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
66
+
67
+ @classmethod
68
+ def from_dict(cls, data: dict[str, Any]) -> SanitizeResponse:
69
+ flags = [MatchFlag.from_dict(f) for f in data.get("flags", [])]
70
+ metrics = SanitizeMetrics.from_dict(data.get("metrics", {}))
71
+ return cls(
72
+ clean=bool(data.get("clean", True)),
73
+ execution_time_ms=float(data.get("execution_time_ms", 0.0)),
74
+ detected_language=str(data.get("detected_language", "tr")),
75
+ sanitized_text=str(data.get("sanitized_text", "")),
76
+ flags=flags,
77
+ metrics=metrics,
78
+ valid_username=data.get("valid_username"),
79
+ reasons=data.get("reasons"),
80
+ raw=data,
81
+ )
82
+
83
+
84
+ @dataclass
85
+ class BatchSanitizeItem:
86
+ """Item specification for batch moderation."""
87
+
88
+ text: str
89
+ id: Optional[str] = None
90
+ mode: Optional[Union[ModerationMode, str]] = None
91
+ lang: Optional[Union[SupportedLanguage, str]] = None
92
+ mask: Optional[bool] = None
93
+ mask_char: Optional[str] = None
94
+ reserved_words: Optional[List[str]] = None
95
+
96
+ def to_dict(self) -> dict[str, Any]:
97
+ d: dict[str, Any] = {"text": self.text}
98
+ if self.id is not None:
99
+ d["id"] = self.id
100
+ if self.mode is not None:
101
+ d["mode"] = self.mode
102
+ if self.lang is not None:
103
+ d["lang"] = self.lang
104
+ if self.mask is not None:
105
+ d["mask"] = self.mask
106
+ if self.mask_char is not None:
107
+ d["maskChar"] = self.mask_char
108
+ if self.reserved_words is not None:
109
+ d["reserved_words"] = self.reserved_words
110
+ return d
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class BatchSanitizeItemResult:
115
+ """Individual result within a batch moderation response."""
116
+
117
+ clean: bool
118
+ execution_time_ms: float
119
+ detected_language: str
120
+ sanitized_text: str
121
+ id: Optional[str] = None
122
+ flags: List[MatchFlag] = field(default_factory=list)
123
+ metrics: SanitizeMetrics = field(default_factory=lambda: SanitizeMetrics(0.0, 1.0))
124
+ valid_username: Optional[bool] = None
125
+ reasons: Optional[List[str]] = None
126
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
127
+
128
+ @classmethod
129
+ def from_dict(cls, data: dict[str, Any]) -> BatchSanitizeItemResult:
130
+ flags = [MatchFlag.from_dict(f) for f in data.get("flags", [])]
131
+ metrics = SanitizeMetrics.from_dict(data.get("metrics", {}))
132
+ return cls(
133
+ id=data.get("id"),
134
+ clean=bool(data.get("clean", True)),
135
+ execution_time_ms=float(data.get("execution_time_ms", 0.0)),
136
+ detected_language=str(data.get("detected_language", "tr")),
137
+ sanitized_text=str(data.get("sanitized_text", "")),
138
+ flags=flags,
139
+ metrics=metrics,
140
+ valid_username=data.get("valid_username"),
141
+ reasons=data.get("reasons"),
142
+ raw=data,
143
+ )
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class BatchSanitizeResponse:
148
+ """Batch moderation evaluation response."""
149
+
150
+ total_items: int
151
+ total_execution_time_ms: float
152
+ results: List[BatchSanitizeItemResult] = field(default_factory=list)
153
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
154
+
155
+ @classmethod
156
+ def from_dict(cls, data: dict[str, Any]) -> BatchSanitizeResponse:
157
+ results = [BatchSanitizeItemResult.from_dict(item) for item in data.get("results", [])]
158
+ return cls(
159
+ total_items=int(data.get("total_items", len(results))),
160
+ total_execution_time_ms=float(data.get("total_execution_time_ms", 0.0)),
161
+ results=results,
162
+ raw=data,
163
+ )
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class UsernameValidationResult:
168
+ """Structured result for username validation."""
169
+
170
+ valid: bool
171
+ reasons: List[str]
172
+ sanitized: str
173
+ execution_time_ms: float
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class HealthResponse:
178
+ """Edge health check response."""
179
+
180
+ status: str
181
+ service: str
182
+
183
+ @classmethod
184
+ def from_dict(cls, data: dict[str, Any]) -> HealthResponse:
185
+ return cls(
186
+ status=str(data.get("status", "unknown")),
187
+ service=str(data.get("service", "unknown")),
188
+ )