cats-scoring 1.3.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.
- cats_scoring-1.3.0/LICENSE +21 -0
- cats_scoring-1.3.0/PKG-INFO +223 -0
- cats_scoring-1.3.0/README.md +191 -0
- cats_scoring-1.3.0/cats/__init__.py +3 -0
- cats_scoring-1.3.0/cats/api/__init__.py +1 -0
- cats_scoring-1.3.0/cats/api/main.py +145 -0
- cats_scoring-1.3.0/cats/api/routes/__init__.py +1 -0
- cats_scoring-1.3.0/cats/api/routes/evaluate.py +162 -0
- cats_scoring-1.3.0/cats/api/schemas.py +69 -0
- cats_scoring-1.3.0/cats/audit/__init__.py +1 -0
- cats_scoring-1.3.0/cats/audit/logger.py +120 -0
- cats_scoring-1.3.0/cats/calibration/__init__.py +24 -0
- cats_scoring-1.3.0/cats/calibration/__main__.py +4 -0
- cats_scoring-1.3.0/cats/calibration/build_dataset.py +220 -0
- cats_scoring-1.3.0/cats/calibration/calibrate.py +109 -0
- cats_scoring-1.3.0/cats/calibration/collect_rss.py +321 -0
- cats_scoring-1.3.0/cats/calibration/dataset.py +65 -0
- cats_scoring-1.3.0/cats/calibration/evaluate.py +237 -0
- cats_scoring-1.3.0/cats/calibration/ga.py +124 -0
- cats_scoring-1.3.0/cats/calibration/label_from_ratings.py +243 -0
- cats_scoring-1.3.0/cats/calibration/merge_snapshots.py +144 -0
- cats_scoring-1.3.0/cats/calibration/objective.py +131 -0
- cats_scoring-1.3.0/cats/calibration/report.py +135 -0
- cats_scoring-1.3.0/cats/calibration/split.py +145 -0
- cats_scoring-1.3.0/cats/core/__init__.py +1 -0
- cats_scoring-1.3.0/cats/core/config.py +58 -0
- cats_scoring-1.3.0/cats/core/db.py +30 -0
- cats_scoring-1.3.0/cats/core/metrics.py +33 -0
- cats_scoring-1.3.0/cats/core/models.py +53 -0
- cats_scoring-1.3.0/cats/core/security.py +173 -0
- cats_scoring-1.3.0/cats/lite.py +123 -0
- cats_scoring-1.3.0/cats/pipeline/__init__.py +1 -0
- cats_scoring-1.3.0/cats/pipeline/normalizer.py +36 -0
- cats_scoring-1.3.0/cats/scoring/__init__.py +1 -0
- cats_scoring-1.3.0/cats/scoring/engine.py +44 -0
- cats_scoring-1.3.0/cats/scoring/explainer.py +53 -0
- cats_scoring-1.3.0/cats/scoring/weights.py +70 -0
- cats_scoring-1.3.0/cats/signals/__init__.py +1 -0
- cats_scoring-1.3.0/cats/signals/coherence.py +128 -0
- cats_scoring-1.3.0/cats/signals/gaming.py +66 -0
- cats_scoring-1.3.0/cats/signals/sentiment.py +76 -0
- cats_scoring-1.3.0/cats/signals/silence.py +31 -0
- cats_scoring-1.3.0/cats/signals/types.py +43 -0
- cats_scoring-1.3.0/cats/signals/volatility.py +31 -0
- cats_scoring-1.3.0/cats_scoring.egg-info/PKG-INFO +223 -0
- cats_scoring-1.3.0/cats_scoring.egg-info/SOURCES.txt +49 -0
- cats_scoring-1.3.0/cats_scoring.egg-info/dependency_links.txt +1 -0
- cats_scoring-1.3.0/cats_scoring.egg-info/requires.txt +13 -0
- cats_scoring-1.3.0/cats_scoring.egg-info/top_level.txt +1 -0
- cats_scoring-1.3.0/pyproject.toml +62 -0
- cats_scoring-1.3.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Leapfrog-LSA
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cats-scoring
|
|
3
|
+
Version: 1.3.0
|
|
4
|
+
Summary: Contextual Ambiguity & Trust Scoring — trust intelligence for OSINT sources
|
|
5
|
+
Author: Leapfrog-LSA
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring
|
|
8
|
+
Project-URL: Documentation, https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring/tree/main/docs
|
|
9
|
+
Project-URL: Changelog, https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: osint,trust-scoring,source-reliability,disinformation
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: pydantic<3.0,>=2.6
|
|
21
|
+
Requires-Dist: pydantic-settings<3.0,>=2.2
|
|
22
|
+
Requires-Dist: spacy<4.0,>=3.7
|
|
23
|
+
Requires-Dist: textblob<1.0,>=0.18
|
|
24
|
+
Requires-Dist: structlog<25.0,>=24.1
|
|
25
|
+
Requires-Dist: httpx<1.0,>=0.27
|
|
26
|
+
Provides-Extra: sbert
|
|
27
|
+
Requires-Dist: sentence-transformers<4.0,>=2.7; extra == "sbert"
|
|
28
|
+
Provides-Extra: bert
|
|
29
|
+
Requires-Dist: transformers<5.0,>=4.40; extra == "bert"
|
|
30
|
+
Requires-Dist: torch<3.0,>=2.2; extra == "bert"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# CATS — Contextual Ambiguity & Trust Scoring
|
|
34
|
+
|
|
35
|
+
> **Trust intelligence for OSINT sources — not fact-checking, but source reliability over time.**
|
|
36
|
+
|
|
37
|
+
[](https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring/actions) [](https://codecov.io/gh/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring) [](https://www.python.org/) [](LICENSE/) [](docs/compliance.md) [](docs/compliance.md)
|
|
38
|
+
|
|
39
|
+
***
|
|
40
|
+
|
|
41
|
+
## What is CATS?
|
|
42
|
+
|
|
43
|
+
| ❌ Fact-checking | ✅ CATS |
|
|
44
|
+
| --------------------------- | -------------------------------------------------------------- |
|
|
45
|
+
| "Is this information true?" | **"How reliable is this source, in this context, right now?"** |
|
|
46
|
+
|
|
47
|
+
CATS analyses the _behavioural patterns_ of a source over time — narrative consistency, sentiment volatility, temporal gaps, and signs of algorithmic manipulation — and returns a transparent, explainable trust score.
|
|
48
|
+
|
|
49
|
+
***
|
|
50
|
+
|
|
51
|
+
## Signals
|
|
52
|
+
|
|
53
|
+
| Signal | What it measures | Method |
|
|
54
|
+
| -------------- | ------------------------------------------- | ---------------------------------------------------------- |
|
|
55
|
+
| **Coherence** | Entity/argument consistency across messages | spaCy NER + Jaccard (or optional Sentence-BERT) similarity |
|
|
56
|
+
| **Volatility** | Abrupt narrative tone changes | TextBlob (or optional BERT) sentiment spike detection |
|
|
57
|
+
| **Silence** | Anomalous temporal gaps in publishing | Gap analysis vs. source-type thresholds |
|
|
58
|
+
| **Gaming** | Signs of algorithmic manipulation | Repetition + TTR + burst + vocab diversity |
|
|
59
|
+
|
|
60
|
+
***
|
|
61
|
+
|
|
62
|
+
## Try it in 5 lines (no infrastructure)
|
|
63
|
+
|
|
64
|
+
No database, no Redis, no API keys — the signal pipeline as a plain library call:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from cats.lite import score
|
|
68
|
+
|
|
69
|
+
result = score([
|
|
70
|
+
{"timestamp": "2026-01-01T08:00:00Z", "text": "Il governo annuncia un piano economico."},
|
|
71
|
+
{"timestamp": "2026-01-01T12:00:00Z", "text": "I sindacati commentano il piano."},
|
|
72
|
+
{"timestamp": "2026-01-02T09:00:00Z", "text": "Il parlamento discute la legge di bilancio."},
|
|
73
|
+
], source_type="news")
|
|
74
|
+
|
|
75
|
+
print(result["trust_score"], result["band"], result["explanation"]["primary_driver"])
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Install with `pip install -r requirements.txt` (plus `make nlp-download` for full-fidelity coherence — without it the NER backend degrades to a neutral value). The full API below adds persistence, auditing and GDPR endpoints.
|
|
79
|
+
|
|
80
|
+
Or try it in the browser: [](https://colab.research.google.com/github/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring/blob/main/examples/cats_lite_demo.ipynb)
|
|
81
|
+
|
|
82
|
+
***
|
|
83
|
+
|
|
84
|
+
## Quick Start (full deployment)
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
# 1. Clone and configure
|
|
88
|
+
git clone https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring.git && cd CATS-Contextual-Ambiguity-Trust-Scoring
|
|
89
|
+
cp .env.example .env # fill in secrets (see .env.example)
|
|
90
|
+
|
|
91
|
+
# 2. Install
|
|
92
|
+
make dev-install # deps + pre-commit hooks
|
|
93
|
+
make nlp-download # spaCy it_core_news_lg + TextBlob corpora
|
|
94
|
+
|
|
95
|
+
# 3. Start services and run
|
|
96
|
+
make docker-up # PostgreSQL 16 + Redis 7
|
|
97
|
+
make db-migrate # Alembic migrations
|
|
98
|
+
uvicorn cats.api.main:app --reload
|
|
99
|
+
|
|
100
|
+
# 4. Test
|
|
101
|
+
make test
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
> **Generate a secure AUDIT\_ENCRYPTION\_KEY**: `make generate-key`
|
|
105
|
+
|
|
106
|
+
***
|
|
107
|
+
|
|
108
|
+
## API Example
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
curl -s -X POST http://localhost:8000/v1/cats/evaluate \
|
|
112
|
+
-H "Authorization: Bearer $CATS_API_KEY" \
|
|
113
|
+
-H "Content-Type: application/json" \
|
|
114
|
+
-d '{
|
|
115
|
+
"source_id": "twitter:example_handle",
|
|
116
|
+
"messages": [
|
|
117
|
+
{"timestamp": "2026-01-01T08:00:00Z", "text": "Governo annuncia piano economico."},
|
|
118
|
+
{"timestamp": "2026-01-01T09:00:00Z", "text": "Protesta dei lavoratori in piazza."},
|
|
119
|
+
{"timestamp": "2026-01-01T10:00:00Z", "text": "Parlamento discute la legge di bilancio."}
|
|
120
|
+
],
|
|
121
|
+
"context": {"source_type": "social"}
|
|
122
|
+
}' | jq
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{
|
|
127
|
+
"trace_id": "550e8400-e29b-41d4-a716-446655440000",
|
|
128
|
+
"score": 68.4,
|
|
129
|
+
"band": "medium_high",
|
|
130
|
+
"requires_review": false,
|
|
131
|
+
"signals": [
|
|
132
|
+
{"name": "coherence", "value": 71.2, "confidence": 0.3},
|
|
133
|
+
{"name": "volatility", "value": 55.0, "confidence": 0.15},
|
|
134
|
+
{"name": "silence", "value": 0.0, "confidence": 0.1},
|
|
135
|
+
{"name": "gaming", "value": 12.8, "confidence": 0.06}
|
|
136
|
+
]
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
***
|
|
141
|
+
|
|
142
|
+
## Trust Score Bands
|
|
143
|
+
|
|
144
|
+
| Score | Band | Recommended Action |
|
|
145
|
+
| ------ | ------------- | ----------------------------- |
|
|
146
|
+
| 80–100 | `high` | Usable for OSINT |
|
|
147
|
+
| 60–79 | `medium_high` | Cross-validate key claims |
|
|
148
|
+
| 40–59 | `medium` | Human review recommended |
|
|
149
|
+
| 20–39 | `low` | Human review required |
|
|
150
|
+
| 0–19 | `very_low` | Do not use without validation |
|
|
151
|
+
|
|
152
|
+
> ⚠️ Scores are **ordinal rankings**, not absolute probabilities (WP 4.3).
|
|
153
|
+
|
|
154
|
+
***
|
|
155
|
+
|
|
156
|
+
## Architecture
|
|
157
|
+
|
|
158
|
+

|
|
159
|
+
|
|
160
|
+
```
|
|
161
|
+
Client (HTTPS + Bearer token)
|
|
162
|
+
│
|
|
163
|
+
nginx (TLS 1.3 · rate 30 req/min)
|
|
164
|
+
│
|
|
165
|
+
FastAPI — 9-phase pipeline
|
|
166
|
+
├─ POST /v1/cats/evaluate
|
|
167
|
+
├─ POST /v1/cats/batch ← evaluate up to 50 sources at once
|
|
168
|
+
├─ GET /v1/cats/explain/{trace_id} ← GDPR Art.14/22
|
|
169
|
+
├─ POST /v1/cats/contest/{trace_id} ← GDPR Art.22
|
|
170
|
+
├─ GET /v1/cats/stats
|
|
171
|
+
└─ GET /health /metrics
|
|
172
|
+
│ │
|
|
173
|
+
Redis 7 PostgreSQL 16
|
|
174
|
+
(rate limiting) (AES-256 audit log)
|
|
175
|
+
+ APScheduler purge
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
The nginx reverse proxy (TLS, rate limiting, security headers) is configured in [`deploy/nginx.conf`](deploy/nginx.conf) and started by `make docker-up`.
|
|
179
|
+
|
|
180
|
+
See [docs/architecture.md](docs/architecture.md) for full signal and security details.
|
|
181
|
+
|
|
182
|
+
***
|
|
183
|
+
|
|
184
|
+
## Documentation
|
|
185
|
+
|
|
186
|
+
| Document | Description |
|
|
187
|
+
| -------------------------------------------- | --------------------------------------------------- |
|
|
188
|
+
| [docs/api.md](docs/api.md) | Full API reference |
|
|
189
|
+
| [docs/architecture.md](docs/architecture.md) | Signal algorithms, weight matrix, security design |
|
|
190
|
+
| [docs/compliance.md](docs/compliance.md) | GDPR + EU AI Act compliance |
|
|
191
|
+
| [docs/eu\_ai\_act/](docs/eu_ai_act/) | EU AI Act conformity scaffold (Annex IV, Art. 9/10) |
|
|
192
|
+
| [docs/calibration.md](docs/calibration.md) | Empirical weight calibration (genetic search) |
|
|
193
|
+
| [CHANGELOG.md](CHANGELOG.md) | Version history |
|
|
194
|
+
| [CONTRIBUTING.md](CONTRIBUTING.md) | Development guide |
|
|
195
|
+
| [SECURITY.md](SECURITY.md) | Vulnerability reporting |
|
|
196
|
+
|
|
197
|
+
***
|
|
198
|
+
|
|
199
|
+
## Known Limitations (WP 4.1)
|
|
200
|
+
|
|
201
|
+
* **NLP accuracy \~55–62% (default)**: spaCy NER + TextBlob; optional BERT sentiment and Sentence-BERT coherence backends are available for higher accuracy (see `.env.example`)
|
|
202
|
+
* **Uncalibrated parameters**: thresholds are initial estimates; signal weights can now be empirically tuned with [`cats.calibration`](docs/calibration.md), but band thresholds remain unvalidated
|
|
203
|
+
* **Small validation set (July 2026)**: calibration/validation currently rests on 50 RSS-labelled sources; see [calibration findings](docs/calibration_findings_2026-07.md) for the honest numbers (full-dataset concordance 0.78, holdout 0.71) and their caveats
|
|
204
|
+
* **Italian-optimised**: using `it_core_news_lg`; other languages degrade accuracy
|
|
205
|
+
* **Ordinal scoring only**: not suitable as sole basis for autonomous decisions
|
|
206
|
+
|
|
207
|
+
***
|
|
208
|
+
|
|
209
|
+
## Roadmap
|
|
210
|
+
|
|
211
|
+
| Version | Status | Key features |
|
|
212
|
+
| -------- | ------ | ------------------------------------------------------------------------------------------------------------------ |
|
|
213
|
+
| **v1.0** | ✅ | spaCy NER · 9-phase pipeline · GDPR API · Docker |
|
|
214
|
+
| **v1.1** | ✅ | BERT Italian sentiment · multi-tenant PostgreSQL · batch endpoint · Prometheus `/metrics` · nginx |
|
|
215
|
+
| **v1.2** | ✅ | Sentence-BERT coherence · explainer attribution · weight calibration |
|
|
216
|
+
| **v1.3** | ✅ | Signal-polarity fix in aggregation · distant-supervision dataset (MBFC + disinfo networks) · snapshot accumulation |
|
|
217
|
+
| v2.0 | 2027 | AUC-ROC ≥ 0.78 · full EU AI Act Annex IV technical documentation |
|
|
218
|
+
|
|
219
|
+
***
|
|
220
|
+
|
|
221
|
+
## License
|
|
222
|
+
|
|
223
|
+
[MIT](LICENSE/) — technical@cats-system.org
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# CATS — Contextual Ambiguity & Trust Scoring
|
|
2
|
+
|
|
3
|
+
> **Trust intelligence for OSINT sources — not fact-checking, but source reliability over time.**
|
|
4
|
+
|
|
5
|
+
[](https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring/actions) [](https://codecov.io/gh/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring) [](https://www.python.org/) [](LICENSE/) [](docs/compliance.md) [](docs/compliance.md)
|
|
6
|
+
|
|
7
|
+
***
|
|
8
|
+
|
|
9
|
+
## What is CATS?
|
|
10
|
+
|
|
11
|
+
| ❌ Fact-checking | ✅ CATS |
|
|
12
|
+
| --------------------------- | -------------------------------------------------------------- |
|
|
13
|
+
| "Is this information true?" | **"How reliable is this source, in this context, right now?"** |
|
|
14
|
+
|
|
15
|
+
CATS analyses the _behavioural patterns_ of a source over time — narrative consistency, sentiment volatility, temporal gaps, and signs of algorithmic manipulation — and returns a transparent, explainable trust score.
|
|
16
|
+
|
|
17
|
+
***
|
|
18
|
+
|
|
19
|
+
## Signals
|
|
20
|
+
|
|
21
|
+
| Signal | What it measures | Method |
|
|
22
|
+
| -------------- | ------------------------------------------- | ---------------------------------------------------------- |
|
|
23
|
+
| **Coherence** | Entity/argument consistency across messages | spaCy NER + Jaccard (or optional Sentence-BERT) similarity |
|
|
24
|
+
| **Volatility** | Abrupt narrative tone changes | TextBlob (or optional BERT) sentiment spike detection |
|
|
25
|
+
| **Silence** | Anomalous temporal gaps in publishing | Gap analysis vs. source-type thresholds |
|
|
26
|
+
| **Gaming** | Signs of algorithmic manipulation | Repetition + TTR + burst + vocab diversity |
|
|
27
|
+
|
|
28
|
+
***
|
|
29
|
+
|
|
30
|
+
## Try it in 5 lines (no infrastructure)
|
|
31
|
+
|
|
32
|
+
No database, no Redis, no API keys — the signal pipeline as a plain library call:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from cats.lite import score
|
|
36
|
+
|
|
37
|
+
result = score([
|
|
38
|
+
{"timestamp": "2026-01-01T08:00:00Z", "text": "Il governo annuncia un piano economico."},
|
|
39
|
+
{"timestamp": "2026-01-01T12:00:00Z", "text": "I sindacati commentano il piano."},
|
|
40
|
+
{"timestamp": "2026-01-02T09:00:00Z", "text": "Il parlamento discute la legge di bilancio."},
|
|
41
|
+
], source_type="news")
|
|
42
|
+
|
|
43
|
+
print(result["trust_score"], result["band"], result["explanation"]["primary_driver"])
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Install with `pip install -r requirements.txt` (plus `make nlp-download` for full-fidelity coherence — without it the NER backend degrades to a neutral value). The full API below adds persistence, auditing and GDPR endpoints.
|
|
47
|
+
|
|
48
|
+
Or try it in the browser: [](https://colab.research.google.com/github/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring/blob/main/examples/cats_lite_demo.ipynb)
|
|
49
|
+
|
|
50
|
+
***
|
|
51
|
+
|
|
52
|
+
## Quick Start (full deployment)
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
# 1. Clone and configure
|
|
56
|
+
git clone https://github.com/Leapfrog-LSA/CATS-Contextual-Ambiguity-Trust-Scoring.git && cd CATS-Contextual-Ambiguity-Trust-Scoring
|
|
57
|
+
cp .env.example .env # fill in secrets (see .env.example)
|
|
58
|
+
|
|
59
|
+
# 2. Install
|
|
60
|
+
make dev-install # deps + pre-commit hooks
|
|
61
|
+
make nlp-download # spaCy it_core_news_lg + TextBlob corpora
|
|
62
|
+
|
|
63
|
+
# 3. Start services and run
|
|
64
|
+
make docker-up # PostgreSQL 16 + Redis 7
|
|
65
|
+
make db-migrate # Alembic migrations
|
|
66
|
+
uvicorn cats.api.main:app --reload
|
|
67
|
+
|
|
68
|
+
# 4. Test
|
|
69
|
+
make test
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
> **Generate a secure AUDIT\_ENCRYPTION\_KEY**: `make generate-key`
|
|
73
|
+
|
|
74
|
+
***
|
|
75
|
+
|
|
76
|
+
## API Example
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
curl -s -X POST http://localhost:8000/v1/cats/evaluate \
|
|
80
|
+
-H "Authorization: Bearer $CATS_API_KEY" \
|
|
81
|
+
-H "Content-Type: application/json" \
|
|
82
|
+
-d '{
|
|
83
|
+
"source_id": "twitter:example_handle",
|
|
84
|
+
"messages": [
|
|
85
|
+
{"timestamp": "2026-01-01T08:00:00Z", "text": "Governo annuncia piano economico."},
|
|
86
|
+
{"timestamp": "2026-01-01T09:00:00Z", "text": "Protesta dei lavoratori in piazza."},
|
|
87
|
+
{"timestamp": "2026-01-01T10:00:00Z", "text": "Parlamento discute la legge di bilancio."}
|
|
88
|
+
],
|
|
89
|
+
"context": {"source_type": "social"}
|
|
90
|
+
}' | jq
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
{
|
|
95
|
+
"trace_id": "550e8400-e29b-41d4-a716-446655440000",
|
|
96
|
+
"score": 68.4,
|
|
97
|
+
"band": "medium_high",
|
|
98
|
+
"requires_review": false,
|
|
99
|
+
"signals": [
|
|
100
|
+
{"name": "coherence", "value": 71.2, "confidence": 0.3},
|
|
101
|
+
{"name": "volatility", "value": 55.0, "confidence": 0.15},
|
|
102
|
+
{"name": "silence", "value": 0.0, "confidence": 0.1},
|
|
103
|
+
{"name": "gaming", "value": 12.8, "confidence": 0.06}
|
|
104
|
+
]
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
***
|
|
109
|
+
|
|
110
|
+
## Trust Score Bands
|
|
111
|
+
|
|
112
|
+
| Score | Band | Recommended Action |
|
|
113
|
+
| ------ | ------------- | ----------------------------- |
|
|
114
|
+
| 80–100 | `high` | Usable for OSINT |
|
|
115
|
+
| 60–79 | `medium_high` | Cross-validate key claims |
|
|
116
|
+
| 40–59 | `medium` | Human review recommended |
|
|
117
|
+
| 20–39 | `low` | Human review required |
|
|
118
|
+
| 0–19 | `very_low` | Do not use without validation |
|
|
119
|
+
|
|
120
|
+
> ⚠️ Scores are **ordinal rankings**, not absolute probabilities (WP 4.3).
|
|
121
|
+
|
|
122
|
+
***
|
|
123
|
+
|
|
124
|
+
## Architecture
|
|
125
|
+
|
|
126
|
+

|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
Client (HTTPS + Bearer token)
|
|
130
|
+
│
|
|
131
|
+
nginx (TLS 1.3 · rate 30 req/min)
|
|
132
|
+
│
|
|
133
|
+
FastAPI — 9-phase pipeline
|
|
134
|
+
├─ POST /v1/cats/evaluate
|
|
135
|
+
├─ POST /v1/cats/batch ← evaluate up to 50 sources at once
|
|
136
|
+
├─ GET /v1/cats/explain/{trace_id} ← GDPR Art.14/22
|
|
137
|
+
├─ POST /v1/cats/contest/{trace_id} ← GDPR Art.22
|
|
138
|
+
├─ GET /v1/cats/stats
|
|
139
|
+
└─ GET /health /metrics
|
|
140
|
+
│ │
|
|
141
|
+
Redis 7 PostgreSQL 16
|
|
142
|
+
(rate limiting) (AES-256 audit log)
|
|
143
|
+
+ APScheduler purge
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The nginx reverse proxy (TLS, rate limiting, security headers) is configured in [`deploy/nginx.conf`](deploy/nginx.conf) and started by `make docker-up`.
|
|
147
|
+
|
|
148
|
+
See [docs/architecture.md](docs/architecture.md) for full signal and security details.
|
|
149
|
+
|
|
150
|
+
***
|
|
151
|
+
|
|
152
|
+
## Documentation
|
|
153
|
+
|
|
154
|
+
| Document | Description |
|
|
155
|
+
| -------------------------------------------- | --------------------------------------------------- |
|
|
156
|
+
| [docs/api.md](docs/api.md) | Full API reference |
|
|
157
|
+
| [docs/architecture.md](docs/architecture.md) | Signal algorithms, weight matrix, security design |
|
|
158
|
+
| [docs/compliance.md](docs/compliance.md) | GDPR + EU AI Act compliance |
|
|
159
|
+
| [docs/eu\_ai\_act/](docs/eu_ai_act/) | EU AI Act conformity scaffold (Annex IV, Art. 9/10) |
|
|
160
|
+
| [docs/calibration.md](docs/calibration.md) | Empirical weight calibration (genetic search) |
|
|
161
|
+
| [CHANGELOG.md](CHANGELOG.md) | Version history |
|
|
162
|
+
| [CONTRIBUTING.md](CONTRIBUTING.md) | Development guide |
|
|
163
|
+
| [SECURITY.md](SECURITY.md) | Vulnerability reporting |
|
|
164
|
+
|
|
165
|
+
***
|
|
166
|
+
|
|
167
|
+
## Known Limitations (WP 4.1)
|
|
168
|
+
|
|
169
|
+
* **NLP accuracy \~55–62% (default)**: spaCy NER + TextBlob; optional BERT sentiment and Sentence-BERT coherence backends are available for higher accuracy (see `.env.example`)
|
|
170
|
+
* **Uncalibrated parameters**: thresholds are initial estimates; signal weights can now be empirically tuned with [`cats.calibration`](docs/calibration.md), but band thresholds remain unvalidated
|
|
171
|
+
* **Small validation set (July 2026)**: calibration/validation currently rests on 50 RSS-labelled sources; see [calibration findings](docs/calibration_findings_2026-07.md) for the honest numbers (full-dataset concordance 0.78, holdout 0.71) and their caveats
|
|
172
|
+
* **Italian-optimised**: using `it_core_news_lg`; other languages degrade accuracy
|
|
173
|
+
* **Ordinal scoring only**: not suitable as sole basis for autonomous decisions
|
|
174
|
+
|
|
175
|
+
***
|
|
176
|
+
|
|
177
|
+
## Roadmap
|
|
178
|
+
|
|
179
|
+
| Version | Status | Key features |
|
|
180
|
+
| -------- | ------ | ------------------------------------------------------------------------------------------------------------------ |
|
|
181
|
+
| **v1.0** | ✅ | spaCy NER · 9-phase pipeline · GDPR API · Docker |
|
|
182
|
+
| **v1.1** | ✅ | BERT Italian sentiment · multi-tenant PostgreSQL · batch endpoint · Prometheus `/metrics` · nginx |
|
|
183
|
+
| **v1.2** | ✅ | Sentence-BERT coherence · explainer attribution · weight calibration |
|
|
184
|
+
| **v1.3** | ✅ | Signal-polarity fix in aggregation · distant-supervision dataset (MBFC + disinfo networks) · snapshot accumulation |
|
|
185
|
+
| v2.0 | 2027 | AUC-ROC ≥ 0.78 · full EU AI Act Annex IV technical documentation |
|
|
186
|
+
|
|
187
|
+
***
|
|
188
|
+
|
|
189
|
+
## License
|
|
190
|
+
|
|
191
|
+
[MIT](LICENSE/) — technical@cats-system.org
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""API layer: FastAPI routes, schemas, and request handling."""
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import time
|
|
3
|
+
from contextlib import asynccontextmanager
|
|
4
|
+
|
|
5
|
+
import structlog
|
|
6
|
+
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
|
7
|
+
from fastapi import FastAPI, Request
|
|
8
|
+
from fastapi.exceptions import RequestValidationError
|
|
9
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
10
|
+
from fastapi.responses import JSONResponse, Response
|
|
11
|
+
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
|
12
|
+
|
|
13
|
+
from cats.api.routes.evaluate import router as evaluate_router
|
|
14
|
+
from cats.audit.logger import purge_expired_audits
|
|
15
|
+
from cats.core.config import settings
|
|
16
|
+
from cats.core.db import AsyncSessionLocal
|
|
17
|
+
from cats.core.metrics import HTTP_LATENCY, HTTP_REQUESTS
|
|
18
|
+
from cats.core.security import init_jwt_keys, init_redis
|
|
19
|
+
from cats.signals.coherence import init_nlp
|
|
20
|
+
|
|
21
|
+
# N-06: JSON structured logging. Use structlog-native processors + a filtering
|
|
22
|
+
# bound logger so level filtering works without a stdlib logging backend (the
|
|
23
|
+
# stdlib `filter_by_level` processor calls isEnabledFor(), which PrintLogger
|
|
24
|
+
# lacks, and would crash on every log call).
|
|
25
|
+
structlog.configure(
|
|
26
|
+
processors=[
|
|
27
|
+
structlog.processors.add_log_level,
|
|
28
|
+
structlog.processors.TimeStamper(fmt="iso"),
|
|
29
|
+
structlog.processors.JSONRenderer(),
|
|
30
|
+
],
|
|
31
|
+
wrapper_class=structlog.make_filtering_bound_logger(getattr(logging, settings.log_level.upper(), logging.INFO)),
|
|
32
|
+
logger_factory=structlog.PrintLoggerFactory(),
|
|
33
|
+
cache_logger_on_first_use=True,
|
|
34
|
+
)
|
|
35
|
+
logger = structlog.get_logger()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@asynccontextmanager
|
|
39
|
+
async def lifespan(app: FastAPI):
|
|
40
|
+
logger.info("startup", env=settings.environment)
|
|
41
|
+
init_jwt_keys() # S-01
|
|
42
|
+
await init_redis() # S-03
|
|
43
|
+
init_nlp(settings.spacy_model) # N-01: singleton
|
|
44
|
+
|
|
45
|
+
# Q-03: max_instances=1 prevents overlapping purge jobs
|
|
46
|
+
sched = AsyncIOScheduler()
|
|
47
|
+
sched.add_job(_purge_job, "cron", hour=2, minute=0, max_instances=1, coalesce=True, misfire_grace_time=3600)
|
|
48
|
+
sched.start()
|
|
49
|
+
yield
|
|
50
|
+
sched.shutdown()
|
|
51
|
+
logger.info("shutdown")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
async def _purge_job():
|
|
55
|
+
async with AsyncSessionLocal() as db:
|
|
56
|
+
await purge_expired_audits(db)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
app = FastAPI(title="CATS API", version="1.2.0", lifespan=lifespan)
|
|
60
|
+
|
|
61
|
+
if settings.cors_origins:
|
|
62
|
+
app.add_middleware(
|
|
63
|
+
CORSMiddleware,
|
|
64
|
+
allow_origins=[o.strip() for o in settings.cors_origins.split(",")],
|
|
65
|
+
allow_credentials=True,
|
|
66
|
+
allow_methods=["*"],
|
|
67
|
+
allow_headers=["*"],
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
app.include_router(evaluate_router, prefix="/v1/cats", tags=["cats"])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# N-07: Prometheus request metrics. Label by the matched route template (not the
|
|
74
|
+
# raw path) to keep label cardinality bounded.
|
|
75
|
+
@app.middleware("http")
|
|
76
|
+
async def _prometheus_middleware(request: Request, call_next):
|
|
77
|
+
start = time.perf_counter()
|
|
78
|
+
response = await call_next(request)
|
|
79
|
+
route = request.scope.get("route")
|
|
80
|
+
path = getattr(route, "path", None) or "unmatched"
|
|
81
|
+
HTTP_REQUESTS.labels(request.method, path, response.status_code).inc()
|
|
82
|
+
HTTP_LATENCY.labels(request.method, path).observe(time.perf_counter() - start)
|
|
83
|
+
return response
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# A-03: RFC 7807 Problem Details
|
|
87
|
+
@app.exception_handler(RequestValidationError)
|
|
88
|
+
async def _val_err(request: Request, exc: RequestValidationError):
|
|
89
|
+
return JSONResponse(
|
|
90
|
+
status_code=422,
|
|
91
|
+
content={
|
|
92
|
+
"type": "about:blank",
|
|
93
|
+
"title": "Validation Error",
|
|
94
|
+
"status": 422,
|
|
95
|
+
"detail": exc.errors(),
|
|
96
|
+
"instance": str(request.url),
|
|
97
|
+
},
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@app.exception_handler(Exception)
|
|
102
|
+
async def _generic_err(request: Request, exc: Exception):
|
|
103
|
+
logger.error("unhandled", error=str(exc), path=str(request.url))
|
|
104
|
+
return JSONResponse(
|
|
105
|
+
status_code=500,
|
|
106
|
+
content={
|
|
107
|
+
"type": "about:blank",
|
|
108
|
+
"title": "Internal Server Error",
|
|
109
|
+
"status": 500,
|
|
110
|
+
"detail": "Unexpected error",
|
|
111
|
+
"instance": str(request.url),
|
|
112
|
+
},
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Q-02: deep health check
|
|
117
|
+
@app.get("/health")
|
|
118
|
+
async def health():
|
|
119
|
+
from cats.core.db import engine
|
|
120
|
+
from cats.core.security import redis_client
|
|
121
|
+
from cats.signals.coherence import nlp
|
|
122
|
+
|
|
123
|
+
checks: dict = {"api": "ok"}
|
|
124
|
+
try:
|
|
125
|
+
await redis_client.ping()
|
|
126
|
+
checks["redis"] = "ok"
|
|
127
|
+
except Exception as e:
|
|
128
|
+
checks["redis"] = f"error:{e}"
|
|
129
|
+
try:
|
|
130
|
+
from sqlalchemy import text
|
|
131
|
+
|
|
132
|
+
async with engine.connect() as conn:
|
|
133
|
+
await conn.execute(text("SELECT 1"))
|
|
134
|
+
checks["database"] = "ok"
|
|
135
|
+
except Exception as e:
|
|
136
|
+
checks["database"] = f"error:{e}"
|
|
137
|
+
checks["nlp"] = "ok" if nlp else "not_loaded"
|
|
138
|
+
|
|
139
|
+
overall = "healthy" if all(v == "ok" for v in checks.values()) else "degraded"
|
|
140
|
+
return {"status": overall, "checks": checks}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@app.get("/metrics")
|
|
144
|
+
async def metrics():
|
|
145
|
+
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""API route handlers."""
|