s7g4/ledger-sentinel
GitHub: s7g4/ledger-sentinel
异步金融交易处理管线,支持 CSV 摄取、数据清洗、规则异常检测与 LLM 分类及叙述性摘要生成。
Stars: 0 | Forks: 0
# Ledger Sentinel
[](https://github.com/s7g4/ledger-sentinel/actions/workflows/ci.yml)
[](https://s7g4.github.io/ledger-sentinel/)
[](https://opensource.org/licenses/MIT)
一个异步金融交易处理后端,能够摄取原始 CSV 文件,执行数据清洗,运行异常检测规则,使用 Google Gemini LLM API 对交易进行分类,并生成叙述性摘要报告。
基于 **FastAPI**、**Celery**、**Redis** 和 **PostgreSQL** 构建。自带**零配置演示模式**:无需 API key 即可端到端运行完整 pipeline。
**完整文档:** [s7g4.github.io/ledger-sentinel](https://s7g4.github.io/ledger-sentinel/),或者使用 `make book-serve` 在本地构建(源码位于 [`book/`](book/src/SUMMARY.md))。
## 系统架构
```
flowchart TD
subgraph clientLayer ["Client Layer"]
C[Client / curl / Frontend]
end
subgraph apiLayer ["API Layer"]
API[FastAPI Application]
end
subgraph queueCache ["Queue & Cache"]
Redis[(Redis Broker)]
end
subgraph workerLayer ["Worker Layer"]
Worker[Celery Worker Processes]
end
subgraph database ["Database"]
DB[(PostgreSQL)]
end
subgraph externalServices ["External Services"]
Gemini[Google Gemini 1.5 Flash / Demo-Mode Fallback]
end
C -- 1. Upload CSV / Query --> API
API -- 2. Save Pending Job --> DB
API -- 3. Enqueue Job Task --> Redis
API -- 4. Return Accept Response (202) --> C
Redis -- 5. Fetch Job Task --> Worker
Worker -- 6. Run Pipeline --> Worker
subgraph pipeline ["Processing Pipeline"]
Clean[1. Data Cleaner]
Anomaly[2. Anomaly Detection]
Classify[3. Batch Classification]
Narrative[4. Narrative Generator]
Clean --> Anomaly --> Classify --> Narrative
end
Worker -- Invoke Pipeline --> pipeline
Classify -- Categorize Uncategorized --> Gemini
Narrative -- Generate Narrative Summary --> Gemini
Worker -- 7. Save Cleaned Txns & Summary --> DB
Worker -- 8. Update Job Status to Completed --> DB
```
有关每个阶段的深入解析,请参见 [`book/src/architecture.md`](book/src/architecture.md)。
## 功能
- **异步摄取**:FastAPI 接受 CSV 上传,并立即将任务排入 Celery 队列,以防止 HTTP 超时。
- **零配置演示模式**:没有 `GEMINI_API_KEY`?pipeline 会自动回退到基于确定规则的分类器和叙述生成器,无需外部 API 调用,也无需账户。请参见[演示模式](book/src/demo_mode.md)。
- **强大的数据清洗**:规范化各种日期格式(`DD-MM-YYYY`、`YYYY/MM/DD`、`YYYY-MM-DD`),清理/去除符号,并对交易进行去重。
- **基于规则的异常检测**:
- 标记超过账户支出中位数 **3 倍**的交易。
- 标记已知仅限国内商户(例如 Swiggy、IRCTC、Ola)的 **美元扣款**。
- **Gemini LLM 集成**:
- 对未分类的交易进行批量分类(每批 20 条),并带有指数退避重试机制。
- 生成叙述,提供整体支出摘要和风险评估。
- **Docker 化环境**:完全容器化设置,包括 FastAPI 后端、Celery worker、Redis 队列、PostgreSQL 数据库和 Flower 监控仪表板。
- **Alembic 数据库迁移**:规范的数据库 schema 版本控制。
- **99% 测试覆盖率**:pipeline、worker、API 和错误处理路径均已覆盖。请参见[测试](book/src/testing.md)。
- **代码检查和类型检查**:使用 Ruff 和 MyPy 集成了 pre-commit hooks。
## 目录结构
```
├── alembic/ # DB migrations configuration & version files
├── app/
│ ├── api/ # API router & route definitions
│ ├── core/ # App configuration, custom exceptions, & logger setup
│ ├── db/ # DB connections & models (Job, Transaction, JobSummary)
│ ├── pipeline/ # Cleaning, anomaly detection & classification/narrative connectors
│ ├── schemas/ # Pydantic schema validation models
│ ├── tasks/ # Celery application & worker task definition
│ └── main.py # App startup & initialization
├── book/ # mdBook documentation site (architecture, demo mode, API reference, ...)
├── sample_data/ # Sample CSV used by the demo script and docs
├── scripts/ # run_demo.sh, the end-to-end demo runner
├── tests/ # Pytest unit & integration test suites
├── Dockerfile # Docker image definition
├── docker-compose.yml # Multi-container service definition
├── Makefile # Task runner for development commands
└── requirements.txt # Production dependencies
```
## 配置
应用程序使用环境变量进行配置。将 `.env.example` 复制到 `.env` 并填入相应的值:
| 变量 | 必填 | 描述 | 示例 |
| ---------------- | -------- | --------------------------- | ------------------------------------------------ |
| `DATABASE_URL` | 是 | PostgreSQL 连接 URL | `postgresql://postgres:postgres@db:5432/ledger_sentinel` |
| `REDIS_URL` | 是 | Redis 连接 URL | `redis://redis:6379/0` |
| `GEMINI_API_KEY` | 否 | Google Gemini API key。省略此项以在[演示模式](book/src/demo_mode.md)下运行。 | `AIzaSy...` |
## 设置与运行
### 前置条件
- 你的机器上需安装 [Docker](https://www.docker.com/) 和 [Docker Compose](https://docs.docker.com/compose/)。
### 快速开始
1. **克隆仓库**并导航至项目目录:
git clone https://github.com/s7g4/ledger-sentinel.git
cd ledger-sentinel
2. **配置你的环境**:
cp .env.example .env
# 可选:添加真实的 GEMINI_API_KEY,或留空以在演示模式下运行
3. **启动所有服务**:
make run
或者如果你没有安装 `make`:
docker compose up --build
4. **服务端点**:
- **FastAPI 后端**:`http://localhost:8000`
- **Flower Celery 仪表板**:`http://localhost:5555`
- **交互式 API 文档 (Swagger UI)**:`http://localhost:8000/docs`
5. **使用单条命令体验完整 pipeline**:
make demo
这将启动服务栈(如果尚未运行)并上传内置的 [`sample_data/transactions_sample.csv`](sample_data/transactions_sample.csv),持续轮询直到任务完成并打印完整结果。无需 API key。
## API 端点快速参考
有关完整的请求/响应 schema,请参见 [API 参考](book/src/api_reference.md)。
- `POST /jobs/upload` - 上传原始 CSV
- `GET /jobs/{job_id}/status` - 检查摄取状态
- `GET /jobs/{job_id}/results` - 获取已处理的交易、异常和叙述性摘要
- `GET /jobs` - 列出所有已处理的作业
- `GET /health` - 存活与就绪检查
## 测试
在本地运行格式化检查、类型验证和测试套件:
### 本地前置条件
创建一个本地 Python 虚拟环境并安装依赖:
```
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt -r requirements-dev.txt
```
### 运行测试
```
make test # Runs Pytest
make test-cov # Runs Pytest with a coverage report
make lint # Checks for linting errors using Ruff
make format-check # Validates code style
make type-check # Runs MyPy static type analysis
```
有关每个测试文件涵盖的内容及其原因,请参见[测试](book/src/testing.md)。
## 路线图
- Render/Fly.io/Railway 的一键部署模板。
- 在 CI 中针对真实的 Postgres/Redis 容器运行集成测试,作为当前基于 SQLite 的单元测试的补充。
- 可插拔的 classifier 接口,这样无需修改 `app/tasks/worker.py` 即可替换为非 Gemini 模型。
## 许可证
本项目基于 MIT 许可证授权 - 详情请参见 [LICENSE](LICENSE) 文件。
标签:AV绕过, FastAPI, LLM分类, PostgreSQL, 异常检测, 异步任务队列, 搜索引擎查询, 数据清洗, 测试用例, 请求拦截, 逆向工具, 金融交易处理