silentguard-ml 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- silentguard_ml-0.1.0/PKG-INFO +23 -0
- silentguard_ml-0.1.0/README.md +13 -0
- silentguard_ml-0.1.0/pyproject.toml +11 -0
- silentguard_ml-0.1.0/setup.cfg +4 -0
- silentguard_ml-0.1.0/src/silentguard/__init__.py +15 -0
- silentguard_ml-0.1.0/src/silentguard/features.py +39 -0
- silentguard_ml-0.1.0/src/silentguard/guard.py +163 -0
- silentguard_ml-0.1.0/src/silentguard/model.py +82 -0
- silentguard_ml-0.1.0/src/silentguard/rules.py +23 -0
- silentguard_ml-0.1.0/src/silentguard/types.py +16 -0
- silentguard_ml-0.1.0/src/silentguard/vectorizer.py +51 -0
- silentguard_ml-0.1.0/src/silentguard_ml.egg-info/PKG-INFO +23 -0
- silentguard_ml-0.1.0/src/silentguard_ml.egg-info/SOURCES.txt +18 -0
- silentguard_ml-0.1.0/src/silentguard_ml.egg-info/dependency_links.txt +1 -0
- silentguard_ml-0.1.0/src/silentguard_ml.egg-info/top_level.txt +1 -0
- silentguard_ml-0.1.0/tests/test_features.py +33 -0
- silentguard_ml-0.1.0/tests/test_guard.py +97 -0
- silentguard_ml-0.1.0/tests/test_model.py +81 -0
- silentguard_ml-0.1.0/tests/test_rules.py +53 -0
- silentguard_ml-0.1.0/tests/test_vectorizer.py +54 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: silentguard-ml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency two-gate spam and bot detection library built from scratch in Python.
|
|
5
|
+
Author: Aimal Khan
|
|
6
|
+
Project-URL: Homepage, https://github.com/aiimallkhann/silentguard
|
|
7
|
+
Project-URL: Demo, https://silentguard-black.vercel.app/docs
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# SilentGuard
|
|
12
|
+
|
|
13
|
+
Zero-dependency, offline Python spam and bot detection library built from first principles.
|
|
14
|
+
|
|
15
|
+
SilentGuard filters form submissions locally without CAPTCHAs or external API calls using a two-gate pipeline:
|
|
16
|
+
|
|
17
|
+
1. **Gate 1 — Deterministic Hard Rules (`rules.py`):** Blocks empty payloads, filled honeypot fields, and impossibly fast bot submissions in microseconds.
|
|
18
|
+
2. **Gate 2 — Local ML Engine (`features.py` + `vectorizer.py` + `model.py`):** Combines lexical signals (uppercase ratio, URL count, max character repetition, Shannon entropy) with a sparse pure-Python TF-IDF vectorizer and L2-regularized Logistic Regression to return a calibrated probability and actionable decision (`allow`, `review`, or `block`).
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install -e .
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# SilentGuard
|
|
2
|
+
|
|
3
|
+
Zero-dependency, offline Python spam and bot detection library built from first principles.
|
|
4
|
+
|
|
5
|
+
SilentGuard filters form submissions locally without CAPTCHAs or external API calls using a two-gate pipeline:
|
|
6
|
+
|
|
7
|
+
1. **Gate 1 — Deterministic Hard Rules (`rules.py`):** Blocks empty payloads, filled honeypot fields, and impossibly fast bot submissions in microseconds.
|
|
8
|
+
2. **Gate 2 — Local ML Engine (`features.py` + `vectorizer.py` + `model.py`):** Combines lexical signals (uppercase ratio, URL count, max character repetition, Shannon entropy) with a sparse pure-Python TF-IDF vectorizer and L2-regularized Logistic Regression to return a calibrated probability and actionable decision (`allow`, `review`, or `block`).
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install -e .
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "silentguard-ml"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Zero-dependency two-gate spam and bot detection library built from scratch in Python."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
authors = [{ name = "Aimal Khan" }]
|
|
8
|
+
|
|
9
|
+
[project.urls]
|
|
10
|
+
Homepage = "https://github.com/aiimallkhann/silentguard"
|
|
11
|
+
Demo = "https://silentguard-black.vercel.app/docs"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from silentguard.features import extract_features
|
|
2
|
+
from silentguard.guard import SilentGuard
|
|
3
|
+
from silentguard.model import LogisticRegression
|
|
4
|
+
from silentguard.rules import check_hard_rules
|
|
5
|
+
from silentguard.types import CheckResult
|
|
6
|
+
from silentguard.vectorizer import TfidfVectorizer
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"CheckResult",
|
|
10
|
+
"LogisticRegression",
|
|
11
|
+
"SilentGuard",
|
|
12
|
+
"TfidfVectorizer",
|
|
13
|
+
"check_hard_rules",
|
|
14
|
+
"extract_features",
|
|
15
|
+
]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import math
|
|
3
|
+
|
|
4
|
+
URL_PATTERN = re.compile(r'(?:https?://|www\.)\S+', re.IGNORECASE)
|
|
5
|
+
|
|
6
|
+
def extract_features(text: str) -> dict[str, float]:
|
|
7
|
+
url_count = len(URL_PATTERN.findall(text))
|
|
8
|
+
url_count = float(url_count)
|
|
9
|
+
letter_char, uppercase_count = 0, 0
|
|
10
|
+
prev_char = None
|
|
11
|
+
current_repeat, max_repeat = 0, 0
|
|
12
|
+
|
|
13
|
+
char_counts: dict[str, int] = {}
|
|
14
|
+
|
|
15
|
+
for char in text:
|
|
16
|
+
if char.isalpha():
|
|
17
|
+
letter_char += 1
|
|
18
|
+
if char.isupper():
|
|
19
|
+
uppercase_count += 1
|
|
20
|
+
if char == prev_char:
|
|
21
|
+
current_repeat += 1
|
|
22
|
+
else:
|
|
23
|
+
current_repeat = 1
|
|
24
|
+
prev_char = char
|
|
25
|
+
char_counts[char] = char_counts.get(char, 0) + 1
|
|
26
|
+
max_repeat = max(max_repeat, current_repeat)
|
|
27
|
+
total_chars = len(text)
|
|
28
|
+
char_entropy = 0.0
|
|
29
|
+
if total_chars > 0:
|
|
30
|
+
for count in char_counts.values():
|
|
31
|
+
p = count / total_chars
|
|
32
|
+
char_entropy -= p * math.log2(p)
|
|
33
|
+
uppercase_ratio = uppercase_count / letter_char if letter_char else 0.0
|
|
34
|
+
return {
|
|
35
|
+
'uppercase_ratio': uppercase_ratio,
|
|
36
|
+
'url_count': url_count,
|
|
37
|
+
'max_char_repeat': float(max_repeat),
|
|
38
|
+
'char_entropy': char_entropy
|
|
39
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from silentguard.features import extract_features
|
|
6
|
+
from silentguard.model import LogisticRegression
|
|
7
|
+
from silentguard.rules import check_hard_rules
|
|
8
|
+
from silentguard.types import CheckResult
|
|
9
|
+
from silentguard.vectorizer import TfidfVectorizer
|
|
10
|
+
|
|
11
|
+
class SilentGuard:
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
review_threshold: float = 0.4,
|
|
15
|
+
block_threshold: float = 0.7,
|
|
16
|
+
min_elapsed_ms: int = 500,
|
|
17
|
+
learning_rate: float = 0.5,
|
|
18
|
+
epochs: int = 200,
|
|
19
|
+
l2: float = 1e-4
|
|
20
|
+
) -> None:
|
|
21
|
+
if not 0.0 <= review_threshold <= block_threshold <= 1.0:
|
|
22
|
+
raise ValueError("Thresholds must satisfy 0.0 <= review_threshold <= block_threshold <= 1.0")
|
|
23
|
+
if min_elapsed_ms < 0:
|
|
24
|
+
raise ValueError("min_elapsed_ms must be non-negative")
|
|
25
|
+
self.review_threshold = review_threshold
|
|
26
|
+
self.block_threshold = block_threshold
|
|
27
|
+
self.min_elapsed_ms = min_elapsed_ms
|
|
28
|
+
self.vectorizer = TfidfVectorizer()
|
|
29
|
+
self.model = LogisticRegression(
|
|
30
|
+
learning_rate=learning_rate,
|
|
31
|
+
epochs=epochs,
|
|
32
|
+
l2=l2,
|
|
33
|
+
)
|
|
34
|
+
self._fitted = False
|
|
35
|
+
|
|
36
|
+
def _combine(
|
|
37
|
+
self,
|
|
38
|
+
tfidf_vec: dict[int, float],
|
|
39
|
+
feats: dict[str, float],
|
|
40
|
+
) -> dict[int, float]:
|
|
41
|
+
combined = dict(tfidf_vec)
|
|
42
|
+
offset = len(self.vectorizer.vocab)
|
|
43
|
+
scaled = (
|
|
44
|
+
feats["uppercase_ratio"],
|
|
45
|
+
min(feats["url_count"], 5.0) / 5.0,
|
|
46
|
+
min(feats["max_char_repeat"], 10.0) / 10.0,
|
|
47
|
+
min(feats["char_entropy"], 6.0) / 6.0,
|
|
48
|
+
)
|
|
49
|
+
for i, val in enumerate(scaled):
|
|
50
|
+
if val != 0.0:
|
|
51
|
+
combined[offset + i] = val
|
|
52
|
+
return combined
|
|
53
|
+
|
|
54
|
+
def _reasons(
|
|
55
|
+
self,
|
|
56
|
+
tfidf_vec: dict[int, float],
|
|
57
|
+
feats: dict[str, float],
|
|
58
|
+
action: str,
|
|
59
|
+
) -> tuple[str, ...]:
|
|
60
|
+
if action == "allow":
|
|
61
|
+
return ()
|
|
62
|
+
|
|
63
|
+
reasons: list[str] = []
|
|
64
|
+
if feats["url_count"] >= 1.0:
|
|
65
|
+
reasons.append("contains_url")
|
|
66
|
+
if feats["uppercase_ratio"] >= 0.6:
|
|
67
|
+
reasons.append("high_uppercase")
|
|
68
|
+
if feats["max_char_repeat"] >= 4.0:
|
|
69
|
+
reasons.append("repeated_chars")
|
|
70
|
+
|
|
71
|
+
idx_to_token = {idx: tok for tok, idx in self.vectorizer.vocab.items()}
|
|
72
|
+
contributions = [
|
|
73
|
+
(self.model.weights.get(idx, 0.0) * val, idx_to_token[idx])
|
|
74
|
+
for idx, val in tfidf_vec.items()
|
|
75
|
+
if self.model.weights.get(idx, 0.0) * val > 0.0
|
|
76
|
+
]
|
|
77
|
+
contributions.sort(reverse=True)
|
|
78
|
+
for _, token in contributions[:3]:
|
|
79
|
+
reasons.append(f"token:{token}")
|
|
80
|
+
|
|
81
|
+
if not reasons:
|
|
82
|
+
reasons.append("ml_spam_score")
|
|
83
|
+
|
|
84
|
+
return tuple(reasons)
|
|
85
|
+
|
|
86
|
+
def fit(self, texts: list[str], labels: list[int]) -> "SilentGuard":
|
|
87
|
+
if not texts or len(texts) != len(labels):
|
|
88
|
+
raise ValueError("texts and labels must be non-empty and have the same length")
|
|
89
|
+
|
|
90
|
+
tfidf_vectors = self.vectorizer.fit_transform(texts)
|
|
91
|
+
combined_vectors = [
|
|
92
|
+
self._combine(vec, extract_features(text))
|
|
93
|
+
for vec, text in zip(tfidf_vectors, texts)
|
|
94
|
+
]
|
|
95
|
+
self.model.fit(combined_vectors, labels)
|
|
96
|
+
self._fitted = True
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
def check(
|
|
100
|
+
self,
|
|
101
|
+
text: str,
|
|
102
|
+
elapsed_ms: int | None = None,
|
|
103
|
+
honeypot: str = "",
|
|
104
|
+
) -> CheckResult:
|
|
105
|
+
if not self._fitted:
|
|
106
|
+
raise RuntimeError("SilentGuard must be fitted or loaded before calling check()")
|
|
107
|
+
|
|
108
|
+
rule_kwargs: dict[str, Any] = {
|
|
109
|
+
"honeypot": honeypot,
|
|
110
|
+
"min_elapsed_ms": self.min_elapsed_ms,
|
|
111
|
+
}
|
|
112
|
+
if elapsed_ms is not None:
|
|
113
|
+
rule_kwargs["elapsed_ms"] = elapsed_ms
|
|
114
|
+
|
|
115
|
+
hard_result = check_hard_rules(text, **rule_kwargs)
|
|
116
|
+
if hard_result is not None:
|
|
117
|
+
return hard_result
|
|
118
|
+
|
|
119
|
+
tfidf_vec = self.vectorizer.transform([text])[0]
|
|
120
|
+
feats = extract_features(text)
|
|
121
|
+
combined = self._combine(tfidf_vec, feats)
|
|
122
|
+
score = self.model.predict_proba_one(combined)
|
|
123
|
+
|
|
124
|
+
if score >= self.block_threshold:
|
|
125
|
+
action = "block"
|
|
126
|
+
elif score >= self.review_threshold:
|
|
127
|
+
action = "review"
|
|
128
|
+
else:
|
|
129
|
+
action = "allow"
|
|
130
|
+
|
|
131
|
+
return CheckResult(
|
|
132
|
+
score=score,
|
|
133
|
+
action=action,
|
|
134
|
+
reasons=self._reasons(tfidf_vec, feats, action),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def save(self, path: str | Path) -> None:
|
|
138
|
+
if not self._fitted:
|
|
139
|
+
raise RuntimeError("Cannot save an unfitted SilentGuard")
|
|
140
|
+
|
|
141
|
+
payload = {
|
|
142
|
+
"review_threshold": self.review_threshold,
|
|
143
|
+
"block_threshold": self.block_threshold,
|
|
144
|
+
"min_elapsed_ms": self.min_elapsed_ms,
|
|
145
|
+
"vocab": self.vectorizer.vocab,
|
|
146
|
+
"idf": self.vectorizer.idf,
|
|
147
|
+
"model": self.model.to_dict(),
|
|
148
|
+
}
|
|
149
|
+
Path(path).write_text(json.dumps(payload), encoding="utf-8")
|
|
150
|
+
|
|
151
|
+
@classmethod
|
|
152
|
+
def load(cls, path: str | Path) -> "SilentGuard":
|
|
153
|
+
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
154
|
+
guard = cls(
|
|
155
|
+
review_threshold=float(payload["review_threshold"]),
|
|
156
|
+
block_threshold=float(payload["block_threshold"]),
|
|
157
|
+
min_elapsed_ms=int(payload["min_elapsed_ms"]),
|
|
158
|
+
)
|
|
159
|
+
guard.vectorizer.vocab = {str(k): int(v) for k, v in payload["vocab"].items()}
|
|
160
|
+
guard.vectorizer.idf = {str(k): float(v) for k, v in payload["idf"].items()}
|
|
161
|
+
guard.model = LogisticRegression.from_dict(payload["model"])
|
|
162
|
+
guard._fitted = True
|
|
163
|
+
return guard
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
def sigmoid (z: float) -> float:
|
|
5
|
+
if z >= 0:
|
|
6
|
+
return 1.0/(1.0 + math.exp(-z))
|
|
7
|
+
exp_z = math.exp(z)
|
|
8
|
+
return exp_z / (1.0 + exp_z)
|
|
9
|
+
|
|
10
|
+
class LogisticRegression:
|
|
11
|
+
def __init__(self, learning_rate: float = 0.5, epochs: int = 200, l2: float = 1e-4):
|
|
12
|
+
if learning_rate <= 0:
|
|
13
|
+
raise ValueError("Learning rate must be positive")
|
|
14
|
+
if epochs <= 0:
|
|
15
|
+
raise ValueError("Epochs must be positive")
|
|
16
|
+
if l2 < 0:
|
|
17
|
+
raise ValueError("L2 must be non-negative")
|
|
18
|
+
|
|
19
|
+
self.learning_rate = learning_rate
|
|
20
|
+
self.epochs = epochs
|
|
21
|
+
self.l2 = l2
|
|
22
|
+
self.weights: dict[int, float] = {}
|
|
23
|
+
self.bias: float = 0.0
|
|
24
|
+
|
|
25
|
+
def fit(self, X: list[dict[int, float]], y: list[int]) -> "LogisticRegression":
|
|
26
|
+
if not X or len(X) != len(y):
|
|
27
|
+
raise ValueError("X and y must be non-empty and have the same length")
|
|
28
|
+
if any(label not in (0, 1) for label in y):
|
|
29
|
+
raise ValueError("y must contain only 0 or 1")
|
|
30
|
+
|
|
31
|
+
feature_indices = {idx for row in X for idx in row}
|
|
32
|
+
self.weights = {idx: 0.0 for idx in feature_indices}
|
|
33
|
+
self.bias = 0.0
|
|
34
|
+
n = len(X)
|
|
35
|
+
|
|
36
|
+
for _ in range(self.epochs):
|
|
37
|
+
grad_w = {idx: 0.0 for idx in self.weights}
|
|
38
|
+
grad_b = 0.0
|
|
39
|
+
|
|
40
|
+
for row, label in zip(X, y):
|
|
41
|
+
error = self.predict_proba_one(row) - label
|
|
42
|
+
grad_b += error
|
|
43
|
+
for idx, val in row.items():
|
|
44
|
+
grad_w[idx] += error * val
|
|
45
|
+
|
|
46
|
+
self.bias -= self.learning_rate * (grad_b / n)
|
|
47
|
+
for idx in self.weights:
|
|
48
|
+
self.weights[idx] -= self.learning_rate * (
|
|
49
|
+
grad_w[idx] / n + self.l2 * self.weights[idx]
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
return self
|
|
53
|
+
|
|
54
|
+
def predict_proba_one (self, x: dict[int, float]) -> float:
|
|
55
|
+
z = self.bias
|
|
56
|
+
for idx, val in x.items():
|
|
57
|
+
z += self.weights.get(idx, 0.0) * val
|
|
58
|
+
return sigmoid(z)
|
|
59
|
+
def predict_proba (self, X: list[dict[int, float]]) -> list[float]:
|
|
60
|
+
return [self.predict_proba_one(x) for x in X]
|
|
61
|
+
def predict(self, X: list[dict[int, float]], threshold: float = 0.5) -> list[int]:
|
|
62
|
+
if not 0.0 <= threshold <= 1.0:
|
|
63
|
+
raise ValueError ("Threshold must be between 0.0 and 1.0")
|
|
64
|
+
return [1 if p >= threshold else 0 for p in self.predict_proba(X)]
|
|
65
|
+
def to_dict (self) -> dict[str, any]:
|
|
66
|
+
return {
|
|
67
|
+
'learning_rate': self.learning_rate,
|
|
68
|
+
'epochs': self.epochs,
|
|
69
|
+
'l2': self.l2,
|
|
70
|
+
'bias': self.bias,
|
|
71
|
+
'weights': {str(idx): weight for idx, weight in sorted(self.weights.items())},
|
|
72
|
+
}
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_dict(cls, data: dict[str, Any]) -> 'LogisticRegression':
|
|
75
|
+
model = cls(
|
|
76
|
+
learning_rate = float(data['learning_rate']),
|
|
77
|
+
epochs=int(data['epochs']),
|
|
78
|
+
l2=float(data['l2']),
|
|
79
|
+
)
|
|
80
|
+
model.bias = float(data['bias'])
|
|
81
|
+
model.weights = {int(k): float(v) for k, v in data['weights'].items()}
|
|
82
|
+
return model
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from silentguard.types import CheckResult
|
|
2
|
+
|
|
3
|
+
def check_hard_rules(
|
|
4
|
+
text: str,
|
|
5
|
+
elapsed_ms: int | None = None,
|
|
6
|
+
honeypot: str = '',
|
|
7
|
+
min_elapsed_ms: int = 500,
|
|
8
|
+
) -> CheckResult | None:
|
|
9
|
+
if elapsed_ms is not None and 0 > elapsed_ms:
|
|
10
|
+
raise ValueError(f'Elapsed ms {elapsed_ms} must be non-negative.')
|
|
11
|
+
if min_elapsed_ms < 0:
|
|
12
|
+
raise ValueError(f'Min Elapsed ms {min_elapsed_ms} must be non-negative.')
|
|
13
|
+
reasons: list[str] = []
|
|
14
|
+
if not text.strip():
|
|
15
|
+
reasons.append('empty_text')
|
|
16
|
+
if honeypot.strip():
|
|
17
|
+
reasons.append('honeypot_filled')
|
|
18
|
+
if elapsed_ms is not None and elapsed_ms < min_elapsed_ms:
|
|
19
|
+
reasons.append('submitted_too_fast')
|
|
20
|
+
if reasons:
|
|
21
|
+
return CheckResult(score=1.0, action='block', reasons=tuple(reasons))
|
|
22
|
+
|
|
23
|
+
return None
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
Action = Literal['allow', 'review', 'block']
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class CheckResult:
|
|
8
|
+
score: float
|
|
9
|
+
action: Action
|
|
10
|
+
reasons: tuple[str, ...] = ()
|
|
11
|
+
|
|
12
|
+
def __post_init__(self):
|
|
13
|
+
if not (0.0 <= self.score <= 1.0):
|
|
14
|
+
raise ValueError (f'Score must be between 0.0 and 1.0. {self.score}')
|
|
15
|
+
if self.action not in ('allow', 'review', 'block'):
|
|
16
|
+
raise ValueError(f'Invalid action: {self.action}')
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
import math
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
TOKEN_PATTERN = re.compile(r'[a-z0-9]+')
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def tokenize(text: str) -> list[str]:
|
|
9
|
+
return TOKEN_PATTERN.findall(text.lower())
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TfidfVectorizer:
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
self.vocab: dict[str, int] = {}
|
|
15
|
+
self.idf: dict[str, float] = {}
|
|
16
|
+
|
|
17
|
+
def fit(self, documents: list[str]) -> "TfidfVectorizer":
|
|
18
|
+
self.vocab = {}
|
|
19
|
+
self.idf = {}
|
|
20
|
+
n_docs = len(documents)
|
|
21
|
+
doc_freq: dict[str, int] = {}
|
|
22
|
+
|
|
23
|
+
for doc in documents:
|
|
24
|
+
for token in set(tokenize(doc)):
|
|
25
|
+
doc_freq[token] = doc_freq.get(token, 0) + 1
|
|
26
|
+
|
|
27
|
+
for idx, token in enumerate(sorted(doc_freq)):
|
|
28
|
+
self.vocab[token] = idx
|
|
29
|
+
self.idf[token] = math.log((1 + n_docs) / (1 + doc_freq[token])) + 1.0
|
|
30
|
+
|
|
31
|
+
return self
|
|
32
|
+
|
|
33
|
+
def transform(self, documents: list[str]) -> list[dict[int, float]]:
|
|
34
|
+
vectors: list[dict[int, float]] = []
|
|
35
|
+
|
|
36
|
+
for doc in documents:
|
|
37
|
+
counts = Counter(tokenize(doc))
|
|
38
|
+
weights = {
|
|
39
|
+
self.vocab[token]: count * self.idf[token]
|
|
40
|
+
for token, count in counts.items()
|
|
41
|
+
if token in self.vocab
|
|
42
|
+
}
|
|
43
|
+
norm = math.sqrt(sum(val * val for val in weights.values()))
|
|
44
|
+
if norm > 0:
|
|
45
|
+
weights = {idx: val / norm for idx, val in weights.items()}
|
|
46
|
+
vectors.append(weights)
|
|
47
|
+
|
|
48
|
+
return vectors
|
|
49
|
+
|
|
50
|
+
def fit_transform(self, documents: list[str]) -> list[dict[int, float]]:
|
|
51
|
+
return self.fit(documents).transform(documents)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: silentguard-ml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency two-gate spam and bot detection library built from scratch in Python.
|
|
5
|
+
Author: Aimal Khan
|
|
6
|
+
Project-URL: Homepage, https://github.com/aiimallkhann/silentguard
|
|
7
|
+
Project-URL: Demo, https://silentguard-black.vercel.app/docs
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# SilentGuard
|
|
12
|
+
|
|
13
|
+
Zero-dependency, offline Python spam and bot detection library built from first principles.
|
|
14
|
+
|
|
15
|
+
SilentGuard filters form submissions locally without CAPTCHAs or external API calls using a two-gate pipeline:
|
|
16
|
+
|
|
17
|
+
1. **Gate 1 — Deterministic Hard Rules (`rules.py`):** Blocks empty payloads, filled honeypot fields, and impossibly fast bot submissions in microseconds.
|
|
18
|
+
2. **Gate 2 — Local ML Engine (`features.py` + `vectorizer.py` + `model.py`):** Combines lexical signals (uppercase ratio, URL count, max character repetition, Shannon entropy) with a sparse pure-Python TF-IDF vectorizer and L2-regularized Logistic Regression to return a calibrated probability and actionable decision (`allow`, `review`, or `block`).
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install -e .
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/silentguard/__init__.py
|
|
4
|
+
src/silentguard/features.py
|
|
5
|
+
src/silentguard/guard.py
|
|
6
|
+
src/silentguard/model.py
|
|
7
|
+
src/silentguard/rules.py
|
|
8
|
+
src/silentguard/types.py
|
|
9
|
+
src/silentguard/vectorizer.py
|
|
10
|
+
src/silentguard_ml.egg-info/PKG-INFO
|
|
11
|
+
src/silentguard_ml.egg-info/SOURCES.txt
|
|
12
|
+
src/silentguard_ml.egg-info/dependency_links.txt
|
|
13
|
+
src/silentguard_ml.egg-info/top_level.txt
|
|
14
|
+
tests/test_features.py
|
|
15
|
+
tests/test_guard.py
|
|
16
|
+
tests/test_model.py
|
|
17
|
+
tests/test_rules.py
|
|
18
|
+
tests/test_vectorizer.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
silentguard
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from silentguard.features import extract_features
|
|
3
|
+
|
|
4
|
+
def test_empty_string():
|
|
5
|
+
result = extract_features('')
|
|
6
|
+
assert result == {
|
|
7
|
+
'uppercase_ratio': 0.0,
|
|
8
|
+
'url_count': 0.0,
|
|
9
|
+
'max_char_repeat': 0.0,
|
|
10
|
+
'char_entropy': 0.0,
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
def test_uppercase_ratio():
|
|
14
|
+
assert extract_features('HELLO123!!!')['uppercase_ratio'] == 1.0
|
|
15
|
+
assert extract_features('Hello')['uppercase_ratio'] == 0.2
|
|
16
|
+
assert extract_features('123!!!')['uppercase_ratio'] == 0.0
|
|
17
|
+
|
|
18
|
+
def test_url_count():
|
|
19
|
+
assert extract_features('http://a.com https://b.com www.c.com')['url_count'] == 3.0
|
|
20
|
+
assert extract_features('Visit HTTPS://SPAM.COM')['url_count'] == 1.0
|
|
21
|
+
assert extract_features('Wait...what?')['url_count'] == 0.0
|
|
22
|
+
|
|
23
|
+
def test_max_char_repeat():
|
|
24
|
+
assert extract_features('aaaa')['max_char_repeat'] == 4.0
|
|
25
|
+
assert extract_features('Hello')['max_char_repeat'] == 2.0
|
|
26
|
+
assert extract_features('A')['max_char_repeat'] == 1.0
|
|
27
|
+
assert extract_features('')['max_char_repeat'] == 0.0
|
|
28
|
+
assert extract_features('123!!!')['max_char_repeat'] == 3.0
|
|
29
|
+
|
|
30
|
+
def test_char_entropy():
|
|
31
|
+
assert extract_features('aaaa')['char_entropy'] == pytest.approx(0.0)
|
|
32
|
+
assert extract_features('abab')['char_entropy'] == pytest.approx(1.0)
|
|
33
|
+
assert extract_features('abcd')['char_entropy'] == pytest.approx(2.0)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from silentguard import SilentGuard
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
TRAIN_TEXTS = [
|
|
7
|
+
"BUY FREE CRYPTO NOW http://scam.com",
|
|
8
|
+
"CLICK HERE CLAIM FREE MONEY WINNER http://win.biz",
|
|
9
|
+
"URGENT FREE BITCOIN PRIZE CLAIM NOW http://bit.ly/x",
|
|
10
|
+
"LIMITED OFFER WIN FREE CASH http://cash.net",
|
|
11
|
+
"FREE BONUS CRYPTO INVESTMENT http://invest.io",
|
|
12
|
+
"Hi, can we reschedule our meeting to Tuesday?",
|
|
13
|
+
"Thanks for sending the project report yesterday.",
|
|
14
|
+
"Let me know when you are available for a quick call.",
|
|
15
|
+
"Here are the notes from our database class.",
|
|
16
|
+
"Could you review my pull request when you have time?",
|
|
17
|
+
]
|
|
18
|
+
TRAIN_LABELS = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_unfitted_guard_raises(tmp_path):
|
|
22
|
+
guard = SilentGuard()
|
|
23
|
+
with pytest.raises(RuntimeError):
|
|
24
|
+
guard.check("Hello")
|
|
25
|
+
with pytest.raises(RuntimeError):
|
|
26
|
+
guard.save(tmp_path / "model.json")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_invalid_config_raises():
|
|
30
|
+
with pytest.raises(ValueError):
|
|
31
|
+
SilentGuard(review_threshold=0.8, block_threshold=0.5)
|
|
32
|
+
with pytest.raises(ValueError):
|
|
33
|
+
SilentGuard(review_threshold=-0.1)
|
|
34
|
+
with pytest.raises(ValueError):
|
|
35
|
+
SilentGuard(block_threshold=1.1)
|
|
36
|
+
with pytest.raises(ValueError):
|
|
37
|
+
SilentGuard(min_elapsed_ms=-1)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_gate1_blocks_before_ml():
|
|
41
|
+
guard = SilentGuard().fit(TRAIN_TEXTS, TRAIN_LABELS)
|
|
42
|
+
|
|
43
|
+
empty = guard.check(" ", elapsed_ms=2000)
|
|
44
|
+
assert empty.action == "block"
|
|
45
|
+
assert empty.score == 1.0
|
|
46
|
+
assert "empty_text" in empty.reasons
|
|
47
|
+
|
|
48
|
+
bot = guard.check("Thanks for the meeting notes.", elapsed_ms=2000, honeypot="bot")
|
|
49
|
+
assert bot.action == "block"
|
|
50
|
+
assert "honeypot_filled" in bot.reasons
|
|
51
|
+
|
|
52
|
+
fast = guard.check("Thanks for the meeting notes.", elapsed_ms=100)
|
|
53
|
+
assert fast.action == "block"
|
|
54
|
+
assert "submitted_too_fast" in fast.reasons
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_gate2_blocks_spam_and_allows_ham():
|
|
58
|
+
guard = SilentGuard().fit(TRAIN_TEXTS, TRAIN_LABELS)
|
|
59
|
+
|
|
60
|
+
spam = guard.check("CLAIM FREE CRYPTO NOW http://spam.org", elapsed_ms=2500)
|
|
61
|
+
assert spam.action == "block"
|
|
62
|
+
assert spam.score >= guard.block_threshold
|
|
63
|
+
assert "contains_url" in spam.reasons
|
|
64
|
+
assert "high_uppercase" in spam.reasons
|
|
65
|
+
|
|
66
|
+
ham = guard.check("Thanks for the meeting notes about the project.", elapsed_ms=2500)
|
|
67
|
+
assert ham.action == "allow"
|
|
68
|
+
assert ham.score < guard.review_threshold
|
|
69
|
+
assert ham.reasons == ()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_review_zone():
|
|
73
|
+
guard = SilentGuard(review_threshold=0.4, block_threshold=0.7).fit(
|
|
74
|
+
["spam", "safe"], [1, 0]
|
|
75
|
+
)
|
|
76
|
+
result = guard.check("word", elapsed_ms=2000)
|
|
77
|
+
assert result.score == pytest.approx(0.5)
|
|
78
|
+
assert result.action == "review"
|
|
79
|
+
assert result.reasons == ("ml_spam_score",)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_save_and_load_roundtrip(tmp_path):
|
|
83
|
+
guard = SilentGuard().fit(TRAIN_TEXTS, TRAIN_LABELS)
|
|
84
|
+
model_path = tmp_path / "silentguard.json"
|
|
85
|
+
guard.save(model_path)
|
|
86
|
+
|
|
87
|
+
loaded = SilentGuard.load(model_path)
|
|
88
|
+
samples = [
|
|
89
|
+
"CLAIM FREE CRYPTO NOW http://spam.org",
|
|
90
|
+
"Thanks for sending the project report.",
|
|
91
|
+
]
|
|
92
|
+
for sample in samples:
|
|
93
|
+
orig = guard.check(sample, elapsed_ms=2000)
|
|
94
|
+
restored = loaded.check(sample, elapsed_ms=2000)
|
|
95
|
+
assert restored.action == orig.action
|
|
96
|
+
assert restored.score == pytest.approx(orig.score)
|
|
97
|
+
assert restored.reasons == orig.reasons
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
from silentguard.model import LogisticRegression, sigmoid
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_sigmoid_values_and_stability():
|
|
8
|
+
assert sigmoid(0.0) == pytest.approx(0.5)
|
|
9
|
+
assert sigmoid(1000.0) == pytest.approx(1.0)
|
|
10
|
+
assert sigmoid(-1000.0) == pytest.approx(0.0)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_fit_separates_spam_and_ham():
|
|
14
|
+
X = [
|
|
15
|
+
{0: 1.0},
|
|
16
|
+
{0: 0.9, 1: 0.2},
|
|
17
|
+
{2: 1.0},
|
|
18
|
+
{2: 0.8, 3: 0.5},
|
|
19
|
+
]
|
|
20
|
+
y = [1, 1, 0, 0]
|
|
21
|
+
|
|
22
|
+
model = LogisticRegression(learning_rate=0.5, epochs=200, l2=1e-4).fit(X, y)
|
|
23
|
+
probs = model.predict_proba(X)
|
|
24
|
+
|
|
25
|
+
assert probs[0] > 0.8
|
|
26
|
+
assert probs[1] > 0.8
|
|
27
|
+
assert probs[2] < 0.2
|
|
28
|
+
assert probs[3] < 0.2
|
|
29
|
+
assert model.predict(X) == y
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_unseen_and_empty_features():
|
|
33
|
+
model = LogisticRegression().fit([{0: 1.0}, {1: 1.0}], [1, 0])
|
|
34
|
+
baseline = sigmoid(model.bias)
|
|
35
|
+
|
|
36
|
+
assert model.predict_proba_one({}) == pytest.approx(baseline)
|
|
37
|
+
assert model.predict_proba_one({999: 5.0}) == pytest.approx(baseline)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_l2_regularization_shrinks_weights():
|
|
41
|
+
X = [{0: 1.0}, {1: 1.0}]
|
|
42
|
+
y = [1, 0]
|
|
43
|
+
|
|
44
|
+
unreg = LogisticRegression(learning_rate=0.5, epochs=200, l2=0.0).fit(X, y)
|
|
45
|
+
reg = LogisticRegression(learning_rate=0.5, epochs=200, l2=1.0).fit(X, y)
|
|
46
|
+
|
|
47
|
+
unreg_norm = sum(w * w for w in unreg.weights.values())
|
|
48
|
+
reg_norm = sum(w * w for w in reg.weights.values())
|
|
49
|
+
assert reg_norm < unreg_norm
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_json_roundtrip():
|
|
53
|
+
X = [{0: 1.0, 2: 0.5}, {1: 1.0}]
|
|
54
|
+
y = [1, 0]
|
|
55
|
+
|
|
56
|
+
model = LogisticRegression().fit(X, y)
|
|
57
|
+
raw_json = json.dumps(model.to_dict())
|
|
58
|
+
restored = LogisticRegression.from_dict(json.loads(raw_json))
|
|
59
|
+
|
|
60
|
+
assert restored.bias == pytest.approx(model.bias)
|
|
61
|
+
assert restored.weights == model.weights
|
|
62
|
+
assert restored.predict_proba(X) == pytest.approx(model.predict_proba(X))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_invalid_inputs():
|
|
66
|
+
with pytest.raises(ValueError):
|
|
67
|
+
LogisticRegression(learning_rate=0.0)
|
|
68
|
+
with pytest.raises(ValueError):
|
|
69
|
+
LogisticRegression(epochs=0)
|
|
70
|
+
with pytest.raises(ValueError):
|
|
71
|
+
LogisticRegression(l2=-0.1)
|
|
72
|
+
|
|
73
|
+
model = LogisticRegression()
|
|
74
|
+
with pytest.raises(ValueError):
|
|
75
|
+
model.fit([], [])
|
|
76
|
+
with pytest.raises(ValueError):
|
|
77
|
+
model.fit([{0: 1.0}], [1, 0])
|
|
78
|
+
with pytest.raises(ValueError):
|
|
79
|
+
model.fit([{0: 1.0}], [2])
|
|
80
|
+
with pytest.raises(ValueError):
|
|
81
|
+
model.predict([{0: 1.0}], threshold=1.5)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from silentguard.rules import check_hard_rules
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_whitespace_text_is_blocked():
|
|
7
|
+
result = check_hard_rules(' \t\n')
|
|
8
|
+
assert result is not None
|
|
9
|
+
assert result.action == 'block'
|
|
10
|
+
assert result.score == 1.0
|
|
11
|
+
assert 'empty_text' in result.reasons
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_clean_submission():
|
|
15
|
+
result = check_hard_rules('Hello, I have a question.', elapsed_ms=2000)
|
|
16
|
+
assert result is None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_honeypot_filled():
|
|
20
|
+
result = check_hard_rules('Hello, I have a question.', honeypot='http://bot.com')
|
|
21
|
+
assert result is not None
|
|
22
|
+
assert result.action == 'block'
|
|
23
|
+
assert result.score == 1.0
|
|
24
|
+
assert 'honeypot_filled' in result.reasons
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_timing_boundary():
|
|
28
|
+
too_fast = check_hard_rules('Hello, I have a question.', elapsed_ms=499)
|
|
29
|
+
assert too_fast is not None
|
|
30
|
+
assert too_fast.action == 'block'
|
|
31
|
+
assert too_fast.score == 1.0
|
|
32
|
+
assert 'submitted_too_fast' in too_fast.reasons
|
|
33
|
+
|
|
34
|
+
on_boundary = check_hard_rules('Hello, I have a question.', elapsed_ms=500)
|
|
35
|
+
assert on_boundary is None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_multiple_triggers():
|
|
39
|
+
result = check_hard_rules(' ', elapsed_ms=100, honeypot='bot')
|
|
40
|
+
assert result is not None
|
|
41
|
+
assert result.action == 'block'
|
|
42
|
+
assert result.score == 1.0
|
|
43
|
+
assert 'empty_text' in result.reasons
|
|
44
|
+
assert 'honeypot_filled' in result.reasons
|
|
45
|
+
assert 'submitted_too_fast' in result.reasons
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_invalid_inputs():
|
|
49
|
+
with pytest.raises(ValueError):
|
|
50
|
+
check_hard_rules('Hello.', elapsed_ms=-1)
|
|
51
|
+
|
|
52
|
+
with pytest.raises(ValueError):
|
|
53
|
+
check_hard_rules('Hello.', min_elapsed_ms=-1)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
from silentguard.vectorizer import TfidfVectorizer, tokenize
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_tokenize():
|
|
8
|
+
assert tokenize("Free Money! 2026") == ["free", "money", "2026"]
|
|
9
|
+
assert tokenize("don't stop") == ["don", "t", "stop"]
|
|
10
|
+
assert tokenize("") == []
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_fit_vocab_and_idf():
|
|
14
|
+
vec = TfidfVectorizer().fit(["free money now", "meeting now"])
|
|
15
|
+
assert vec.vocab == {"free": 0, "meeting": 1, "money": 2, "now": 3}
|
|
16
|
+
assert vec.idf["now"] == pytest.approx(1.0)
|
|
17
|
+
assert vec.idf["free"] == pytest.approx(math.log(3 / 2) + 1.0)
|
|
18
|
+
assert vec.idf["meeting"] == pytest.approx(math.log(3 / 2) + 1.0)
|
|
19
|
+
assert vec.idf["money"] == pytest.approx(math.log(3 / 2) + 1.0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_duplicate_tokens_do_not_inflate_df():
|
|
23
|
+
vec = TfidfVectorizer().fit(["free free free", "meeting"])
|
|
24
|
+
assert vec.idf["free"] == pytest.approx(math.log(3 / 2) + 1.0)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_transform_oov_and_l2_norm():
|
|
28
|
+
vec = TfidfVectorizer().fit(["free money now", "meeting now"])
|
|
29
|
+
vectors = vec.transform(["now free crypto now"])
|
|
30
|
+
assert len(vectors) == 1
|
|
31
|
+
|
|
32
|
+
v = vectors[0]
|
|
33
|
+
assert set(v.keys()) == {0, 3}
|
|
34
|
+
|
|
35
|
+
w0 = math.log(3 / 2) + 1.0
|
|
36
|
+
w3 = 2.0
|
|
37
|
+
norm = math.sqrt(w0 * w0 + w3 * w3)
|
|
38
|
+
assert v[0] == pytest.approx(w0 / norm)
|
|
39
|
+
assert v[3] == pytest.approx(w3 / norm)
|
|
40
|
+
assert math.sqrt(sum(val * val for val in v.values())) == pytest.approx(1.0)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_transform_empty_and_all_oov():
|
|
44
|
+
vec = TfidfVectorizer().fit(["free money now", "meeting now"])
|
|
45
|
+
assert vec.transform(["", "crypto giveaway"]) == [{}, {}]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_refit_resets_state_and_fit_transform():
|
|
49
|
+
vec = TfidfVectorizer().fit(["free money"])
|
|
50
|
+
vectors = vec.fit_transform(["hello world"])
|
|
51
|
+
assert vec.vocab == {"hello": 0, "world": 1}
|
|
52
|
+
assert "free" not in vec.vocab
|
|
53
|
+
assert "free" not in vec.idf
|
|
54
|
+
assert vectors == vec.transform(["hello world"])
|