vigimod 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vigimod/__init__.py +18 -0
- vigimod/_version.py +1 -0
- vigimod/aio.py +27 -0
- vigimod/client.py +139 -0
- vigimod/py.typed +0 -0
- vigimod/types.py +35 -0
- vigimod-0.1.0.dist-info/METADATA +120 -0
- vigimod-0.1.0.dist-info/RECORD +10 -0
- vigimod-0.1.0.dist-info/WHEEL +4 -0
- vigimod-0.1.0.dist-info/licenses/LICENSE +16 -0
vigimod/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Official Python client for the VigiMod content moderation API (https://www.vigimod.com).
|
|
2
|
+
|
|
3
|
+
from vigimod import VigiMod
|
|
4
|
+
|
|
5
|
+
client = VigiMod() # reads VIGIMOD_API_KEY
|
|
6
|
+
result = client.moderate("you are an idiot", categories=["toxic", "insult"])
|
|
7
|
+
if result.flagged:
|
|
8
|
+
print(result.flags, result.scores)
|
|
9
|
+
|
|
10
|
+
In asyncio code (discord.py, FastAPI) use AsyncVigiMod: the same methods, awaitable.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from .aio import AsyncVigiMod
|
|
14
|
+
from .client import APIError, RateLimitError, VigiMod, VigiModError
|
|
15
|
+
from .types import ModerationResult
|
|
16
|
+
|
|
17
|
+
__all__ = ["VigiMod", "AsyncVigiMod", "ModerationResult", "VigiModError", "APIError", "RateLimitError"]
|
|
18
|
+
from ._version import VERSION as __version__
|
vigimod/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
VERSION = "0.1.0"
|
vigimod/aio.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any, Iterable, Mapping
|
|
5
|
+
|
|
6
|
+
from .client import DEFAULT_BASE_URL, VigiMod
|
|
7
|
+
from .types import ModerationResult
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AsyncVigiMod:
|
|
11
|
+
"""The same client for asyncio code (discord.py, FastAPI, aiohttp bots): every method is awaitable and runs the
|
|
12
|
+
request in a worker thread, so the event loop never blocks. Same arguments as VigiMod."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2):
|
|
15
|
+
self._sync = VigiMod(api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
|
|
16
|
+
|
|
17
|
+
async def moderate(self, text: str, **options: Any) -> ModerationResult:
|
|
18
|
+
return await asyncio.to_thread(self._sync.moderate, text, **options)
|
|
19
|
+
|
|
20
|
+
async def moderate_batch(self, items: Iterable[Mapping[str, Any] | str]) -> list[ModerationResult]:
|
|
21
|
+
return await asyncio.to_thread(self._sync.moderate_batch, list(items))
|
|
22
|
+
|
|
23
|
+
async def events(self, after: int = 0, limit: int = 100) -> dict[str, Any]:
|
|
24
|
+
return await asyncio.to_thread(self._sync.events, after, limit)
|
|
25
|
+
|
|
26
|
+
async def status(self) -> dict[str, Any]:
|
|
27
|
+
return await asyncio.to_thread(self._sync.status)
|
vigimod/client.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Iterable, Mapping
|
|
10
|
+
|
|
11
|
+
from .types import ModerationResult
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://api.vigimod.com"
|
|
14
|
+
from . import _version
|
|
15
|
+
|
|
16
|
+
_USER_AGENT = f"vigimod-python/{_version.VERSION}"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class VigiModError(Exception):
|
|
20
|
+
"""Base error of this package."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class APIError(VigiModError):
|
|
24
|
+
"""The API answered with an error (4xx or 5xx)."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, status: int, message: str, body: Any = None):
|
|
27
|
+
super().__init__(f"{status}: {message}")
|
|
28
|
+
self.status = status
|
|
29
|
+
self.body = body
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RateLimitError(APIError):
|
|
33
|
+
"""429: too many messages for this key. retry_after is in seconds, when the API says it."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, status: int, message: str, body: Any = None, retry_after: float | None = None):
|
|
36
|
+
super().__init__(status, message, body)
|
|
37
|
+
self.retry_after = retry_after
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class VigiMod:
|
|
41
|
+
"""Client for the VigiMod API.
|
|
42
|
+
|
|
43
|
+
api_key: your key (default: the VIGIMOD_API_KEY environment variable). Create one at https://my.vigimod.com.
|
|
44
|
+
base_url: the API address (default https://api.vigimod.com).
|
|
45
|
+
timeout: seconds per request.
|
|
46
|
+
max_retries: retries on 429 and 5xx answers and on network errors, with a growing pause.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2):
|
|
50
|
+
key = api_key or os.environ.get("VIGIMOD_API_KEY")
|
|
51
|
+
if not key:
|
|
52
|
+
raise VigiModError("No API key: pass api_key=... or set VIGIMOD_API_KEY (get one free at https://my.vigimod.com)")
|
|
53
|
+
self._key = key
|
|
54
|
+
self.base_url = base_url.rstrip("/")
|
|
55
|
+
self.timeout = timeout
|
|
56
|
+
self.max_retries = max_retries
|
|
57
|
+
|
|
58
|
+
# ---- endpoints ----
|
|
59
|
+
|
|
60
|
+
def moderate(self, text: str, *, categories: Iterable[str] | None = None, rules: Mapping[str, Any] | None = None,
|
|
61
|
+
context: Iterable[str] | None = None, thresholds: Mapping[str, float] | None = None,
|
|
62
|
+
user_id: str | None = None, scope: str | None = None, block_slurs: bool | None = None,
|
|
63
|
+
policy: str | None = None, ref: str | None = None) -> ModerationResult:
|
|
64
|
+
"""Score one message. Every argument but text is optional; see https://www.vigimod.com/en/docs."""
|
|
65
|
+
body = _clean({"text": text, "categories": _list(categories), "rules": _dict(rules), "context": _list(context),
|
|
66
|
+
"thresholds": _dict(thresholds), "user_id": user_id, "scope": scope, "block_slurs": block_slurs,
|
|
67
|
+
"policy": policy, "ref": ref})
|
|
68
|
+
return ModerationResult.from_json(self._request("POST", "/moderate", body))
|
|
69
|
+
|
|
70
|
+
def moderate_batch(self, items: Iterable[Mapping[str, Any] | str]) -> list[ModerationResult]:
|
|
71
|
+
"""Score several messages in one call. Each item is a text or a dict with the same fields as moderate()."""
|
|
72
|
+
payload = [{"text": i} if isinstance(i, str) else _clean(dict(i)) for i in items]
|
|
73
|
+
data = self._request("POST", "/moderate/batch", {"items": payload})
|
|
74
|
+
return [ModerationResult.from_json(r) for r in data.get("results", [])]
|
|
75
|
+
|
|
76
|
+
def events(self, after: int = 0, limit: int = 100) -> dict[str, Any]:
|
|
77
|
+
"""The account's events of the last 7 days (the same as the webhooks), oldest first."""
|
|
78
|
+
return self._request("GET", "/events?" + urllib.parse.urlencode({"after": after, "limit": limit}))
|
|
79
|
+
|
|
80
|
+
def status(self) -> dict[str, Any]:
|
|
81
|
+
"""The model version, its categories and what the options support."""
|
|
82
|
+
return self._request("GET", "/status")
|
|
83
|
+
|
|
84
|
+
# ---- transport ----
|
|
85
|
+
|
|
86
|
+
def _request(self, method: str, path: str, body: Any = None) -> Any:
|
|
87
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
88
|
+
headers = {"X-API-Key": self._key, "Accept": "application/json", "User-Agent": _USER_AGENT}
|
|
89
|
+
if data is not None:
|
|
90
|
+
headers["Content-Type"] = "application/json"
|
|
91
|
+
attempt = 0
|
|
92
|
+
while True:
|
|
93
|
+
req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
|
|
94
|
+
try:
|
|
95
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
96
|
+
return json.loads(res.read() or b"null")
|
|
97
|
+
except urllib.error.HTTPError as e:
|
|
98
|
+
err = _error(e)
|
|
99
|
+
if attempt < self.max_retries and (e.code == 429 or e.code >= 500):
|
|
100
|
+
wait = err.retry_after if isinstance(err, RateLimitError) and err.retry_after else 0.5 * 2 ** attempt
|
|
101
|
+
time.sleep(min(wait, 30))
|
|
102
|
+
attempt += 1
|
|
103
|
+
continue
|
|
104
|
+
raise err from None
|
|
105
|
+
except (urllib.error.URLError, TimeoutError) as e:
|
|
106
|
+
if attempt < self.max_retries:
|
|
107
|
+
time.sleep(0.5 * 2 ** attempt)
|
|
108
|
+
attempt += 1
|
|
109
|
+
continue
|
|
110
|
+
raise VigiModError(f"Could not reach {self.base_url}: {e}") from e
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _error(e: urllib.error.HTTPError) -> APIError:
|
|
114
|
+
raw = e.read()
|
|
115
|
+
try:
|
|
116
|
+
body = json.loads(raw)
|
|
117
|
+
except ValueError:
|
|
118
|
+
body = raw.decode(errors="replace")
|
|
119
|
+
message = body.get("detail") or body.get("error") if isinstance(body, dict) else body
|
|
120
|
+
if e.code == 429:
|
|
121
|
+
ra = e.headers.get("Retry-After")
|
|
122
|
+
try:
|
|
123
|
+
retry = float(ra) if ra else None
|
|
124
|
+
except ValueError:
|
|
125
|
+
retry = None
|
|
126
|
+
return RateLimitError(e.code, str(message or "rate limited"), body, retry)
|
|
127
|
+
return APIError(e.code, str(message or e.reason), body)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _clean(d: dict[str, Any]) -> dict[str, Any]:
|
|
131
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _list(x: Iterable[str] | None) -> list[str] | None:
|
|
135
|
+
return None if x is None else list(x)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _dict(x: Mapping[str, Any] | None) -> dict[str, Any] | None:
|
|
139
|
+
return None if x is None else dict(x)
|
vigimod/py.typed
ADDED
|
File without changes
|
vigimod/types.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class ModerationResult:
|
|
9
|
+
"""The answer for one message.
|
|
10
|
+
|
|
11
|
+
scores: 0 to 1 per category and per rule ("rule:<name>"); spam is None without user_id.
|
|
12
|
+
flags: True where the score passed its threshold.
|
|
13
|
+
flagged: True if any category or rule is flagged.
|
|
14
|
+
raw: the full JSON answer (spam_info, blocklist_matches, policy, action, ref, review_id, model_version).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
scores: dict[str, float | None]
|
|
18
|
+
flags: dict[str, bool]
|
|
19
|
+
flagged: bool
|
|
20
|
+
raw: dict[str, Any] = field(repr=False)
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def action(self) -> str | None:
|
|
24
|
+
"""The policy action decided for this message (e.g. "review", "delete", "warn", "timeout", "ban"), if any."""
|
|
25
|
+
a = self.raw.get("action")
|
|
26
|
+
return a.get("type") if isinstance(a, dict) else a
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def model_version(self) -> str | None:
|
|
30
|
+
return self.raw.get("model_version")
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_json(cls, data: dict[str, Any]) -> "ModerationResult":
|
|
34
|
+
return cls(scores=dict(data.get("scores") or {}), flags=dict(data.get("flags") or {}),
|
|
35
|
+
flagged=bool(data.get("flagged")), raw=data)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: vigimod
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the VigiMod content moderation API: toxicity, hate, spam and custom rules in 26 languages.
|
|
5
|
+
Project-URL: Homepage, https://www.vigimod.com
|
|
6
|
+
Project-URL: Documentation, https://www.vigimod.com/en/docs
|
|
7
|
+
Project-URL: API reference, https://api.vigimod.com/openapi.json
|
|
8
|
+
Author-email: VigiMod <support@vigimod.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: chat moderation,content moderation,discord,hate speech,moderation,perspective api,profanity,spam,toxicity
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Communications :: Chat
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# VigiMod for Python
|
|
23
|
+
|
|
24
|
+
Official Python client for the [VigiMod](https://www.vigimod.com) content moderation API: toxicity, insults, hate, threats, sexual content, self-harm, advertising and per-user spam, plus rules you write in plain language, reading the conversation, in 26 languages. No dependencies.
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install vigimod
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Get a free API key (free during the beta) at [my.vigimod.com](https://my.vigimod.com) and set `VIGIMOD_API_KEY`.
|
|
31
|
+
|
|
32
|
+
## Moderate a message
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from vigimod import VigiMod
|
|
36
|
+
|
|
37
|
+
client = VigiMod() # reads VIGIMOD_API_KEY
|
|
38
|
+
|
|
39
|
+
result = client.moderate("you are an idiot", categories=["toxic", "insult"])
|
|
40
|
+
result.flagged # True
|
|
41
|
+
result.flags # {"toxic": True, "insult": True}
|
|
42
|
+
result.scores["toxic"] # 0.9999
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## In a Discord bot (asyncio)
|
|
46
|
+
|
|
47
|
+
`AsyncVigiMod` has the same methods, awaitable, so the bot never blocks:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import discord
|
|
51
|
+
from vigimod import AsyncVigiMod
|
|
52
|
+
|
|
53
|
+
vigimod = AsyncVigiMod()
|
|
54
|
+
intents = discord.Intents.default()
|
|
55
|
+
intents.message_content = True
|
|
56
|
+
bot = discord.Client(intents=intents)
|
|
57
|
+
|
|
58
|
+
@bot.event
|
|
59
|
+
async def on_message(message):
|
|
60
|
+
if message.author.bot:
|
|
61
|
+
return
|
|
62
|
+
result = await vigimod.moderate(
|
|
63
|
+
message.content,
|
|
64
|
+
user_id=str(message.author.id), # per-user spam score
|
|
65
|
+
scope=str(message.guild.id), # one spam history per server
|
|
66
|
+
rules={"no-ads": "No advertising other Discord servers"},
|
|
67
|
+
)
|
|
68
|
+
if result.flagged:
|
|
69
|
+
await message.delete()
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Context and your own rules
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
result = client.moderate(
|
|
76
|
+
"lmao the dog dies at the end",
|
|
77
|
+
context=["anyone watched the finale last night?", "not yet, tonight!"],
|
|
78
|
+
rules={"no-spoilers": "No spoilers about movies or series"},
|
|
79
|
+
)
|
|
80
|
+
result.flags["rule:no-spoilers"] # True
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Per-user spam, slurs and policies
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
client.moderate(text, user_id=author_id, scope=server_id) # spam score from repeated messages
|
|
87
|
+
client.moderate(text, block_slurs=True) # slur lists in six languages
|
|
88
|
+
client.moderate(text, policy="pol_0123456789abcdef") # a policy made in the dashboard
|
|
89
|
+
result.action # "review", "delete", "warn", "timeout" or "ban"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Many messages at once
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
results = client.moderate_batch(["first message", {"text": "second", "categories": ["hate"]}])
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Errors and limits
|
|
99
|
+
|
|
100
|
+
`RateLimitError` (429) and server errors are retried twice with a pause; after that the error is raised. `APIError` has `.status` and `.body`.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from vigimod import RateLimitError
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
client.moderate(text)
|
|
107
|
+
except RateLimitError as e:
|
|
108
|
+
print("slow down, retry in", e.retry_after)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Coming from Perspective API?
|
|
112
|
+
|
|
113
|
+
VigiMod also answers Perspective's `comments:analyze` requests: change the host and the key. See the [migration guide](https://www.vigimod.com/en/perspective-api-alternative).
|
|
114
|
+
|
|
115
|
+
## Links
|
|
116
|
+
|
|
117
|
+
- [Documentation](https://www.vigimod.com/en/docs) · [Pricing](https://www.vigimod.com/en/pricing) · [Benchmark](https://www.vigimod.com/en/benchmark) · [Free toxicity checker](https://www.vigimod.com/en/tools/toxicity-checker)
|
|
118
|
+
- Questions: support@vigimod.com
|
|
119
|
+
|
|
120
|
+
MIT licence.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
vigimod/__init__.py,sha256=Sxytvv_gNtXVG5N8ZHKXTD7TlSUDx9jEveO_HF53pCk,716
|
|
2
|
+
vigimod/_version.py,sha256=CpXi3jGlx23RvRyU7iytOMZrnspdWw4yofS8lpP1AJU,18
|
|
3
|
+
vigimod/aio.py,sha256=g0fEReydmf9b_G1PZkTY8_uAwD64zuhQH0lu9bMRPT4,1239
|
|
4
|
+
vigimod/client.py,sha256=frzENPYxBcNi_Vl6XjFEmXj_PTNDoVlghhOco0OaRWY,5962
|
|
5
|
+
vigimod/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
vigimod/types.py,sha256=5TEFU9W5-7nGqQuTRHNMV1y8ccLnni_tefU-E_EX7to,1240
|
|
7
|
+
vigimod-0.1.0.dist-info/METADATA,sha256=wkgXbmTEGFztxU_z9mhGZAktwVh9FDWY_6nWJ03dcJ4,4064
|
|
8
|
+
vigimod-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
vigimod-0.1.0.dist-info/licenses/LICENSE,sha256=QTxZjEC1Qe4oT0pIDze0eUWiF3-nvFHeaTXrJY2AEQA,1064
|
|
10
|
+
vigimod-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VigiMod
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
6
|
+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
|
7
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
|
8
|
+
persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
11
|
+
Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
14
|
+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
15
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
16
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|