ajaykumarreddy-k/-NARRATIVE-SHIELD
GitHub: ajaykumarreddy-k/-NARRATIVE-SHIELD
基于 FastAPI 构建的三层分析平台,用于实时检测文本中的 AI 虚假信息并生成含操纵手法标注的可解释性报告。
Stars: 0 | Forks: 0
# 🛡️ NarrativeShield — Backend API
## 概述
基于 FastAPI 的后端,为 NarrativeShield 的 3 层分析 pipeline 提供支持:
| 层级 | 模块 | 功能说明 |
|---|---|---|
| **L1** | `statistical_engine.py` | 词汇重复、熵、句子一致性 — 离线运行,<50ms |
| **L2** | `gemini_layer.py` → `ollama_layer.py` | Gemini 2.0 Flash (主要) → Ollama (备选) → 仅统计 |
| **L3** | `db_matcher.py` | SQLite 模式数据库 — 32+ 条带有严重程度的恶意短语匹配 |
## 目录结构
```
backend/
├── main.py ← FastAPI server (run this)
├── pipeline.py ← 3-layer orchestrator
├── statistical_engine.py ← Layer 1: offline statistical fingerprinting
├── gemini_layer.py ← Layer 2a: Google Gemini 2.0 Flash
├── ollama_layer.py ← Layer 2b: Ollama local LLM fallback
├── db_matcher.py ← Layer 3: SQLite pattern matching (auto-seeds)
├── pyproject.toml ← uv project config
├── requirements.txt ← pip-compatible dep list
├── llm_malign_detector/
│ ├── narrative_shield.db ← SQLite DB (auto-created on first run)
│ ├── models.py
│ ├── schemas.py
│ └── parser_engine.py
└── .env.example ← Copy → .env and add your Gemini API key
```
## 快速开始
### 1. 安装依赖 (uv — 推荐)
```
cd backend
uv sync
```
或使用 pip:
```
pip install -r requirements.txt
```
### 2. 启动服务器
```
uv run uvicorn main:app --reload --port 8000
```
```
# 验证其正在运行:
curl http://localhost:8000/api/health
```
### 3. (可选) 启动 Ollama 作为本地 LLM 备选
```
ollama serve
ollama pull llama3.2 # or mistral, llama3.1 — engine auto-detects
```
## API Endpoints
| 方法 | 路径 | 描述 |
|---|---|---|
| `GET` | `/api/health` | 系统状态 — LLM 模式、数据库状态、模式数量 |
| `POST` | `/api/analyze` | **主要 endpoint** — 运行完整的 3 层分析 |
| `GET` | `/api/models` | 列出可用的 Ollama 模型 |
| `GET` | `/api/patterns/count` | 已加载的恶意模式数量 |
| `GET` | `/docs` | 自动生成的 Swagger UI |
### POST `/api/analyze` — 请求
```
{
"text": "The elites don't want you to know...",
"api_key": "AIzaSy..."
}
```
### POST `/api/analyze` — 响应
```
{
"ai_probability": 87,
"manipulation_score": 79,
"stat_score": 61.3,
"confidence": "high",
"verdict": "HIGH_RISK",
"verdict_sub": "Multiple manipulation techniques detected",
"technique": "Fear Mongering / Emotional Manipulation",
"summary": "Content uses tribal framing and false urgency tactics...",
"phrases": [
{
"phrase": "the elites",
"category": "us_vs_them",
"catLabel": "Us vs Them",
"severity": "HIGH",
"char_start": 4,
"char_end": 14,
"reason": "Tribal framing — divides audience against an out-group",
"source": "db_match"
}
],
"explain": [
{ "feat": "Repetition Ratio", "pct": 42, "color": "#7c3aed" }
],
"layers": { "l1": 61, "l2": 79, "l3": 60 },
"scan_id": "SCN-4821",
"text_hash": "A3F9B2C1",
"proc_time": "1.2s",
"text_stats": { "word_count": 84, "sentence_count": 6 },
"model_used": "gemini"
}
```
## Pipeline 备选链
```
User submits text + API key
│
▼
[L1] Statistical Engine ─────────────────────── always runs (<50ms)
│
▼
[L2] Gemini 2.0 Flash ─── fails? ──► Ollama ─── fails? ──► Stat-only fallback
│
▼
[L3] SQLite DB Matcher ─── not available? ──► 44-pattern inline fallback
│
▼
Merged result → JSON response
```
## 数据库 — 自动种子植入
`db_matcher.py` 在首次导入时会自动创建并为 `narrative_shield.db` 植入数据。
无需手动设置。内置了涵盖 7 个类别的 **32 个模式**:
| 类别 | 示例 |
|---|---|
| `emotional_amplifier` | "shocking truth", "wake up people" |
| `us_vs_them` | "the elites", "deep state", "real citizens" |
| `false_urgency` | "before it's deleted", "share immediately" |
| `fake_authority` | "experts agree", "insiders confirm" |
| `conspiracy_frame` | "cover-up", "what they don't tell" |
| `fear_trigger` | "imminent threat", "blackout" |
| `coordinated_marker` | "spread the word", "share this before" |
## 环境变量
```
# .env (从 .env.example 复制 — 切勿提交)
GEMINI_API_KEY=AIzaSy... # Optional — can be passed per-request instead
```
## 使用 cURL 进行测试
```
# Health check
curl http://localhost:8000/api/health
# 全面分析(替换 API key)
curl -X POST http://localhost:8000/api/analyze \
-H "Content-Type: application/json" \
-d '{
"text": "Wake up people! The deep state is orchestrating a collapse. Share immediately before it gets deleted.",
"api_key": "YOUR_GEMINI_KEY"
}'
# 无 API key 也可运行(使用 statistical + DB pattern fallback)
curl -X POST http://localhost:8000/api/analyze \
-H "Content-Type: application/json" \
-d '{"text": "Wake up people! The deep state...", "api_key": ""}'
```
## 性能目标
| 指标 | 目标 | 备注 |
|---|---|---|
| 第 1 层 (统计) | < 50ms | 纯 Python,无 API |
| 第 2 层 (Gemini) | < 2s | Gemini 2.0 Flash 免费层级 |
| 第 2 层 (Ollama) | < 5s | 本地模型,取决于硬件 |
| 第 3 层 (数据库) | < 10ms | SQLite 索引查找 |
| **端到端** | **< 3s** | 使用 Gemini |
## 评委演示流程
```
# 终端 1:启动后端
cd backend && uv sync && uv run uvicorn main:app --reload --port 8000
# 终端 2:启动前端
cd .. && npm run dev
# 打开 http://localhost:3000
# 1. 点击演示案例 "Deepfake Transcript"
# 2. 添加你的 Gemini API key(点击状态按钮)
# 3. 点击 ANALYZE NARRATIVE
# 4. 观察仪表读数达到 80%+,短语亮起红灯
# 5. 展示 /docs 以体现技术可信度
```
标签:AI风险缓解, AV绕过, DLL 劫持, FastAPI, Python, 人工智能, 大语言模型, 文本分析, 无后门, 用户模式Hook绕过, 虚假信息检测, 逆向工具