Compare commits

..
1 Commits
Author SHA1 Message Date
super e22c86f0d0 Initial commit 2026-02-23 13:13:14 +00:00
155 changed files with 61 additions and 30369 deletions

No files matched your search

-16
View File
@@ -1,16 +0,0 @@
JWT_SECRET=change-me
DATABASE_BACKEND=postgres
DATABASE_URL=
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning
PUBLIC_BASE_URL=http://127.0.0.1:8891
DIFY_BASE_URL=https://api.dify.ai/v1
DIFY_API_KEY=
INTEGRATION_API_KEY=change-me-internal
INTEGRATION_DOWNLOAD_SECRET=change-me-download-signing-secret
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=admin123456
TASK_EXECUTION_MODE=rq
DIFY_SYNC_MAX_RETRIES=4
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
DIFY_SYNC_COOLDOWN_SECONDS=60
-75
View File
@@ -1,75 +0,0 @@
# =========================
# Secrets / env
# =========================
.env
.env.*
!.env.example
backend.env
backend.env.*
!backend.env.example
*.key
*.pem
*secret*
*token*
# =========================
# OS / IDE
# =========================
.DS_Store
Thumbs.db
.idea/
.vscode/
# =========================
# Python
# =========================
__pycache__/
*.pyc
*.pyo
*.pyd
.pytest_cache/
.venv/
venv/
python/
# =========================
# Node
# =========================
frontend/node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# =========================
# Build outputs
# =========================
frontend/dist/
dist/
build/
out/
target/
# =========================
# Runtime temp/logs
# =========================
tmp_run/
*.log
# =========================
# Databases (不要提交测试数据/本地库)
# =========================
*.db
*.sqlite
*.sqlite3
# =========================
# Archives / bundles (不要提交打包产物)
# =========================
*.zip
*.tar.gz
*.tgz
# =========================
# Optional: staging deploy output (如果是生成物就忽略)
# =========================
.deploy-stage/
-423
View File
@@ -1,423 +0,0 @@
# 文档清洗系统对外接口文档
版本:`v1`
适用对象:需要根据 Dify 文档信息反查文档清洗系统中的本地原文件,并获取原文件下载地址的外部系统。
## 1. 接入目标
外部系统通常已经从 Dify 拿到了某条知识库文档的以下信息:
- `dataset_id`
- `remote_document_id`
其中:
- `dataset_id` = Dify 知识库 id
- `remote_document_id` = Dify 文档 id
- `remote_document_id` 应从 Dify 文档接口返回的 `id` 获取,不是 batch id
外部系统可使用本文档提供的接口,反查这条 Dify 文档在文档清洗系统中的本地映射关系,并获取原文件下载地址。
## 2. 接入原则
- 外部系统应由服务端调用查询接口,不要在前端浏览器中保存 `INTEGRATION_API_KEY`。
- 查询接口需要鉴权。
- 文件下载地址为短期签名链接,前端可直接打开,不需要再附带鉴权 key。
- 下载链接过期后,应重新调用查询接口获取新的下载链接。
## 3. 基础信息
- Base URL:`http://192.168.100.230:8891`
- 鉴权方式:HTTP Header
- Header 名称:`X-Integration-Key`
请求示例:
```http
X-Integration-Key: <平台分配的对接密钥>
```
说明:
- 该 key 由文档清洗系统平台方提供。
- 外部系统请将该 key 保存在自身服务端配置中,不要下发到前端页面。
## 4. 推荐对接流程
### 4.1 外部系统后端流程
1. 从 Dify 获取目标文档的:
- `dataset_id`
- `remote_document_id`
2. 调用文档清洗系统查询接口:
- `GET /api/integration/dify-file`
3. 解析返回结果,读取:
- 文件名
- 所属知识库
- 所属部门
- 原文件下载地址
4. 将需要展示的字段返回给自身前端页面。
5. 前端用户点击下载时,直接打开 `source_download_url`。
### 4.2 外部系统前端流程
1. 调用外部系统自己的后端接口。
2. 展示外部系统后端返回的文件信息。
3. 用户点击“下载原文件”时,直接访问 `source_download_url`。
4. 如果下载失败且提示链接失效,由外部系统后端重新查询一次并返回新链接。
## 5. 核心接口:按 Dify 文档反查本地文件
- 方法:`GET`
- 路径:`/api/integration/dify-file`
### 5.1 请求参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `dataset_id` | `string` | 是 | Dify 知识库 id |
| `remote_document_id` | `string` | 是 | Dify 文档 id,应取自 Dify 文档接口返回的 `id` |
### 5.2 请求头
```http
X-Integration-Key: <平台分配的对接密钥>
```
### 5.3 请求示例
```bash
curl -H "X-Integration-Key: YOUR_KEY" \
"http://192.168.100.230:8891/api/integration/dify-file?dataset_id=7a9f158c-90f5-478a-8956-2732c72a7546&remote_document_id=abcd1234"
```
### 5.4 成功响应示例
```json
{
"queried_at": "2026-04-01T12:00:00+08:00",
"document_id": 14,
"knowledge_base": {
"id": 3,
"name": "03 质量",
"department_id": 2,
"department_name": "质量部",
"dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546"
},
"title": "假期控制程序1",
"source_filename": "假期控制程序1.doc",
"source_ext": ".doc",
"file_name": "假期控制程序1.doc",
"version_id": 22,
"version_no": 1,
"convert_status": "success",
"sync_status": "synced",
"uploaded_at": "2026-04-01T11:32:10+08:00",
"converted_at": "2026-04-01T11:33:05+08:00",
"download_url_expires_at": "2026-04-01T12:15:00+08:00",
"source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx",
"markdown_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=md&token=yyyyy",
"markdown_download_url_expires_at": "2026-04-01T12:15:00+08:00",
"markdown_public_url": "http://192.168.100.230:8891/storage/markdown/group_0003/document_000014/v001/document.md",
"dify": {
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
"remote_document_id": "abcd1234",
"status": "synced",
"last_indexing_status": "completed",
"last_synced_at": "2026-04-01T11:34:20+08:00"
}
}
```
## 6. 核心接口:批量按 Dify 文档反查本地文件
- 方法:`POST`
- 路径:`/api/integration/dify-files/resolve`
### 6.1 请求头
```http
X-Integration-Key: <平台分配的对接密钥>
Content-Type: application/json
```
### 6.2 请求体
```json
{
"items": [
{
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
"remote_document_id": "abcd1234"
},
{
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
"remote_document_id": "efgh5678"
}
]
}
```
说明:
- `items` 为待查询列表。
- 建议每次批量查询控制在 `100` 条以内。
- 返回结果会按请求里的输入顺序返回。
- `remote_document_id` 应取自 Dify 文档接口返回的 `id`,不是 batch id。
### 6.3 请求示例
```bash
curl -X POST \
-H "X-Integration-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d "{\"items\":[{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"abcd1234\"},{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"efgh5678\"}]}" \
"http://192.168.100.230:8891/api/integration/dify-files/resolve"
```
### 6.4 成功响应示例
```json
{
"data": [
{
"request": {
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
"remote_document_id": "abcd1234"
},
"found": true,
"document": {
"document_id": 14,
"source_filename": "假期控制程序1.doc",
"source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx",
"knowledge_base": {
"id": 3,
"name": "03 质量",
"department_id": 2,
"department_name": "质量部",
"dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546"
},
"dify": {
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
"remote_document_id": "abcd1234"
}
}
},
{
"request": {
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
"remote_document_id": "efgh5678"
},
"found": false,
"document": null
}
]
}
```
### 6.5 返回说明
- `request`
- 原样回显本次输入的查询条件
- `found`
- 是否命中文档清洗系统中的本地映射
- `document`
- 命中时返回完整文档信息
- 未命中时返回 `null`
## 6.6 版本映射说明
- 反查接口返回的是“命中的同步版本”,不是盲目返回当前最新版本。
- 如果同一文档本地后来又上传了新版本,但新版本尚未同步到 Dify,接口仍会返回旧的已同步版本。
- 如果某条文档从未同步到 Dify,则不会存在可用的 `remote_document_id` 映射。
## 7. 返回字段说明
### 7.1 顶层字段
| 字段名 | 类型 | 说明 |
|---|---|---|
| `queried_at` | `string` | 本次查询结果生成时间 |
| `document_id` | `integer` | 文档清洗系统内部文档 id |
| `title` | `string` | 文档清洗系统内部文档标题 |
| `source_filename` | `string` | 原始上传文件名 |
| `source_ext` | `string` | 原文件扩展名 |
| `file_name` | `string` | 与 `source_filename` 相同,便于统一读取 |
| `version_id` | `integer` | 当前版本 id |
| `version_no` | `integer` | 当前版本号 |
| `convert_status` | `string` | 转换状态,如 `queued` `running` `success` `failed` |
| `sync_status` | `string` | 同步状态,如 `unsynced` `syncing` `synced` `sync_failed` |
| `uploaded_at` | `string` | 原文件上传时间 |
| `converted_at` | `string` | Markdown 转换完成时间 |
| `download_url_expires_at` | `string` | 原文件下载链接过期时间 |
| `source_download_url` | `string` | 原文件签名下载链接 |
| `markdown_download_url` | `string` | Markdown 签名下载链接 |
| `markdown_download_url_expires_at` | `string` | Markdown 下载链接过期时间 |
| `markdown_public_url` | `string` | Markdown 在本系统内的访问地址 |
| `knowledge_base` | `object` | 所属知识库信息 |
| `dify` | `object` | Dify 映射信息 |
### 7.2 `knowledge_base` 字段说明
| 字段名 | 类型 | 说明 |
|---|---|---|
| `id` | `integer` | 文档清洗系统内部知识库 id |
| `name` | `string` | 知识库名称 |
| `department_id` | `integer` \| `null` | 所属部门 id |
| `department_name` | `string` \| `null` | 所属部门名称 |
| `dify_dataset_id` | `string` \| `null` | 该知识库在 Dify 对应的 dataset id |
### 7.3 `dify` 字段说明
| 字段名 | 类型 | 说明 |
|---|---|---|
| `dataset_id` | `string` | Dify 知识库 id |
| `remote_document_id` | `string` | Dify 文档 id |
| `status` | `string` | 本地记录的最近同步状态 |
| `last_indexing_status` | `string` | Dify 最近索引状态 |
| `last_synced_at` | `string` \| `null` | 最近同步完成时间 |
## 8. 下载说明
### 8.1 下载接口
外部系统通常不需要自己拼下载接口,直接使用查询结果中的:
- `source_download_url`
- `markdown_download_url`
即可。
### 8.2 下载接口格式
- 方法:`GET`
- 路径:`/api/integration/download`
请求参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `version_id` | `integer` | 是 | 文档清洗系统内部版本 id |
| `kind` | `string` | 是 | `source` 或 `md` |
| `token` | `string` | 是 | 签名令牌 |
示例:
```text
http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx
```
### 8.3 下载接口说明
- 下载接口不需要再附带 `X-Integration-Key`。
- 这是一个短期签名链接,可直接在浏览器打开。
- 链接过期后,请重新调用查询接口获取新的下载链接。
## 9. 可选查询接口
如果外部系统不是从 Dify 文档开始反查,也可使用以下接口。
### 9.1 获取知识库列表
- 方法:`GET`
- 路径:`/api/integration/knowledge-bases`
查询参数:
| 参数名 | 必填 | 说明 |
|---|---|---|
| `department_id` | 否 | 按部门筛选 |
| `q` | 否 | 按知识库名称模糊搜索 |
请求示例:
```bash
curl -H "X-Integration-Key: YOUR_KEY" \
"http://192.168.100.230:8891/api/integration/knowledge-bases"
```
### 9.2 获取文件列表
- 方法:`GET`
- 路径:`/api/integration/files`
查询参数:
| 参数名 | 必填 | 说明 |
|---|---|---|
| `knowledge_base_id` | 否 | 按知识库筛选 |
| `department_id` | 否 | 按部门筛选 |
| `file_name` | 否 | 按文件名或标题模糊搜索 |
请求示例:
```bash
curl -H "X-Integration-Key: YOUR_KEY" \
"http://192.168.100.230:8891/api/integration/files?knowledge_base_id=3"
```
### 9.3 获取单个文件详情
- 方法:`GET`
- 路径:`/api/integration/files/{file_id}`
请求示例:
```bash
curl -H "X-Integration-Key: YOUR_KEY" \
"http://192.168.100.230:8891/api/integration/files/14"
```
## 10. 状态码说明
### 10.1 查询接口
| 状态码 | 说明 |
|---|---|
| `200` | 查询成功 |
| `401` | 鉴权失败,`X-Integration-Key` 无效 |
| `404` | 未找到对应的本地文件映射 |
| `503` | 接口未配置完成,通常为平台未配置 `INTEGRATION_API_KEY` |
### 10.2 下载接口
| 状态码 | 说明 |
|---|---|
| `200` | 下载成功 |
| `401` | 签名无效或已过期 |
| `404` | 文件不存在 |
| `409` | 请求 `md`,但 Markdown 尚未生成 |
## 11. 对接建议
- 外部系统前端不要直接调用查询接口。
- 外部系统后端负责:
- 保存 integration key
- 调用查询接口
- 将结果整理后返回给自身前端
- 外部系统前端负责:
- 展示文件信息
- 使用 `source_download_url` 直接下载原文件
## 12. 最小接入流程
1. 外部系统从 Dify 获取:
- `dataset_id`
- `remote_document_id`
2. 外部系统后端调用:
- `GET /api/integration/dify-file?dataset_id=...&remote_document_id=...`
3. 从返回结果中读取:
- `source_filename`
- `source_download_url`
- `knowledge_base.name`
- `knowledge_base.department_name`
4. 将上述字段展示给用户。
5. 用户点击下载时,直接打开 `source_download_url`。
## 13. 对接注意事项
- `source_download_url` 为短期签名链接,不是永久地址。
- `source_download_url` 可直接用于下载,无需再次附加鉴权 key。
- 若链接过期,外部系统应重新调用查询接口获取新链接。
- 若返回 `404`,表示该 Dify 文档在文档清洗系统中没有本地文件映射。
+36
View File
@@ -0,0 +1,36 @@
# hxops
#### Description
hxops
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
+25 -198
View File
@@ -1,210 +1,37 @@
# Document Cleaning
# hxops
Independent internal web system for document cleaning, version tracking, batch download, and manual sync into Dify datasets.
#### 介绍
hxops
## Stack
#### 软件架构
软件架构说明
- Frontend: Vue 3, Vite, Tailwind, Uppy
- Backend: FastAPI, SQLAlchemy, Alembic
- Queue: RQ + Redis
- Worker runtime: Python + LibreOffice
- Database: SQLite or PostgreSQL (configurable)
## Project Layout
#### 安装教程
- `frontend/`: Vue workspace UI
- `backend/`: FastAPI API, RQ worker tasks, vendored `edkb_system`
- `project-governance/`: Codex skill governance, workflow docs, and audit snapshots
- `docker-compose.yml`: full deployment stack for `192.168.100.230`
1. xxxx
2. xxxx
3. xxxx
## Local Run
#### 使用说明
1. Copy `.env.example` to `.env` and fill in `DIFY_API_KEY`.
2. Start services:
1. xxxx
2. xxxx
3. xxxx
```bash
docker compose up --build -d
```
#### 参与贡献
3. Open `http://localhost:8891`.
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
Default login comes from `.env`:
- username: `admin`
- password: `admin123456`
#### 特技
## Local Direct Run Without Docker
Use this mode on a workstation that does not have Docker available.
1. Copy `backend/backend.env.example` to `backend/.env`.
2. Choose a database mode in `backend/.env`:
```env
# Option A: local SQLite
DATABASE_BACKEND=sqlite
DATABASE_URL=
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
# Option B: local/shared PostgreSQL
DATABASE_BACKEND=postgres
DATABASE_URL=
POSTGRES_DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
```
`DATABASE_URL` remains supported as a direct override. If it is set, it takes priority over `DATABASE_BACKEND`.
3. Keep `TASK_EXECUTION_MODE=sync` for local smoke tests.
4. You can now use the project-local Python runtime under `python/`.
5. Start the backend:
```bash
cd backend
python -m alembic upgrade head
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
```
6. Start the frontend in another terminal:
```bash
cd frontend
npm run dev -- --host 127.0.0.1 --port 5174
```
7. Open `http://127.0.0.1:5174`.
Convenience scripts in the project root:
```powershell
.\start-local-backend.ps1
.\start-local-frontend.ps1
.\start-local-dev.ps1
```
Notes:
- `start-local-backend.ps1` runs Alembic first, then starts FastAPI.
- `start-local-frontend.ps1` starts the Vite dev server.
- `start-local-dev.ps1` starts both in background and writes logs to `tmp_run/`.
Notes:
- In local direct mode, queue tasks run inline through the API process.
- Real Dify sync still requires a valid `DIFY_API_KEY`.
- Server deployment should continue using `docker compose`.
## Production Deployment
The compose file is already configured for the planned entrypoint:
- `http://192.168.100.230:8891`
Deploy on the target server with:
```bash
docker compose --env-file .env up --build -d
```
Database selection is now configurable through `.env`:
```env
# Option A: use the compose PostgreSQL service
DATABASE_BACKEND=postgres
DATABASE_URL=
POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning
# Option B: use SQLite
DATABASE_BACKEND=sqlite
DATABASE_URL=
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
# Option C: explicit override
DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
```
Notes:
- `DATABASE_URL` has the highest priority.
- When running inside Docker, `localhost` points to the container itself. A host-level PostgreSQL service must use a reachable host name or IP instead of `localhost`.
Current deployment path on the server:
- `/home/inspur/tools/document-cleaning`
## Core Flows
- Upload one or many files into a group.
- Deduplicate by `SHA-256` within the same group.
- Create a new version when title matches but content changed.
- Convert in the background through RQ workers.
- Download original files or generated markdown individually or in bulk.
- Manually sync selected documents to Dify.
- Auto-create a Dify dataset on first sync for each group.
## Dify Integration
- Group name maps to one Dify dataset.
- Sync uses cleaned markdown text, not the raw original file.
- Existing logical documents are updated in Dify instead of duplicated.
- Dataset defaults are managed in the admin console.
## External Integration API
Use this when another internal site needs to query knowledge-base/file relationships without direct database access.
1. Set `INTEGRATION_API_KEY` in `.env`.
2. Optionally set `INTEGRATION_DOWNLOAD_SECRET` to a dedicated signing secret. If omitted, the app falls back to `JWT_SECRET`.
3. Call the query API with `X-Integration-Key: <your key>`.
Recommended pattern:
- External site backend stores `INTEGRATION_API_KEY`
- Backend calls this system's query API
- Query response returns short-lived signed download URLs
- External site frontend opens those signed URLs directly without carrying the integration key
Example endpoints:
- `GET /api/integration/knowledge-bases`
- `GET /api/integration/files?knowledge_base_id=123`
- `GET /api/integration/files?file_name=report`
- `GET /api/integration/files/456`
- `GET /api/integration/dify-file?dataset_id=<dify_dataset_id>&remote_document_id=<dify_document_id>`
- `GET /api/integration/download?version_id=<local_version_id>&kind=source&token=<signed token>`
- `GET /api/integration/download?version_id=<local_version_id>&kind=md&token=<signed token>`
## Dify Sync Throttling
To avoid overloading Dify when many files are pushed at once, sync jobs now support retry backoff and a short global cooldown gate.
Relevant `.env` knobs:
```env
DIFY_SYNC_MAX_RETRIES=4
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
DIFY_SYNC_COOLDOWN_SECONDS=60
```
Behavior:
- Retryable Dify congestion errors such as `too many clients already` are not marked failed immediately.
- The sync job is re-queued with backoff.
- A short global cooldown prevents the next sync jobs from hammering Dify during the same congestion window.
## Tests
Backend:
```bash
cd backend
python -m pytest tests -q
```
Frontend:
```bash
cd frontend
npm install
npm run build
```
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
-20
View File
@@ -1,20 +0,0 @@
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends libreoffice fonts-noto-cjk curl \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY . /app
EXPOSE 8000
CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
-36
View File
@@ -1,36 +0,0 @@
[alembic]
script_location = migrations
sqlalchemy.url = sqlite:///./document_cleaning.db
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers = console
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
-1
View File
@@ -1 +0,0 @@
"""Document Cleaning backend package."""
-1
View File
@@ -1 +0,0 @@
from app.api import admin, auth, files, groups, integration, jobs
-454
View File
@@ -1,454 +0,0 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, or_
from sqlalchemy.orm import Session, joinedload
from app.config import get_settings
from app.database import get_db
from app.deps import require_admin
from app.models import Department, Document, DocumentVersion, Group, Job, SystemSetting, User, UserDepartmentAccess, UserGroupAccess
from app.schemas import (
DepartmentCreateRequest,
DepartmentDeleteRequest,
DepartmentUpdateRequest,
SettingsUpdateRequest,
UserCreateRequest,
UserUpdateRequest,
)
from app.security import hash_password
from app.serializers import serialize_department, serialize_settings, serialize_user
from app.services.dify_service import DifyError, DifyService
from app.services.watchdog_service import (
local_convert_health_summary,
local_sync_health_summary,
read_watchdog_snapshot,
recover_stale_converts,
recover_stale_syncs,
)
from app.user_policy import PRIMARY_SUPER_ADMIN_USERNAME, is_primary_super_admin_username
router = APIRouter(prefix="/admin", tags=["admin"])
def _replace_user_department_access(db: Session, *, user_id: int, primary_department_id: int | None, department_ids: list[int]) -> None:
existing_accesses = db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user_id).all()
for access in existing_accesses:
db.delete(access)
db.flush()
requested_ids = sorted({item for item in department_ids if item is not None} | ({primary_department_id} if primary_department_id is not None else set()))
if not requested_ids:
return
existing_ids = {row[0] for row in db.query(Department.id).filter(Department.id.in_(requested_ids)).all()}
missing_ids = sorted(set(requested_ids) - existing_ids)
if missing_ids:
raise HTTPException(
status_code=404,
detail=f"Department(s) not found: {', '.join(map(str, missing_ids))}",
)
for department_id in requested_ids:
if department_id == primary_department_id:
continue
db.add(UserDepartmentAccess(user_id=user_id, department_id=department_id))
def _validate_super_admin_constraints(*, username: str, requested_role: str | None, requested_active: bool | None = None) -> None:
if requested_role == "super_admin" and not is_primary_super_admin_username(username):
raise HTTPException(status_code=400, detail=f"Only {PRIMARY_SUPER_ADMIN_USERNAME} can be a super admin.")
if is_primary_super_admin_username(username):
if requested_role is not None and requested_role != "super_admin":
raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} must remain a super admin.")
if requested_active is False:
raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} cannot be deactivated.")
def _department_metrics_query(db: Session):
knowledge_base_counts = (
db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count"))
.group_by(Group.department_id)
.subquery()
)
primary_user_counts = (
db.query(
User.primary_department_id.label("department_id"),
func.count(User.id).label("primary_user_count"),
)
.group_by(User.primary_department_id)
.subquery()
)
extra_user_counts = (
db.query(
UserDepartmentAccess.department_id.label("department_id"),
func.count(UserDepartmentAccess.id).label("extra_user_count"),
)
.group_by(UserDepartmentAccess.department_id)
.subquery()
)
return (
db.query(
Department,
(func.coalesce(primary_user_counts.c.primary_user_count, 0) + func.coalesce(extra_user_counts.c.extra_user_count, 0)).label(
"user_count"
),
func.coalesce(knowledge_base_counts.c.knowledge_base_count, 0).label("knowledge_base_count"),
)
.outerjoin(primary_user_counts, primary_user_counts.c.department_id == Department.id)
.outerjoin(extra_user_counts, extra_user_counts.c.department_id == Department.id)
.outerjoin(knowledge_base_counts, knowledge_base_counts.c.department_id == Department.id)
.order_by(Department.name.asc())
)
def _department_reference_summary(db: Session, department_id: int) -> dict[str, int]:
return {
"knowledge_base_count": db.query(func.count(Group.id)).filter(Group.department_id == department_id).scalar() or 0,
"primary_user_count": db.query(func.count(User.id)).filter(User.primary_department_id == department_id).scalar() or 0,
"extra_user_count": db.query(func.count(UserDepartmentAccess.id)).filter(UserDepartmentAccess.department_id == department_id).scalar() or 0,
}
@router.get("/departments")
def list_all_departments(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
rows = _department_metrics_query(db).all()
return {
"data": [
serialize_department(item, user_count=user_count, knowledge_base_count=knowledge_base_count)
for item, user_count, knowledge_base_count in rows
]
}
@router.post("/departments")
def create_department(
payload: DepartmentCreateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
name = payload.name.strip()
if not name:
raise HTTPException(status_code=400, detail="Department name is required.")
exists = db.query(Department).filter(func.lower(Department.name) == name.lower()).first()
if exists:
raise HTTPException(status_code=409, detail="Department already exists.")
department = Department(name=name, description=payload.description)
db.add(department)
db.commit()
db.refresh(department)
return serialize_department(department)
@router.patch("/departments/{department_id}")
def update_department(
department_id: int,
payload: DepartmentUpdateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
department = db.query(Department).filter(Department.id == department_id).first()
if not department:
raise HTTPException(status_code=404, detail="Department not found.")
if payload.name is not None:
name = payload.name.strip()
if not name:
raise HTTPException(status_code=400, detail="Department name is required.")
conflict = (
db.query(Department)
.filter(func.lower(Department.name) == name.lower(), Department.id != department_id)
.first()
)
if conflict:
raise HTTPException(status_code=409, detail="Department already exists.")
department.name = name
if payload.description is not None:
department.description = payload.description
db.commit()
db.refresh(department)
return serialize_department(department)
@router.delete("/departments/{department_id}")
def delete_department(
department_id: int,
payload: DepartmentDeleteRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
department = db.query(Department).filter(Department.id == department_id).first()
if not department:
raise HTTPException(status_code=404, detail="Department not found.")
target_department = None
if payload.target_department_id is not None:
if payload.target_department_id == department_id:
raise HTTPException(status_code=400, detail="Migration target must be a different department.")
target_department = db.query(Department).filter(Department.id == payload.target_department_id).first()
if not target_department:
raise HTTPException(status_code=404, detail="Migration target department not found.")
reference_summary = _department_reference_summary(db, department_id)
has_references = any(reference_summary.values())
if has_references and target_department is None:
raise HTTPException(
status_code=400,
detail="Department still has knowledge bases or users. Choose another department to migrate first.",
)
if target_department is not None:
db.query(Group).filter(Group.department_id == department_id).update(
{Group.department_id: target_department.id},
synchronize_session=False,
)
affected_users = (
db.query(User)
.options(joinedload(User.department_accesses))
.filter(
or_(
User.primary_department_id == department_id,
User.department_accesses.any(UserDepartmentAccess.department_id == department_id),
)
)
.all()
)
for user in affected_users:
if user.primary_department_id == department_id:
user.primary_department_id = target_department.id
migrated_access_ids = [access.department_id for access in user.department_accesses if access.department_id != department_id]
if user.primary_department_id != target_department.id:
migrated_access_ids.append(target_department.id)
_replace_user_department_access(
db,
user_id=user.id,
primary_department_id=user.primary_department_id,
department_ids=migrated_access_ids,
)
db.query(Department).filter(Department.id == department_id).delete(synchronize_session=False)
db.commit()
return {
"deleted_department_id": department_id,
"migrated_to_department_id": target_department.id if target_department else None,
**reference_summary,
}
@router.get("/users")
def list_users(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
users = (
db.query(User)
.options(joinedload(User.primary_department), joinedload(User.department_accesses))
.order_by(User.username.asc())
.all()
)
return {"data": [serialize_user(item) for item in users]}
@router.post("/users")
def create_user(
payload: UserCreateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
if payload.primary_department_id is None:
raise HTTPException(status_code=400, detail="Primary department is required.")
exists = db.query(User).filter(User.username == payload.username).first()
if exists:
raise HTTPException(status_code=409, detail="Username already exists.")
_validate_super_admin_constraints(username=payload.username, requested_role=payload.role, requested_active=True)
user = User(
username=payload.username,
full_name=payload.full_name,
password_hash=hash_password(payload.password),
role=payload.role,
is_active=True,
primary_department_id=payload.primary_department_id,
)
db.add(user)
db.flush()
db.refresh(user)
_replace_user_department_access(
db,
user_id=user.id,
primary_department_id=payload.primary_department_id,
department_ids=payload.accessible_department_ids,
)
db.commit()
db.refresh(user)
return serialize_user(user)
@router.patch("/users/{user_id}")
def update_user(
user_id: int,
payload: UserUpdateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
user = db.query(User).options(joinedload(User.department_accesses)).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found.")
_validate_super_admin_constraints(
username=user.username,
requested_role=payload.role,
requested_active=payload.is_active,
)
if payload.full_name is not None:
user.full_name = payload.full_name
if payload.role is not None:
user.role = payload.role
if payload.is_active is not None:
user.is_active = payload.is_active
if payload.password:
user.password_hash = hash_password(payload.password)
target_primary_department_id = payload.primary_department_id if payload.primary_department_id is not None else user.primary_department_id
if payload.primary_department_id is not None:
user.primary_department_id = payload.primary_department_id
if payload.accessible_department_ids is not None or payload.primary_department_id is not None:
_replace_user_department_access(
db,
user_id=user.id,
primary_department_id=target_primary_department_id,
department_ids=payload.accessible_department_ids or [],
)
db.commit()
db.refresh(user)
return serialize_user(user)
@router.delete("/users/{user_id}")
def delete_user(
user_id: int,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found.")
if is_primary_super_admin_username(user.username):
raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} cannot be deleted.")
if user.id == admin.id:
raise HTTPException(status_code=400, detail="You cannot delete your own account.")
db.query(Group).filter(Group.created_by_id == user_id).update({Group.created_by_id: None}, synchronize_session=False)
db.query(Document).filter(Document.created_by_id == user_id).update({Document.created_by_id: None}, synchronize_session=False)
db.query(DocumentVersion).filter(DocumentVersion.uploader_id == user_id).update(
{DocumentVersion.uploader_id: None},
synchronize_session=False,
)
db.query(Job).filter(Job.created_by_id == user_id).update({Job.created_by_id: None}, synchronize_session=False)
db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user_id).delete(synchronize_session=False)
db.query(UserGroupAccess).filter(UserGroupAccess.user_id == user_id).delete(synchronize_session=False)
db.query(User).filter(User.id == user_id).delete(synchronize_session=False)
db.commit()
return {"deleted_user_id": user_id}
@router.get("/settings")
def get_settings_row(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
settings_row = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
if not settings_row:
raise HTTPException(status_code=404, detail="Settings not found.")
return serialize_settings(settings_row)
@router.get("/dify-models")
def list_dify_models(admin: User = Depends(require_admin)):
try:
dify = DifyService()
embedding_models = dify.list_available_embedding_models()
rerank_models = dify.list_available_rerank_models()
default_embedding_provider, default_embedding_model = dify.resolve_embedding_model_choice()
default_rerank_provider, default_rerank_model = dify.resolve_rerank_model_choice()
except DifyError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
return {
"embedding_models": [
{"provider": item.provider, "model": item.model, "label": item.label}
for item in embedding_models
],
"rerank_models": [
{"provider": item.provider, "model": item.model, "label": item.label}
for item in rerank_models
],
"automatic_defaults": {
"embedding_model_provider": default_embedding_provider,
"embedding_model": default_embedding_model,
"reranking_model_provider": default_rerank_provider,
"reranking_model": default_rerank_model,
},
}
@router.get("/dify-health")
def get_dify_health(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
settings = get_settings()
return {
"dify_base_url": settings.dify_base_url,
"dify_api_configured": bool(settings.dify_api_key),
"watchdog_snapshot": read_watchdog_snapshot(settings),
"local_convert_health": local_convert_health_summary(
db,
timeout_seconds=settings.watchdog_stale_convert_timeout_seconds,
orphan_grace_seconds=settings.watchdog_convert_orphan_grace_seconds,
settings=settings,
),
"local_sync_health": local_sync_health_summary(
db,
timeout_seconds=settings.watchdog_stale_sync_timeout_seconds,
),
}
@router.post("/recover-stale-syncs")
def run_stale_sync_recovery(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
settings = get_settings()
return recover_stale_syncs(
db,
timeout_seconds=settings.watchdog_stale_sync_timeout_seconds,
)
@router.post("/recover-stale-converts")
def run_stale_convert_recovery(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
settings = get_settings()
return recover_stale_converts(
db,
timeout_seconds=settings.watchdog_stale_convert_timeout_seconds,
orphan_grace_seconds=settings.watchdog_convert_orphan_grace_seconds,
settings=settings,
)
@router.patch("/settings")
def update_settings_row(
payload: SettingsUpdateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
settings_row = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
if not settings_row:
raise HTTPException(status_code=404, detail="Settings not found.")
for field in [
"dify_permission",
"indexing_technique",
"search_method",
"doc_form",
"embedding_model_provider",
"embedding_model",
"reranking_model_provider",
"reranking_model",
"top_k",
"score_threshold_enabled",
]:
value = getattr(payload, field)
if value is not None:
setattr(settings_row, field, value)
if payload.score_threshold is not None:
settings_row.score_threshold = str(payload.score_threshold)
db.commit()
db.refresh(settings_row)
return serialize_settings(settings_row)
-23
View File
@@ -1,23 +0,0 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.database import get_db
from app.models import User
from app.schemas import LoginRequest, TokenResponse
from app.security import create_access_token, verify_password
from app.serializers import serialize_user
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login", response_model=TokenResponse)
def login(payload: LoginRequest, db: Session = Depends(get_db)):
user = db.query(User).filter(User.username == payload.username, User.is_active.is_(True)).first()
if not user or not verify_password(payload.password, user.password_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
token = create_access_token(user.username)
return TokenResponse(access_token=token, user=serialize_user(user))
-32
View File
@@ -1,32 +0,0 @@
from __future__ import annotations
from fastapi import APIRouter, Depends
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.database import get_db
from app.deps import accessible_department_ids, get_current_user
from app.models import Department, Group, User
from app.serializers import serialize_department
router = APIRouter(prefix="/departments", tags=["departments"])
@router.get("")
def list_departments(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
department_ids = accessible_department_ids(db, user)
group_counts = (
db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count"))
.group_by(Group.department_id)
.subquery()
)
query = (
db.query(Department, func.coalesce(group_counts.c.knowledge_base_count, 0).label("knowledge_base_count"))
.outerjoin(group_counts, group_counts.c.department_id == Department.id)
.order_by(Department.name.asc())
)
if department_ids is not None:
query = query.filter(Department.id.in_(department_ids or [-1]))
rows = query.all()
return {"data": [serialize_department(item, knowledge_base_count=count) for item, count in rows]}
-490
View File
@@ -1,490 +0,0 @@
from __future__ import annotations
import shutil
import uuid
from datetime import date
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
from sqlalchemy import func
from sqlalchemy.orm import Session, joinedload
from app.config import get_settings
from app.database import get_db
from app.deps import accessible_group_ids, ensure_group_access, get_current_user
from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, User
from app.schemas import BatchDownloadRequest, BatchSyncRequest
from app.serializers import current_version, serialize_document, serialize_job, serialize_version
from app.services.queue_service import get_queue
from app.services.storage_service import build_zip, remove_path_if_exists, sha256_file, version_dir
router = APIRouter(prefix="/files", tags=["files"])
settings = get_settings()
MAX_BATCH_UPLOAD_FILES = 500
def _group_scope_filter(db: Session, user: User):
group_ids = accessible_group_ids(db, user)
return None if group_ids is None else (group_ids or [-1])
def _get_document_for_user(db: Session, user: User, file_id: int) -> Document | None:
query = (
db.query(Document)
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
.filter(Document.id == file_id, Document.is_deleted.is_(False))
)
group_ids = _group_scope_filter(db, user)
if group_ids is not None:
query = query.filter(Document.group_id.in_(group_ids))
return query.first()
def _create_job(
db: Session,
*,
job_type: str,
created_by_id: int,
group_id: int,
document_id: int,
version_id: int,
payload: dict | None = None,
) -> Job:
job = Job(
id=str(uuid.uuid4()),
job_type=job_type,
status="queued",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=created_by_id,
payload=payload or {},
)
db.add(job)
db.commit()
db.refresh(job)
return job
def _enqueue(job: Job, task_name: str, version_id: int, db: Session) -> Job:
return _enqueue_args(job, task_name, db, version_id)
def _enqueue_args(job: Job, task_name: str, db: Session, *task_args) -> Job:
queue = get_queue()
rq_job = queue.enqueue(task_name, job.id, *task_args)
job.queue_job_id = rq_job.id
db.commit()
db.refresh(job)
return job
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
if not path_value:
return None
raw_target = Path(path_value)
data_root = settings.data_root.resolve(strict=False)
if raw_target.is_absolute():
target = raw_target
else:
resolved_raw = raw_target.resolve(strict=False)
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
if parent:
target = target.parent
resolved = target.resolve(strict=False)
if not resolved.is_relative_to(data_root):
return None
return resolved
def _cleanup_document_storage(document: Document) -> None:
targets: set[Path] = set()
for version in document.versions:
for candidate in (
_resolve_storage_target(version.source_path, parent=True),
_resolve_storage_target(version.md_path, parent=True),
_resolve_storage_target(version.asset_dir),
):
if candidate is not None:
targets.add(candidate)
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
remove_path_if_exists(target)
@router.post("/upload")
async def upload_files(
group_id: int = Form(...),
files: list[UploadFile] = File(default_factory=list),
file: UploadFile | None = File(None),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
ensure_group_access(db, user, group_id)
group = db.query(Group).filter(Group.id == group_id).first()
if not group:
raise HTTPException(status_code=404, detail="Group not found.")
incoming = list(files)
if file is not None:
incoming.append(file)
if not incoming:
raise HTTPException(status_code=400, detail="No files uploaded.")
if len(incoming) > MAX_BATCH_UPLOAD_FILES:
raise HTTPException(
status_code=400,
detail=f"Batch upload accepts at most {MAX_BATCH_UPLOAD_FILES} files at a time.",
)
created: list[dict] = []
duplicates: list[dict] = []
for upload in incoming:
tmp_dir = settings.data_root / "tmp" / "uploads"
tmp_dir.mkdir(parents=True, exist_ok=True)
tmp_path = tmp_dir / f"{uuid.uuid4()}_{Path(upload.filename).name}"
with tmp_path.open("wb") as handle:
while True:
chunk = await upload.read(1024 * 1024)
if not chunk:
break
handle.write(chunk)
digest = sha256_file(tmp_path)
ext = Path(upload.filename).suffix.lower()
title = Path(upload.filename).stem
duplicate_version = (
db.query(DocumentVersion)
.join(Document, Document.id == DocumentVersion.document_id)
.filter(
Document.group_id == group.id,
Document.is_deleted.is_(False),
DocumentVersion.source_sha256 == digest,
)
.first()
)
if duplicate_version:
duplicates.append(
{
"filename": upload.filename,
"document_id": duplicate_version.document_id,
"version_id": duplicate_version.id,
"reason": "same_sha256_in_group",
}
)
tmp_path.unlink(missing_ok=True)
continue
document = (
db.query(Document)
.options(joinedload(Document.versions))
.filter(
Document.group_id == group.id,
func.lower(Document.title) == title.lower(),
Document.is_deleted.is_(False),
)
.first()
)
if document is None:
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version_no = 1
else:
for item in document.versions:
if item.is_current:
item.is_current = False
db.commit()
version_no = (document.versions[0].version_no + 1) if document.versions else 1
sync_status = "unsynced"
prior_sync = (
db.query(DifySyncRecord)
.join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id)
.filter(DocumentVersion.document_id == document.id, DifySyncRecord.status == "synced")
.first()
)
if prior_sync:
sync_status = "stale"
source_dir = version_dir("original", group.id, document.id, version_no)
source_dir.mkdir(parents=True, exist_ok=True)
final_source = source_dir / Path(upload.filename).name
shutil.move(str(tmp_path), str(final_source))
version = DocumentVersion(
document_id=document.id,
version_no=version_no,
is_current=True,
source_filename=Path(upload.filename).name,
source_ext=ext,
source_path=str(final_source),
source_sha256=digest,
file_size=final_source.stat().st_size,
uploader_id=user.id,
convert_status="queued",
sync_status=sync_status,
)
db.add(version)
db.commit()
db.refresh(version)
job = _create_job(
db,
job_type="convert",
created_by_id=user.id,
group_id=group.id,
document_id=document.id,
version_id=version.id,
payload={"filename": upload.filename},
)
_enqueue(job, "app.tasks.run_convert_job", version.id, db)
created.append(
{
"document_id": document.id,
"version_id": version.id,
"job": serialize_job(job),
}
)
return {"created": created, "duplicates": duplicates}
@router.get("/group/{group_id}")
def list_group_files(
group_id: int,
q: str | None = None,
status: str | None = None,
sync_status: str | None = None,
file_type: str | None = None,
uploaded_from: str | None = None,
uploaded_to: str | None = None,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
ensure_group_access(db, user, group_id)
query = (
db.query(Document)
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
.order_by(Document.updated_at.desc())
)
documents = query.all()
filtered: list[Document] = []
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
for document in documents:
version = current_version(document)
if version is None:
continue
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
if q and q.lower() not in document.title.lower():
continue
if status and version.convert_status != status:
continue
if sync_status and version.sync_status != sync_status:
continue
if file_type and version.source_ext != file_type:
continue
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
continue
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
continue
filtered.append(document)
return {"data": [serialize_document(document) for document in filtered]}
@router.get("/{file_id}")
def get_file(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
document = _get_document_for_user(db, user, file_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
payload = serialize_document(document)
payload["versions"] = [serialize_version(item) for item in document.versions]
return payload
@router.get("/{file_id}/download")
def download_file(
file_id: int,
kind: str = Query("md"),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
document = _get_document_for_user(db, user, file_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
version = current_version(document)
if not version:
raise HTTPException(status_code=404, detail="No version found.")
if kind == "source":
path = Path(version.source_path)
filename = version.source_filename
else:
if not version.md_path:
raise HTTPException(status_code=409, detail="Markdown not ready.")
path = Path(version.md_path)
filename = f"{document.title}.md"
if not path.exists():
raise HTTPException(status_code=404, detail="File missing on disk.")
return FileResponse(path, filename=filename)
@router.post("/download-batch")
def batch_download(
payload: BatchDownloadRequest,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
query = (
db.query(Document)
.options(joinedload(Document.versions))
.filter(Document.id.in_(payload.document_ids), Document.is_deleted.is_(False))
)
group_ids = _group_scope_filter(db, user)
if group_ids is not None:
query = query.filter(Document.group_id.in_(group_ids))
documents = query.all()
if not documents:
raise HTTPException(status_code=404, detail="No documents found.")
bundle_id = str(uuid.uuid4())
bundle_dir = settings.data_root / "tmp" / "downloads"
bundle_path = bundle_dir / f"download_{bundle_id}.zip"
entries: list[tuple[Path, str]] = []
for document in documents:
version = current_version(document)
if not version:
continue
if payload.kind == "source":
entries.append((Path(version.source_path), version.source_filename))
else:
if version.md_path:
entries.append((Path(version.md_path), f"{document.title}.md"))
if not entries:
raise HTTPException(status_code=409, detail="No downloadable files available.")
build_zip(entries, bundle_path)
download_date = date.today().strftime("%Y%m%d")
return FileResponse(bundle_path, filename=f"文件下载_{download_date}.zip")
@router.post("/{file_id}/retry-convert")
def retry_convert(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
document = _get_document_for_user(db, user, file_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
version = current_version(document)
if not version:
raise HTTPException(status_code=404, detail="Version not found.")
job = _create_job(
db,
job_type="convert",
created_by_id=user.id,
group_id=document.group_id,
document_id=document.id,
version_id=version.id,
payload={"retry": True},
)
_enqueue(job, "app.tasks.run_convert_job", version.id, db)
return serialize_job(job)
@router.post("/{file_id}/sync-dify")
def sync_dify(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
document = _get_document_for_user(db, user, file_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
version = current_version(document)
if not version or version.convert_status != "success":
raise HTTPException(status_code=409, detail="Document is not ready for sync.")
if version.sync_status == "synced":
raise HTTPException(status_code=409, detail="Current version is already synced to Dify.")
if version.sync_status == "syncing":
raise HTTPException(status_code=409, detail="Current version is already syncing to Dify.")
version.sync_status = "syncing"
db.commit()
job = _create_job(
db,
job_type="sync",
created_by_id=user.id,
group_id=document.group_id,
document_id=document.id,
version_id=version.id,
payload={"single": True},
)
_enqueue(job, "app.tasks.run_sync_job", version.id, db)
return serialize_job(job)
@router.post("/sync-dify-batch")
def batch_sync(
payload: BatchSyncRequest,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
query = db.query(Document).options(joinedload(Document.versions)).filter(Document.id.in_(payload.document_ids))
group_ids = _group_scope_filter(db, user)
if group_ids is not None:
query = query.filter(Document.group_id.in_(group_ids))
documents = query.all()
jobs: list[dict] = []
for document in documents:
if document.is_deleted:
continue
version = current_version(document)
if not version or version.convert_status != "success":
continue
if version.sync_status in {"synced", "syncing"}:
continue
version.sync_status = "syncing"
db.commit()
job = _create_job(
db,
job_type="sync",
created_by_id=user.id,
group_id=document.group_id,
document_id=document.id,
version_id=version.id,
payload={"batch": True},
)
_enqueue(job, "app.tasks.run_sync_job", version.id, db)
jobs.append(serialize_job(job))
return {"data": jobs}
@router.delete("/{file_id}")
def delete_file(
file_id: int,
delete_dify: bool = Query(False),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
document = _get_document_for_user(db, user, file_id)
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
version = current_version(document)
original_title = document.title
document.is_deleted = True
document.title = f"{document.title}__deleted__{document.id}"
db.commit()
try:
job = _create_job(
db,
job_type="delete",
created_by_id=user.id,
group_id=document.group_id,
document_id=document.id,
version_id=version.id if version else None,
payload={"delete_dify": delete_dify},
)
_enqueue_args(job, "app.tasks.run_delete_document_job", db, document.id)
except Exception:
document.is_deleted = False
document.title = original_title
db.commit()
raise
return {"deleted": True}
-757
View File
@@ -1,757 +0,0 @@
from __future__ import annotations
from datetime import date
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, or_
from sqlalchemy.orm import Session, joinedload
from app.config import get_settings
from app.database import get_db
from app.deps import (
accessible_department_ids,
accessible_group_ids,
ensure_department_access,
ensure_group_access,
get_current_user,
require_admin,
)
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, SystemSetting, User
from app.schemas import DifyImportRequest, GroupCreateRequest, GroupUpdateRequest
from app.serializers import current_version, serialize_document, serialize_group
from app.services.dify_service import DifyError, DifyService
from app.services.storage_service import public_storage_url, remove_path_if_exists, sha256_file, version_dir
from app.time_utils import utc_now
import requests
router = APIRouter(prefix="/groups", tags=["groups"])
settings = get_settings()
def _scoped_group_ids(db: Session, user: User) -> list[int] | None:
return accessible_group_ids(db, user)
def _scoped_department_ids(db: Session, user: User) -> list[int] | None:
return accessible_department_ids(db, user)
def _scoped_groups_query(db: Session, user: User, *, department_id: int | None = None):
query = db.query(Group)
group_ids = _scoped_group_ids(db, user)
if group_ids is not None:
query = query.filter(Group.id.in_(group_ids or [-1]))
if department_id is not None:
query = query.filter(Group.department_id == department_id)
return query
def _document_name_key(name: str) -> str:
trimmed = (name or "").strip().lower()
candidate = Path(trimmed)
return candidate.stem if candidate.suffix else trimmed
def _normalized_document_title(name: str) -> str:
candidate = Path((name or "").strip())
return candidate.stem if candidate.suffix else candidate.name
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
if not path_value:
return None
raw_target = Path(path_value)
data_root = settings.data_root.resolve(strict=False)
if raw_target.is_absolute():
target = raw_target
else:
resolved_raw = raw_target.resolve(strict=False)
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
if parent:
target = target.parent
resolved = target.resolve(strict=False)
if not resolved.is_relative_to(data_root):
return None
return resolved
def _cleanup_document_storage(document: Document) -> None:
targets: set[Path] = set()
for version in document.versions:
for candidate in (
_resolve_storage_target(version.source_path, parent=True),
_resolve_storage_target(version.md_path, parent=True),
_resolve_storage_target(version.asset_dir),
):
if candidate is not None:
targets.add(candidate)
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
remove_path_if_exists(target)
def _local_documents_for_group(group: Group) -> dict[str, list[dict]]:
local_docs: dict[str, list[dict]] = {}
for document in group.documents:
if document.is_deleted:
continue
version = current_version(document)
if version is None:
continue
local_docs.setdefault(_document_name_key(document.title), []).append(
{
"document_id": document.id,
"title": document.title,
"source_ext": version.source_ext,
"convert_status": version.convert_status,
"sync_status": version.sync_status,
"remote_document_id": version.sync_records[0].remote_document_id if version.sync_records else None,
}
)
return local_docs
def _remote_documents_for_dataset(dify: DifyService, dataset_id: str | None) -> dict[str, list[dict]]:
if not dataset_id:
return {}
remote_docs: dict[str, list[dict]] = {}
for remote in dify.list_documents(dataset_id=dataset_id):
remote_docs.setdefault(_document_name_key(remote.name), []).append(
{
"document_id": remote.id,
"name": remote.name,
"indexing_status": remote.indexing_status,
"display_status": remote.display_status,
"enabled": remote.enabled,
}
)
return remote_docs
def _diff_status(local_entry: dict | None, remote_entry: dict | None) -> str:
if local_entry and not remote_entry:
return "local_only"
if remote_entry and not local_entry:
return "dify_only"
if (
(local_entry or {}).get("sync_status") != "synced"
or (remote_entry or {}).get("indexing_status") not in {"completed", "completed_with_warning"}
):
return "attention"
return "matched"
def _build_diff_rows(
*,
knowledge_base_name: str,
dataset_id: str | None,
local_docs: dict[str, list[dict]],
remote_docs: dict[str, list[dict]],
group: Group | None = None,
term: str = "",
include_knowledge_base: bool = False,
) -> list[dict]:
rows: list[dict] = []
for key in sorted(set(local_docs) | set(remote_docs)):
local_entries = list(local_docs.get(key, []))
remote_entries = list(remote_docs.get(key, []))
local_entries.sort(
key=lambda item: (
f"{item.get('title') or ''}{item.get('source_ext') or ''}".lower(),
int(item.get("document_id") or 0),
)
)
remote_entries.sort(
key=lambda item: (
(item.get("name") or "").lower(),
str(item.get("document_id") or ""),
)
)
paired_rows: list[tuple[dict | None, dict | None]] = []
remaining_remote = remote_entries.copy()
for local_entry in local_entries:
local_full_name = f"{local_entry.get('title') or ''}{local_entry.get('source_ext') or ''}".lower()
match_index = next(
(
index
for index, remote_entry in enumerate(remaining_remote)
if (remote_entry.get("name") or "").strip().lower() == local_full_name
),
None,
)
if match_index is None and remaining_remote:
match_index = 0
if match_index is None:
paired_rows.append((local_entry, None))
else:
paired_rows.append((local_entry, remaining_remote.pop(match_index)))
paired_rows.extend((None, remote_entry) for remote_entry in remaining_remote)
for index, (local_entry, remote_entry) in enumerate(paired_rows, start=1):
display_name = (local_entry or {}).get("title") or (remote_entry or {}).get("name") or key
haystacks = [display_name.lower(), knowledge_base_name.lower()]
if term and not any(term in item for item in haystacks):
continue
row = {
"key": f"{knowledge_base_name}:{key}:{index}" if include_knowledge_base else f"{key}:{index}",
"status": _diff_status(local_entry, remote_entry),
"local": local_entry,
"remote": remote_entry,
"display_name": display_name,
}
if include_knowledge_base:
row["knowledge_base"] = {
"group_id": group.id if group else None,
"name": knowledge_base_name,
"dataset_id": dataset_id,
}
rows.append(row)
return rows
def _summarize_diff_rows(rows: list[dict]) -> dict[str, int]:
return {
"matched": sum(1 for row in rows if row["status"] == "matched"),
"local_only": sum(1 for row in rows if row["status"] == "local_only"),
"dify_only": sum(1 for row in rows if row["status"] == "dify_only"),
"attention": sum(1 for row in rows if row["status"] == "attention"),
}
def _create_group_from_remote_name(*, db: Session, admin: User, group_name: str) -> Group:
if admin.primary_department_id is None:
raise HTTPException(status_code=400, detail="Admin must belong to a department before importing Dify documents.")
return _create_group_from_remote_name_in_department(
db=db,
admin=admin,
group_name=group_name,
department_id=admin.primary_department_id,
)
def _create_group_from_remote_name_in_department(
*,
db: Session,
admin: User,
group_name: str,
department_id: int,
) -> Group:
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
existing = (
db.query(Group)
.filter(Group.department_id == department_id, Group.name == group_name)
.first()
)
if existing:
return existing
group = Group(
name=group_name,
description=None,
department_id=department_id,
created_by_id=admin.id,
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
search_method=defaults.search_method if defaults else "hybrid_search",
doc_form=defaults.doc_form if defaults else "text_model",
top_k=defaults.top_k if defaults else 5,
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
score_threshold=defaults.score_threshold if defaults else "0.35",
)
db.add(group)
db.commit()
db.refresh(group)
return group
def _download_remote_upload(upload_file: dict | None) -> tuple[str, bytes] | None:
if not upload_file:
return None
download_url = upload_file.get("download_url") or upload_file.get("url")
if not download_url:
return None
response = requests.get(download_url, timeout=60)
response.raise_for_status()
filename = upload_file.get("name") or "remote-file"
return filename, response.content
def _import_dify_document_to_local(
*,
db: Session,
user: User,
dataset_id: str,
remote_document_id: str,
group: Group,
) -> Document:
dify = DifyService()
detail = dify.get_document_detail(dataset_id=dataset_id, document_id=remote_document_id)
remote_name = (detail.get("name") or "").strip() or remote_document_id
title = _normalized_document_title(remote_name)
existing = (
db.query(Document)
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
.filter(
Document.group_id == group.id,
func.lower(Document.title) == title.lower(),
Document.is_deleted.is_(False),
)
.first()
)
if existing:
raise HTTPException(status_code=409, detail="Document already exists locally. Refresh diff and retry.")
segments = dify.list_document_segments(dataset_id=dataset_id, document_id=remote_document_id)
markdown_text = "\n\n".join(item.content.strip() for item in segments if item.content and item.content.strip()).strip()
if not markdown_text:
raise HTTPException(status_code=409, detail="Remote Dify document has no importable content.")
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version_no = 1
source_dir = version_dir("original", group.id, document.id, version_no)
markdown_dir = version_dir("markdown", group.id, document.id, version_no)
source_dir.mkdir(parents=True, exist_ok=True)
markdown_dir.mkdir(parents=True, exist_ok=True)
markdown_target = markdown_dir / "document.md"
markdown_target.write_text(markdown_text, encoding="utf-8")
source_filename = remote_name if Path(remote_name).suffix else f"{remote_name}.md"
source_ext = Path(source_filename).suffix.lower() or ".md"
source_target = source_dir / source_filename
upload_file = None
try:
upload_file = dify.get_upload_file(dataset_id=dataset_id, document_id=remote_document_id)
except DifyError:
upload_file = None
downloaded = None
if upload_file:
try:
downloaded = _download_remote_upload(upload_file)
except Exception:
downloaded = None
if downloaded:
source_filename, source_bytes = downloaded
source_ext = Path(source_filename).suffix.lower() or ".bin"
source_target = source_dir / source_filename
source_target.write_bytes(source_bytes)
else:
source_target.write_text(markdown_text, encoding="utf-8")
source_filename = source_target.name
source_ext = ".md"
version = DocumentVersion(
document_id=document.id,
version_no=version_no,
is_current=True,
source_filename=source_filename,
source_ext=source_ext,
source_path=str(source_target),
source_sha256=sha256_file(source_target),
md_path=str(markdown_target),
md_public_url=public_storage_url(markdown_target),
asset_dir=None,
file_size=source_target.stat().st_size,
word_count=len(markdown_text.split()),
convert_status="success",
sync_status="synced",
uploader_id=user.id,
uploaded_at=utc_now(),
converted_at=utc_now(),
warnings_json=[{"message": "imported_from_dify"}],
)
db.add(version)
db.commit()
db.refresh(version)
sync_record = DifySyncRecord(
version_id=version.id,
dataset_id=dataset_id,
remote_document_id=remote_document_id,
status="synced",
last_indexing_status=detail.get("indexing_status"),
last_synced_at=utc_now(),
error=None,
)
db.add(sync_record)
if group.dify_dataset_id != dataset_id:
group.dify_dataset_id = dataset_id
db.commit()
db.refresh(document)
return document
def _group_name_conflict(
db: Session,
*,
department_id: int | None,
name: str,
exclude_group_id: int | None = None,
) -> bool:
query = db.query(Group).filter(Group.department_id == department_id, Group.name == name)
if exclude_group_id is not None:
query = query.filter(Group.id != exclude_group_id)
return db.query(query.exists()).scalar()
@router.get("")
def list_groups(
department_id: int | None = Query(None),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
if department_id is not None:
ensure_department_access(db, user, department_id)
group_ids = _scoped_group_ids(db, user)
document_counts_query = (
db.query(
Document.group_id.label("group_id"),
func.count(Document.id).label("document_count"),
)
.filter(Document.is_deleted.is_(False))
.group_by(Document.group_id)
)
if group_ids is not None:
document_counts_query = document_counts_query.filter(Document.group_id.in_(group_ids or [-1]))
document_counts = document_counts_query.subquery()
query = db.query(
Group,
func.coalesce(document_counts.c.document_count, 0).label("document_count"),
).options(joinedload(Group.department)).outerjoin(document_counts, document_counts.c.group_id == Group.id)
if group_ids is not None:
query = query.filter(Group.id.in_(group_ids or [-1]))
if department_id is not None:
query = query.filter(Group.department_id == department_id)
groups = query.order_by(Group.name.asc()).all()
return {
"data": [serialize_group(group, document_count=document_count) for group, document_count in groups]
}
@router.get("/summary")
def get_dashboard_summary(
department_id: int | None = Query(None),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
if department_id is not None:
ensure_department_access(db, user, department_id)
group_ids = _scoped_group_ids(db, user)
knowledge_base_query = db.query(Group)
file_query = db.query(Document).filter(Document.is_deleted.is_(False))
if group_ids is not None:
scoped_filter = group_ids or [-1]
knowledge_base_query = knowledge_base_query.filter(Group.id.in_(scoped_filter))
file_query = file_query.filter(Document.group_id.in_(scoped_filter))
if department_id is not None:
knowledge_base_query = knowledge_base_query.filter(Group.department_id == department_id)
file_query = file_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
knowledge_base_count = knowledge_base_query.count()
file_count = file_query.count()
running_query = (
db.query(DocumentVersion)
.join(Document, Document.id == DocumentVersion.document_id)
.filter(Document.is_deleted.is_(False), DocumentVersion.is_current.is_(True))
.filter(
or_(
DocumentVersion.convert_status.in_(["queued", "running"]),
DocumentVersion.sync_status == "syncing",
)
)
)
if group_ids is not None:
running_query = running_query.filter(Document.group_id.in_(group_ids or [-1]))
if department_id is not None:
running_query = running_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
running_count = running_query.count()
return {
"knowledge_base_count": knowledge_base_count,
"file_count": file_count,
"running_count": running_count,
}
@router.get("/dify-diff-global")
def get_global_dify_diff(
q: str | None = Query(None),
department_id: int | None = Query(None),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
if department_id is not None:
ensure_department_access(db, user, department_id)
groups_query = (
db.query(Group)
.options(joinedload(Group.department))
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
)
group_ids = _scoped_group_ids(db, user)
if group_ids is not None:
groups_query = groups_query.filter(Group.id.in_(group_ids or [-1]))
if department_id is not None:
groups_query = groups_query.filter(Group.department_id == department_id)
groups = groups_query.order_by(Group.name.asc()).all()
dify = DifyService()
datasets = dify.list_datasets()
datasets_by_id = {item.id: item for item in datasets}
datasets_by_name = {item.name: item for item in datasets}
used_dataset_ids: set[str] = set()
term = (q or "").strip().lower()
rows: list[dict] = []
for group in groups:
dataset = datasets_by_id.get(group.dify_dataset_id or "") or datasets_by_name.get(group.name)
dataset_id = dataset.id if dataset else group.dify_dataset_id
if dataset:
used_dataset_ids.add(dataset.id)
rows.extend(
_build_diff_rows(
knowledge_base_name=group.name,
dataset_id=dataset_id,
local_docs=_local_documents_for_group(group),
remote_docs=_remote_documents_for_dataset(dify, dataset.id if dataset else group.dify_dataset_id),
group=group,
term=term,
include_knowledge_base=True,
)
)
return {"summary": _summarize_diff_rows(rows), "rows": rows}
@router.post("/import-dify-document")
def import_dify_document(
payload: DifyImportRequest,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
target_group: Group | None = None
if payload.group_id is not None:
ensure_group_access(db, user, payload.group_id)
target_group = db.query(Group).filter(Group.id == payload.group_id).first()
if not target_group:
raise HTTPException(status_code=404, detail="Knowledge base not found.")
else:
if user.role not in {"admin", "super_admin"}:
raise HTTPException(status_code=403, detail="Admin permission required.")
knowledge_base_name = (payload.knowledge_base_name or "").strip()
if not knowledge_base_name:
raise HTTPException(status_code=400, detail="Knowledge base name is required for Dify import.")
department_id = payload.department_id or user.primary_department_id
if department_id is None:
raise HTTPException(status_code=400, detail="Department is required for Dify import.")
ensure_department_access(db, user, department_id)
target_group = _create_group_from_remote_name_in_department(
db=db,
admin=user,
group_name=knowledge_base_name,
department_id=department_id,
)
document = _import_dify_document_to_local(
db=db,
user=user,
dataset_id=payload.dataset_id,
remote_document_id=payload.remote_document_id,
group=target_group,
)
return {
"group_id": target_group.id,
"group_name": target_group.name,
"document": serialize_document(document),
}
@router.post("")
def create_group(
payload: GroupCreateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
ensure_department_access(db, admin, payload.department_id)
if _group_name_conflict(db, department_id=payload.department_id, name=payload.name):
raise HTTPException(status_code=409, detail="Group already exists.")
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
group = Group(
name=payload.name,
description=payload.description,
department_id=payload.department_id,
created_by_id=admin.id,
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
search_method=defaults.search_method if defaults else "hybrid_search",
doc_form=defaults.doc_form if defaults else "text_model",
top_k=defaults.top_k if defaults else 5,
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
score_threshold=defaults.score_threshold if defaults else "0.35",
)
db.add(group)
db.commit()
db.refresh(group)
return serialize_group(group)
@router.patch("/{group_id}")
def update_group(
group_id: int,
payload: GroupUpdateRequest,
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
ensure_group_access(db, admin, group_id)
group = db.query(Group).filter(Group.id == group_id).first()
if not group:
raise HTTPException(status_code=404, detail="Group not found.")
old_name = group.name
target_name = payload.name or group.name
target_department_id = payload.department_id if payload.department_id is not None else group.department_id
if payload.department_id is not None and payload.department_id != group.department_id:
ensure_department_access(db, admin, payload.department_id)
if payload.name or payload.department_id is not None:
if _group_name_conflict(
db,
department_id=target_department_id,
name=target_name,
exclude_group_id=group.id,
):
raise HTTPException(status_code=409, detail="Group already exists.")
if payload.name:
group.name = payload.name
if payload.description is not None:
group.description = payload.description
if payload.department_id is not None and payload.department_id != group.department_id:
group.department_id = payload.department_id
db.commit()
if payload.rename_dify and group.dify_dataset_id and payload.name and payload.name != old_name:
dify = DifyService()
dify.update_dataset(dataset_id=group.dify_dataset_id, name=payload.name)
db.refresh(group)
return serialize_group(group)
@router.delete("/{group_id}")
def delete_group(
group_id: int,
delete_dify: bool = Query(False),
db: Session = Depends(get_db),
admin: User = Depends(require_admin),
):
ensure_group_access(db, admin, group_id)
group = (
db.query(Group)
.options(joinedload(Group.department))
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
.filter(Group.id == group_id)
.first()
)
if not group:
raise HTTPException(status_code=404, detail="Group not found.")
running_job = (
db.query(Job)
.filter(Job.group_id == group.id, Job.status.in_(["queued", "running"]))
.first()
)
if running_job:
raise HTTPException(status_code=409, detail="Group has running jobs and cannot be deleted.")
if delete_dify and group.dify_dataset_id:
dify = DifyService()
dify.delete_dataset(dataset_id=group.dify_dataset_id)
for document in group.documents:
_cleanup_document_storage(document)
db.query(Job).filter(Job.group_id == group.id).delete(synchronize_session=False)
for document in list(group.documents):
db.delete(document)
db.delete(group)
db.commit()
return {"deleted": True}
@router.get("/{group_id}/files")
def list_group_files(
group_id: int,
q: str | None = Query(None),
status: str | None = Query(None),
sync_status: str | None = Query(None),
file_type: str | None = Query(None),
uploaded_from: str | None = Query(None),
uploaded_to: str | None = Query(None),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
ensure_group_access(db, user, group_id)
query = (
db.query(Document)
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
.order_by(Document.updated_at.desc())
)
documents = query.all()
filtered: list[Document] = []
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
for document in documents:
version = current_version(document)
if version is None:
continue
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
if q and q.lower() not in document.title.lower():
continue
if status and version.convert_status != status:
continue
if sync_status and version.sync_status != sync_status:
continue
if file_type and version.source_ext != file_type:
continue
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
continue
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
continue
filtered.append(document)
return {"data": [serialize_document(document) for document in filtered]}
@router.get("/{group_id}/dify-diff")
def get_group_dify_diff(
group_id: int,
q: str | None = Query(None),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
ensure_group_access(db, user, group_id)
group = (
db.query(Group)
.options(joinedload(Group.department))
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
.filter(Group.id == group_id)
.first()
)
if not group:
raise HTTPException(status_code=404, detail="Group not found.")
term = (q or "").strip().lower()
dify = DifyService() if group.dify_dataset_id else None
rows = _build_diff_rows(
knowledge_base_name=group.name,
dataset_id=group.dify_dataset_id,
local_docs=_local_documents_for_group(group),
remote_docs=_remote_documents_for_dataset(dify, group.dify_dataset_id) if dify else {},
group=group,
term=term,
)
return {"group": serialize_group(group), "summary": _summarize_diff_rows(rows), "rows": rows}
-378
View File
@@ -1,378 +0,0 @@
from __future__ import annotations
from pathlib import Path
from pydantic import BaseModel
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import FileResponse
from sqlalchemy import func
from sqlalchemy.orm import Session, joinedload
from app.config import get_settings
from app.database import get_db
from app.deps import require_integration_key
from app.models import DifySyncRecord, Document, DocumentVersion, Group
from app.security import create_integration_download_token, decode_integration_download_token
from app.serializers import current_version, serialize_group
from app.time_utils import utc_now
router = APIRouter(prefix="/integration", tags=["integration"])
settings = get_settings()
class DifyResolveItem(BaseModel):
remote_document_id: str
dataset_id: str | None = None
class DifyResolveRequest(BaseModel):
items: list[DifyResolveItem]
def _document_query(db: Session):
return (
db.query(Document)
.options(
joinedload(Document.group).joinedload(Group.department),
joinedload(Document.versions).joinedload(DocumentVersion.sync_records),
)
.filter(Document.is_deleted.is_(False))
)
def _knowledge_base_summary(group: Group, *, document_count: int) -> dict:
payload = serialize_group(group, document_count=document_count)
payload["knowledge_base_id"] = payload["id"]
return payload
def _integration_document_payload(
document: Document,
*,
version: DocumentVersion | None = None,
sync_record: DifySyncRecord | None = None,
) -> dict:
version = version or current_version(document)
if version is None:
raise HTTPException(status_code=404, detail="No current version found.")
sync_record = sync_record or (version.sync_records[0] if version.sync_records else None)
try:
source_token, source_expires_at = create_integration_download_token(
file_id=document.id,
version_id=version.id,
kind="source",
)
except RuntimeError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
md_token = None
md_expires_at = None
if version.md_path:
try:
md_token, md_expires_at = create_integration_download_token(
file_id=document.id,
version_id=version.id,
kind="md",
)
except RuntimeError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
return {
"queried_at": utc_now().isoformat(),
"document_id": document.id,
"knowledge_base": {
"id": document.group.id,
"name": document.group.name,
"department_id": document.group.department_id,
"department_name": document.group.department.name if document.group.department else None,
"dify_dataset_id": document.group.dify_dataset_id,
},
"title": document.title,
"source_filename": version.source_filename,
"source_ext": version.source_ext,
"file_name": version.source_filename,
"version_id": version.id,
"version_no": version.version_no,
"convert_status": version.convert_status,
"sync_status": version.sync_status,
"uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None,
"converted_at": version.converted_at.isoformat() if version.converted_at else None,
"download_url_expires_at": source_expires_at.isoformat(),
"source_download_url": (
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
f"?version_id={version.id}&kind=source&token={source_token}"
),
"markdown_download_url": (
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
f"?version_id={version.id}&kind=md&token={md_token}"
if version.md_path and md_token
else None
),
"markdown_download_url_expires_at": md_expires_at.isoformat() if md_expires_at else None,
"markdown_public_url": version.md_public_url,
"dify": {
"dataset_id": sync_record.dataset_id if sync_record else document.group.dify_dataset_id,
"remote_document_id": sync_record.remote_document_id if sync_record else None,
"status": sync_record.status if sync_record else None,
"last_indexing_status": sync_record.last_indexing_status if sync_record else None,
"last_synced_at": sync_record.last_synced_at.isoformat() if sync_record and sync_record.last_synced_at else None,
},
}
@router.get("/knowledge-bases")
def list_knowledge_bases(
department_id: int | None = None,
q: str | None = None,
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
document_counts = (
db.query(Document.group_id.label("group_id"), func.count(Document.id).label("document_count"))
.filter(Document.is_deleted.is_(False))
.group_by(Document.group_id)
.subquery()
)
query = (
db.query(Group, func.coalesce(document_counts.c.document_count, 0).label("document_count"))
.outerjoin(document_counts, document_counts.c.group_id == Group.id)
.options(joinedload(Group.department))
.order_by(Group.name.asc())
)
if department_id is not None:
query = query.filter(Group.department_id == department_id)
if q:
query = query.filter(Group.name.ilike(f"%{q.strip()}%"))
rows = query.all()
return {"data": [_knowledge_base_summary(group, document_count=document_count) for group, document_count in rows]}
@router.get("/files")
def list_files(
knowledge_base_id: int | None = None,
department_id: int | None = None,
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
query = _document_query(db)
if knowledge_base_id is not None:
query = query.filter(Document.group_id == knowledge_base_id)
if department_id is not None:
query = query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
documents = query.order_by(Document.updated_at.desc()).all()
normalized = file_name.strip().lower() if file_name else None
payload: list[dict] = []
for document in documents:
version = current_version(document)
if version is None:
continue
if normalized and normalized not in version.source_filename.lower() and normalized not in document.title.lower():
continue
payload.append(_integration_document_payload(document))
return {"data": payload}
@router.get("/knowledge-bases/{knowledge_base_id}/files")
def list_files_for_knowledge_base(
knowledge_base_id: int,
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
return list_files(
knowledge_base_id=knowledge_base_id,
file_name=file_name,
db=db,
_="integration",
)
@router.get("/files/{file_id}")
def get_file_detail(
file_id: int,
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
document = _document_query(db).filter(Document.id == file_id).first()
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
return _integration_document_payload(document)
@router.get("/dify-file")
def get_file_detail_by_dify(
remote_document_id: str = Query(..., description="Dify document id."),
dataset_id: str | None = Query(default=None, description="Optional Dify dataset id."),
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
record_query = (
db.query(DifySyncRecord)
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
.join(Document, Document.id == DocumentVersion.document_id)
.options(
joinedload(DifySyncRecord.version)
.joinedload(DocumentVersion.document)
.joinedload(Document.group)
.joinedload(Group.department),
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
)
.filter(
Document.is_deleted.is_(False),
DifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
)
if dataset_id:
record_query = record_query.filter(DifySyncRecord.dataset_id == dataset_id)
record = record_query.first()
if not record or not record.version or not record.version.document:
raise HTTPException(status_code=404, detail="No local file mapping found for the given Dify document.")
return _integration_document_payload(record.version.document, version=record.version, sync_record=record)
@router.post("/dify-files/resolve")
def resolve_files_by_dify(
payload: DifyResolveRequest,
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
if not payload.items:
return {"data": []}
remote_ids = sorted({item.remote_document_id for item in payload.items if item.remote_document_id})
dataset_ids = sorted({item.dataset_id for item in payload.items if item.dataset_id})
record_query = (
db.query(DifySyncRecord)
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
.join(Document, Document.id == DocumentVersion.document_id)
.options(
joinedload(DifySyncRecord.version)
.joinedload(DocumentVersion.document)
.joinedload(Document.group)
.joinedload(Group.department),
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
)
.filter(
Document.is_deleted.is_(False),
DifySyncRecord.remote_document_id.in_(remote_ids),
)
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
)
if dataset_ids:
record_query = record_query.filter(
(DifySyncRecord.dataset_id.in_(dataset_ids)) | (DifySyncRecord.dataset_id.is_(None))
)
records = record_query.all()
records_by_key: dict[tuple[str | None, str], DifySyncRecord] = {}
records_by_remote: dict[str, DifySyncRecord] = {}
for record in records:
key = (record.dataset_id, record.remote_document_id)
records_by_key.setdefault(key, record)
records_by_remote.setdefault(record.remote_document_id, record)
data: list[dict] = []
for item in payload.items:
record = records_by_key.get((item.dataset_id, item.remote_document_id))
if record is None and item.dataset_id is None:
record = records_by_remote.get(item.remote_document_id)
data.append(
{
"request": {
"dataset_id": item.dataset_id,
"remote_document_id": item.remote_document_id,
},
"found": bool(record and record.version and record.version.document),
"document": (
_integration_document_payload(record.version.document, version=record.version, sync_record=record)
if record and record.version and record.version.document
else None
),
}
)
return {"data": data}
@router.get("/files/{file_id}/download")
def download_file(
file_id: int,
kind: str = Query(default="md"),
db: Session = Depends(get_db),
_: str = Depends(require_integration_key),
):
document = _document_query(db).filter(Document.id == file_id).first()
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
version = current_version(document)
if not version:
raise HTTPException(status_code=404, detail="No version found.")
if kind == "source":
path = Path(version.source_path)
filename = version.source_filename
else:
if not version.md_path:
raise HTTPException(status_code=409, detail="Markdown not ready.")
path = Path(version.md_path)
filename = f"{document.title}.md"
if not path.exists():
raise HTTPException(status_code=404, detail="File missing on disk.")
return FileResponse(path, filename=filename)
@router.get("/download")
def download_file_from_signed_url(
file_id: int | None = Query(default=None),
version_id: int | None = Query(default=None),
kind: str = Query(default="source"),
token: str = Query(...),
db: Session = Depends(get_db),
):
try:
payload = decode_integration_download_token(token)
except RuntimeError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
if not payload:
raise HTTPException(status_code=401, detail="Invalid or expired download token.")
expected_kind = payload.get("kind")
expected_version_id = payload.get("version_id")
expected_file_id = payload.get("file_id")
if expected_kind != kind:
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
if expected_version_id is not None:
if version_id != int(expected_version_id):
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
version = db.query(DocumentVersion).join(Document).filter(
DocumentVersion.id == version_id,
Document.is_deleted.is_(False),
).first()
if not version or not version.document:
raise HTTPException(status_code=404, detail="Version not found.")
document = version.document
else:
if file_id is None or expected_file_id is None or int(expected_file_id) != file_id:
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
document = _document_query(db).filter(Document.id == file_id).first()
if not document:
raise HTTPException(status_code=404, detail="Document not found.")
version = current_version(document)
if not version:
raise HTTPException(status_code=404, detail="No version found.")
if kind == "source":
path = Path(version.source_path)
filename = version.source_filename
else:
if not version.md_path:
raise HTTPException(status_code=409, detail="Markdown not ready.")
path = Path(version.md_path)
filename = f"{document.title}.md"
if not path.exists():
raise HTTPException(status_code=404, detail="File missing on disk.")
return FileResponse(path, filename=filename)
-47
View File
@@ -1,47 +0,0 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.database import get_db
from app.deps import accessible_group_ids, get_current_user, is_super_admin
from app.models import Job, User
from app.serializers import serialize_job
router = APIRouter(prefix="/jobs", tags=["jobs"])
@router.get("")
def list_jobs(
limit: int = 50,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
query = db.query(Job).order_by(Job.created_at.desc())
if not is_super_admin(user):
group_ids = accessible_group_ids(db, user)
if user.role == "admin":
query = query.filter(or_(Job.created_by_id == user.id, Job.group_id.in_(group_ids or [-1])))
else:
query = query.filter(Job.created_by_id == user.id)
jobs = query.limit(min(limit, 200)).all()
return {"data": [serialize_job(job) for job in jobs]}
@router.get("/{job_id}")
def get_job(job_id: str, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
job = db.query(Job).filter(Job.id == job_id).first()
if not job:
raise HTTPException(status_code=404, detail="Job not found.")
if is_super_admin(user):
return serialize_job(job)
if user.role == "admin":
group_ids = accessible_group_ids(db, user)
if job.created_by_id != user.id and job.group_id not in (group_ids or []):
raise HTTPException(status_code=403, detail="Forbidden")
return serialize_job(job)
if job.created_by_id != user.id:
raise HTTPException(status_code=403, detail="Forbidden")
return serialize_job(job)
-112
View File
@@ -1,112 +0,0 @@
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from typing import Literal
from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
app_name: str = "Document Cleaning"
api_prefix: str = "/api"
jwt_secret: str = "change-me-in-production"
jwt_algorithm: str = "HS256"
access_token_expire_minutes: int = 720
database_backend: Literal["sqlite", "postgres"] = "sqlite"
database_url: str = ""
sqlite_database_url: str = "sqlite:///./document_cleaning.db"
postgres_database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/document_cleaning"
redis_url: str = "redis://redis:6379/0"
data_root: Path = Field(default=Path("./data"))
public_base_url: str = "http://192.168.100.230:8891"
allowed_origins: str = "http://192.168.100.230:8891,http://localhost:5173"
dify_base_url: str = "https://api.dify.ai/v1"
dify_api_key: str = ""
dify_permission: str = "all_team_members"
default_indexing_technique: str = "high_quality"
default_search_method: str = "hybrid_search"
default_doc_form: str = "text_model"
default_embedding_model_provider: str = ""
default_embedding_model: str = ""
default_reranking_model_provider: str = ""
default_reranking_model: str = ""
default_top_k: int = 5
default_score_threshold_enabled: bool = True
default_score_threshold: float = 0.35
default_admin_username: str = "admin"
default_admin_password: str = "admin123456"
default_admin_name: str = "System Admin"
integration_api_key: str = ""
integration_download_secret: str = ""
integration_download_expire_minutes: int = 15
rq_queue_name: str = "document-cleaning"
rq_default_timeout: int = 3600
task_execution_mode: Literal["rq", "sync"] = "rq"
dify_sync_max_retries: int = 4
dify_sync_retry_schedule: str = "30,60,120,300"
dify_sync_cooldown_seconds: int = 60
watchdog_stale_sync_timeout_seconds: int = 900
watchdog_stale_convert_timeout_seconds: int = 900
watchdog_convert_orphan_grace_seconds: int = 120
edkb_word_timeout_sec: int = 120
edkb_file_timeout_sec: int = 900
def origins_list(self) -> list[str]:
return [item.strip() for item in self.allowed_origins.split(",") if item.strip()]
def dify_sync_retry_delays(self) -> list[int]:
values: list[int] = []
for raw in self.dify_sync_retry_schedule.split(","):
token = raw.strip()
if not token:
continue
try:
parsed = int(token)
except ValueError:
continue
if parsed > 0:
values.append(parsed)
return values or [30, 60, 120, 300]
@staticmethod
def _normalize_database_url(url: str) -> str:
normalized = url.strip()
if normalized.startswith("postgresql://"):
return normalized.replace("postgresql://", "postgresql+psycopg://", 1)
return normalized
@model_validator(mode="after")
def resolve_database_url(self) -> "Settings":
if self.database_url:
self.database_url = self._normalize_database_url(self.database_url)
return self
selected = self.sqlite_database_url if self.database_backend == "sqlite" else self.postgres_database_url
self.database_url = self._normalize_database_url(selected)
return self
def ensure_data_dirs(self) -> None:
for name in ["original", "markdown", "assets", "jobs", "tmp"]:
(self.data_root / name).mkdir(parents=True, exist_ok=True)
@lru_cache
def get_settings() -> Settings:
settings = Settings()
settings.ensure_data_dirs()
return settings
-31
View File
@@ -1,31 +0,0 @@
from __future__ import annotations
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker
from app.config import get_settings
settings = get_settings()
connect_args: dict[str, object] = {}
if settings.database_url.startswith("sqlite"):
connect_args["check_same_thread"] = False
engine = create_engine(
settings.database_url,
future=True,
pool_pre_ping=True,
connect_args=connect_args,
)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
-94
View File
@@ -1,94 +0,0 @@
from __future__ import annotations
from fastapi import Depends, Header, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from app.config import get_settings
from app.database import get_db
from app.models import Group, User, UserDepartmentAccess
from app.security import decode_access_token
settings = get_settings()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.api_prefix}/auth/login")
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
username = decode_access_token(token)
if not username:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
user = db.query(User).filter(User.username == username, User.is_active.is_(True)).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
return user
def is_super_admin(user: User) -> bool:
return user.role == "super_admin"
def is_admin(user: User) -> bool:
return user.role in {"super_admin", "admin"}
def accessible_department_ids(db: Session, user: User) -> list[int] | None:
department_ids = set()
if user.primary_department_id is not None:
department_ids.add(user.primary_department_id)
department_ids.update(
item.department_id
for item in db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user.id).all()
if item.department_id is not None
)
return sorted(department_ids)
def accessible_group_ids(db: Session, user: User) -> list[int] | None:
department_ids = accessible_department_ids(db, user) or [-1]
return [item[0] for item in db.query(Group.id).filter(Group.department_id.in_(department_ids)).all()]
def require_super_admin(user: User = Depends(get_current_user)) -> User:
if not is_super_admin(user):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin only")
return user
def require_admin(user: User = Depends(get_current_user)) -> User:
if not is_admin(user):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin only")
return user
def ensure_department_access(db: Session, user: User, department_id: int) -> None:
if department_id not in (accessible_department_ids(db, user) or []):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
def ensure_group_access(db: Session, user: User, group_id: int) -> None:
group = db.query(Group.id, Group.department_id).filter(Group.id == group_id).first()
if not group:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Knowledge base not found.")
if group.department_id not in (accessible_department_ids(db, user) or []):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
def require_integration_key(
x_integration_key: str | None = Header(default=None, alias="X-Integration-Key"),
authorization: str | None = Header(default=None),
) -> str:
configured_key = settings.integration_api_key
if not configured_key:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Integration API is not configured.")
token = x_integration_key
if not token and authorization:
scheme, _, credentials = authorization.partition(" ")
if scheme.lower() == "bearer" and credentials:
token = credentials
if token != configured_key:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid integration key")
return token
-50
View File
@@ -1,50 +0,0 @@
from __future__ import annotations
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from app.api import admin, auth, departments, files, groups, integration, jobs
from app.config import get_settings
from app.database import SessionLocal
from app.services.bootstrap_service import ensure_defaults
settings = get_settings()
@asynccontextmanager
async def lifespan(_: FastAPI):
db = SessionLocal()
try:
ensure_defaults(db)
yield
finally:
db.close()
app = FastAPI(title=settings.app_name, lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.origins_list(),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth.router, prefix=settings.api_prefix)
app.include_router(departments.router, prefix=settings.api_prefix)
app.include_router(groups.router, prefix=settings.api_prefix)
app.include_router(files.router, prefix=settings.api_prefix)
app.include_router(integration.router, prefix=settings.api_prefix)
app.include_router(jobs.router, prefix=settings.api_prefix)
app.include_router(admin.router, prefix=settings.api_prefix)
app.mount("/storage", StaticFiles(directory=settings.data_root), name="storage")
@app.get("/health")
def health() -> dict:
return {"status": "ok"}
-243
View File
@@ -1,243 +0,0 @@
from __future__ import annotations
from datetime import datetime
from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base
from app.time_utils import utc_now
class Department(Base):
__tablename__ = "departments"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[str] = mapped_column(String(128), unique=True, index=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now()
)
users: Mapped[list["User"]] = relationship(back_populates="primary_department")
user_accesses: Mapped[list["UserDepartmentAccess"]] = relationship(
back_populates="department", cascade="all, delete-orphan"
)
groups: Mapped[list["Group"]] = relationship(back_populates="department")
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
full_name: Mapped[str | None] = mapped_column(String(128), nullable=True)
password_hash: Mapped[str] = mapped_column(String(255))
role: Mapped[str] = mapped_column(String(16), default="user")
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
primary_department_id: Mapped[int | None] = mapped_column(ForeignKey("departments.id"), index=True, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
primary_department: Mapped[Department | None] = relationship(back_populates="users")
department_accesses: Mapped[list["UserDepartmentAccess"]] = relationship(
back_populates="user", cascade="all, delete-orphan"
)
groups_created: Mapped[list["Group"]] = relationship(back_populates="created_by")
group_accesses: Mapped[list["UserGroupAccess"]] = relationship(
back_populates="user", cascade="all, delete-orphan"
)
documents_created: Mapped[list["Document"]] = relationship(back_populates="created_by")
versions_uploaded: Mapped[list["DocumentVersion"]] = relationship(back_populates="uploaded_by")
jobs_created: Mapped[list["Job"]] = relationship(back_populates="created_by")
class SystemSetting(Base):
__tablename__ = "system_settings"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
dify_permission: Mapped[str] = mapped_column(String(32), default="all_team_members")
indexing_technique: Mapped[str] = mapped_column(String(32), default="high_quality")
search_method: Mapped[str] = mapped_column(String(32), default="hybrid_search")
doc_form: Mapped[str] = mapped_column(String(32), default="text_model")
embedding_model_provider: Mapped[str | None] = mapped_column(String(128), nullable=True)
embedding_model: Mapped[str | None] = mapped_column(String(128), nullable=True)
reranking_model_provider: Mapped[str | None] = mapped_column(String(128), nullable=True)
reranking_model: Mapped[str | None] = mapped_column(String(128), nullable=True)
top_k: Mapped[int] = mapped_column(Integer, default=5)
score_threshold_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
score_threshold: Mapped[str] = mapped_column(String(32), default="0.35")
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now()
)
class Group(Base):
__tablename__ = "groups"
__table_args__ = (UniqueConstraint("department_id", "name", name="uq_groups_department_name"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[str] = mapped_column(String(128), index=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
dify_dataset_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
dify_sync_policy: Mapped[str] = mapped_column(String(32), default="manual")
indexing_technique: Mapped[str] = mapped_column(String(32), default="high_quality")
search_method: Mapped[str] = mapped_column(String(32), default="hybrid_search")
doc_form: Mapped[str] = mapped_column(String(32), default="text_model")
top_k: Mapped[int] = mapped_column(Integer, default=5)
score_threshold_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
score_threshold: Mapped[str] = mapped_column(String(32), default="0.35")
created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now()
)
department: Mapped[Department] = relationship(back_populates="groups")
created_by: Mapped[User | None] = relationship(back_populates="groups_created")
user_accesses: Mapped[list["UserGroupAccess"]] = relationship(
back_populates="group", cascade="all, delete-orphan"
)
documents: Mapped[list["Document"]] = relationship(back_populates="group")
class UserDepartmentAccess(Base):
__tablename__ = "user_department_access"
__table_args__ = (UniqueConstraint("user_id", "department_id", name="uq_user_department_access"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
user: Mapped[User] = relationship(back_populates="department_accesses")
department: Mapped[Department] = relationship(back_populates="user_accesses")
class UserGroupAccess(Base):
__tablename__ = "user_group_access"
__table_args__ = (UniqueConstraint("user_id", "group_id", name="uq_user_group_access"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
group_id: Mapped[int] = mapped_column(ForeignKey("groups.id"), index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
user: Mapped[User] = relationship(back_populates="group_accesses")
group: Mapped[Group] = relationship(back_populates="user_accesses")
class Document(Base):
__tablename__ = "documents"
__table_args__ = (UniqueConstraint("group_id", "title", name="uq_documents_group_title"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
group_id: Mapped[int] = mapped_column(ForeignKey("groups.id"), index=True)
title: Mapped[str] = mapped_column(String(255))
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now()
)
group: Mapped[Group] = relationship(back_populates="documents")
created_by: Mapped[User | None] = relationship(back_populates="documents_created")
versions: Mapped[list["DocumentVersion"]] = relationship(
back_populates="document", cascade="all, delete-orphan", order_by="DocumentVersion.version_no.desc()"
)
class DocumentVersion(Base):
__tablename__ = "document_versions"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
document_id: Mapped[int] = mapped_column(ForeignKey("documents.id"), index=True)
version_no: Mapped[int] = mapped_column(Integer)
is_current: Mapped[bool] = mapped_column(Boolean, default=True)
source_filename: Mapped[str] = mapped_column(String(255))
source_ext: Mapped[str] = mapped_column(String(16))
source_path: Mapped[str] = mapped_column(Text)
source_sha256: Mapped[str] = mapped_column(String(64), index=True)
md_path: Mapped[str | None] = mapped_column(Text, nullable=True)
md_public_url: Mapped[str | None] = mapped_column(Text, nullable=True)
asset_dir: Mapped[str | None] = mapped_column(Text, nullable=True)
file_size: Mapped[int] = mapped_column(Integer)
word_count: Mapped[int] = mapped_column(Integer, default=0)
convert_status: Mapped[str] = mapped_column(String(32), default="queued")
sync_status: Mapped[str] = mapped_column(String(32), default="unsynced")
uploader_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
uploaded_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
converted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
failed_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
warnings_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
document: Mapped[Document] = relationship(back_populates="versions")
uploaded_by: Mapped[User | None] = relationship(back_populates="versions_uploaded")
jobs: Mapped[list["Job"]] = relationship(back_populates="version")
sync_records: Mapped[list["DifySyncRecord"]] = relationship(
back_populates="version", cascade="all, delete-orphan", order_by="DifySyncRecord.updated_at.desc()"
)
class Job(Base):
__tablename__ = "jobs"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
job_type: Mapped[str] = mapped_column(String(32), index=True)
status: Mapped[str] = mapped_column(String(32), default="queued", index=True)
queue_job_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
group_id: Mapped[int | None] = mapped_column(ForeignKey("groups.id"), nullable=True)
document_id: Mapped[int | None] = mapped_column(ForeignKey("documents.id"), nullable=True)
version_id: Mapped[int | None] = mapped_column(ForeignKey("document_versions.id"), nullable=True)
created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
progress: Mapped[int] = mapped_column(Integer, default=0)
message: Mapped[str | None] = mapped_column(Text, nullable=True)
error: Mapped[str | None] = mapped_column(Text, nullable=True)
payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
version: Mapped[DocumentVersion | None] = relationship(back_populates="jobs")
created_by: Mapped[User | None] = relationship(back_populates="jobs_created")
class DifySyncRecord(Base):
__tablename__ = "dify_sync_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
version_id: Mapped[int] = mapped_column(ForeignKey("document_versions.id"), index=True)
dataset_id: Mapped[str] = mapped_column(String(128))
remote_document_id: Mapped[str] = mapped_column(String(128))
batch: Mapped[str | None] = mapped_column(String(128), nullable=True)
status: Mapped[str] = mapped_column(String(32), default="syncing")
last_indexing_status: Mapped[str | None] = mapped_column(String(64), nullable=True)
error: Mapped[str | None] = mapped_column(Text, nullable=True)
last_synced_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now()
)
version: Mapped[DocumentVersion] = relationship(back_populates="sync_records")
-105
View File
@@ -1,105 +0,0 @@
from __future__ import annotations
from datetime import datetime
from pydantic import BaseModel, Field
class LoginRequest(BaseModel):
username: str
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
user: dict
class GroupCreateRequest(BaseModel):
name: str
description: str | None = None
department_id: int
class GroupUpdateRequest(BaseModel):
name: str | None = None
description: str | None = None
department_id: int | None = None
rename_dify: bool = False
class BatchDownloadRequest(BaseModel):
document_ids: list[int] = Field(default_factory=list)
kind: str = "md"
class BatchSyncRequest(BaseModel):
document_ids: list[int] = Field(default_factory=list)
class UserCreateRequest(BaseModel):
username: str
password: str
full_name: str | None = None
role: str = "user"
primary_department_id: int
accessible_department_ids: list[int] = Field(default_factory=list)
class UserUpdateRequest(BaseModel):
full_name: str | None = None
role: str | None = None
password: str | None = None
is_active: bool | None = None
primary_department_id: int | None = None
accessible_department_ids: list[int] | None = None
class DifyImportRequest(BaseModel):
dataset_id: str
remote_document_id: str
group_id: int | None = None
department_id: int | None = None
knowledge_base_name: str | None = None
class DepartmentCreateRequest(BaseModel):
name: str
description: str | None = None
class DepartmentUpdateRequest(BaseModel):
name: str | None = None
description: str | None = None
class DepartmentDeleteRequest(BaseModel):
target_department_id: int | None = None
class SettingsUpdateRequest(BaseModel):
dify_permission: str | None = None
indexing_technique: str | None = None
search_method: str | None = None
doc_form: str | None = None
embedding_model_provider: str | None = None
embedding_model: str | None = None
reranking_model_provider: str | None = None
reranking_model: str | None = None
top_k: int | None = None
score_threshold_enabled: bool | None = None
score_threshold: float | None = None
class JobResponse(BaseModel):
id: str
job_type: str
status: str
progress: int
message: str | None = None
error: str | None = None
created_at: datetime | None = None
started_at: datetime | None = None
finished_at: datetime | None = None
result: dict | None = None
-74
View File
@@ -1,74 +0,0 @@
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.config import get_settings
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
def verify_password(plain_password: str, password_hash: str) -> bool:
return pwd_context.verify(plain_password, password_hash)
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(subject: str) -> str:
settings = get_settings()
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
payload = {"sub": subject, "exp": expire}
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
def decode_access_token(token: str) -> str | None:
settings = get_settings()
try:
payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
except JWTError:
return None
return payload.get("sub")
def _integration_download_secret() -> str:
settings = get_settings()
if settings.integration_download_secret:
return settings.integration_download_secret
raise RuntimeError("Integration download secret is not configured.")
def create_integration_download_token(
*,
file_id: int | None = None,
version_id: int | None = None,
kind: str,
) -> tuple[str, datetime]:
settings = get_settings()
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.integration_download_expire_minutes)
payload = {
"typ": "integration_download",
"kind": kind,
"exp": expire,
}
if file_id is not None:
payload["file_id"] = file_id
if version_id is not None:
payload["version_id"] = version_id
token = jwt.encode(payload, _integration_download_secret(), algorithm=settings.jwt_algorithm)
return token, expire
def decode_integration_download_token(token: str) -> dict | None:
settings = get_settings()
try:
payload = jwt.decode(token, _integration_download_secret(), algorithms=[settings.jwt_algorithm])
except JWTError:
return None
if payload.get("typ") != "integration_download":
return None
return payload
-171
View File
@@ -1,171 +0,0 @@
from __future__ import annotations
from app.models import Department, Document, DocumentVersion, DifySyncRecord, Group, Job, SystemSetting, User
from app.user_policy import is_primary_super_admin_username
def current_version(document: Document) -> DocumentVersion | None:
for version in document.versions:
if version.is_current:
return version
return document.versions[0] if document.versions else None
def serialize_user(user: User) -> dict:
visible_department_ids = set()
if user.primary_department_id is not None:
visible_department_ids.add(user.primary_department_id)
visible_department_ids.update(item.department_id for item in user.department_accesses)
return {
"id": user.id,
"username": user.username,
"full_name": user.full_name,
"role": user.role,
"is_primary_super_admin": is_primary_super_admin_username(user.username),
"is_active": user.is_active,
"primary_department_id": user.primary_department_id,
"primary_department_name": user.primary_department.name if user.primary_department else None,
"accessible_department_ids": sorted(visible_department_ids),
"extra_department_ids": sorted(item.department_id for item in user.department_accesses),
"created_at": user.created_at.isoformat() if user.created_at else None,
}
def serialize_department(
department: Department,
*,
user_count: int | None = None,
knowledge_base_count: int | None = None,
) -> dict:
return {
"id": department.id,
"name": department.name,
"description": department.description,
"user_count": int(user_count or 0),
"knowledge_base_count": int(knowledge_base_count or 0),
"created_at": department.created_at.isoformat() if department.created_at else None,
"updated_at": department.updated_at.isoformat() if department.updated_at else None,
}
def serialize_user_brief(user: User | None) -> dict | None:
if user is None:
return None
return {
"id": user.id,
"username": user.username,
"full_name": user.full_name,
}
def serialize_group(group: Group, *, document_count: int | None = None) -> dict:
return {
"id": group.id,
"name": group.name,
"description": group.description,
"department_id": group.department_id,
"department_name": group.department.name if group.department else None,
"dify_dataset_id": group.dify_dataset_id,
"dify_sync_policy": group.dify_sync_policy,
"indexing_technique": group.indexing_technique,
"search_method": group.search_method,
"doc_form": group.doc_form,
"top_k": group.top_k,
"score_threshold_enabled": group.score_threshold_enabled,
"score_threshold": float(group.score_threshold),
"document_count": int(document_count or 0),
"created_at": group.created_at.isoformat() if group.created_at else None,
"updated_at": group.updated_at.isoformat() if group.updated_at else None,
}
def serialize_sync_record(record: DifySyncRecord) -> dict:
return {
"id": record.id,
"dataset_id": record.dataset_id,
"remote_document_id": record.remote_document_id,
"batch": record.batch,
"status": record.status,
"last_indexing_status": record.last_indexing_status,
"error": record.error,
"last_synced_at": record.last_synced_at.isoformat() if record.last_synced_at else None,
}
def serialize_version(version: DocumentVersion | None) -> dict | None:
if version is None:
return None
return {
"id": version.id,
"document_id": version.document_id,
"version_no": version.version_no,
"is_current": version.is_current,
"source_filename": version.source_filename,
"source_ext": version.source_ext,
"source_path": version.source_path,
"md_path": version.md_path,
"md_public_url": version.md_public_url,
"asset_dir": version.asset_dir,
"file_size": version.file_size,
"word_count": version.word_count,
"convert_status": version.convert_status,
"sync_status": version.sync_status,
"uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None,
"uploaded_by": serialize_user_brief(version.uploaded_by),
"converted_at": version.converted_at.isoformat() if version.converted_at else None,
"failed_reason": version.failed_reason,
"warnings": version.warnings_json or [],
}
def serialize_document(document: Document) -> dict:
version = current_version(document)
sync = version.sync_records[0] if version and version.sync_records else None
return {
"id": document.id,
"group_id": document.group_id,
"title": document.title,
"is_deleted": document.is_deleted,
"created_at": document.created_at.isoformat() if document.created_at else None,
"updated_at": document.updated_at.isoformat() if document.updated_at else None,
"current_version": serialize_version(version),
"sync_record": serialize_sync_record(sync) if sync else None,
"version_count": len(document.versions),
}
def serialize_job(job: Job) -> dict:
return {
"id": job.id,
"job_type": job.job_type,
"status": job.status,
"queue_job_id": job.queue_job_id,
"group_id": job.group_id,
"document_id": job.document_id,
"version_id": job.version_id,
"progress": job.progress,
"message": job.message,
"error": job.error,
"payload": job.payload,
"result": job.result,
"created_at": job.created_at.isoformat() if job.created_at else None,
"started_at": job.started_at.isoformat() if job.started_at else None,
"finished_at": job.finished_at.isoformat() if job.finished_at else None,
}
def serialize_settings(settings: SystemSetting) -> dict:
return {
"dify_permission": settings.dify_permission,
"indexing_technique": settings.indexing_technique,
"search_method": settings.search_method,
"doc_form": settings.doc_form,
"embedding_model_provider": settings.embedding_model_provider,
"embedding_model": settings.embedding_model,
"reranking_model_provider": settings.reranking_model_provider,
"reranking_model": settings.reranking_model,
"top_k": settings.top_k,
"score_threshold_enabled": settings.score_threshold_enabled,
"score_threshold": float(settings.score_threshold),
"updated_at": settings.updated_at.isoformat() if settings.updated_at else None,
}
-84
View File
@@ -1,84 +0,0 @@
from __future__ import annotations
from sqlalchemy.orm import Session
from app.config import get_settings
from app.models import SystemSetting, User, UserDepartmentAccess
from app.security import hash_password
from app.user_policy import PRIMARY_SUPER_ADMIN_USERNAME
def ensure_defaults(db: Session) -> None:
settings = get_settings()
system = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
if system is None:
system = SystemSetting(
id=1,
dify_permission=settings.dify_permission,
indexing_technique=settings.default_indexing_technique,
search_method=settings.default_search_method,
doc_form=settings.default_doc_form,
embedding_model_provider=settings.default_embedding_model_provider or None,
embedding_model=settings.default_embedding_model or None,
reranking_model_provider=settings.default_reranking_model_provider or None,
reranking_model=settings.default_reranking_model or None,
top_k=settings.default_top_k,
score_threshold_enabled=settings.default_score_threshold_enabled,
score_threshold=str(settings.default_score_threshold),
)
db.add(system)
primary_super_admin = db.query(User).filter(User.username == PRIMARY_SUPER_ADMIN_USERNAME).first()
if primary_super_admin is None:
primary_super_admin = User(
username=PRIMARY_SUPER_ADMIN_USERNAME,
full_name=settings.default_admin_name,
password_hash=hash_password(settings.default_admin_password),
role="super_admin",
is_active=True,
primary_department_id=None,
)
db.add(primary_super_admin)
else:
primary_super_admin.role = "super_admin"
primary_super_admin.is_active = True
legacy_adam = db.query(User).filter(User.username == "adam").first()
if legacy_adam is not None:
legacy_adam.role = "admin"
if settings.default_admin_username and settings.default_admin_username != PRIMARY_SUPER_ADMIN_USERNAME:
secondary_admin = db.query(User).filter(User.username == settings.default_admin_username).first()
if secondary_admin is None:
secondary_admin = User(
username=settings.default_admin_username,
full_name=settings.default_admin_name,
password_hash=hash_password(settings.default_admin_password),
role="admin",
is_active=True,
primary_department_id=None,
)
db.add(secondary_admin)
elif secondary_admin.role == "super_admin":
secondary_admin.role = "admin"
other_super_admins = (
db.query(User)
.filter(User.role == "super_admin", User.username != PRIMARY_SUPER_ADMIN_USERNAME)
.all()
)
for user in other_super_admins:
user.role = "admin"
db.flush()
existing_access = {
(row.user_id, row.department_id)
for row in db.query(UserDepartmentAccess.user_id, UserDepartmentAccess.department_id).all()
}
for user in db.query(User).all():
if user.primary_department_id is not None and (user.id, user.primary_department_id) not in existing_access:
db.add(UserDepartmentAccess(user_id=user.id, department_id=user.primary_department_id))
db.commit()
-442
View File
@@ -1,442 +0,0 @@
from __future__ import annotations
import time
from dataclasses import dataclass
from typing import Any
import requests
from app.config import get_settings
class DifyError(RuntimeError):
pass
@dataclass
class DatasetRef:
id: str
name: str
@dataclass
class ModelRef:
provider: str
model: str
label: str
@dataclass
class RemoteDocumentRef:
id: str
name: str
indexing_status: str | None
display_status: str | None
enabled: bool
@dataclass
class RemoteDocumentSegment:
id: str
position: int
content: str
class DifyService:
preferred_embedding_models = (
("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Embedding-8B"),
("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Embedding-4B"),
("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Embedding-0.6B"),
)
preferred_rerank_models = (
("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Reranker-8B"),
("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Reranker-4B"),
("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Reranker-0.6B"),
)
def __init__(self) -> None:
settings = get_settings()
self.base_url = settings.dify_base_url.rstrip("/")
self.api_key = settings.dify_api_key
self.permission = settings.dify_permission
self.timeout = 60
def _headers(self) -> dict[str, str]:
if not self.api_key:
raise DifyError("Dify API key is not configured.")
return {"Authorization": f"Bearer {self.api_key}"}
def _request(self, method: str, path: str, **kwargs):
url = f"{self.base_url}{path}"
headers = kwargs.pop("headers", {})
merged = self._headers()
merged.update(headers)
response = requests.request(method, url, headers=merged, timeout=self.timeout, **kwargs)
if response.status_code >= 400:
raise DifyError(f"Dify API {method} {path} failed: {response.status_code} {response.text}")
if response.status_code == 204:
return None
return response.json()
def list_datasets(self) -> list[DatasetRef]:
payload = self._request("GET", "/datasets")
return [DatasetRef(id=item["id"], name=item["name"]) for item in payload.get("data", [])]
def list_documents(self, *, dataset_id: str, limit: int = 100) -> list[RemoteDocumentRef]:
documents: list[RemoteDocumentRef] = []
page = 1
while True:
payload = self._request("GET", f"/datasets/{dataset_id}/documents", params={"page": page, "limit": limit})
documents.extend(
[
RemoteDocumentRef(
id=item["id"],
name=item.get("name") or "",
indexing_status=item.get("indexing_status"),
display_status=item.get("display_status"),
enabled=bool(item.get("enabled", True)),
)
for item in payload.get("data", [])
]
)
if not payload.get("has_more"):
break
page += 1
return documents
def _list_models(self, *, model_type: str) -> list[ModelRef]:
payload = self._request("GET", f"/workspaces/current/models/model-types/{model_type}")
items: list[ModelRef] = []
for provider_entry in payload.get("data", []):
if provider_entry.get("status") not in {None, "active"}:
continue
provider = provider_entry.get("provider")
provider_label = (
provider_entry.get("label", {}).get("en_US")
or provider_entry.get("label", {}).get("zh_Hans")
or provider
)
if not provider:
continue
for model_entry in provider_entry.get("models", []):
if model_entry.get("status") not in {None, "active"}:
continue
model = model_entry.get("model")
if not model:
continue
model_label = model_entry.get("label", {}).get("en_US") or model_entry.get("label", {}).get("zh_Hans") or model
items.append(ModelRef(provider=provider, model=model, label=f"{provider_label} / {model_label}"))
return items
def list_available_embedding_models(self) -> list[ModelRef]:
return self._list_models(model_type="text-embedding")
def list_available_rerank_models(self) -> list[ModelRef]:
return self._list_models(model_type="rerank")
def _resolve_model_choice(
self,
*,
requested_provider: str | None,
requested_model: str | None,
available: list[ModelRef],
preferred: tuple[tuple[str, str], ...],
) -> tuple[str | None, str | None]:
if requested_provider and requested_model:
return requested_provider, requested_model
if not available:
return None, None
available_keys = {(item.provider, item.model) for item in available}
for candidate in preferred:
if candidate in available_keys:
return candidate
first = available[0]
return first.provider, first.model
def resolve_embedding_model_choice(
self,
*,
provider: str | None = None,
model: str | None = None,
) -> tuple[str | None, str | None]:
return self._resolve_model_choice(
requested_provider=provider,
requested_model=model,
available=self.list_available_embedding_models(),
preferred=self.preferred_embedding_models,
)
def resolve_rerank_model_choice(
self,
*,
provider: str | None = None,
model: str | None = None,
) -> tuple[str | None, str | None]:
return self._resolve_model_choice(
requested_provider=provider,
requested_model=model,
available=self.list_available_rerank_models(),
preferred=self.preferred_rerank_models,
)
def ensure_dataset(
self,
*,
dataset_name: str,
description: str | None,
permission: str | None,
indexing_technique: str,
search_method: str,
top_k: int,
score_threshold_enabled: bool,
score_threshold: float,
doc_form: str,
embedding_model_provider: str | None = None,
embedding_model: str | None = None,
reranking_model_provider: str | None = None,
reranking_model: str | None = None,
) -> str:
resolved_embedding_provider, resolved_embedding_model = self.resolve_embedding_model_choice(
provider=embedding_model_provider,
model=embedding_model,
)
resolved_rerank_provider, resolved_rerank_model = (None, None)
if search_method == "hybrid_search":
resolved_rerank_provider, resolved_rerank_model = self.resolve_rerank_model_choice(
provider=reranking_model_provider,
model=reranking_model,
)
existing = next((item for item in self.list_datasets() if item.name == dataset_name), None)
if existing:
self.update_dataset(
dataset_id=existing.id,
name=dataset_name,
description=description,
indexing_technique=indexing_technique,
search_method=search_method,
top_k=top_k,
score_threshold_enabled=score_threshold_enabled,
score_threshold=score_threshold,
doc_form=doc_form,
embedding_model_provider=resolved_embedding_provider,
embedding_model=resolved_embedding_model,
reranking_model_provider=resolved_rerank_provider,
reranking_model=resolved_rerank_model,
)
return existing.id
payload = {
"name": dataset_name,
"description": description or "",
"permission": permission or self.permission,
"indexing_technique": indexing_technique,
"doc_form": doc_form,
"retrieval_model": {
"search_method": search_method,
"reranking_enable": bool(resolved_rerank_provider and resolved_rerank_model),
"top_k": top_k,
"score_threshold_enabled": score_threshold_enabled,
"score_threshold": score_threshold,
},
}
if resolved_embedding_provider and resolved_embedding_model:
payload["embedding_model_provider"] = resolved_embedding_provider
payload["embedding_model"] = resolved_embedding_model
if resolved_rerank_provider and resolved_rerank_model:
payload["retrieval_model"]["reranking_mode"] = "reranking_model"
payload["retrieval_model"]["reranking_model"] = {
"reranking_provider_name": resolved_rerank_provider,
"reranking_model_name": resolved_rerank_model,
}
created = self._request("POST", "/datasets", json=payload)
dataset_id = created["id"]
self.update_dataset(
dataset_id=dataset_id,
name=dataset_name,
description=description,
indexing_technique=indexing_technique,
search_method=search_method,
top_k=top_k,
score_threshold_enabled=score_threshold_enabled,
score_threshold=score_threshold,
doc_form=doc_form,
embedding_model_provider=resolved_embedding_provider,
embedding_model=resolved_embedding_model,
reranking_model_provider=resolved_rerank_provider,
reranking_model=resolved_rerank_model,
)
return dataset_id
def update_dataset(
self,
*,
dataset_id: str,
name: str | None = None,
description: str | None = None,
indexing_technique: str | None = None,
search_method: str | None = None,
top_k: int | None = None,
score_threshold_enabled: bool | None = None,
score_threshold: float | None = None,
doc_form: str | None = None,
embedding_model_provider: str | None = None,
embedding_model: str | None = None,
reranking_model_provider: str | None = None,
reranking_model: str | None = None,
) -> dict:
payload: dict[str, object] = {}
if name is not None:
payload["name"] = name
if description is not None:
payload["description"] = description
if indexing_technique is not None:
payload["indexing_technique"] = indexing_technique
if doc_form is not None:
payload["doc_form"] = doc_form
if embedding_model_provider is not None and embedding_model is not None:
payload["embedding_model_provider"] = embedding_model_provider
payload["embedding_model"] = embedding_model
if (
search_method is not None
or top_k is not None
or score_threshold_enabled is not None
or score_threshold is not None
or reranking_model_provider is not None
or reranking_model is not None
):
reranking_enabled = bool(reranking_model_provider and reranking_model and (search_method or "hybrid_search") == "hybrid_search")
payload["retrieval_model"] = {
"search_method": search_method or "hybrid_search",
"reranking_enable": reranking_enabled,
"top_k": top_k if top_k is not None else 5,
"score_threshold_enabled": bool(score_threshold_enabled),
"score_threshold": score_threshold if score_threshold_enabled else None,
}
if reranking_enabled:
payload["retrieval_model"]["reranking_mode"] = "reranking_model"
payload["retrieval_model"]["reranking_model"] = {
"reranking_provider_name": reranking_model_provider,
"reranking_model_name": reranking_model,
}
return self._request("PATCH", f"/datasets/{dataset_id}", json=payload)
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
payload = {
"name": name,
"text": text,
"indexing_technique": indexing_technique,
"doc_form": doc_form,
"process_rule": {"mode": "automatic"},
}
return self._request("POST", f"/datasets/{dataset_id}/document/create-by-text", json=payload)
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
payload = {
"name": name,
"text": text,
"process_rule": {"mode": "automatic"},
}
return self._request(
"POST",
f"/datasets/{dataset_id}/documents/{document_id}/update-by-text",
json=payload,
)
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
return self._request("GET", f"/datasets/{dataset_id}/documents/{document_id}")
def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100) -> list[RemoteDocumentSegment]:
segments: list[RemoteDocumentSegment] = []
page = 1
while True:
payload = self._request(
"GET",
f"/datasets/{dataset_id}/documents/{document_id}/segments",
params={"page": page, "limit": limit},
)
items = payload.get("data", []) if isinstance(payload, dict) else []
segments.extend(
[
RemoteDocumentSegment(
id=item.get("id") or "",
position=int(item.get("position") or 0),
content=item.get("content") or "",
)
for item in items
]
)
if not payload.get("has_more"):
break
page += 1
segments.sort(key=lambda item: item.position)
return segments
def get_upload_file(self, *, dataset_id: str, document_id: str) -> dict[str, Any] | None:
try:
payload = self._request("GET", f"/datasets/{dataset_id}/documents/{document_id}/upload-file")
except DifyError as exc:
message = str(exc)
if " 404 " in message or '"status":404' in message:
return None
raise
return payload if isinstance(payload, dict) else None
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
payload = self._request("GET", f"/datasets/{dataset_id}/documents/{batch}/indexing-status")
return payload.get("data", [])
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
deadline = time.time() + timeout_seconds
latest: dict | None = None
while time.time() < deadline:
data = self.get_indexing_status(dataset_id=dataset_id, batch=batch)
latest = data[0] if data else None
status = (latest or {}).get("indexing_status")
if status in {"completed", "completed_with_warning"}:
return latest or {}
if status in {"error", "failed", "stopped"}:
raise DifyError((latest or {}).get("error") or f"Indexing failed with status={status}")
time.sleep(5)
last_status = (latest or {}).get("indexing_status") or "unknown"
last_display_status = (latest or {}).get("display_status") or "unknown"
raise DifyError(
f"Timed out waiting for Dify indexing. Last indexing_status={last_status}, display_status={last_display_status}."
)
def wait_for_document_indexing(
self,
*,
dataset_id: str,
document_id: str,
timeout_seconds: int = 300,
) -> dict:
deadline = time.time() + timeout_seconds
latest: dict | None = None
while time.time() < deadline:
latest = self.get_document_detail(dataset_id=dataset_id, document_id=document_id)
status = (latest or {}).get("indexing_status")
if status in {"completed", "completed_with_warning"}:
return latest or {}
if status in {"error", "failed", "stopped"}:
raise DifyError((latest or {}).get("error") or f"Indexing failed with status={status}")
time.sleep(5)
last_status = (latest or {}).get("indexing_status") or "unknown"
last_display_status = (latest or {}).get("display_status") or "unknown"
raise DifyError(
f"Timed out waiting for Dify indexing. Last indexing_status={last_status}, display_status={last_display_status}."
)
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self._request("DELETE", f"/datasets/{dataset_id}/documents/{document_id}")
def delete_dataset(self, *, dataset_id: str) -> None:
self._request("DELETE", f"/datasets/{dataset_id}")
-82
View File
@@ -1,82 +0,0 @@
from __future__ import annotations
import importlib
import traceback
from datetime import timedelta
from app.config import get_settings
DIFY_SYNC_COOLDOWN_GATE = "dify-sync-cooldown"
class InlineJobRef:
def __init__(self, job_id: str) -> None:
self.id = job_id
class InlineQueue:
def enqueue(self, task_name: str, *args, **kwargs) -> InlineJobRef:
job_id = str(args[0]) if args else f"inline:{task_name}"
module_name, function_name = task_name.rsplit(".", 1)
task = getattr(importlib.import_module(module_name), function_name)
try:
task(*args, **kwargs)
except Exception:
traceback.print_exc()
return InlineJobRef(f"inline:{job_id}")
def enqueue_in(self, delay: timedelta, task_name: str, *args, **kwargs) -> InlineJobRef:
if delay.total_seconds() <= 0:
return self.enqueue(task_name, *args, **kwargs)
job_id = str(args[0]) if args else f"inline:{task_name}"
return InlineJobRef(f"inline-delayed:{job_id}")
def get_redis_connection():
settings = get_settings()
if settings.task_execution_mode == "sync":
return None
from redis import Redis
return Redis.from_url(settings.redis_url)
def _gate_key(name: str) -> str:
settings = get_settings()
return f"{settings.rq_queue_name}:{name}"
def set_delay_gate(name: str, ttl_seconds: int) -> None:
redis = get_redis_connection()
if redis is None or ttl_seconds <= 0:
return
try:
redis.setex(_gate_key(name), ttl_seconds, "1")
except Exception:
return
def get_delay_gate_ttl(name: str) -> int:
redis = get_redis_connection()
if redis is None:
return 0
try:
ttl = redis.ttl(_gate_key(name))
except Exception:
return 0
if ttl is None or ttl < 0:
return 0
return int(ttl)
def get_queue():
settings = get_settings()
if settings.task_execution_mode == "sync":
return InlineQueue()
from rq import Queue
redis = get_redis_connection()
return Queue(name=settings.rq_queue_name, connection=redis, default_timeout=settings.rq_default_timeout)
-92
View File
@@ -1,92 +0,0 @@
from __future__ import annotations
import base64
import hashlib
import mimetypes
import re
import shutil
import zipfile
from pathlib import Path
from app.config import get_settings
settings = get_settings()
DATA_IMAGE_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
re.IGNORECASE | re.DOTALL,
)
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def group_dir(group_id: int, category: str) -> Path:
return settings.data_root / category / f"group_{group_id:04d}"
def version_dir(category: str, group_id: int, document_id: int, version_no: int) -> Path:
return group_dir(group_id, category) / f"document_{document_id:06d}" / f"v{version_no:03d}"
def public_storage_url(path: Path) -> str:
relative = path.relative_to(settings.data_root).as_posix()
return f"{settings.public_base_url.rstrip('/')}/storage/{relative}"
def guess_image_ext(fmt: str) -> str:
fmt = fmt.lower().strip()
if fmt in {"jpeg", "jpg"}:
return "jpg"
if fmt in {"png", "gif", "bmp", "webp"}:
return fmt
return "png"
def rewrite_embedded_images(markdown_text: str, assets_dir: Path) -> tuple[str, int]:
assets_dir.mkdir(parents=True, exist_ok=True)
seen: dict[str, str] = {}
count = 0
def repl(match: re.Match[str]) -> str:
nonlocal count
alt = match.group("alt") or "image"
fmt = guess_image_ext(match.group("fmt") or "png")
raw = base64.b64decode(match.group("b64"))
digest = hashlib.sha256(raw).hexdigest()
existing = seen.get(digest)
if existing is None:
count += 1
filename = f"img_{count:03d}_{digest[:8]}.{fmt}"
target = assets_dir / filename
target.write_bytes(raw)
existing = filename
seen[digest] = existing
return f"![{alt}]({existing})"
return DATA_IMAGE_RE.sub(repl, markdown_text), len(seen)
def remove_path_if_exists(path: Path) -> None:
if path.is_dir():
shutil.rmtree(path, ignore_errors=True)
elif path.exists():
path.unlink(missing_ok=True)
def build_zip(source_paths: list[tuple[Path, str]], output_path: Path) -> Path:
output_path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as archive:
for path, archive_name in source_paths:
if path.exists():
archive.write(path, arcname=archive_name)
return output_path
-495
View File
@@ -1,495 +0,0 @@
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import timedelta, timezone
from pathlib import Path
from typing import Any
from redis import Redis
from sqlalchemy.orm import Session
from app.config import Settings, get_settings
from app.models import DifySyncRecord, DocumentVersion, Job
from app.time_utils import utc_now
SNAPSHOT_RELATIVE_PATH = Path("watchdog/dify-health.json")
@dataclass
class StaleSyncCandidate:
version: DocumentVersion
active_job: Job | None
sync_record: DifySyncRecord | None
reason: str
age_seconds: int
@dataclass
class StaleConvertCandidate:
version: DocumentVersion
active_job: Job | None
reason: str
age_seconds: int
def _as_aware_utc(value):
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _live_queue_job_ids(settings: Settings | None = None) -> set[str] | None:
resolved = settings or get_settings()
try:
redis = Redis.from_url(resolved.redis_url)
raw_ids = redis.lrange(f"rq:queue:{resolved.rq_queue_name}", 0, -1)
return {item.decode("utf-8") if isinstance(item, bytes) else str(item) for item in raw_ids}
except Exception:
return None
def watchdog_snapshot_path(settings: Settings | None = None) -> Path:
resolved = settings or get_settings()
path = resolved.data_root / SNAPSHOT_RELATIVE_PATH
path.parent.mkdir(parents=True, exist_ok=True)
return path
def read_watchdog_snapshot(settings: Settings | None = None) -> dict[str, Any] | None:
path = watchdog_snapshot_path(settings)
if not path.exists():
return None
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
return {
"available": False,
"status": "invalid_snapshot",
"path": str(path),
"error": str(exc),
}
if isinstance(payload, dict):
payload.setdefault("available", True)
payload.setdefault("path", str(path))
return payload
return {
"available": False,
"status": "invalid_snapshot",
"path": str(path),
"error": "Snapshot must be a JSON object.",
}
def local_sync_health_summary(db: Session, *, timeout_seconds: int) -> dict[str, Any]:
stale_candidates = find_stale_sync_candidates(db, timeout_seconds=timeout_seconds)
recent_failures = (
db.query(Job)
.filter(Job.job_type == "sync", Job.status == "failed")
.order_by(Job.created_at.desc())
.limit(5)
.all()
)
active_jobs = (
db.query(Job)
.filter(Job.job_type == "sync", Job.status.in_(("queued", "running")))
.order_by(Job.created_at.desc())
.all()
)
syncing_versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "syncing").count()
sync_failed_versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "sync_failed").count()
return {
"timeout_seconds": timeout_seconds,
"syncing_versions": syncing_versions,
"sync_failed_versions": sync_failed_versions,
"active_sync_jobs": len(active_jobs),
"stale_candidates": len(stale_candidates),
"active_jobs": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"status": job.status,
"created_at": job.created_at.isoformat() if job.created_at else None,
"started_at": job.started_at.isoformat() if job.started_at else None,
"message": job.message,
}
for job in active_jobs[:10]
],
"recent_failures": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"created_at": job.created_at.isoformat() if job.created_at else None,
"finished_at": job.finished_at.isoformat() if job.finished_at else None,
"error": job.error,
}
for job in recent_failures
],
"stale_versions": [
{
"document_id": candidate.version.document_id,
"version_id": candidate.version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"sync_record_id": candidate.sync_record.id if candidate.sync_record else None,
"remote_document_id": candidate.sync_record.remote_document_id if candidate.sync_record else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
for candidate in stale_candidates[:20]
],
}
def local_convert_health_summary(
db: Session,
*,
timeout_seconds: int,
orphan_grace_seconds: int,
settings: Settings | None = None,
) -> dict[str, Any]:
stale_candidates = find_stale_convert_candidates(
db,
timeout_seconds=timeout_seconds,
orphan_grace_seconds=orphan_grace_seconds,
settings=settings,
)
recent_failures = (
db.query(Job)
.filter(Job.job_type == "convert", Job.status == "failed")
.order_by(Job.created_at.desc())
.limit(5)
.all()
)
active_jobs = (
db.query(Job)
.filter(Job.job_type == "convert", Job.status.in_(("queued", "running")))
.order_by(Job.created_at.desc())
.all()
)
pending_versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status.in_(("queued", "running"))).count()
failed_versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status == "failed").count()
return {
"timeout_seconds": timeout_seconds,
"orphan_grace_seconds": orphan_grace_seconds,
"pending_versions": pending_versions,
"failed_versions": failed_versions,
"active_convert_jobs": len(active_jobs),
"stale_candidates": len(stale_candidates),
"active_jobs": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"status": job.status,
"queue_job_id": job.queue_job_id,
"created_at": job.created_at.isoformat() if job.created_at else None,
"started_at": job.started_at.isoformat() if job.started_at else None,
"message": job.message,
}
for job in active_jobs[:10]
],
"recent_failures": [
{
"id": job.id,
"document_id": job.document_id,
"version_id": job.version_id,
"created_at": job.created_at.isoformat() if job.created_at else None,
"finished_at": job.finished_at.isoformat() if job.finished_at else None,
"error": job.error,
}
for job in recent_failures
],
"stale_versions": [
{
"document_id": candidate.version.document_id,
"version_id": candidate.version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
for candidate in stale_candidates[:20]
],
}
def find_stale_sync_candidates(db: Session, *, timeout_seconds: int) -> list[StaleSyncCandidate]:
cutoff = utc_now() - timedelta(seconds=timeout_seconds)
versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "syncing").all()
candidates: list[StaleSyncCandidate] = []
for version in versions:
active_job = (
db.query(Job)
.filter(
Job.version_id == version.id,
Job.job_type == "sync",
Job.status.in_(("queued", "running")),
)
.order_by(Job.created_at.desc())
.first()
)
sync_record = (
db.query(DifySyncRecord)
.filter(
DifySyncRecord.version_id == version.id,
DifySyncRecord.status == "syncing",
)
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
.first()
)
candidate: StaleSyncCandidate | None = None
active_job_created_at = _as_aware_utc(active_job.created_at) if active_job else None
sync_record_updated_at = _as_aware_utc(sync_record.updated_at) if sync_record else None
sync_record_created_at = _as_aware_utc(sync_record.created_at) if sync_record else None
uploaded_at = _as_aware_utc(version.uploaded_at)
if active_job and active_job_created_at and active_job_created_at <= cutoff:
age_seconds = int((utc_now() - active_job_created_at).total_seconds())
candidate = StaleSyncCandidate(
version=version,
active_job=active_job,
sync_record=sync_record,
reason="Sync job exceeded watchdog timeout.",
age_seconds=age_seconds,
)
elif sync_record and sync_record_updated_at and sync_record_updated_at <= cutoff:
age_seconds = int((utc_now() - sync_record_updated_at).total_seconds())
candidate = StaleSyncCandidate(
version=version,
active_job=active_job,
sync_record=sync_record,
reason="Sync record exceeded watchdog timeout without completion.",
age_seconds=age_seconds,
)
elif not active_job:
baseline = None
if sync_record_created_at:
baseline = sync_record_created_at
elif uploaded_at:
baseline = uploaded_at
if baseline and baseline <= cutoff:
age_seconds = int((utc_now() - baseline).total_seconds())
candidate = StaleSyncCandidate(
version=version,
active_job=None,
sync_record=sync_record,
reason="Sync status has no active job and exceeded watchdog timeout.",
age_seconds=age_seconds,
)
if candidate is not None:
candidates.append(candidate)
return candidates
def find_stale_convert_candidates(
db: Session,
*,
timeout_seconds: int,
orphan_grace_seconds: int,
settings: Settings | None = None,
) -> list[StaleConvertCandidate]:
cutoff = utc_now() - timedelta(seconds=timeout_seconds)
orphan_cutoff = utc_now() - timedelta(seconds=orphan_grace_seconds)
live_queue_job_ids = _live_queue_job_ids(settings)
versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status.in_(("queued", "running"))).all()
candidates: list[StaleConvertCandidate] = []
for version in versions:
active_job = (
db.query(Job)
.filter(
Job.version_id == version.id,
Job.job_type == "convert",
Job.status.in_(("queued", "running")),
)
.order_by(Job.created_at.desc())
.first()
)
candidate: StaleConvertCandidate | None = None
active_job_created_at = _as_aware_utc(active_job.created_at) if active_job else None
active_job_started_at = _as_aware_utc(active_job.started_at) if active_job else None
uploaded_at = _as_aware_utc(version.uploaded_at)
queue_job_present = (
bool(active_job and active_job.queue_job_id)
and live_queue_job_ids is not None
and active_job.queue_job_id in live_queue_job_ids
)
if active_job and active_job.status == "running":
baseline = active_job_started_at or active_job_created_at
if baseline and baseline <= cutoff:
age_seconds = int((utc_now() - baseline).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=active_job,
reason="Convert job exceeded watchdog timeout while running.",
age_seconds=age_seconds,
)
elif active_job and active_job.status == "queued":
if active_job.queue_job_id and live_queue_job_ids is not None and not queue_job_present and active_job_created_at and active_job_created_at <= orphan_cutoff:
age_seconds = int((utc_now() - active_job_created_at).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=active_job,
reason="Convert job is missing from Redis queue beyond watchdog grace period.",
age_seconds=age_seconds,
)
elif not active_job.queue_job_id and active_job_created_at and active_job_created_at <= orphan_cutoff:
age_seconds = int((utc_now() - active_job_created_at).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=active_job,
reason="Convert job has no queue id and exceeded watchdog grace period.",
age_seconds=age_seconds,
)
elif not active_job and uploaded_at and uploaded_at <= orphan_cutoff:
age_seconds = int((utc_now() - uploaded_at).total_seconds())
candidate = StaleConvertCandidate(
version=version,
active_job=None,
reason="Convert status has no active job and exceeded watchdog grace period.",
age_seconds=age_seconds,
)
if candidate is not None:
candidates.append(candidate)
return candidates
def recover_stale_syncs(
db: Session,
*,
timeout_seconds: int,
reason_prefix: str = "Marked stale by watchdog after timeout.",
) -> dict[str, Any]:
candidates = find_stale_sync_candidates(db, timeout_seconds=timeout_seconds)
now = utc_now()
recovered_versions = 0
recovered_jobs = 0
recovered_records = 0
documents: list[dict[str, Any]] = []
seen_versions: set[int] = set()
for candidate in candidates:
version = candidate.version
if version.id in seen_versions:
continue
seen_versions.add(version.id)
if version.sync_status == "syncing":
version.sync_status = "sync_failed"
recovered_versions += 1
if candidate.active_job and candidate.active_job.status in {"queued", "running"}:
candidate.active_job.status = "failed"
candidate.active_job.message = "Dify sync failed"
candidate.active_job.error = f"{reason_prefix} {candidate.reason}"
candidate.active_job.finished_at = now
recovered_jobs += 1
syncing_records = db.query(DifySyncRecord).filter(
DifySyncRecord.version_id == version.id,
DifySyncRecord.status == "syncing",
)
for record in syncing_records:
record.status = "sync_failed"
record.error = record.error or f"{reason_prefix} {candidate.reason}"
recovered_records += 1
documents.append(
{
"document_id": version.document_id,
"version_id": version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"sync_record_id": candidate.sync_record.id if candidate.sync_record else None,
"remote_document_id": candidate.sync_record.remote_document_id if candidate.sync_record else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
)
if recovered_versions or recovered_jobs or recovered_records:
db.commit()
return {
"timeout_seconds": timeout_seconds,
"recovered_versions": recovered_versions,
"recovered_jobs": recovered_jobs,
"recovered_records": recovered_records,
"documents": documents,
}
def recover_stale_converts(
db: Session,
*,
timeout_seconds: int,
orphan_grace_seconds: int,
reason_prefix: str = "Marked convert as failed by watchdog.",
settings: Settings | None = None,
) -> dict[str, Any]:
candidates = find_stale_convert_candidates(
db,
timeout_seconds=timeout_seconds,
orphan_grace_seconds=orphan_grace_seconds,
settings=settings,
)
now = utc_now()
recovered_versions = 0
recovered_jobs = 0
documents: list[dict[str, Any]] = []
seen_versions: set[int] = set()
for candidate in candidates:
version = candidate.version
if version.id in seen_versions:
continue
seen_versions.add(version.id)
if version.convert_status in {"queued", "running"}:
version.convert_status = "failed"
version.failed_reason = f"{reason_prefix} {candidate.reason}"
recovered_versions += 1
if candidate.active_job and candidate.active_job.status in {"queued", "running"}:
candidate.active_job.status = "failed"
candidate.active_job.message = "Conversion failed"
candidate.active_job.error = f"{reason_prefix} {candidate.reason}"
candidate.active_job.finished_at = now
recovered_jobs += 1
documents.append(
{
"document_id": version.document_id,
"version_id": version.id,
"active_job_id": candidate.active_job.id if candidate.active_job else None,
"age_seconds": candidate.age_seconds,
"reason": candidate.reason,
}
)
if recovered_versions or recovered_jobs:
db.commit()
return {
"timeout_seconds": timeout_seconds,
"orphan_grace_seconds": orphan_grace_seconds,
"recovered_versions": recovered_versions,
"recovered_jobs": recovered_jobs,
"documents": documents,
}
-462
View File
@@ -1,462 +0,0 @@
from __future__ import annotations
import os
import shutil
from datetime import timedelta
from pathlib import Path
from sqlalchemy.orm import Session
from app.config import get_settings
from app.database import SessionLocal
from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, SystemSetting
from app.services.dify_service import DifyError, DifyService
from app.services.queue_service import (
DIFY_SYNC_COOLDOWN_GATE,
get_delay_gate_ttl,
get_queue,
set_delay_gate,
)
from app.services.storage_service import (
public_storage_url,
rewrite_embedded_images,
version_dir,
)
from app.time_utils import utc_now
from edkb_system.config import SystemConfig
from edkb_system.controller import build_knowledge
def _db() -> Session:
return SessionLocal()
def _find_generated_markdown(output_root: Path) -> Path:
candidates = [path for path in output_root.rglob("*.md") if not path.name.startswith("_")]
if not candidates:
raise RuntimeError("No markdown output produced by edkb_system.")
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _set_job_running(db: Session, job: Job, message: str) -> None:
job.status = "running"
job.progress = 10
job.message = message
job.started_at = utc_now()
db.commit()
def _payload_dict(job: Job) -> dict:
return dict(job.payload or {})
def _is_retryable_dify_error(exc: Exception) -> bool:
message = str(exc).lower()
if "too many clients already" in message:
return True
if "timed out waiting for dify indexing" in message and ("waiting" in message or "queuing" in message):
return True
return False
def _retry_delay_seconds(attempt: int) -> int:
settings = get_settings()
delays = settings.dify_sync_retry_delays()
index = max(0, min(attempt - 1, len(delays) - 1))
return delays[index]
def _requeue_sync_job(
db: Session,
*,
job: Job,
version: DocumentVersion,
retry_count: int,
delay_seconds: int,
message: str,
last_error: str | None = None,
) -> None:
queue = get_queue()
rq_job = queue.enqueue_in(timedelta(seconds=delay_seconds), "app.tasks.run_sync_job", job.id, version.id)
payload = _payload_dict(job)
payload["sync_retry_count"] = retry_count
payload["sync_retry_after_seconds"] = delay_seconds
if last_error:
payload["sync_last_error"] = last_error
job.payload = payload
job.queue_job_id = rq_job.id
job.status = "queued"
job.progress = 0
job.message = message
job.error = None
job.started_at = None
job.finished_at = None
version.sync_status = "syncing"
db.commit()
def _schedule_retryable_sync(
db: Session,
*,
job: Job,
version: DocumentVersion,
exc: Exception,
) -> bool:
settings = get_settings()
if settings.task_execution_mode == "sync":
# Sync mode has no delayed executor, so fail visibly instead of leaving the job queued forever.
return False
payload = _payload_dict(job)
current_retry_count = int(payload.get("sync_retry_count") or 0)
if current_retry_count >= settings.dify_sync_max_retries:
return False
next_retry_count = current_retry_count + 1
delay_seconds = _retry_delay_seconds(next_retry_count)
cooldown_seconds = max(delay_seconds, settings.dify_sync_cooldown_seconds)
set_delay_gate(DIFY_SYNC_COOLDOWN_GATE, cooldown_seconds)
_requeue_sync_job(
db,
job=job,
version=version,
retry_count=next_retry_count,
delay_seconds=delay_seconds,
message=f"Dify busy, retrying in {delay_seconds}s (attempt {next_retry_count}/{settings.dify_sync_max_retries}).",
last_error=str(exc),
)
return True
def _defer_sync_for_cooldown(
db: Session,
*,
job: Job,
version: DocumentVersion,
cooldown_ttl: int,
) -> None:
retry_count = int(_payload_dict(job).get("sync_retry_count") or 0)
delay_seconds = max(5, cooldown_ttl)
_requeue_sync_job(
db,
job=job,
version=version,
retry_count=retry_count,
delay_seconds=delay_seconds,
message=f"Dify cooldown active, retrying in {delay_seconds}s.",
)
def run_convert_job(job_id: str, version_id: int) -> None:
settings = get_settings()
os.environ["EDKB_WORD_TIMEOUT_SEC"] = str(settings.edkb_word_timeout_sec)
os.environ["EDKB_FILE_TIMEOUT_SEC"] = str(settings.edkb_file_timeout_sec)
# Keep image extraction inside this system. The bundled converter
# defaults to external image-hosting unless explicitly disabled.
os.environ["MINIO_UPLOAD_ENABLED"] = "false"
os.environ["MINIO_ALLOW_EMBED_FALLBACK"] = "true"
db = _db()
try:
job = db.query(Job).filter(Job.id == job_id).first()
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
if not job or not version:
return
_set_job_running(db, job, "Converting source document")
version.convert_status = "running"
version.failed_reason = None
db.commit()
document = db.query(Document).filter(Document.id == version.document_id).first()
if not document:
raise RuntimeError("Document not found.")
work_root = settings.data_root / "jobs" / job.id
input_dir = work_root / "input"
output_dir = work_root / "output"
cache_dir = work_root / "cache"
input_dir.mkdir(parents=True, exist_ok=True)
output_dir.mkdir(parents=True, exist_ok=True)
cache_dir.mkdir(parents=True, exist_ok=True)
staged_source = input_dir / version.source_filename
shutil.copy2(version.source_path, staged_source)
config = SystemConfig.load(None)
result = build_knowledge(staged_source, output_dir, config, cache_dir)
failures = [item for item in result if item.get("status") == "failed"]
if failures:
raise RuntimeError(failures[0].get("error") or "Conversion failed.")
markdown_source = _find_generated_markdown(output_dir)
raw_markdown = markdown_source.read_text(encoding="utf-8")
markdown_target_dir = version_dir("markdown", document.group_id, document.id, version.version_no)
assets_target_dir = version_dir("assets", document.group_id, document.id, version.version_no)
markdown_target_dir.mkdir(parents=True, exist_ok=True)
markdown_target = markdown_target_dir / "document.md"
rewritten_markdown, image_count = rewrite_embedded_images(raw_markdown, assets_target_dir)
asset_prefix = public_storage_url(assets_target_dir)
rewritten_markdown = rewritten_markdown.replace("](img_", f"]({asset_prefix}/img_")
asset_dir_value = str(assets_target_dir.relative_to(settings.data_root))
markdown_target.write_text(rewritten_markdown, encoding="utf-8")
previous_synced = (
db.query(DifySyncRecord)
.join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id)
.filter(DocumentVersion.document_id == document.id, DifySyncRecord.status == "synced")
.first()
)
version.md_path = str(markdown_target)
version.md_public_url = public_storage_url(markdown_target)
version.asset_dir = asset_dir_value
version.word_count = len(rewritten_markdown.split())
version.convert_status = "success"
version.sync_status = "stale" if previous_synced else "unsynced"
version.converted_at = utc_now()
version.warnings_json = [{"message": f"embedded_images={image_count}"}]
job.status = "success"
job.progress = 100
job.message = "Conversion completed"
job.result = {
"md_path": version.md_path,
"md_public_url": version.md_public_url,
"image_count": image_count,
}
job.finished_at = utc_now()
db.commit()
shutil.rmtree(work_root, ignore_errors=True)
except Exception as exc:
if "job" in locals() and job is not None:
job.status = "failed"
job.error = str(exc)
job.message = "Conversion failed"
job.finished_at = utc_now()
if "version" in locals() and version is not None:
version.convert_status = "failed"
version.failed_reason = str(exc)
db.commit()
raise
finally:
db.close()
def run_sync_job(job_id: str, version_id: int) -> None:
settings = get_settings()
db = _db()
sync_record = None
try:
job = db.query(Job).filter(Job.id == job_id).first()
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
if not job or not version:
return
cooldown_ttl = get_delay_gate_ttl(DIFY_SYNC_COOLDOWN_GATE)
if cooldown_ttl > 0:
_defer_sync_for_cooldown(db, job=job, version=version, cooldown_ttl=cooldown_ttl)
return
_set_job_running(db, job, "Syncing document to Dify")
if version.convert_status != "success" or not version.md_path:
raise RuntimeError("Document is not ready for Dify sync.")
document = db.query(Document).filter(Document.id == version.document_id).first()
group = db.query(Group).filter(Group.id == document.group_id).first() if document else None
if not document or not group:
raise RuntimeError("Document group not found.")
version.sync_status = "syncing"
db.commit()
dify = DifyService()
system = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
dataset_id = dify.ensure_dataset(
dataset_name=group.name,
description=group.description,
permission=system.dify_permission if system else None,
indexing_technique=group.indexing_technique,
search_method=group.search_method,
top_k=group.top_k,
score_threshold_enabled=group.score_threshold_enabled,
score_threshold=float(group.score_threshold),
doc_form=group.doc_form,
embedding_model_provider=system.embedding_model_provider if system else None,
embedding_model=system.embedding_model if system else None,
reranking_model_provider=system.reranking_model_provider if system else None,
reranking_model=system.reranking_model if system else None,
)
if group.dify_dataset_id != dataset_id:
group.dify_dataset_id = dataset_id
db.commit()
sync_record = (
db.query(DifySyncRecord)
.filter(DifySyncRecord.version_id == version.id, DifySyncRecord.status == "syncing")
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
.first()
)
if sync_record and sync_record.dataset_id == dataset_id and sync_record.remote_document_id:
if sync_record.batch:
indexing = dify.wait_for_indexing(dataset_id=dataset_id, batch=sync_record.batch)
else:
indexing = dify.wait_for_document_indexing(
dataset_id=dataset_id,
document_id=sync_record.remote_document_id,
)
sync_record.status = "synced"
sync_record.last_indexing_status = indexing.get("indexing_status", "completed")
sync_record.last_synced_at = utc_now()
sync_record.error = None
version.sync_status = "synced"
job.status = "success"
job.progress = 100
job.message = "Dify sync completed"
job.error = None
job.result = {
"dataset_id": dataset_id,
"remote_document_id": sync_record.remote_document_id,
"batch": sync_record.batch,
"indexing_status": sync_record.last_indexing_status,
}
job.finished_at = utc_now()
db.commit()
return
markdown_text = Path(version.md_path).read_text(encoding="utf-8")
existing_record = (
db.query(DifySyncRecord)
.join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id)
.filter(DocumentVersion.document_id == document.id)
.order_by(DifySyncRecord.updated_at.desc())
.first()
)
previous_remote_document_id = existing_record.remote_document_id if existing_record else None
if previous_remote_document_id:
try:
dify.delete_document(dataset_id=dataset_id, document_id=previous_remote_document_id)
except DifyError:
# Failed or stale remote documents should not block a fresh resync.
pass
response = dify.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=markdown_text,
doc_form=group.doc_form,
indexing_technique=group.indexing_technique,
)
sync_record = DifySyncRecord(
version_id=version.id,
dataset_id=dataset_id,
remote_document_id=response["document"]["id"],
batch=response.get("batch"),
status="syncing",
)
db.add(sync_record)
db.commit()
batch = sync_record.batch
if batch:
indexing = dify.wait_for_indexing(dataset_id=dataset_id, batch=batch)
else:
indexing = dify.wait_for_document_indexing(
dataset_id=dataset_id,
document_id=sync_record.remote_document_id,
)
sync_record.status = "synced"
sync_record.last_indexing_status = indexing.get("indexing_status", "completed")
sync_record.last_synced_at = utc_now()
sync_record.error = None
version.sync_status = "synced"
job.status = "success"
job.progress = 100
job.message = "Dify sync completed"
job.result = {
"dataset_id": dataset_id,
"remote_document_id": sync_record.remote_document_id,
"batch": sync_record.batch,
"indexing_status": sync_record.last_indexing_status,
}
job.finished_at = utc_now()
db.commit()
except (Exception, DifyError) as exc:
if "job" in locals() and job is not None and "version" in locals() and version is not None and _is_retryable_dify_error(exc):
if sync_record is not None:
sync_record.error = str(exc)
if _schedule_retryable_sync(db, job=job, version=version, exc=exc):
return
if "job" in locals() and job is not None:
job.status = "failed"
job.error = str(exc)
job.message = "Dify sync failed"
job.finished_at = utc_now()
if "version" in locals() and version is not None:
version.sync_status = "sync_failed"
if sync_record is not None:
sync_record.status = "sync_failed"
sync_record.error = str(exc)
if "dify" in locals() and "dataset_id" in locals() and sync_record.batch:
try:
latest = dify.get_indexing_status(dataset_id=dataset_id, batch=sync_record.batch)
sync_record.last_indexing_status = (latest[0] if latest else {}).get("indexing_status")
except Exception:
pass
db.commit()
raise
finally:
db.close()
def run_delete_document_job(job_id: str, document_id: int) -> None:
db = _db()
try:
from app.api.files import _cleanup_document_storage
job = db.query(Job).filter(Job.id == job_id).first()
document = db.query(Document).filter(Document.id == document_id).first()
if not job:
return
_set_job_running(db, job, "Deleting document assets")
payload = _payload_dict(job)
delete_dify = bool(payload.get("delete_dify"))
remote_keys: set[tuple[str, str]] = set()
if document:
for version in document.versions:
for record in version.sync_records:
if record.dataset_id and record.remote_document_id:
remote_keys.add((record.dataset_id, record.remote_document_id))
if delete_dify and remote_keys:
dify = DifyService()
for dataset_id, remote_document_id in remote_keys:
dify.delete_document(dataset_id=dataset_id, document_id=remote_document_id)
if document:
_cleanup_document_storage(document)
job.status = "success"
job.progress = 100
job.message = "Document delete completed"
job.error = None
job.result = {
"deleted": True,
"delete_dify": delete_dify,
"remote_document_count": len(remote_keys),
}
job.finished_at = utc_now()
db.commit()
except Exception as exc:
if "job" in locals() and job is not None:
job.status = "failed"
job.error = str(exc)
job.message = "Document delete failed"
job.finished_at = utc_now()
db.commit()
raise
finally:
db.close()
-7
View File
@@ -1,7 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
def utc_now() -> datetime:
return datetime.now(timezone.utc)
-8
View File
@@ -1,8 +0,0 @@
from __future__ import annotations
PRIMARY_SUPER_ADMIN_USERNAME = "admin"
def is_primary_super_admin_username(username: str | None) -> bool:
return (username or "").strip().lower() == PRIMARY_SUPER_ADMIN_USERNAME
-91
View File
@@ -1,91 +0,0 @@
from __future__ import annotations
import argparse
import json
from app.config import get_settings
from app.database import SessionLocal
from app.services.watchdog_service import (
local_convert_health_summary,
local_sync_health_summary,
recover_stale_converts,
recover_stale_syncs,
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Document Cleaning watchdog helpers")
subparsers = parser.add_subparsers(dest="command", required=True)
summary = subparsers.add_parser("summary", help="Print local sync health summary")
summary.add_argument("--timeout-seconds", type=int, default=None)
convert_summary = subparsers.add_parser("convert-summary", help="Print local convert health summary")
convert_summary.add_argument("--timeout-seconds", type=int, default=None)
convert_summary.add_argument("--orphan-grace-seconds", type=int, default=None)
recover = subparsers.add_parser("recover-stale-syncs", help="Recover stale syncing records")
recover.add_argument("--timeout-seconds", type=int, default=None)
recover.add_argument(
"--reason-prefix",
default="Marked stale by watchdog after timeout.",
)
recover_convert = subparsers.add_parser("recover-stale-converts", help="Recover stale convert records")
recover_convert.add_argument("--timeout-seconds", type=int, default=None)
recover_convert.add_argument("--orphan-grace-seconds", type=int, default=None)
recover_convert.add_argument(
"--reason-prefix",
default="Marked convert as failed by watchdog.",
)
return parser
def main() -> None:
parser = build_parser()
args = parser.parse_args()
settings = get_settings()
db = SessionLocal()
try:
if args.command == "summary":
timeout_seconds = args.timeout_seconds or settings.watchdog_stale_sync_timeout_seconds
payload = local_sync_health_summary(db, timeout_seconds=timeout_seconds)
elif args.command == "convert-summary":
timeout_seconds = args.timeout_seconds or settings.watchdog_stale_convert_timeout_seconds
orphan_grace_seconds = args.orphan_grace_seconds or settings.watchdog_convert_orphan_grace_seconds
payload = local_convert_health_summary(
db,
timeout_seconds=timeout_seconds,
orphan_grace_seconds=orphan_grace_seconds,
settings=settings,
)
elif args.command == "recover-stale-syncs":
timeout_seconds = args.timeout_seconds or settings.watchdog_stale_sync_timeout_seconds
payload = recover_stale_syncs(
db,
timeout_seconds=timeout_seconds,
reason_prefix=args.reason_prefix,
)
elif args.command == "recover-stale-converts":
timeout_seconds = args.timeout_seconds or settings.watchdog_stale_convert_timeout_seconds
orphan_grace_seconds = args.orphan_grace_seconds or settings.watchdog_convert_orphan_grace_seconds
payload = recover_stale_converts(
db,
timeout_seconds=timeout_seconds,
orphan_grace_seconds=orphan_grace_seconds,
reason_prefix=args.reason_prefix,
settings=settings,
)
else:
parser.error(f"Unsupported command: {args.command}")
return
finally:
db.close()
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
-17
View File
@@ -1,17 +0,0 @@
JWT_SECRET=change-me
DATABASE_BACKEND=sqlite
DATABASE_URL=
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
POSTGRES_DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
REDIS_URL=redis://127.0.0.1:6379/0
PUBLIC_BASE_URL=http://127.0.0.1:8000
DIFY_BASE_URL=https://api.dify.ai/v1
DIFY_API_KEY=
INTEGRATION_API_KEY=change-me-internal
INTEGRATION_DOWNLOAD_SECRET=change-me-download-signing-secret
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=admin123456
TASK_EXECUTION_MODE=sync
DIFY_SYNC_MAX_RETRIES=4
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
DIFY_SYNC_COOLDOWN_SECONDS=60
-1
View File
@@ -1 +0,0 @@
"""Enterprise KB Skill System orchestrator package."""
-167
View File
@@ -1,167 +0,0 @@
from __future__ import annotations
import json
from pathlib import Path
import typer
from edkb_system.config import SystemConfig
from edkb_system.contracts import Context
from edkb_system.controller import build_knowledge
from edkb_system.skills import (
flow_reconstruct,
loader_excel,
loader_pdf,
table_linearize,
)
app = typer.Typer(help="Enterprise KB multi-skill orchestrator")
def _write_failed_files_report(out_dir: Path, failed: list[dict]) -> tuple[Path, Path]:
txt_path = out_dir / "_failed_files.txt"
json_path = out_dir / "_failed_files.json"
if not failed:
for p in [txt_path, json_path]:
if p.exists():
p.unlink()
return txt_path, json_path
out_dir.mkdir(parents=True, exist_ok=True)
lines: list[str] = []
payload: list[dict] = []
for idx, item in enumerate(failed, start=1):
file_name = str(item.get("file") or "unknown").strip() or "unknown"
reason = str(item.get("error") or "unknown error")
elapsed_ms = int(item.get("elapsed_ms") or 0)
elapsed_s = f"{elapsed_ms / 1000:.3f}s"
is_timeout = "timed out" in reason.lower()
payload.append(
{
"index": idx,
"file": file_name,
"reason": reason,
"elapsed_ms": elapsed_ms,
"timed_out": is_timeout,
}
)
lines.extend(
[
f"[{idx}] {file_name}",
f"reason: {reason}",
f"elapsed: {elapsed_s}",
f"timed_out: {'true' if is_timeout else 'false'}",
"",
]
)
txt_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
json_path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
return txt_path, json_path
@app.command("build")
def build_cmd(
input_path: str = typer.Argument(..., metavar="PATH"),
out: str = typer.Option(..., "--out"),
config: str | None = typer.Option(None, "--config"),
skip: list[str] | None = typer.Option(
None,
"--skip",
help="Skip files by glob pattern (match name or relative path, repeatable)",
),
resume: bool = typer.Option(
False,
"--resume/--no-resume",
help="Skip files whose target markdown already exists",
),
prune_stale: bool = typer.Option(
False,
"--prune-stale/--keep-stale",
help="Remove stale markdown/intermediate leftovers in output before build",
),
) -> None:
cfg = SystemConfig.load(config)
root = Path(__file__).resolve().parents[2]
temp_dir = root / "work" / "cache"
in_path = Path(input_path)
if not in_path.exists():
typer.echo(f"Input path not found: {in_path}")
typer.echo("Create the folder and put documents in it, e.g. work/input")
raise typer.Exit(code=2)
results = build_knowledge(
in_path,
Path(out),
cfg,
temp_dir,
skip_patterns=skip or [],
resume=resume,
prune_stale_output=prune_stale,
)
ok = [r for r in results if r.get("status") == "success"]
failed = [r for r in results if r.get("status") == "failed"]
skipped = [r for r in results if r.get("status") == "skipped"]
typer.echo(
"Completed files: "
f"{len(results)} (success={len(ok)}, failed={len(failed)}, skipped={len(skipped)})"
)
if failed:
txt_path, json_path = _write_failed_files_report(Path(out), failed)
for r in failed:
file_name = str(r.get("file", "")).strip() or "unknown"
reason = str(r.get("error") or "unknown error")
typer.echo(f"- Failed: {file_name}")
typer.echo(f" - reason: {reason}")
typer.echo(f"- Failed list: {txt_path}")
typer.echo(f"- Failed json: {json_path}")
else:
_write_failed_files_report(Path(out), [])
typer.echo(f"- Output dir: {Path(out)}")
@app.command("inspect-flow")
def inspect_flow_cmd(
file: str = typer.Argument(..., metavar="FILE"),
out: str = typer.Option(..., "--out"),
) -> None:
ctx = Context(file_type="pdf")
blocks = loader_pdf.run({"file_path": file}, ctx)
data = flow_reconstruct.run(blocks, ctx)
out_dir = Path(out)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "inspect_flow.md").write_text(
"\n\n".join(data.get("flow_markdowns", [])), encoding="utf-8"
)
(out_dir / "inspect_flow_debug.json").write_text(
json.dumps(data.get("debug", []), ensure_ascii=False, indent=2),
encoding="utf-8",
)
typer.echo("inspect-flow done")
@app.command("inspect-excel")
def inspect_excel_cmd(
file: str = typer.Argument(..., metavar="FILE"),
out: str = typer.Option(..., "--out"),
) -> None:
ctx = Context(file_type="xlsx")
tables = loader_excel.run({"file_path": file, "work_dir": str(Path(out))}, ctx)
md = table_linearize.run(tables, ctx)
out_dir = Path(out)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "inspect_excel.md").write_text(md, encoding="utf-8")
(out_dir / "inspect_excel_schema.json").write_text(
json.dumps(
[{"sheet": t.get("sheet"), "headers": t.get("headers")} for t in tables],
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
typer.echo("inspect-excel done")
if __name__ == "__main__":
app()
-53
View File
@@ -1,53 +0,0 @@
from __future__ import annotations
import json
from pathlib import Path
from pydantic import BaseModel, Field
class RouterConfig(BaseModel):
scan_likelihood_threshold: float = 0.6
flow_likelihood_threshold: float = 0.5
table_likelihood_threshold: float = 0.5
class OCRConfig(BaseModel):
enable: bool = True
engine: str = "rapidocr"
min_confidence: float = 0.3
class ChunkConfig(BaseModel):
enable: bool = True
max_chars: int = 1200
overlap_chars: int = 150
add_heading_path_prefix: bool = True
class CleanConfig(BaseModel):
dedup_min_repeats: int = 3
merge_short_line_chars: int = 15
class SystemConfig(BaseModel):
router: RouterConfig = Field(default_factory=RouterConfig)
ocr: OCRConfig = Field(default_factory=OCRConfig)
chunk: ChunkConfig = Field(default_factory=ChunkConfig)
clean: CleanConfig = Field(default_factory=CleanConfig)
@classmethod
def load(cls, path: str | None) -> "SystemConfig":
if not path:
return cls()
p = Path(path)
raw = p.read_text(encoding="utf-8")
if p.suffix.lower() in {".yaml", ".yml"}:
import yaml
data = yaml.safe_load(raw) or {}
elif p.suffix.lower() == ".json":
data = json.loads(raw)
else:
raise ValueError("config only supports yaml/yml/json")
return cls.model_validate(data)
-54
View File
@@ -1,54 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Block:
id: str
page: int
type: str
text: str
bbox: tuple[float, float, float, float]
meta: dict[str, Any] = field(default_factory=dict)
def cx(self) -> float:
return (self.bbox[0] + self.bbox[2]) / 2.0
def cy(self) -> float:
return (self.bbox[1] + self.bbox[3]) / 2.0
@dataclass
class Chunk:
id: str
heading_path: str
text: str
index: int
source: str
@dataclass
class Context:
file_type: str = ""
pages: int = 0
images: int = 0
ocr_characters: int = 0
flows_detected: int = 0
warnings: list[str] = field(default_factory=list)
confidence: float = 1.0
extras: dict[str, Any] = field(default_factory=dict)
@dataclass
class DocumentProfile:
file_type: str
text_density: float
has_images: bool
has_tables: bool
flow_likelihood: float
scan_likelihood: float
table_likelihood: float
language_hint: str
recommended_pipeline: list[str]
-893
View File
@@ -1,893 +0,0 @@
from __future__ import annotations
import json
import fnmatch
import multiprocessing as mp
import os
import re
import shutil
import time
import traceback
from pathlib import Path
from edkb_system.config import SystemConfig
from edkb_system.contracts import Context
from edkb_system.discovery import discover
from edkb_system.skills import (
chunk,
clean,
doc_to_pdf,
export,
flow_reconstruct,
intake_router,
loader_csv,
loader_docx,
loader_excel,
loader_pdf,
loader_pptx,
ocr,
postcheck,
quality_gate,
table_linearize,
)
from edkb_system.skills.common import blocks_to_plain_markdown
from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids
_STEP_ALIAS = {
"edkb-intake-router": "route",
"edkb-loader-docx": "docx",
"edkb-doc-to-pdf": "doc2pdf",
"edkb-loader-pdf": "pdf",
"edkb-loader-pptx": "pptx",
"edkb-loader-excel": "excel",
"edkb-loader-csv": "csv",
"edkb-ocr": "ocr",
"edkb-flow-reconstruct": "flow",
"edkb-table-linearize": "table",
"edkb-clean": "clean",
"edkb-chunk": "chunk",
"edkb-quality-gate": "qgate",
"edkb-export": "export",
"edkb-postcheck": "check",
}
def _step_alias(step: str) -> str:
return _STEP_ALIAS.get(step, step.replace("edkb-", ""))
def _extract_doc_header_from_flow(flow_mds: list[str]) -> str | None:
if not flow_mds:
return None
for line in "\n".join(flow_mds).splitlines():
if "文件编号" not in line or "文件级别" not in line or "版本" not in line:
continue
s = " ".join(line.split())
m = re.search(r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", s)
if m:
return f"文件编号 {m.group(1)} 文件级别 {m.group(2)} 版本 {m.group(3)}"
return None
def _inject_doc_header_from_flow(text: str, flow_mds: list[str]) -> str:
if "文件编号" in text:
return text
meta = _extract_doc_header_from_flow(flow_mds)
if not meta:
return text
if text.startswith("制定部门"):
i = text.find("\n")
if i >= 0:
return text[: i + 1] + meta + "\n" + text[i + 1 :]
return meta + "\n" + text
def _inject_source_title_if_missing(text: str, source_stem: str) -> str:
if not source_stem:
return text
preview = "\n".join(text.splitlines()[:20])
norm_preview = re.sub(r"\s+", "", preview)
norm_source = re.sub(r"\s+", "", source_stem)
if norm_source in norm_preview:
return text
return source_stem + "\n" + text
def _promote_title_above_meta(text: str) -> str:
lines = text.splitlines()
if len(lines) < 2:
return text
first_idx = next((i for i, x in enumerate(lines) if x.strip()), None)
if first_idx is None:
return text
second_idx = next(
(i for i in range(first_idx + 1, len(lines)) if lines[i].strip()), None
)
if second_idx is None:
return text
first = lines[first_idx].strip()
second = lines[second_idx].strip()
if "文件编号" not in first:
return text
if (
re.match(r"^[一二三四五六七八九十]+、", second)
or second.startswith("制定部门")
or second.startswith("文件修订履历")
or "文件编号" in second
):
return text
if len(second) > 80:
return text
lines[first_idx], lines[second_idx] = lines[second_idx], lines[first_idx]
return "\n".join(lines)
def _promote_dept_header_near_top(text: str) -> str:
lines = text.splitlines()
pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+")
idx = next(
(i for i, ln in enumerate(lines) if pat.search(" ".join(ln.split()))), None
)
if idx is None or idx <= 4:
return text
line = lines.pop(idx)
insert_at = 1
for i, ln in enumerate(lines[:6]):
if ln.strip().startswith("文件编号"):
insert_at = i + 1
break
lines.insert(insert_at, line)
return "\n".join(lines)
def _ocr_payload_map(blocks: list) -> dict[str, str]:
out: dict[str, str] = {}
for b in blocks:
if getattr(b, "type", "") != "ocr_text" or not str(
getattr(b, "id", "")
).startswith("ocr-"):
continue
txt = (getattr(b, "text", "") or "").strip()
if txt.startswith("OCR_TEXT:"):
txt = txt[len("OCR_TEXT:") :].strip()
txt = re.sub(r"(?m)^\s*-\s*", "", txt)
txt = " ".join(x.strip() for x in txt.splitlines() if x.strip())
if txt and txt != "<empty>":
out[str(b.id)[len("ocr-") :]] = txt
return out
def _has_non_flow_image_content(blocks: list) -> bool:
img_ids = [str(b.id) for b in blocks if getattr(b, "type", "") == "image"]
if not img_ids:
return False
ocr_map = _ocr_payload_map(blocks)
info_kw = re.compile(r"分数值|频繁程度|严重性|LEC|评分基准|风险积分|事故发生")
flow_kw = re.compile(r"备料|取样|资料确认|品质检验|判定|产品出货|NG|OK|不合格品")
for iid in img_ids:
payload = ocr_map.get(iid, "")
if not payload:
continue
if info_kw.search(payload):
return True
if len(payload) >= 80 and len(flow_kw.findall(payload)) <= 2:
return True
return False
def _derive_source_category(file_path: Path, input_path: Path) -> str:
if input_path.is_dir():
try:
rel = file_path.relative_to(input_path)
if len(rel.parts) >= 2:
return rel.parts[0]
return input_path.name or "uncategorized"
except Exception:
return file_path.parent.name or "uncategorized"
return input_path.parent.name or "uncategorized"
def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path:
if input_path.is_dir():
try:
rel = file_path.relative_to(input_path)
except Exception:
rel = Path(file_path.name)
if len(rel.parts) == 1:
root_name = input_path.name
if root_name and root_name.lower() not in {"input", "work"}:
rel = Path(root_name) / rel
else:
parent_name = file_path.parent.name
if parent_name and parent_name.lower() not in {"input", "work"}:
rel = Path(parent_name) / file_path.name
else:
rel = Path(file_path.name)
return rel.with_suffix(".md")
def _normalize_path_for_match(p: Path | str) -> str:
return str(p).replace("\\", "/")
def _file_timeout_sec() -> int | None:
raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip()
try:
value = int(raw)
except ValueError:
value = 0
return value if value > 0 else None
def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
if input_path.is_file():
candidates = [input_path]
elif input_path.exists():
candidates = [p for p in input_path.rglob("*") if p.is_file()]
else:
return []
removed: list[Path] = []
for file in candidates:
name = file.name
if not (name.startswith("~$") or name.startswith("~WRL")):
continue
try:
file.unlink()
except Exception:
continue
removed.append(file)
return removed
def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None:
if not patterns:
return None
lowered_candidates = [c.lower() for c in candidates if c]
for pat in patterns:
norm_pat = _normalize_path_for_match(pat).strip().lower()
if not norm_pat:
continue
for cand in lowered_candidates:
if fnmatch.fnmatch(cand, norm_pat):
return pat
return None
def _prune_stale_markdowns(output_dir: Path, expected: set[Path]) -> None:
keep_names = {"INDEX.md", "POSTCHECK_ISSUES.md"}
expected_resolved = {p.resolve() for p in expected}
for md in output_dir.rglob("*.md"):
if md.name in keep_names:
continue
try:
resolved = md.resolve()
except Exception:
resolved = md
if resolved in expected_resolved:
continue
try:
md.unlink()
except Exception:
continue
def _run_one_worker(payload: dict, queue: mp.Queue) -> None:
try:
cfg = SystemConfig.model_validate(payload["config"])
res = _run_one(
Path(payload["file_path"]),
Path(payload["out_root"]),
Path(payload["temp_dir"]),
cfg,
source_root=Path(payload["source_root"])
if payload.get("source_root")
else None,
source_category=payload.get("source_category"),
final_md_path=(
Path(payload["final_md_path"]) if payload.get("final_md_path") else None
),
progress_label=payload.get("progress_label"),
)
queue.put({"ok": True, "result": res})
except Exception as exc:
queue.put({"ok": False, "error": str(exc), "detail": traceback.format_exc()})
def _run_one_with_timeout(
file_path: Path,
out_root: Path,
temp_dir: Path,
cfg: SystemConfig,
source_root: Path | None = None,
source_category: str | None = None,
final_md_path: Path | None = None,
progress_label: str | None = None,
) -> dict:
timeout = _file_timeout_sec()
if not timeout:
return _run_one(
file_path,
out_root,
temp_dir,
cfg,
source_root=source_root,
source_category=source_category,
final_md_path=final_md_path,
progress_label=progress_label,
)
ctx = mp.get_context("spawn")
queue: mp.Queue = ctx.Queue()
before_pids = _list_winword_pids()
payload = {
"file_path": str(file_path),
"out_root": str(out_root),
"temp_dir": str(temp_dir),
"config": cfg.model_dump(),
"source_root": str(source_root) if source_root else None,
"source_category": source_category,
"final_md_path": str(final_md_path) if final_md_path else None,
"progress_label": progress_label,
}
proc = ctx.Process(target=_run_one_worker, args=(payload, queue))
proc.start()
proc.join(timeout)
if proc.is_alive():
proc.terminate()
proc.join(5)
after_pids = _list_winword_pids()
_kill_winword_pids(after_pids - before_pids)
raise TimeoutError(
f"file processing timed out after {timeout}s: {file_path.name}"
)
if queue.empty():
if proc.exitcode not in {0, None}:
raise RuntimeError(
f"file worker exited unexpectedly (code={proc.exitcode}): {file_path.name}"
)
raise RuntimeError(f"file worker returned no result: {file_path.name}")
message = queue.get()
if message.get("ok"):
return message["result"]
detail = str(message.get("detail") or "")
raise RuntimeError(str(message.get("error") or detail or "unknown worker error"))
marker_files = {
"01_raw_layout.json",
"02_flow_procedure.md",
"03_clean.md",
"04_chunks.jsonl",
"report.md",
"trace_pipeline.json",
"postcheck.json",
}
for d in list(output_dir.iterdir()):
if not d.is_dir():
continue
try:
names = {p.name for p in d.iterdir()}
except Exception:
continue
if names & marker_files:
shutil.rmtree(d, ignore_errors=True)
for d in sorted(output_dir.rglob("*"), key=lambda x: len(x.parts), reverse=True):
if not d.is_dir():
continue
try:
if d == output_dir:
continue
next(d.iterdir())
except StopIteration:
try:
d.rmdir()
except Exception:
pass
except Exception:
continue
def _run_one(
file_path: Path,
out_root: Path,
temp_dir: Path,
cfg: SystemConfig,
source_root: Path | None = None,
source_category: str | None = None,
final_md_path: Path | None = None,
progress_label: str | None = None,
) -> dict:
ctx = Context()
trace_steps: list[str] = []
timings_ms: dict[str, int] = {}
def _mark(step: str, started: float) -> None:
timings_ms[step] = int((time.perf_counter() - started) * 1000)
def _announce(stage: str) -> None:
if not progress_label:
return
print(f"{progress_label} stage: {stage}", flush=True)
out_dir = out_root / file_path.stem
out_dir.mkdir(parents=True, exist_ok=True)
for stale in [
out_dir / "inspect_flow_debug.json",
out_dir / "trace_pipeline.json",
out_dir / "postcheck.json",
]:
if stale.exists():
stale.unlink()
t0 = time.perf_counter()
profile = intake_router.run({"file_path": str(file_path)}, ctx, cfg.router)
_mark("edkb-intake-router", t0)
trace_steps.append("edkb-intake-router")
blocks = []
tables = None
text = ""
flow_mds: list[str] = []
if profile.file_type in {"doc", "docx"}:
_announce("doc/docx parse")
t0 = time.perf_counter()
docx_blocks = loader_docx.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-loader-docx", t0)
trace_steps.append("edkb-loader-docx")
table_blocks = sum(1 for b in docx_blocks if b.type == "table")
prefer_docx = table_blocks > 0
docx_images = [b for b in docx_blocks if b.type == "image"]
docx_non_images = [b for b in docx_blocks if b.type != "image"]
pdf_blocks = None
if "edkb-doc-to-pdf" in profile.recommended_pipeline and (
(profile.file_type == "doc" and not prefer_docx) or not docx_blocks
):
_announce("doc to pdf")
t0 = time.perf_counter()
conv = doc_to_pdf.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-doc-to-pdf", t0)
trace_steps.append("edkb-doc-to-pdf")
pdf_path = conv.get("pdf_path")
if pdf_path:
_announce("pdf load")
t0 = time.perf_counter()
pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx)
_mark("edkb-loader-pdf", t0)
trace_steps.append("edkb-loader-pdf")
blocks = pdf_blocks
else:
blocks = docx_blocks
else:
blocks = docx_blocks
if (
profile.file_type == "doc"
and "edkb-doc-to-pdf" in profile.recommended_pipeline
and (not prefer_docx or not docx_blocks)
):
if pdf_blocks is None:
_announce("doc to pdf")
t0 = time.perf_counter()
conv = doc_to_pdf.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-doc-to-pdf", t0)
trace_steps.append("edkb-doc-to-pdf")
pdf_path = conv.get("pdf_path")
if pdf_path:
_announce("pdf load")
t0 = time.perf_counter()
pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx)
_mark("edkb-loader-pdf", t0)
trace_steps.append("edkb-loader-pdf")
if pdf_blocks is not None:
pdf_images = [b for b in pdf_blocks if b.type == "image"]
if pdf_images and len(pdf_images) > len(docx_images):
blocks = docx_non_images + pdf_images
ctx.warnings.append(
f"doc image source switched to pdf: {len(docx_images)} -> {len(pdf_images)}"
)
elif not blocks:
blocks = pdf_blocks
elif profile.file_type == "pdf":
_announce("pdf load")
t0 = time.perf_counter()
blocks = loader_pdf.run({"file_path": str(file_path)}, ctx)
_mark("edkb-loader-pdf", t0)
trace_steps.append("edkb-loader-pdf")
elif profile.file_type in {"ppt", "pptx"}:
_announce("ppt/pptx load")
t0 = time.perf_counter()
blocks = loader_pptx.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-loader-pptx", t0)
trace_steps.append("edkb-loader-pptx")
elif profile.file_type in {"xls", "xlsx"}:
_announce("excel load")
t0 = time.perf_counter()
tables = loader_excel.run(
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
)
_mark("edkb-loader-excel", t0)
trace_steps.append("edkb-loader-excel")
elif profile.file_type == "csv":
t0 = time.perf_counter()
tables = loader_csv.run({"file_path": str(file_path)}, ctx)
_mark("edkb-loader-csv", t0)
trace_steps.append("edkb-loader-csv")
else:
ctx.warnings.append(f"unsupported file type: {profile.file_type}")
if blocks:
ctx.images = sum(1 for b in blocks if b.type == "image")
should_ocr = cfg.ocr.enable and (
"edkb-ocr" in profile.recommended_pipeline
or any(b.type == "image" for b in blocks)
)
if profile.file_type in {"ppt", "pptx"}:
should_ocr = False
if should_ocr:
_announce("ocr")
t0 = time.perf_counter()
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
_mark("edkb-ocr", t0)
trace_steps.append("edkb-ocr")
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
policy_text = doc_kind == "policy_text"
has_non_flow_info = _has_non_flow_image_content(blocks)
has_page_image_mode = bool(ctx.extras.get("pdf_page_image_mode_pages"))
has_figure_anchor = any(
(b.text or "")
and re.search(
r"^\s*\d+(?:\.\d+){1,3}\s*[^\n]{0,40}(?:示意图|图示)\s*$",
b.text,
)
for b in blocks
if b.type in {"heading", "paragraph"}
)
suppress_images = False
if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor:
if policy_text and not has_non_flow_info and not has_page_image_mode:
suppress_images = True
elif (
doc_kind == "flow_procedure"
and not has_non_flow_info
and not has_page_image_mode
):
suppress_images = True
if suppress_images:
blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}]
trace_steps.append("edkb-image-suppress(no_figure_anchor)")
flow_info = {}
if "edkb-flow-reconstruct" in profile.recommended_pipeline:
_announce("flow reconstruct")
t0 = time.perf_counter()
flow_info = flow_reconstruct.run(blocks, ctx)
_mark("edkb-flow-reconstruct", t0)
trace_steps.append("edkb-flow-reconstruct")
flow_mds = flow_info.get("flow_markdowns", [])
if flow_info.get("debug"):
(out_dir / "inspect_flow_debug.json").write_text(
json.dumps(flow_info["debug"], ensure_ascii=False, indent=2),
encoding="utf-8",
)
text = blocks_to_plain_markdown(blocks)
text = _inject_doc_header_from_flow(text, flow_mds)
elif tables is not None:
_announce("table linearize")
t0 = time.perf_counter()
text = table_linearize.run(tables, ctx)
_mark("edkb-table-linearize", t0)
trace_steps.append("edkb-table-linearize")
_announce("clean")
t0 = time.perf_counter()
clean_md = clean.run(
text, ctx, cfg.clean.dedup_min_repeats, cfg.clean.merge_short_line_chars
)
_mark("edkb-clean", t0)
clean_md = _inject_source_title_if_missing(clean_md, file_path.stem)
clean_md = _promote_title_above_meta(clean_md)
meta = _extract_doc_header_from_flow(flow_mds)
has_meta_line = bool(
re.search(r"文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S+", clean_md)
or ("| 文件编号 |" in clean_md and "| 文件级别 |" in clean_md)
)
if meta and not has_meta_line:
if clean_md.startswith("制定部门"):
i = clean_md.find("\n")
if i >= 0:
clean_md = clean_md[: i + 1] + meta + "\n" + clean_md[i + 1 :]
else:
clean_md = clean_md + "\n" + meta + "\n"
else:
clean_md = meta + "\n" + clean_md
clean_md = _promote_title_above_meta(clean_md)
clean_md = _promote_dept_header_near_top(clean_md)
trace_steps.append("edkb-clean")
chunks = []
if cfg.chunk.enable:
_announce("chunk")
t0 = time.perf_counter()
chunks = chunk.run(
{"source": file_path.name, "text": clean_md},
ctx,
max_chars=cfg.chunk.max_chars,
overlap_chars=cfg.chunk.overlap_chars,
add_heading_path_prefix=cfg.chunk.add_heading_path_prefix,
)
_mark("edkb-chunk", t0)
trace_steps.append("edkb-chunk")
t0 = time.perf_counter()
chunks = quality_gate.run(chunks, ctx)
_mark("edkb-quality-gate", t0)
trace_steps.append("edkb-quality-gate")
else:
ctx.warnings.append(
"chunk disabled by config: skip edkb-chunk/edkb-quality-gate"
)
trace_steps.append("edkb-chunk(skipped)")
trace_steps.append("edkb-quality-gate(skipped)")
source_rel_path = file_path.name
if source_root is not None:
try:
source_rel_path = str(file_path.relative_to(source_root))
except Exception:
source_rel_path = file_path.name
target_md_path = final_md_path
if target_md_path is None:
target_md_path = out_root / f"{file_path.stem}.md"
_announce("export")
t0 = time.perf_counter()
export.run(
{
"out_dir": str(out_dir),
"source_file": file_path.name,
"source_rel_path": source_rel_path,
"source_category": source_category or "",
"flat_md_path": str(target_md_path),
"clean_md": clean_md,
"chunks": chunks,
"blocks": blocks,
"flow_markdowns": flow_mds,
},
ctx,
)
_mark("edkb-export", t0)
trace_steps.append("edkb-export")
exported_clean_md = clean_md
exported_clean_path = out_dir / "03_clean.md"
if exported_clean_path.exists():
try:
exported_clean_md = exported_clean_path.read_text(encoding="utf-8")
except Exception:
exported_clean_md = clean_md
_announce("postcheck")
t0 = time.perf_counter()
check = postcheck.run({"out_dir": str(out_dir), "clean_md": exported_clean_md}, ctx)
_mark("edkb-postcheck", t0)
(out_dir / "postcheck.json").write_text(
json.dumps(check, ensure_ascii=False, indent=2), encoding="utf-8"
)
if check.get("status") != "pass":
failed = ", ".join(check.get("failed_required", []))
ctx.warnings.append(f"postcheck failed: {failed}")
if check.get("issue_count", 0) > 0:
issue_codes: list[str] = []
for it in check.get("issues", [])[:3]:
code = str(it.get("code", "")).strip()
if code and code not in issue_codes:
issue_codes.append(code)
if issue_codes:
ctx.warnings.append(
f"postcheck issues: {check.get('issue_count', 0)} ({', '.join(issue_codes)})"
)
else:
ctx.warnings.append(f"postcheck issues: {check.get('issue_count', 0)}")
trace_steps.append("edkb-postcheck")
(out_dir / "trace_pipeline.json").write_text(
json.dumps(
{
"file": file_path.name,
"recommended_pipeline": profile.recommended_pipeline,
"executed_steps": trace_steps,
"timings_ms": timings_ms,
"intake": ctx.extras.get("intake", {}),
},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
return {
"file": file_path.name,
"out_dir": str(out_dir),
"warnings": ctx.warnings,
"timings_ms": timings_ms,
}
def build_knowledge(
input_path: Path,
output_dir: Path,
config: SystemConfig,
temp_dir: Path,
skip_patterns: list[str] | None = None,
resume: bool = False,
prune_stale_output: bool = False,
) -> list[dict]:
removed_temp_files = _cleanup_input_temp_files(input_path)
if removed_temp_files:
for removed in removed_temp_files:
print(f"cleanup-temp: {removed}", flush=True)
files = discover(input_path)
output_dir.mkdir(parents=True, exist_ok=True)
temp_dir.mkdir(parents=True, exist_ok=True)
patterns = [p for p in (skip_patterns or []) if str(p).strip()]
for stale in [output_dir / "INDEX.md", output_dir / "POSTCHECK_ISSUES.md"]:
if stale.exists():
stale.unlink()
for lock_md in output_dir.glob("~$*.md"):
if lock_md.is_file():
lock_md.unlink()
if prune_stale_output:
expected_paths = {
(output_dir / _derive_output_rel_md(file, input_path)).resolve()
for file in files
}
_prune_stale_markdowns(output_dir, expected_paths)
source_root = input_path if input_path.is_dir() else input_path.parent
results: list[dict] = []
total = len(files)
for idx, file in enumerate(files, start=1):
flat_out = output_dir / f"{file.stem}.md"
mirror_out = output_dir / _derive_output_rel_md(file, input_path)
source_rel_path = file.name
try:
source_rel_path = _normalize_path_for_match(file.relative_to(source_root))
except Exception:
source_rel_path = _normalize_path_for_match(file)
matched_pattern = _matches_pattern(
[
_normalize_path_for_match(file),
source_rel_path,
file.name,
],
patterns,
)
if matched_pattern:
print(
f"[{idx}/{total}] skipped(pattern): {source_rel_path} ({matched_pattern})",
flush=True,
)
results.append(
{
"file": file.name,
"out_dir": str(output_dir / file.stem),
"warnings": [],
"status": "skipped",
"skip_reason": f"pattern:{matched_pattern}",
"elapsed_ms": 0,
}
)
continue
if resume and mirror_out.exists() and mirror_out.stat().st_size > 0:
print(f"[{idx}/{total}] skipped(resume): {source_rel_path}", flush=True)
results.append(
{
"file": file.name,
"out_dir": str(output_dir / file.stem),
"warnings": [],
"status": "skipped",
"skip_reason": "resume-existing-output",
"elapsed_ms": 0,
}
)
continue
print(f"[{idx}/{total}] processing: {file.name}", flush=True)
if flat_out.exists():
flat_out.unlink()
if mirror_out != flat_out and mirror_out.exists():
mirror_out.unlink()
started = time.perf_counter()
try:
source_category = _derive_source_category(file, input_path)
res = _run_one_with_timeout(
file,
output_dir,
temp_dir,
config,
source_root=source_root,
source_category=source_category,
final_md_path=mirror_out,
progress_label=f"[{idx}/{total}] {file.name}",
)
elapsed_ms = int((time.perf_counter() - started) * 1000)
res["status"] = "success"
res["elapsed_ms"] = elapsed_ms
results.append(res)
print(
f"[{idx}/{total}] success: {file.name} ({elapsed_ms / 1000:.3f}s)",
flush=True,
)
timings = res.get("timings_ms", {}) or {}
if timings:
top = sorted(timings.items(), key=lambda x: x[1], reverse=True)[:3]
top_text = ", ".join(
f"{_step_alias(k)}={v / 1000:.3f}s" for k, v in top
)
print(f"[{idx}/{total}] time: {top_text}", flush=True)
out_dir_str = str(res.get("out_dir", "")).strip()
doc_artifact_dir = Path(out_dir_str) if out_dir_str else None
if (
doc_artifact_dir is not None
and doc_artifact_dir.exists()
and doc_artifact_dir.parent == output_dir
):
shutil.rmtree(doc_artifact_dir)
except Exception as exc:
elapsed_ms = int((time.perf_counter() - started) * 1000)
detail = traceback.format_exc()
doc_artifact_dir = output_dir / file.stem
if doc_artifact_dir.exists():
shutil.rmtree(doc_artifact_dir)
if flat_out.exists():
flat_out.unlink()
if mirror_out.exists() and mirror_out != flat_out:
mirror_out.unlink()
results.append(
{
"file": file.name,
"out_dir": str(output_dir / file.stem),
"warnings": [str(exc)],
"status": "failed",
"elapsed_ms": elapsed_ms,
"error": str(exc),
"error_detail": detail,
}
)
print(
f"[{idx}/{total}] failed: {file.name} ({elapsed_ms / 1000:.3f}s)",
flush=True,
)
print(f"[{idx}/{total}] reason: {exc}", flush=True)
print(detail.rstrip(), flush=True)
return results
-22
View File
@@ -1,22 +0,0 @@
from __future__ import annotations
from pathlib import Path
SUPPORTED_EXTS = {".doc", ".docx", ".pdf", ".xls", ".xlsx", ".csv", ".ppt", ".pptx"}
def discover(path: Path) -> list[Path]:
if path.is_file():
if path.name.startswith("~$"):
return []
return [path] if path.suffix.lower() in SUPPORTED_EXTS else []
if not path.exists():
raise FileNotFoundError(path)
files = [
p
for p in path.rglob("*")
if p.is_file()
and not p.name.startswith("~$")
and p.suffix.lower() in SUPPORTED_EXTS
]
return sorted(files, key=lambda x: str(x))
-1
View File
@@ -1 +0,0 @@
"""Atomic skills for enterprise KB pipeline."""
-90
View File
@@ -1,90 +0,0 @@
from __future__ import annotations
import hashlib
import re
from edkb_system.contracts import Chunk, Context
HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$")
def _chunk_id(source: str, heading: str, index: int, text: str) -> str:
raw = f"{source}|{heading}|{index}|{text}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def run(
input_data: dict,
context: Context,
max_chars: int = 1200,
overlap_chars: int = 150,
add_heading_path_prefix: bool = True,
) -> list[Chunk]:
source = input_data["source"]
md = input_data["text"]
lines = md.splitlines()
stack: list[str] = []
sections: list[tuple[str, str]] = []
buf: list[str] = []
def heading() -> str:
return " > ".join(stack) if stack else "ROOT"
for ln in lines:
m = HEAD_RE.match(ln.strip())
if m:
if buf:
sections.append((heading(), "\n".join(buf).strip()))
buf = []
level = len(m.group(1))
text = m.group(2).strip()
while len(stack) >= level:
stack.pop()
stack.append(text)
else:
buf.append(ln)
if buf:
sections.append((heading(), "\n".join(buf).strip()))
out: list[Chunk] = []
idx = 0
for hp, body in sections:
paras = [p.strip() for p in body.split("\n\n") if p.strip()]
acc = ""
for p in paras:
cand = (acc + "\n\n" + p).strip() if acc else p
if len(cand) <= max_chars:
acc = cand
continue
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
overlap = txt[-overlap_chars:] if overlap_chars > 0 else ""
acc = (overlap + "\n\n" + p).strip()
else:
acc = p[:max_chars]
if acc:
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
out.append(
Chunk(
id=_chunk_id(source, hp, idx, txt),
heading_path=hp,
text=txt,
index=idx,
source=source,
)
)
idx += 1
return out
File diff suppressed because it is too large. Load diff
-244
View File
@@ -1,244 +0,0 @@
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import asdict
from pathlib import Path
from typing import Any
from edkb_system.contracts import Block
def hash_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def hash_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def _page_image_structured_lines(payload: str) -> list[str]:
tokens = [x.strip() for x in payload.split(";") if x.strip()]
if not tokens:
return []
cert_context_hits = 0
cert_context_pat = re.compile(
r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|"
r"检测报告|測試報告|材质证明|物性表",
re.IGNORECASE,
)
for tok in tokens:
if cert_context_pat.search(tok):
cert_context_hits += 1
if cert_context_hits < 2:
return []
def _find(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
if rx.search(tok):
return tok
return ""
def _find_match(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
m = rx.search(tok)
if m:
return m.group(0)
return ""
def _find_after(anchor_pat: str, value_pat: str = r".+") -> str:
anchor_rx = re.compile(anchor_pat, re.IGNORECASE)
value_rx = re.compile(value_pat, re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not anchor_rx.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if value_rx.search(cand) and not anchor_rx.search(cand):
return cand
return ""
def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]:
out: list[tuple[str, str]] = []
seen: set[str] = set()
for key, value in values:
v = value.strip()
if not v:
continue
marker = f"{key}:{v.lower()}"
if marker in seen:
continue
seen.add(marker)
out.append((key, v))
return out
certificate_no = ""
cert_anchor = re.compile(
r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE
)
cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not cert_anchor.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if re.search(r"fax|tel|date", cand, re.IGNORECASE):
continue
if cert_value.fullmatch(cand):
certificate_no = cand
break
if certificate_no:
break
if not certificate_no:
certificate_no = _find_match(
r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b"
) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b")
issue_date = _find(
r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}"
)
spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+")
product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find(
r"HDG[-A-Z0-9 ]*COIL"
)
customer = _find(r"CORPORATION|COMPANY|STEEL")
order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find(
r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*"
)
weight = ""
for idx, tok in enumerate(tokens):
if tok.lower() == "kg" and idx > 0:
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1])
weight = (m.group(0) if m else tokens[idx - 1]) + " kg"
break
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE)
if m:
weight = m.group(0)
break
tensile: list[tuple[str, str]] = []
for idx, tok in enumerate(tokens):
if tok in {"降伏", "抗拉", "硬度"}:
for cand in tokens[idx + 1 : idx + 4]:
if re.fullmatch(r"\d+(?:\.\d+)?", cand):
tensile.append((tok, cand))
break
fields = _uniq(
[
("证书编号", certificate_no),
("日期", issue_date),
("客户", customer),
("产品", product),
("规格", spec),
("订单/追踪号", order_no),
("重量", weight),
]
)
if not fields and not tensile:
return []
lines = ["## 识别整理版", ""]
for key, value in fields:
lines.append(f"- {key}:{value}")
if tensile:
if fields:
lines.append("")
lines.append("### 关键数值")
lines.append("")
lines.append("| 项目 | 数值 |")
lines.append("| --- | --- |")
for key, value in _uniq(tensile):
lines.append(f"| {key} | {value} |")
lines.extend(["", "## 原始识别结果", ""])
return lines
def blocks_to_plain_markdown(blocks: list[Block]) -> str:
def _ocr_payload(txt: str) -> str:
payload = txt
if payload.startswith("OCR_TEXT:"):
payload = payload[len("OCR_TEXT:") :].strip()
if not payload or payload == "<empty>":
return ""
payload = re.sub(r"(?m)^\s*-\s*", "", payload)
payload = ";".join(x.strip() for x in payload.splitlines() if x.strip())
return payload
ocr_by_image: dict[str, str] = {}
for b in blocks:
if b.type != "ocr_text" or not b.id.startswith("ocr-"):
continue
payload = _ocr_payload((b.text or "").strip())
if payload:
ocr_by_image[b.id[len("ocr-") :]] = payload
page_text_chars: dict[int, int] = {}
page_body_chars: dict[int, int] = {}
for b in blocks:
if b.type in {"ocr_text", "image"}:
continue
txt = (b.text or "").strip()
if not txt:
continue
page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt)
if b.type != "heading":
page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt)
lines: list[str] = []
image_idx = 0
for b in sorted(
[x for x in blocks if x.type != "ocr_text"],
key=lambda x: (x.page, x.cy(), x.cx()),
):
txt = (b.text or "").strip()
if not txt and b.type != "image":
continue
if b.type == "heading":
lines.append(f"## {txt}")
elif b.type == "image":
data_uri = b.meta.get("data_uri") if b.meta else None
if data_uri:
image_idx += 1
if b.meta and b.meta.get("page_image"):
lines.append(f"![page-image-{b.page}]({data_uri})")
else:
lines.append(f"![image-{image_idx}]({data_uri})")
ocr_text = ocr_by_image.get(b.id)
if ocr_text:
suppress_pptx_ocr = bool(
b.meta and b.meta.get("page_image_source") == "pptx"
) and (
page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
)
if (
b.meta
and b.meta.get("page_image")
and b.meta.get("page_image_source") != "pptx"
):
lines.extend(_page_image_structured_lines(ocr_text))
if not suppress_pptx_ocr:
lines.append(f"图中文字:{ocr_text}")
else:
lines.append("![image]")
else:
lines.append(txt)
return "\n\n".join(lines).strip() + "\n"
def dump_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
def block_to_dict(block: Block) -> dict[str, Any]:
return asdict(block)
-83
View File
@@ -1,83 +0,0 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from edkb_system.contracts import Context
from edkb_system.skills.word_bridge import convert_with_word
def _find_soffice() -> str | None:
candidates = [
os.environ.get("EDKB_SOFFICE"),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
for c in candidates:
if not c:
continue
if c == "soffice":
return c
if Path(c).exists():
return c
return None
def _convert_with_word(path: Path, out_dir: Path) -> Path:
output = out_dir / f"{path.stem}.pdf"
return convert_with_word(path.resolve(), output.resolve(), 17)
def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path:
output = out_dir / f"{path.stem}.pdf"
cmd = [
soffice,
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
stderr = (proc.stderr or "").strip() or "no stderr"
raise RuntimeError(
f"soffice conversion failed (code={proc.returncode}): {stderr}"
)
if not output.exists():
raise RuntimeError(f"soffice conversion produced no output: {output}")
return output
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
out_dir = work_dir / "flow_pdf"
out_dir.mkdir(parents=True, exist_ok=True)
errors: list[str] = []
if os.name == "nt":
try:
pdf = _convert_with_word(file_path, out_dir)
return {"pdf_path": str(pdf), "converter": "word"}
except Exception as exc:
errors.append(f"word: {exc}")
soffice = _find_soffice()
if soffice:
try:
pdf = _convert_with_soffice(file_path, out_dir, soffice)
return {"pdf_path": str(pdf), "converter": "soffice"}
except Exception as exc:
errors.append(f"soffice: {exc}")
else:
errors.append("soffice: not found")
context.warnings.append(
"doc->pdf conversion unavailable; fallback to docx text parser"
)
context.warnings.append("doc->pdf details: " + "; ".join(errors))
return {"pdf_path": None, "converter": None}
-567
View File
@@ -1,567 +0,0 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
import os
import re
import shutil
from dataclasses import asdict, replace
from pathlib import Path
from urllib.parse import quote, urlparse
from edkb_system.contracts import Block, Chunk, Context
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
_EMBEDDED_IMG_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_LOOSE_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_ANY_RE = re.compile(
r"!\[[^\]]*\]\(data:image/.*?\)",
re.IGNORECASE | re.DOTALL,
)
_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__"
_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__"
def _bool_env(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _sanitize_segment(raw: str) -> str:
s = (raw or "").strip()
if not s:
return "untitled"
s = re.sub(r"\s+", "_", s)
s = s.replace("/", "_").replace("\\", "_")
s = re.sub(r"[:*?\"<>|]", "_", s)
s = re.sub(r"_+", "_", s).strip("._")
return s or "untitled"
def _build_object_prefix(
source_category: str, source_rel_path: str, source_file: str
) -> str:
rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/")
parts = [p for p in rel.split("/") if p and p not in {".", ".."}]
category = _sanitize_segment(source_category)
if not category:
if len(parts) >= 2:
category = _sanitize_segment(parts[0])
else:
category = "uncategorized"
if parts and _sanitize_segment(parts[0]) == category:
parts = parts[1:]
if parts:
doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"]
else:
doc_parts = [Path(source_file or "document").stem or "document"]
normalized = [category] + [_sanitize_segment(p) for p in doc_parts]
normalized = [p for p in normalized if p]
return "/".join(normalized)
def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]:
endpoint = (raw_endpoint or "").strip()
secure_default = False
if "://" in endpoint:
parsed = urlparse(endpoint)
secure_default = parsed.scheme.lower() == "https"
endpoint = parsed.netloc or parsed.path
endpoint = endpoint.strip().rstrip("/")
return endpoint, secure_default
def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str:
base = (raw_base or "").strip().rstrip("/")
if not base:
scheme = "https" if secure else "http"
return f"{scheme}://{endpoint}".rstrip("/")
if "://" not in base:
scheme = "https" if secure else "http"
return f"{scheme}://{base}".rstrip("/")
return base.rstrip("/")
def _quote_object_name(object_name: str) -> str:
return "/".join(quote(seg, safe="") for seg in object_name.split("/"))
def _ext_from_blob(blob: bytes) -> str | None:
if blob.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if blob.startswith(b"\xff\xd8\xff"):
return "jpg"
if blob.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if blob.startswith(b"BM"):
return "bmp"
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
return "webp"
return None
def _normalize_ext(fmt: str, blob: bytes) -> str:
f = (fmt or "").lower().strip()
if f in {"jpeg", "jpg"}:
return "jpg"
if f in {"png", "gif", "bmp", "webp"}:
return f
guessed = _ext_from_blob(blob)
return guessed or "png"
def _content_type_for_ext(ext: str) -> str:
if ext == "jpg":
return "image/jpeg"
if ext == "png":
return "image/png"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
return "application/octet-stream"
def _is_valid_image_blob(blob: bytes) -> bool:
if len(blob) < 8:
return False
if _ext_from_blob(blob):
return True
# Unknown format fallback: keep only if not tiny garbage.
return len(blob) >= 64
class _MinioStorage:
def __init__(
self,
*,
endpoint: str,
bucket_name: str,
access_key: str,
secret_key: str,
secure: bool,
public_base: str,
) -> None:
import importlib
minio_mod = importlib.import_module("minio")
minio_ctor = getattr(minio_mod, "Minio")
self.bucket_name = bucket_name
self.public_base = public_base.rstrip("/")
self.client = minio_ctor(
endpoint,
access_key=access_key,
secret_key=secret_key,
secure=secure,
)
if not self.client.bucket_exists(bucket_name):
self.client.make_bucket(bucket_name)
def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None:
stream = io.BytesIO(blob)
self.client.put_object(
self.bucket_name,
object_name,
stream,
len(blob),
content_type=content_type,
)
def list_prefix(self, prefix: str) -> list[str]:
return [
obj.object_name
for obj in self.client.list_objects(
self.bucket_name,
prefix=prefix,
recursive=True,
)
]
def remove_object(self, object_name: str) -> None:
self.client.remove_object(self.bucket_name, object_name)
def build_url(self, object_name: str) -> str:
return (
f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}"
)
class _RemoteImageRewriter:
def __init__(
self,
*,
context: Context,
source_file: str,
source_rel_path: str,
source_category: str,
) -> None:
self.context = context
self.source_file = source_file
self.source_rel_path = source_rel_path
self.source_category = source_category
self.object_prefix = _build_object_prefix(
source_category, source_rel_path, source_file
)
self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False)
self.storage: _MinioStorage | None = None
self._storage_initialized = False
self.uri_cache: dict[str, str] = {}
self.sha_cache: dict[str, tuple[str, str]] = {}
self.referenced_objects: set[str] = set()
self.uploaded_count = 0
self.reused_count = 0
self.invalid_removed_count = 0
self.kept_embedded_count = 0
self.stale_removed_count = 0
self._upload_error_warn_count = 0
self._saw_embedded_image = False
self._next_image_index = 1
def _build_storage(self) -> _MinioStorage | None:
if not _bool_env("MINIO_UPLOAD_ENABLED", True):
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled by MINIO_UPLOAD_ENABLED"
)
return None
raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED")
endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
endpoint, secure_default = _normalize_endpoint(endpoint_raw)
secure = _bool_env("MINIO_SECURE", secure_default)
if not endpoint:
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled: MINIO_ENDPOINT is empty"
)
return None
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
public_base = _normalize_public_base(
os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure
)
try:
return _MinioStorage(
endpoint=endpoint,
bucket_name=bucket_name,
access_key=access_key,
secret_key=secret_key,
secure=secure,
public_base=public_base,
)
except Exception as exc:
if self.allow_embed_fallback:
self.context.warnings.append(
f"image-hosting unavailable, keep embedded image: {exc}"
)
return None
raise RuntimeError(f"image-hosting unavailable: {exc}")
def _warn_upload_error(self, msg: str) -> None:
if self._upload_error_warn_count < 5:
self.context.warnings.append(msg)
self._upload_error_warn_count += 1
def _ensure_storage(self) -> None:
if self._storage_initialized:
return
self.storage = self._build_storage()
self._storage_initialized = True
def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
fmt = (fmt or "png").lower()
b64_clean = re.sub(r"\s+", "", b64_raw)
try:
blob = base64.b64decode(b64_clean, validate=False)
except Exception:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
if not _is_valid_image_blob(blob):
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
self._ensure_storage()
if self.storage is None:
if not self.allow_embed_fallback:
raise RuntimeError(
"image-hosting unavailable: embedded fallback is disabled"
)
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
return _KEEP_IMAGE
sha = hashlib.sha256(blob).hexdigest()
cached_sha = self.sha_cache.get(sha)
if cached_sha is not None:
url, object_name = cached_sha
self.referenced_objects.add(object_name)
self.reused_count += 1
self.uri_cache[uri] = url
return url
ext = _normalize_ext(fmt, blob)
content_type = _content_type_for_ext(ext)
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
self._next_image_index += 1
object_name = (
f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name
)
try:
self.storage.put_bytes(object_name, blob, content_type)
url = self.storage.build_url(object_name)
self.sha_cache[sha] = (url, object_name)
self.referenced_objects.add(object_name)
self.uploaded_count += 1
self.uri_cache[uri] = url
return url
except Exception as exc:
if not self.allow_embed_fallback:
raise RuntimeError(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
) from exc
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
self._warn_upload_error(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
)
return _KEEP_IMAGE
def _process_match(self, m: re.Match[str]) -> str:
return self._process_embedded_uri(
m.group("uri"),
m.group("fmt") or "png",
m.group("b64") or "",
)
def _process_loose_uri(self, uri: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
head, sep, b64_raw = uri.partition(",")
if not sep:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
fmt = "png"
m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE)
if m:
fmt = (m.group("fmt") or "png").lower()
return self._process_embedded_uri(uri, fmt, b64_raw)
def replace_text(self, text: str) -> str:
if not text or "data:image/" not in text:
return text
self._saw_embedded_image = True
def repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_match(m)
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_RE.sub(repl, text)
if "data:image/" in out:
def loose_repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_loose_uri(m.group("uri") or "")
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out)
if not self.allow_embed_fallback and "data:image/" in out:
dropped_before = self.invalid_removed_count
out = _EMBEDDED_IMG_LOOSE_RE.sub("", out)
out = _EMBEDDED_IMG_ANY_RE.sub("", out)
removed = self.invalid_removed_count - dropped_before
if "data:image/" in out:
self.context.warnings.append(
"image-hosting left non-markdown data:image content; kept as-is"
)
else:
self.context.warnings.append(
"image-hosting removed unsupported embedded images"
+ (f": {removed}" if removed > 0 else "")
)
out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out)
return out
def finalize(self) -> None:
if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True):
self._ensure_storage()
if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True):
prefix = f"{self.object_prefix}/"
try:
for object_name in self.storage.list_prefix(prefix):
if object_name in self.referenced_objects:
continue
self.storage.remove_object(object_name)
self.stale_removed_count += 1
except Exception as exc:
self.context.warnings.append(
f"image-hosting cleanup failed ({self.source_file}): {exc}"
)
if self.invalid_removed_count > 0:
self.context.warnings.append(
f"image-hosting removed invalid images: {self.invalid_removed_count}"
)
if self.kept_embedded_count > 0 and self.storage is None:
self.context.warnings.append(
"image-hosting unavailable: keep legacy data:image embeds"
)
if (
self.uploaded_count > 0
or self.reused_count > 0
or self.stale_removed_count > 0
):
self.context.warnings.append(
"image-hosting synced "
f"(uploaded={self.uploaded_count}, reused={self.reused_count}, "
f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})"
)
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
out_dir.mkdir(parents=True, exist_ok=True)
source_file = input_data.get("source_file", "")
source_rel_path = input_data.get("source_rel_path", source_file)
source_category = input_data.get("source_category", "")
source_stem = Path(source_file).stem if source_file else out_dir.name
flat_clean_path = Path(
input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md")
)
view_clean_path = out_dir / "03_clean_view.md"
view_images_dir = out_dir / "images_view"
for p in [
out_dir / "01_raw_layout.json",
out_dir / "02_flow_procedure.md",
out_dir / "03_clean.md",
out_dir / "04_chunks.jsonl",
out_dir / "report.md",
view_clean_path,
flat_clean_path,
]:
if p.exists():
p.unlink()
chunks_dir = out_dir / "chunks"
if chunks_dir.exists():
shutil.rmtree(chunks_dir)
if view_images_dir.exists():
shutil.rmtree(view_images_dir)
clean_md: str = input_data.get("clean_md", "")
chunks: list[Chunk] = input_data.get("chunks", [])
blocks: list[Block] = input_data.get("blocks", [])
flow_markdowns: list[str] = input_data.get("flow_markdowns", [])
rewriter = _RemoteImageRewriter(
context=context,
source_file=source_file,
source_rel_path=source_rel_path,
source_category=source_category,
)
clean_md = rewriter.replace_text(clean_md)
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
rewriter.finalize()
_write(out_dir / "03_clean.md", clean_md)
_write(flat_clean_path, clean_md)
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
chunks_dir.mkdir(parents=True, exist_ok=True)
for c in exported_chunks:
_write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n")
if flow_markdowns:
_write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n")
_write(
out_dir / "01_raw_layout.json",
json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n",
)
report_lines = [
f"# Report: {input_data.get('source_file', '')}",
"",
f"- pages: {context.pages}",
f"- images: {context.images}",
f"- ocr_characters: {context.ocr_characters}",
f"- flows_detected: {context.flows_detected}",
f"- confidence: {context.confidence:.2f}",
"",
"## warnings",
]
if context.warnings:
report_lines.extend([f"- {w}" for w in context.warnings])
else:
report_lines.append("- none")
report_lines.extend(
[
"",
"## recommended_dify_settings",
"- Index: High Quality",
"- Retrieval: Hybrid",
"- Chunking: General",
"",
]
)
_write(out_dir / "report.md", "\n".join(report_lines))
return {"out_dir": str(out_dir)}
@@ -1,142 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
import networkx as nx
from edkb_system.contracts import Block, Context
@dataclass
class Node:
id: str
text: str
page: int
kind: str
bbox: tuple[float, float, float, float]
def _is_decision(text: str) -> bool:
kws = ["判定", "判断", "是否", "if", "check"]
s = text.lower()
return any(k in s for k in kws)
def _dist(a: Node, b: Node) -> float:
ax = (a.bbox[0] + a.bbox[2]) / 2.0
ay = (a.bbox[1] + a.bbox[3]) / 2.0
bx = (b.bbox[0] + b.bbox[2]) / 2.0
by = (b.bbox[1] + b.bbox[3]) / 2.0
return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
def run(input_data: list[Block], context: Context) -> dict:
blocks = [
b
for b in input_data
if b.type in {"textbox", "shape", "diamond", "arrow_label", "paragraph"}
and b.text.strip()
]
by_page: dict[int, list[Block]] = {}
for b in blocks:
by_page.setdefault(b.page, []).append(b)
page_markdowns: list[str] = []
debug: list[dict] = []
for page in sorted(by_page):
cands = by_page[page]
nodes: list[Node] = []
labels: list[Node] = []
for b in cands:
text = b.text.strip()
if b.type == "arrow_label" or text.upper() in {
"NG",
"OK",
"Y",
"N",
"YES",
"NO",
}:
labels.append(Node(b.id, text, b.page, "label", b.bbox))
continue
kind = "decision" if (_is_decision(text) or b.type == "diamond") else "step"
nodes.append(Node(b.id, text, b.page, kind, b.bbox))
nodes = sorted(
nodes,
key=lambda n: (
(n.bbox[1] + n.bbox[3]) / 2.0,
(n.bbox[0] + n.bbox[2]) / 2.0,
),
)
if not nodes:
continue
g = nx.DiGraph()
for n in nodes:
g.add_node(n.id, node=n)
for i, src in enumerate(nodes[:-1]):
dst = nodes[i + 1]
g.add_edge(src.id, dst.id, label=None)
for dec in [n for n in nodes if n.kind == "decision"]:
right_steps = [
n
for n in nodes
if ((n.bbox[0] + n.bbox[2]) / 2.0) > ((dec.bbox[0] + dec.bbox[2]) / 2.0)
]
if right_steps:
target = min(right_steps, key=lambda x: _dist(dec, x))
label_node = None
right_labels = [
l
for l in labels
if ((l.bbox[0] + l.bbox[2]) / 2.0)
> ((dec.bbox[0] + dec.bbox[2]) / 2.0)
]
if right_labels:
label_node = min(right_labels, key=lambda x: _dist(dec, x))
g.add_edge(
dec.id, target.id, label=(label_node.text if label_node else "分支")
)
ordered = nodes
idx_map = {n.id: i + 1 for i, n in enumerate(ordered)}
cycles = list(nx.simple_cycles(g))
cyc_nodes = {nid for cyc in cycles for nid in cyc}
lines = [f"## Page {page} Procedure"]
for n in ordered:
title = n.text
if n.kind == "decision" and not title.startswith("判定"):
title = f"判定:{title}"
lines.append(f"{idx_map[n.id]}. {title}")
if n.kind == "decision":
for _, dst, data in g.out_edges(n.id, data=True):
if data.get("label") is None:
continue
label = data.get("label") or "分支"
if dst in cyc_nodes:
lines.append(f"- {label} -> 返回到步骤{idx_map.get(dst, '?')}")
else:
dst_text = g.nodes[dst]["node"].text
lines.append(f"- {label} -> {dst_text}")
page_markdowns.append("\n".join(lines))
debug.append(
{
"page": page,
"nodes": [
{"id": n.id, "text": n.text, "kind": n.kind, "bbox": list(n.bbox)}
for n in nodes
],
"edges": [
{"src": s, "dst": d, "label": data.get("label")}
for s, d, data in g.edges(data=True)
],
}
)
context.flows_detected = len(page_markdowns)
return {"flow_markdowns": page_markdowns, "debug": debug}
-419
View File
@@ -1,419 +0,0 @@
from __future__ import annotations
import re
import zipfile
from pathlib import Path
from edkb_system.config import RouterConfig
from edkb_system.contracts import Context, DocumentProfile
_DOC_KIND_STRATEGY = {
"flow_procedure": {
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
"disable": set(),
},
"policy_text": {
"enable": set(),
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
},
"tabular_record": {
"enable": set(),
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
},
"mixed": {
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
"disable": set(),
},
}
def _keyword_score(name: str, keywords: dict[str, float]) -> float:
score = 0.0
for k, w in keywords.items():
if k in name:
score += w
return score
def _score_text_keywords(text: str, keywords: dict[str, float]) -> float:
score = 0.0
for k, w in keywords.items():
if k in text:
score += w
return score
def _has_flow_evidence(stem: str, content: dict) -> bool:
name = stem.lower()
strong_name_hit = any(
k in name for k in ["流程", "流程图", "判定", "作业标准", "检验作业"]
)
flow_hits = int(content.get("flow_hits", 0) or 0)
shape_hits = int(content.get("shape_hits", 0) or 0)
if flow_hits >= 6:
return True
if flow_hits >= 3 and shape_hits >= 1:
return True
return strong_name_hit
def _probe_docx_xml(path: Path) -> dict:
signals = {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
try:
with zipfile.ZipFile(path) as zf:
xml_parts = [
n for n in zf.namelist() if n.startswith("word/") and n.endswith(".xml")
]
xml_blob = ""
for n in xml_parts[:12]:
try:
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
except Exception:
continue
except Exception:
return signals
if not xml_blob:
return signals
text = xml_blob.lower()
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
signals["table_hits"] = text.count("<w:tbl")
signals["image_hits"] = text.count("<a:blip") + text.count("<v:imagedata")
signals["shape_hits"] = (
text.count("<w:drawing") + text.count("<v:shape") + text.count("<wps:wsp")
)
flow_kw = {
"流程": 0.3,
"流程图": 0.4,
"判定": 0.25,
"检验": 0.2,
"作业": 0.15,
}
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
return signals
def _probe_pdf(path: Path) -> dict:
signals = {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
try:
blob = path.read_bytes()[: 2 * 1024 * 1024]
except Exception:
return signals
text = blob.decode("latin-1", errors="ignore")
signals["image_hits"] = text.count("/Subtype /Image") + text.count("/Image")
text_ops = text.count(" BT") + text.count(" ET")
signals["has_text"] = text_ops >= 10
return signals
def _probe_pptx(path: Path) -> dict:
signals = {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
try:
with zipfile.ZipFile(path) as zf:
xml_parts = [
n
for n in zf.namelist()
if n.startswith("ppt/slides/") and n.endswith(".xml")
]
xml_blob = ""
for n in xml_parts[:20]:
try:
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
except Exception:
continue
except Exception:
return signals
if not xml_blob:
return signals
text = xml_blob.lower()
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
signals["table_hits"] = text.count("<a:tbl")
signals["image_hits"] = text.count("<a:blip")
signals["shape_hits"] = text.count("<p:sp") + text.count("<p:cxnsp")
flow_kw = {"流程": 0.4, "流程图": 0.5, "送样": 0.3, "承认": 0.3, "判定": 0.25}
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
return signals
def _probe_content(file_path: Path, ext: str) -> dict:
if ext == ".docx":
return _probe_docx_xml(file_path)
if ext == ".doc":
cache_docx = file_path.parents[1] / "cache" / f"{file_path.stem}.docx"
if cache_docx.exists():
return _probe_docx_xml(cache_docx)
return {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
if ext == ".pdf":
return _probe_pdf(file_path)
if ext == ".pptx":
return _probe_pptx(file_path)
if ext == ".ppt":
cache_pptx = file_path.parents[1] / "cache" / f"{file_path.stem}.pptx"
if cache_pptx.exists():
return _probe_pptx(cache_pptx)
return {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
if ext in {".xls", ".xlsx", ".csv"}:
return {
"has_text": True,
"table_hits": 8,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
return {
"has_text": False,
"table_hits": 0,
"flow_hits": 0,
"image_hits": 0,
"shape_hits": 0,
}
def _build_pipeline(
ext: str,
doc_kind: str,
scan_likelihood: float,
cfg: RouterConfig,
) -> list[str]:
strategy = _DOC_KIND_STRATEGY.get(doc_kind, _DOC_KIND_STRATEGY["mixed"])
enable = set(strategy["enable"])
disable = set(strategy["disable"])
pipeline: list[str] = []
if ext in {".doc", ".docx"}:
pipeline.append("edkb-loader-docx")
if "edkb-doc-to-pdf" in enable and "edkb-doc-to-pdf" not in disable:
pipeline.append("edkb-doc-to-pdf")
elif ext == ".pdf":
pipeline.append("edkb-loader-pdf")
elif ext in {".ppt", ".pptx"}:
pipeline.append("edkb-loader-pptx")
elif ext in {".xls", ".xlsx"}:
pipeline.extend(["edkb-loader-excel", "edkb-table-linearize"])
elif ext == ".csv":
pipeline.extend(["edkb-loader-csv", "edkb-table-linearize"])
if ext in {".doc", ".docx", ".pdf", ".ppt", ".pptx"}:
if scan_likelihood >= cfg.scan_likelihood_threshold:
pipeline.append("edkb-ocr")
if "edkb-flow-reconstruct" in enable and "edkb-flow-reconstruct" not in disable:
pipeline.append("edkb-flow-reconstruct")
pipeline.extend(
[
"edkb-clean",
"edkb-chunk",
"edkb-quality-gate",
"edkb-export",
"edkb-postcheck",
]
)
return pipeline
def _decide_doc_kind(
stem: str, ext: str, content: dict
) -> tuple[str, float, float, float, list[str]]:
s = stem.lower()
reasons: list[str] = []
flow_pos = {
"流程图": 0.5,
"作业流程": 0.45,
"流程": 0.25,
"检验": 0.25,
"作业标准": 0.35,
"sop": 0.35,
"判定": 0.2,
"oqc": 0.2,
"iqc": 0.2,
}
flow_neg = {
"管理办法": 0.35,
"制度": 0.3,
"守则": 0.3,
"规定": 0.25,
"手册": 0.2,
}
table_pos = {
"台账": 0.45,
"清单": 0.35,
"记录": 0.25,
"表单": 0.4,
"excel": 0.4,
}
flow_raw = 0.35 + _keyword_score(s, flow_pos) - _keyword_score(s, flow_neg)
table_raw = 0.15 + _keyword_score(s, table_pos)
if ext in {".xls", ".xlsx", ".csv"}:
table_raw += 0.55
if ext == ".pdf":
flow_raw += 0.05
if ext in {".ppt", ".pptx"}:
flow_raw += 0.1
flow_raw += min(0.45, 0.04 * content.get("flow_hits", 0))
flow_raw += min(0.25, 0.02 * content.get("shape_hits", 0))
table_raw += min(0.55, 0.08 * content.get("table_hits", 0))
if content.get("image_hits", 0) >= 2 and ext in {
".doc",
".docx",
".pdf",
".ppt",
".pptx",
}:
flow_raw += 0.05
flow_likelihood = max(0.05, min(0.95, flow_raw))
table_likelihood = max(0.05, min(0.95, table_raw))
text_density = 0.55
flow_evidence = _has_flow_evidence(stem, content)
if not flow_evidence:
flow_likelihood = min(flow_likelihood, 0.59)
if content.get("table_hits", 0) >= 1:
table_likelihood = max(table_likelihood, 0.65)
if (
flow_evidence
and flow_likelihood >= 0.65
and (table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1)
):
doc_kind = "mixed"
reasons.append("content indicates mixed flow+table document")
elif table_likelihood >= 0.75 and (flow_likelihood < 0.6 or not flow_evidence):
doc_kind = "tabular_record"
reasons.append("content indicates table-like document")
elif not flow_evidence and (
table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1
):
doc_kind = "tabular_record"
reasons.append("content indicates text+table document without flow")
elif flow_evidence and flow_likelihood >= 0.65:
doc_kind = "flow_procedure"
reasons.append("content indicates flow/procedure document")
elif flow_likelihood <= 0.35 or not flow_evidence:
doc_kind = "policy_text"
reasons.append("content indicates policy/management text")
else:
doc_kind = "mixed"
reasons.append("content indicates mixed document")
return doc_kind, flow_likelihood, table_likelihood, text_density, reasons
def _derive_content_modes(
ext: str,
stem: str,
content: dict,
flow_likelihood: float,
table_likelihood: float,
) -> list[str]:
modes: set[str] = set()
if content.get("has_text") or ext in {
".doc",
".docx",
".pdf",
".ppt",
".pptx",
".xls",
".xlsx",
".csv",
}:
modes.add("text")
if content.get("image_hits", 0) > 0:
modes.add("image")
if table_likelihood >= 0.65 or content.get("table_hits", 0) >= 1:
modes.add("table")
if _has_flow_evidence(stem, content) and flow_likelihood >= 0.6:
modes.add("flow")
return sorted(modes)
def run(input_data: dict, context: Context, cfg: RouterConfig) -> DocumentProfile:
file_path = Path(input_data["file_path"])
ext = file_path.suffix.lower()
file_type = ext.lstrip(".")
size = file_path.stat().st_size if file_path.exists() else 0
has_tables = ext in {".xls", ".xlsx", ".csv"}
content_signals = _probe_content(file_path, ext)
doc_kind, flow_likelihood, table_likelihood, text_density, reasons = (
_decide_doc_kind(file_path.stem, ext, content_signals)
)
content_modes = _derive_content_modes(
ext, file_path.stem, content_signals, flow_likelihood, table_likelihood
)
scan_likelihood = 0.2
if ext == ".pdf" and size > 3 * 1024 * 1024:
scan_likelihood = 0.65
has_images = ext in {".pdf", ".doc", ".docx", ".ppt", ".pptx"}
pipeline = _build_pipeline(ext, doc_kind, scan_likelihood, cfg)
context.file_type = file_type
context.extras["intake"] = {
"doc_kind": doc_kind,
"content_modes": content_modes,
"route_reasons": reasons,
"strategy": {
"enable": sorted(_DOC_KIND_STRATEGY.get(doc_kind, {}).get("enable", set())),
"disable": sorted(
_DOC_KIND_STRATEGY.get(doc_kind, {}).get("disable", set())
),
},
"content_signals": content_signals,
"flow_likelihood": round(flow_likelihood, 3),
"table_likelihood": round(table_likelihood, 3),
"scan_likelihood": round(scan_likelihood, 3),
"pipeline": pipeline,
}
return DocumentProfile(
file_type=file_type,
text_density=text_density,
has_images=has_images,
has_tables=has_tables,
flow_likelihood=flow_likelihood,
scan_likelihood=scan_likelihood,
table_likelihood=table_likelihood,
language_hint="zh",
recommended_pipeline=pipeline,
)
-39
View File
@@ -1,39 +0,0 @@
from __future__ import annotations
import csv
from pathlib import Path
from edkb_system.contracts import Context
def run(input_data: dict, context: Context) -> dict:
file_path = Path(input_data["file_path"])
raw = None
for enc in ("utf-8-sig", "utf-8", "gb18030"):
try:
raw = file_path.read_text(encoding=enc)
break
except UnicodeDecodeError:
continue
if raw is None:
raw = file_path.read_text(errors="ignore")
sample = raw[:4096]
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
delim = dialect.delimiter
except Exception:
delim = ","
rows = [
r
for r in csv.reader(raw.splitlines(), delimiter=delim)
if any(c.strip() for c in r)
]
table = {
"sheet": "csv",
"headers": rows[0] if rows else [],
"rows": rows[1:] if len(rows) > 1 else [],
}
context.extras["tables_count"] = 1
return table
File diff suppressed because it is too large. Load diff
@@ -1,89 +0,0 @@
from __future__ import annotations
import os
import subprocess
from pathlib import Path
from openpyxl import load_workbook
from edkb_system.contracts import Context
def _soffice_candidates() -> list[str]:
return [
os.environ.get("EDKB_SOFFICE", "").strip(),
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"soffice",
]
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
output = out_dir / f"{path.stem}.xlsx"
errors: list[str] = []
for soffice in _soffice_candidates():
if not soffice:
continue
cmd = [
soffice,
"--headless",
"--convert-to",
"xlsx",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
errors.append(f"soffice not found: {soffice}")
continue
if proc.returncode == 0 and output.exists():
return output
stderr = (proc.stderr or "").strip()
errors.append(
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
)
joined = "; ".join(errors) if errors else "no converter attempted"
raise RuntimeError(
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。"
f" details: {joined}"
)
def _norm(v) -> str:
return "" if v is None else str(v).strip()
def _trim_trailing_empty(vals: list[str]) -> list[str]:
end = len(vals)
while end > 0 and not vals[end - 1]:
end -= 1
return vals[:end]
def run(input_data: dict, context: Context) -> list[dict]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".xls":
file_path = _convert_xls_to_xlsx(file_path, work_dir)
wb = load_workbook(str(file_path), data_only=True)
tables: list[dict] = []
for ws in wb.worksheets:
rows: list[list[str]] = []
for row in ws.iter_rows(values_only=True):
vals = _trim_trailing_empty([_norm(v) for v in row])
if any(vals):
rows.append(vals)
if not rows:
continue
width = max(len(r) for r in rows)
normalized = [r + [""] * (width - len(r)) for r in rows]
tables.append(
{"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]}
)
context.extras["tables_count"] = len(tables)
return tables
-250
View File
@@ -1,250 +0,0 @@
from __future__ import annotations
import base64
import io
from pathlib import Path
from edkb_system.contracts import Block, Context
def _is_scanned(text_chars: int, pages: int) -> bool:
return text_chars < int(300 * max(pages, 1) / 10)
def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
b64 = base64.b64encode(blob).decode("ascii")
return f"data:{content_type};base64,{b64}"
def _normalize_box(
bounds: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
x0, y0, x1, y1 = bounds
left = min(x0, x1)
right = max(x0, x1)
top = min(y0, y1)
bottom = max(y0, y1)
return (left, top, right, bottom)
def _page_image_stats(
page_width: float,
page_height: float,
image_boxes: list[tuple[float, float, float, float]],
) -> dict[str, float]:
if page_width <= 0 or page_height <= 0 or not image_boxes:
return {
"count": float(len(image_boxes)),
"largest_ratio": 0.0,
"total_ratio": 0.0,
}
page_area = max(page_width * page_height, 1.0)
largest_ratio = 0.0
total_ratio = 0.0
for raw in image_boxes:
x0, y0, x1, y1 = _normalize_box(raw)
width = max(x1 - x0, 0.0)
height = max(y1 - y0, 0.0)
ratio = min((width * height) / page_area, 1.0)
largest_ratio = max(largest_ratio, ratio)
total_ratio += ratio
return {
"count": float(len(image_boxes)),
"largest_ratio": largest_ratio,
"total_ratio": min(total_ratio, 1.5),
}
def _should_use_page_image_mode(
*,
scan_likely: bool,
text_chars: int,
image_count: int,
largest_ratio: float,
total_ratio: float,
) -> bool:
if scan_likely:
if image_count == 0:
return True
if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3:
return True
if text_chars <= 120 and (
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
):
return True
return False
def _collect_image_boxes(
file_path: Path, page_count: int
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
except Exception:
return {}
out: dict[int, list[tuple[float, float, float, float]]] = {}
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
for page_idx in range(page_count):
page = doc[page_idx]
boxes: list[tuple[float, float, float, float]] = []
try:
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
try:
bounds = obj.get_bounds()
except Exception:
bounds = obj.get_pos()
boxes.append(tuple(float(v) for v in bounds))
except Exception:
boxes = []
out[page_idx + 1] = boxes
except Exception:
return {}
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
return out
def _render_page_png(
file_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def run(input_data: dict, context: Context) -> list[Block]:
file_path = Path(input_data["file_path"])
blocks: list[Block] = []
try:
from pypdf import PdfReader
reader = PdfReader(str(file_path))
context.pages = len(reader.pages)
text_chars = 0
page_payloads: list[dict] = []
for page_idx, p in enumerate(reader.pages, start=1):
text = (p.extract_text() or "").strip()
images: list[dict] = []
if text:
text_chars += len(text)
try:
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
data = getattr(img, "data", None)
if not data:
continue
ext = (getattr(img, "image_format", "") or "").lower()
ct = f"image/{ext}" if ext else "image/png"
images.append({"id": img_idx, "data": data, "content_type": ct})
except Exception:
pass
page_payloads.append({"page": page_idx, "text": text, "images": images})
scan_likely = _is_scanned(text_chars, context.pages)
image_boxes_by_page = _collect_image_boxes(file_path, context.pages)
page_image_mode_pages: list[int] = []
for payload in page_payloads:
page_idx = int(payload["page"])
text = str(payload["text"] or "")
page_images = list(payload["images"])
image_boxes = image_boxes_by_page.get(page_idx, [])
stats = _page_image_stats(1000.0, 1000.0, image_boxes)
use_page_image_mode = _should_use_page_image_mode(
scan_likely=scan_likely,
text_chars=len(text),
image_count=len(page_images) or int(stats["count"]),
largest_ratio=float(stats["largest_ratio"]),
total_ratio=float(stats["total_ratio"]),
)
if text:
blocks.append(
Block(
id=f"pdf-{page_idx}",
page=page_idx,
type="paragraph",
text=text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
)
)
if use_page_image_mode:
rendered = _render_page_png(file_path, page_idx)
if rendered:
blocks.append(
Block(
id=f"pdf-page-{page_idx}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"page_image": True,
},
)
)
context.images += 1
page_image_mode_pages.append(page_idx)
continue
for item in page_images:
blocks.append(
Block(
id=f"pdf-{page_idx}-img-{item['id']}",
page=page_idx,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(
item["data"], str(item["content_type"])
)
},
)
)
context.images += 1
if scan_likely:
context.warnings.append("pdf likely scanned; OCR recommended")
context.extras["scan_likely"] = True
if page_image_mode_pages:
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
context.warnings.append(
"pdf page-image mode pages: "
+ ", ".join(str(x) for x in page_image_mode_pages)
)
except Exception as exc:
context.warnings.append(f"PDF parse failed: {exc}")
return blocks
-478
View File
@@ -1,478 +0,0 @@
from __future__ import annotations
import base64
import hashlib
import io
import re
import subprocess
from pathlib import Path
from edkb_system.contracts import Block, Context
def _to_data_uri(blob: bytes, content_type: str) -> str:
return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}"
def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pptx",
str(path),
"--outdir",
str(out_dir),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
if proc.returncode != 0:
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
output = out_dir / f"{path.stem}.pptx"
if not output.exists():
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
return output
def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None:
out_dir.mkdir(parents=True, exist_ok=True)
cmd = [
"soffice",
"--headless",
"--convert-to",
"pdf",
str(path),
"--outdir",
str(out_dir),
]
try:
proc = subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
return None
if proc.returncode != 0:
return None
output = out_dir / f"{path.stem}.pdf"
return output if output.exists() else None
def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]:
out_dir.mkdir(parents=True, exist_ok=True)
app = None
pres = None
output: dict[int, bytes] = {}
try:
from win32com.client import DispatchEx
app = DispatchEx("PowerPoint.Application")
pres = app.Presentations.Open(str(path), WithWindow=False)
for idx, slide in enumerate(pres.Slides, start=1):
target = out_dir / f"slide_{idx:03d}.png"
slide.Export(str(target), "PNG")
if target.exists():
output[idx] = target.read_bytes()
except Exception:
return {}
finally:
if pres is not None:
try:
pres.Close()
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
return output
def _norm_text(text: str) -> str:
return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip()
def _shape_bbox(shape) -> tuple[float, float, float, float]:
left = float(getattr(shape, "left", 0))
top = float(getattr(shape, "top", 0))
width = float(getattr(shape, "width", 0))
height = float(getattr(shape, "height", 0))
return (left, top, left + width, top + height)
def _image_pixel_size(blob: bytes) -> tuple[int, int]:
try:
from PIL import Image
with Image.open(io.BytesIO(blob)) as im:
return int(im.width), int(im.height)
except Exception:
return (0, 0)
def _is_small_decorative_image(
blob: bytes, bbox: tuple[float, float, float, float], slide_area: float
) -> bool:
width_px, height_px = _image_pixel_size(blob)
pixel_area = max(width_px, 0) * max(height_px, 0)
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
if (
width_px
and height_px
and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400)
):
return True
if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000:
return True
return False
def _is_dominant_picture(
bbox: tuple[float, float, float, float], slide_area: float
) -> bool:
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
if slide_area <= 0:
return False
return box_area / slide_area >= 0.45
def _table_to_markdown(table) -> str:
rows: list[list[str]] = []
for row in table.rows:
vals = [
" ".join(
p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip()
)
for cell in row.cells
]
vals = [v.strip() for v in vals]
if any(vals):
rows.append(vals)
if not rows:
return ""
width = max(len(r) for r in rows)
norm = [r + [""] * (width - len(r)) for r in rows]
header = norm[0]
body = norm[1:]
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
lines.extend("| " + " | ".join(r) + " |" for r in body)
return "\n".join(lines)
def _render_pdf_page_png(
pdf_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
try:
import pypdfium2 as pdfium
except Exception:
return None
doc = None
try:
doc = pdfium.PdfDocument(str(pdf_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
finally:
try:
if doc is not None:
doc.close()
except Exception:
pass
def _crop_rendered_region(
rendered: bytes,
*,
crop_bbox: tuple[float, float, float, float],
slide_width: float,
slide_height: float,
padding: float = 0.03,
) -> bytes | None:
try:
from PIL import Image
with Image.open(io.BytesIO(rendered)) as im:
x0, y0, x1, y1 = crop_bbox
pad_x = slide_width * padding
pad_y = slide_height * padding
x0 = max(0.0, x0 - pad_x)
y0 = max(0.0, y0 - pad_y)
x1 = min(slide_width, x1 + pad_x)
y1 = min(slide_height, y1 + pad_y)
if x1 <= x0 or y1 <= y0:
return None
scale_x = im.width / max(slide_width, 1.0)
scale_y = im.height / max(slide_height, 1.0)
box = (
int(x0 * scale_x),
int(y0 * scale_y),
int(x1 * scale_x),
int(y1 * scale_y),
)
cropped = im.crop(box)
buf = io.BytesIO()
cropped.save(buf, format="PNG")
return buf.getvalue()
except Exception:
return None
def _union_bboxes(
boxes: list[tuple[float, float, float, float]],
) -> tuple[float, float, float, float] | None:
if not boxes:
return None
x0 = min(b[0] for b in boxes)
y0 = min(b[1] for b in boxes)
x1 = max(b[2] for b in boxes)
y1 = max(b[3] for b in boxes)
return (x0, y0, x1, y1)
def _bbox_overlap_ratio(
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
) -> float:
ax0, ay0, ax1, ay1 = a
bx0, by0, bx1, by1 = b
ix0 = max(ax0, bx0)
iy0 = max(ay0, by0)
ix1 = min(ax1, bx1)
iy1 = min(ay1, by1)
if ix1 <= ix0 or iy1 <= iy0:
return 0.0
inter = (ix1 - ix0) * (iy1 - iy0)
area = max((ax1 - ax0) * (ay1 - ay0), 1.0)
return inter / area
def _pick_slide_title(flat_shapes) -> str:
candidates: list[tuple[float, float, str]] = []
for shape in flat_shapes:
if not getattr(shape, "has_text_frame", False):
continue
txt = _norm_text(getattr(shape, "text", ""))
if not txt:
continue
top = float(getattr(shape, "top", 0))
left = float(getattr(shape, "left", 0))
candidates.append((top, left, txt))
if not candidates:
return ""
candidates.sort(key=lambda x: (x[0], x[1]))
preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})")
for top, left, txt in candidates[:6]:
first_line = txt.splitlines()[0].strip()
if preferred_pat.match(first_line) and top <= 1200000:
return first_line
for top, left, txt in candidates[:6]:
first_line = txt.splitlines()[0].strip()
if 2 <= len(first_line) <= 30 and top <= 1800000:
return first_line
return candidates[0][2].splitlines()[0].strip()
def _iter_shapes(shapes):
from pptx.enum.shapes import MSO_SHAPE_TYPE
for shape in shapes:
yield shape
if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP:
for child in _iter_shapes(shape.shapes):
yield child
def run(input_data: dict, context: Context) -> list[Block]:
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".ppt":
file_path = _convert_ppt_to_pptx(file_path, work_dir)
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
prs = Presentation(str(file_path))
slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides")
pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir)
context.pages = len(prs.slides)
blocks: list[Block] = []
img_idx = 0
blk_idx = 0
slide_area = float(prs.slide_width) * float(prs.slide_height)
for slide_no, slide in enumerate(prs.slides, start=1):
flat_shapes = list(_iter_shapes(slide.shapes))
title_text = _norm_text(
getattr(getattr(slide.shapes, "title", None), "text", "")
)
if not title_text:
title_text = _pick_slide_title(flat_shapes)
heading_text = f"第{slide_no}页"
if title_text:
heading_text = f"第{slide_no}页 {title_text}"
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-heading-{blk_idx}",
page=slide_no,
type="heading",
text=heading_text,
bbox=(0.0, 0.0, 0.0, 0.0),
)
)
seen_image_hashes: set[str] = set()
dominant_pictures = 0
shape_heavy = 0
flow_boxes: list[tuple[float, float, float, float]] = []
suppress_all_images = title_text == "目录"
for shape in flat_shapes:
try:
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
image = shape.image
bbox = _shape_bbox(shape)
blob_hash = hashlib.sha1(image.blob).hexdigest()
if blob_hash in seen_image_hashes:
continue
seen_image_hashes.add(blob_hash)
if _is_small_decorative_image(image.blob, bbox, slide_area):
continue
if _is_dominant_picture(bbox, slide_area):
dominant_pictures += 1
elif shape.shape_type in {
MSO_SHAPE_TYPE.AUTO_SHAPE,
MSO_SHAPE_TYPE.LINE,
MSO_SHAPE_TYPE.FREEFORM,
}:
shape_heavy += 1
bbox = _shape_bbox(shape)
mid_x = (bbox[0] + bbox[2]) / 2.0
if (
bbox[2] > bbox[0]
and bbox[3] > bbox[1]
and mid_x >= float(prs.slide_width) * 0.18
):
flow_boxes.append(bbox)
except Exception as exc:
context.warnings.append(f"pptx picture skipped: {exc}")
seen_image_hashes.clear()
render_flow_focus = (
(not suppress_all_images)
and bool(slide_pngs or pdf_path)
and shape_heavy >= 8
and dominant_pictures == 0
)
flow_crop: tuple[float, float, float, float] | None = None
if render_flow_focus:
rendered = slide_pngs.get(slide_no)
if rendered is None and pdf_path is not None:
rendered = _render_pdf_page_png(pdf_path, slide_no)
if rendered:
flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height))
img_idx += 1
blocks.append(
Block(
id=f"pptx-flow-{slide_no}-{img_idx}",
page=slide_no,
type="image",
text="",
bbox=flow_crop,
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"flow_focus": True,
"flow_focus_source": "pptx",
"rendered_slide": True,
},
)
)
for shape in flat_shapes:
try:
if getattr(shape, "has_table", False):
table_md = _table_to_markdown(shape.table)
if table_md:
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-table-{blk_idx}",
page=slide_no,
type="table",
text=table_md,
bbox=_shape_bbox(shape),
)
)
continue
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
if render_flow_focus or suppress_all_images:
continue
is_dominant = False
image = shape.image
bbox = _shape_bbox(shape)
blob_hash = hashlib.sha1(image.blob).hexdigest()
if blob_hash in seen_image_hashes:
continue
seen_image_hashes.add(blob_hash)
if _is_small_decorative_image(image.blob, bbox, slide_area):
continue
is_dominant = _is_dominant_picture(bbox, slide_area)
img_idx += 1
ext = (getattr(image, "ext", "png") or "png").lower()
ct = f"image/{'jpeg' if ext == 'jpg' else ext}"
meta: dict[str, object] = {
"data_uri": _to_data_uri(image.blob, ct),
"blob_sha1": blob_hash,
}
if is_dominant:
meta["page_image"] = True
meta["page_image_source"] = "pptx"
blocks.append(
Block(
id=f"pptx-img-{slide_no}-{img_idx}",
page=slide_no,
type="image",
text="",
bbox=bbox,
meta=meta,
)
)
continue
if getattr(shape, "has_text_frame", False):
txt = _norm_text(shape.text)
bbox = _shape_bbox(shape)
if not txt or txt == title_text:
continue
if title_text and txt.startswith(title_text):
txt = txt[len(title_text) :].lstrip("\n ::;;,,")
txt = _norm_text(txt)
if not txt:
continue
if re.fullmatch(r"\d+", txt):
continue
if flow_crop is not None and len(txt) <= 28:
continue
if txt and txt != title_text:
blk_idx += 1
blocks.append(
Block(
id=f"pptx-{slide_no}-text-{blk_idx}",
page=slide_no,
type="paragraph",
text=txt,
bbox=bbox,
)
)
except Exception as exc:
context.warnings.append(f"pptx shape skipped: {exc}")
context.extras["slides_count"] = len(prs.slides)
return blocks
-97
View File
@@ -1,97 +0,0 @@
from __future__ import annotations
import base64
import io
import re
from edkb_system.contracts import Block, Context
def _decode_data_uri_image(data_uri: str):
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
if not m:
return None
try:
raw = base64.b64decode(m.group(1), validate=False)
except Exception:
return None
try:
import numpy as np
from PIL import Image
with Image.open(io.BytesIO(raw)) as im:
return np.array(im.convert("RGB"))
except Exception:
return None
def run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
blocks = input_data
try:
from rapidocr_onnxruntime import RapidOCR # type: ignore
except Exception:
context.warnings.append("RapidOCR unavailable; skip OCR")
return blocks
engine = RapidOCR()
out: list[Block] = []
for b in blocks:
out.append(b)
if b.type != "image":
continue
context.images += 1
image_obj = b.meta.get("image")
if image_obj is None and b.meta and b.meta.get("data_uri"):
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
if image_obj is None:
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
continue
try:
result, _ = engine(image_obj)
lines = []
for it in result or []:
if len(it) < 3:
continue
txt = str(it[1]).strip()
conf = float(it[2])
if txt and conf >= min_confidence:
lines.append(txt)
if lines:
text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines)
context.ocr_characters += sum(len(x) for x in lines)
else:
text = "OCR_TEXT: <empty>"
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text=text,
bbox=b.bbox,
)
)
except Exception as exc:
context.warnings.append(f"OCR failed: {exc}")
out.append(
Block(
id=f"ocr-{b.id}",
page=b.page,
type="ocr_text",
text="OCR_TEXT: <empty>",
bbox=b.bbox,
)
)
return out
-192
View File
@@ -1,192 +0,0 @@
from __future__ import annotations
import json
import re
from pathlib import Path
from edkb_system.contracts import Context
def _has_doc_meta(text: str) -> bool:
flat = " ".join(text.split())
has_header = bool(
re.search(r"制定部门.+制/修订日期.+页码", flat)
or re.search(r"Created Dept\..+Date.+Page", flat)
)
has_meta = bool(
re.search(r"文件编号.+文件级别.+版本", flat)
or re.search(r"Doc\.\s*No\..+File\s*Level.+Rev\.?", flat)
)
return has_header or has_meta
def _expect_doc_meta(text: str) -> bool:
keys = ["文件编号", "文件级别", "制/修订日期", "制定部门", "页码"]
return any(k in text for k in keys)
def _expect_flow_artifacts(text: str) -> bool:
if "作业流程图" not in text:
return False
hints = ["序号", "流程说明", "责任", "相关记录"]
return sum(1 for h in hints if h in text) >= 2
def _expect_related_forms_table(text: str) -> bool:
if "相关表单" not in text:
return False
return ("表单编号" in text) or bool(re.search(r"PB-\d{2,}", text))
def _has_source_images(out_dir: Path) -> bool:
raw = out_dir / "01_raw_layout.json"
if not raw.exists():
return False
try:
data = json.loads(raw.read_text(encoding="utf-8"))
if isinstance(data, list):
for b in data:
if isinstance(b, dict) and b.get("type") == "image":
return True
except Exception:
return False
return False
def _has_markdown_image_reference(text: str) -> bool:
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
target = (m.group(1) or "").strip()
if target.startswith("data:image/"):
return True
if target.startswith("http://") or target.startswith("https://"):
return True
return False
def _has_remote_image_url(text: str) -> bool:
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
target = (m.group(1) or "").strip()
if target.startswith("http://") or target.startswith("https://"):
return True
return False
def _expect_revision_table(text: str) -> bool:
if "文件修订履历" in text:
return True
hint = ["日期", "修订章节", "主要修订内容", "版本", "修改人"]
return sum(1 for h in hint if h in text) >= 4
def _collect_issues(text: str) -> list[dict]:
issues: list[dict] = []
lines = text.splitlines()
num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}\s+")
non_empty = [(i + 1, ln.strip()) for i, ln in enumerate(lines) if ln.strip()]
if len(non_empty) >= 2:
l1, s1 = non_empty[0]
l2, s2 = non_empty[1]
if "文件编号" in s1 and "文件编号" not in s2 and not s2.startswith("制定部门"):
if not re.match(r"^[一二三四五六七八九十]+、", s2):
issues.append(
{
"code": "title_below_meta",
"line": l1,
"text": f"meta before title: {s1[:80]}",
}
)
for i, ln in enumerate(lines, start=1):
s = ln.strip()
if not s:
continue
if s.startswith("|"):
continue
if re.search(r"\d+\.\d+(?:\.\d+)?\s+.+\s+\d+\.\d+(?:\.\d+)?\s+", s):
issues.append(
{"code": "inline_numbered_sections", "line": i, "text": s[:180]}
)
if re.search(r"[七八]、参考文件\s+[七八]、相关表单", s):
issues.append({"code": "inline_section_titles", "line": i, "text": s[:180]})
for i in range(1, len(lines) - 1):
if lines[i].strip():
continue
prev = lines[i - 1].strip()
nxt = lines[i + 1].strip()
if num_pat.match(prev) and num_pat.match(nxt):
issues.append(
{
"code": "blank_between_numbered_sections",
"line": i + 1,
"text": f"{prev[:70]} / {nxt[:70]}",
}
)
return issues
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
clean_md = input_data.get("clean_md", "")
checks = {
"has_doc_meta": _has_doc_meta(clean_md),
"has_revision_table": bool(
(re.search(r"\|\s*(?:日期|文件日期)\b", clean_md) is not None)
and re.search(r"\|\s*.*修订章节", clean_md)
and re.search(r"\|\s*版本\b", clean_md)
),
"has_flow_table": "| 序号 | 流程说明 | 责任部门 | 相关记录 |" in clean_md,
"has_related_forms_table": bool(
re.search(r"\|\s*表单编号\s*\|", clean_md)
and re.search(r"\|\s*[-:]{3,}\s*\|", clean_md)
),
"has_flow_file": (out_dir / "02_flow_procedure.md").exists(),
"has_embedded_images": _has_markdown_image_reference(clean_md),
"has_remote_image_urls": _has_remote_image_url(clean_md),
}
flow_expected = _expect_flow_artifacts(clean_md)
expected = {
"has_doc_meta": _expect_doc_meta(clean_md),
"has_revision_table": _expect_revision_table(clean_md),
"has_flow_table": flow_expected,
"has_related_forms_table": _expect_related_forms_table(clean_md),
"has_flow_file": flow_expected,
"has_embedded_images": _has_source_images(out_dir),
}
failed_required = [k for k, v in expected.items() if v and not checks.get(k, False)]
status = "pass" if not failed_required else "fail"
issues = _collect_issues(clean_md)
if expected["has_embedded_images"] and not checks["has_embedded_images"]:
issues.append(
{
"code": "image_not_embedded",
"line": 0,
"text": "source has image blocks but markdown has no image references",
}
)
if "data:image/" in clean_md:
issues.append(
{
"code": "legacy_base64_image",
"line": 0,
"text": "markdown still contains legacy data:image base64 payload",
}
)
return {
"status": status,
"checks": checks,
"expected": expected,
"failed_required": failed_required,
"issues": issues,
"issue_count": len(issues),
"warnings_count": len(context.warnings),
}
@@ -1,23 +0,0 @@
from __future__ import annotations
from edkb_system.contracts import Chunk, Context
def run(input_data: list[Chunk], context: Context) -> list[Chunk]:
chunks = input_data
if not chunks:
context.warnings.append("quality_gate: no chunks generated")
context.confidence = min(context.confidence, 0.5)
return chunks
short_count = sum(1 for c in chunks if len(c.text.strip()) < 60)
if short_count:
context.warnings.append(f"quality_gate: {short_count} short chunks")
context.confidence = min(context.confidence, 0.8)
unique_texts = len({c.text for c in chunks})
if unique_texts < len(chunks):
context.warnings.append("quality_gate: duplicate chunks detected")
context.confidence = min(context.confidence, 0.75)
return chunks
@@ -1,55 +0,0 @@
from __future__ import annotations
from edkb_system.contracts import Context
COND_KWS = ["条件", "判定", "if", "IF"]
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
def _find_col(headers: list[str], kws: list[str]) -> int | None:
for i, h in enumerate(headers):
s = (h or "").lower()
if any(k.lower() in s for k in kws):
return i
return None
def _to_table_md(headers: list[str], rows: list[list[str]]) -> str:
hs = [h or "-" for h in headers]
out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"]
for r in rows:
vals = [r[i] if i < len(r) else "" for i in range(len(hs))]
out.append("| " + " | ".join(vals) + " |")
return "\n".join(out)
def run(input_data: list[dict] | dict, context: Context) -> str:
tables = input_data if isinstance(input_data, list) else [input_data]
parts: list[str] = []
for t in tables:
headers = [str(x).strip() for x in t.get("headers", [])]
rows = [[str(c).strip() for c in row] for row in t.get("rows", [])]
parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}")
cidx = _find_col(headers, COND_KWS)
aidx = _find_col(headers, ACT_KWS)
oidx = _find_col(headers, OWN_KWS)
if cidx is not None and aidx is not None:
for row in rows:
cond = row[cidx] if cidx < len(row) else "满足条件"
act = row[aidx] if aidx < len(row) else "执行处理"
owner = (
row[oidx] if oidx is not None and oidx < len(row) else "相关责任方"
)
parts.append(
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
)
else:
parts.append(_to_table_md(headers, rows))
parts.append("")
return "\n".join(parts).strip() + "\n"
-249
View File
@@ -1,249 +0,0 @@
from __future__ import annotations
import os
import subprocess
import sys
import threading
import time
import ctypes
from pathlib import Path
def _list_winword_pids() -> set[int]:
if os.name != "nt":
return set()
try:
proc = subprocess.run(
["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"],
capture_output=True,
text=True,
check=False,
)
except Exception:
return set()
out: set[int] = set()
for line in (proc.stdout or "").splitlines():
line = line.strip()
if not line or line.startswith("INFO:"):
continue
cols = [part.strip().strip('"') for part in line.split('","')]
if len(cols) < 2:
cols = [part.strip().strip('"') for part in line.split(",")]
if len(cols) < 2:
continue
try:
out.add(int(cols[1]))
except ValueError:
continue
return out
def _kill_winword_pids(pids: set[int]) -> None:
if os.name != "nt":
return
for pid in sorted(pids):
try:
subprocess.run(
["taskkill", "/PID", str(pid), "/F"],
capture_output=True,
text=True,
check=False,
)
except Exception:
continue
def _word_timeout_sec() -> int:
raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip()
try:
value = int(raw)
except ValueError:
value = 120
return max(value, 10)
def _should_accept_word_dialog(
window_title: str, child_texts: list[str], button_texts: list[str]
) -> bool:
text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip())
if not text_blob:
return False
has_repair_prompt = any(
token in text_blob
for token in [
"出现严重错误",
"是否仍要打开",
"serious error",
"do you still want to open",
]
)
if not has_repair_prompt:
return False
return any(
text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower()
for text in button_texts
)
def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]:
stop_event = threading.Event()
if os.name != "nt":
return stop_event, None
def _window_text(user32, hwnd: int) -> str:
length = user32.GetWindowTextLengthW(hwnd)
if length <= 0:
return ""
buf = ctypes.create_unicode_buffer(length + 1)
user32.GetWindowTextW(hwnd, buf, length + 1)
return buf.value
def _class_name(user32, hwnd: int) -> str:
buf = ctypes.create_unicode_buffer(256)
user32.GetClassNameW(hwnd, buf, 255)
return buf.value
def _click_yes_if_needed() -> None:
user32 = ctypes.windll.user32
bm_click = 0x00F5
vk_return = 0x0D
wm_keydown = 0x0100
wm_keyup = 0x0101
while not stop_event.is_set():
windows: list[int] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
def enum_windows(hwnd, lparam):
windows.append(int(hwnd))
return True
user32.EnumWindows(enum_windows, 0)
for hwnd in windows:
title = _window_text(user32, hwnd)
cls = _class_name(user32, hwnd).lower()
if "Microsoft Word" not in title and cls != "#32770":
continue
child_hwnds: list[int] = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
def enum_children(child_hwnd, lparam):
child_hwnds.append(int(child_hwnd))
return True
user32.EnumChildWindows(hwnd, enum_children, 0)
child_texts = [_window_text(user32, child) for child in child_hwnds]
button_hwnds = [
child
for child in child_hwnds
if _class_name(user32, child).lower() == "button"
]
button_texts = [_window_text(user32, child) for child in button_hwnds]
if not _should_accept_word_dialog(title, child_texts, button_texts):
continue
user32.SetForegroundWindow(hwnd)
for child, text in zip(button_hwnds, button_texts):
normalized = text.strip().lower()
if normalized.startswith(("是", "yes")) or "&y" in normalized:
user32.SendMessageW(child, bm_click, 0, 0)
break
else:
user32.PostMessageW(hwnd, wm_keydown, vk_return, 0)
user32.PostMessageW(hwnd, wm_keyup, vk_return, 0)
stop_event.wait(0.5)
thread = threading.Thread(target=_click_yes_if_needed, daemon=True)
thread.start()
return stop_event, thread
def convert_with_word(path: Path, output: Path, file_format: int) -> Path:
timeout = _word_timeout_sec()
before_pids = _list_winword_pids()
cmd = [
sys.executable,
"-m",
"edkb_system.skills.word_bridge",
str(path),
str(output),
str(file_format),
]
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
after_pids = _list_winword_pids()
_kill_winword_pids(after_pids - before_pids)
raise RuntimeError(
f"Word conversion timed out after {timeout}s: {path.name}"
) from exc
if proc.returncode != 0:
err = (proc.stderr or proc.stdout or "unknown error").strip()
raise RuntimeError(f"Word conversion failed: {err}")
if not output.exists() or output.stat().st_size <= 0:
raise RuntimeError(f"Word conversion produced no output: {output}")
return output
def _child_main(argv: list[str]) -> int:
if len(argv) != 4:
print("usage: word_bridge <input> <output> <file_format>", file=sys.stderr)
return 2
src = Path(argv[1]).resolve()
out = Path(argv[2]).resolve()
file_format = int(argv[3])
out.parent.mkdir(parents=True, exist_ok=True)
stop_event, watcher = _start_word_dialog_watcher()
word = None
doc = None
try:
from win32com.client import DispatchEx
word = DispatchEx("Word.Application")
word.Visible = False
word.DisplayAlerts = 0
try:
word.Options.SaveNormalPrompt = False
except Exception:
pass
doc = word.Documents.Open(
FileName=str(src),
ReadOnly=True,
AddToRecentFiles=False,
ConfirmConversions=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
doc.SaveAs(str(out), FileFormat=file_format)
finally:
stop_event.set()
if watcher is not None:
watcher.join(timeout=1)
if doc is not None:
try:
doc.Close(False)
except Exception:
pass
if word is not None:
try:
word.Quit()
except Exception:
pass
return 0
if __name__ == "__main__":
raise SystemExit(_child_main(sys.argv))
-49
View File
@@ -1,49 +0,0 @@
from __future__ import annotations
from logging.config import fileConfig
from pathlib import Path
import sys
from alembic import context
from sqlalchemy import engine_from_config, pool
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.config import get_settings
from app.database import Base
from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, SystemSetting, User
config = context.config
settings = get_settings()
config.set_main_option("sqlalchemy.url", settings.database_url)
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
@@ -1,150 +0,0 @@
"""initial schema
Revision ID: 20260327_0001
Revises:
Create Date: 2026-03-27 23:30:00
"""
from alembic import op
import sqlalchemy as sa
revision = "20260327_0001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("username", sa.String(length=64), nullable=False),
sa.Column("full_name", sa.String(length=128), nullable=True),
sa.Column("password_hash", sa.String(length=255), nullable=False),
sa.Column("role", sa.String(length=16), nullable=False, server_default="user"),
sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
op.create_index("ix_users_username", "users", ["username"], unique=True)
op.create_table(
"system_settings",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("dify_permission", sa.String(length=32), nullable=False, server_default="all_team_members"),
sa.Column("indexing_technique", sa.String(length=32), nullable=False, server_default="high_quality"),
sa.Column("search_method", sa.String(length=32), nullable=False, server_default="hybrid_search"),
sa.Column("doc_form", sa.String(length=32), nullable=False, server_default="text_model"),
sa.Column("top_k", sa.Integer(), nullable=False, server_default="5"),
sa.Column("score_threshold_enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
sa.Column("score_threshold", sa.String(length=32), nullable=False, server_default="0.35"),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
op.create_table(
"groups",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("dify_dataset_id", sa.String(length=128), nullable=True),
sa.Column("dify_sync_policy", sa.String(length=32), nullable=False, server_default="manual"),
sa.Column("indexing_technique", sa.String(length=32), nullable=False, server_default="high_quality"),
sa.Column("search_method", sa.String(length=32), nullable=False, server_default="hybrid_search"),
sa.Column("doc_form", sa.String(length=32), nullable=False, server_default="text_model"),
sa.Column("top_k", sa.Integer(), nullable=False, server_default="5"),
sa.Column("score_threshold_enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
sa.Column("score_threshold", sa.String(length=32), nullable=False, server_default="0.35"),
sa.Column("created_by_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
op.create_index("ix_groups_name", "groups", ["name"], unique=True)
op.create_table(
"documents",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("group_id", sa.Integer(), sa.ForeignKey("groups.id"), nullable=False),
sa.Column("title", sa.String(length=255), nullable=False),
sa.Column("is_deleted", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("created_by_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.UniqueConstraint("group_id", "title", name="uq_documents_group_title"),
)
op.create_table(
"document_versions",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("document_id", sa.Integer(), sa.ForeignKey("documents.id"), nullable=False),
sa.Column("version_no", sa.Integer(), nullable=False),
sa.Column("is_current", sa.Boolean(), nullable=False, server_default=sa.true()),
sa.Column("source_filename", sa.String(length=255), nullable=False),
sa.Column("source_ext", sa.String(length=16), nullable=False),
sa.Column("source_path", sa.Text(), nullable=False),
sa.Column("source_sha256", sa.String(length=64), nullable=False),
sa.Column("md_path", sa.Text(), nullable=True),
sa.Column("md_public_url", sa.Text(), nullable=True),
sa.Column("asset_dir", sa.Text(), nullable=True),
sa.Column("file_size", sa.Integer(), nullable=False),
sa.Column("word_count", sa.Integer(), nullable=False, server_default="0"),
sa.Column("convert_status", sa.String(length=32), nullable=False, server_default="queued"),
sa.Column("sync_status", sa.String(length=32), nullable=False, server_default="unsynced"),
sa.Column("uploader_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
sa.Column("uploaded_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("converted_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("failed_reason", sa.Text(), nullable=True),
sa.Column("warnings_json", sa.JSON(), nullable=True),
)
op.create_index("ix_document_versions_source_sha256", "document_versions", ["source_sha256"], unique=False)
op.create_table(
"jobs",
sa.Column("id", sa.String(length=36), primary_key=True),
sa.Column("job_type", sa.String(length=32), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False, server_default="queued"),
sa.Column("queue_job_id", sa.String(length=64), nullable=True),
sa.Column("group_id", sa.Integer(), sa.ForeignKey("groups.id"), nullable=True),
sa.Column("document_id", sa.Integer(), sa.ForeignKey("documents.id"), nullable=True),
sa.Column("version_id", sa.Integer(), sa.ForeignKey("document_versions.id"), nullable=True),
sa.Column("created_by_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
sa.Column("progress", sa.Integer(), nullable=False, server_default="0"),
sa.Column("message", sa.Text(), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
sa.Column("payload", sa.JSON(), nullable=True),
sa.Column("result", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
)
op.create_index("ix_jobs_status", "jobs", ["status"], unique=False)
op.create_index("ix_jobs_job_type", "jobs", ["job_type"], unique=False)
op.create_table(
"dify_sync_records",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("version_id", sa.Integer(), sa.ForeignKey("document_versions.id"), nullable=False),
sa.Column("dataset_id", sa.String(length=128), nullable=False),
sa.Column("remote_document_id", sa.String(length=128), nullable=False),
sa.Column("batch", sa.String(length=128), nullable=True),
sa.Column("status", sa.String(length=32), nullable=False, server_default="syncing"),
sa.Column("last_indexing_status", sa.String(length=64), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
sa.Column("last_synced_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
def downgrade() -> None:
op.drop_table("dify_sync_records")
op.drop_index("ix_jobs_job_type", table_name="jobs")
op.drop_index("ix_jobs_status", table_name="jobs")
op.drop_table("jobs")
op.drop_index("ix_document_versions_source_sha256", table_name="document_versions")
op.drop_table("document_versions")
op.drop_table("documents")
op.drop_index("ix_groups_name", table_name="groups")
op.drop_table("groups")
op.drop_table("system_settings")
op.drop_index("ix_users_username", table_name="users")
op.drop_table("users")
@@ -1,31 +0,0 @@
"""add dify model defaults to system settings
Revision ID: 20260328_0002
Revises: 20260327_0001
Create Date: 2026-03-28 09:30:00
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "20260328_0002"
down_revision = "20260327_0001"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("system_settings", sa.Column("embedding_model_provider", sa.String(length=128), nullable=True))
op.add_column("system_settings", sa.Column("embedding_model", sa.String(length=128), nullable=True))
op.add_column("system_settings", sa.Column("reranking_model_provider", sa.String(length=128), nullable=True))
op.add_column("system_settings", sa.Column("reranking_model", sa.String(length=128), nullable=True))
def downgrade() -> None:
op.drop_column("system_settings", "reranking_model")
op.drop_column("system_settings", "reranking_model_provider")
op.drop_column("system_settings", "embedding_model")
op.drop_column("system_settings", "embedding_model_provider")
@@ -1,37 +0,0 @@
"""roles and group access
Revision ID: 20260329_0003
Revises: 20260328_0002
Create Date: 2026-03-29 09:30:00
"""
from alembic import op
import sqlalchemy as sa
revision = "20260329_0003"
down_revision = "20260328_0002"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"user_group_access",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False),
sa.Column("group_id", sa.Integer(), sa.ForeignKey("groups.id"), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.UniqueConstraint("user_id", "group_id", name="uq_user_group_access"),
)
op.create_index("ix_user_group_access_user_id", "user_group_access", ["user_id"], unique=False)
op.create_index("ix_user_group_access_group_id", "user_group_access", ["group_id"], unique=False)
op.execute("UPDATE users SET role = 'super_admin' WHERE role = 'admin'")
def downgrade() -> None:
op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin'")
op.drop_index("ix_user_group_access_group_id", table_name="user_group_access")
op.drop_index("ix_user_group_access_user_id", table_name="user_group_access")
op.drop_table("user_group_access")
@@ -1,85 +0,0 @@
"""departments and unique super admin
Revision ID: 20260329_0004
Revises: 20260329_0003
Create Date: 2026-03-29 15:40:00
"""
from alembic import op
import sqlalchemy as sa
revision = "20260329_0004"
down_revision = "20260329_0003"
branch_labels = None
depends_on = None
DEFAULT_DEPARTMENT_NAME = "默认部门"
def upgrade() -> None:
op.create_table(
"departments",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("name", sa.String(length=128), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
)
op.create_index("ix_departments_name", "departments", ["name"], unique=True)
op.add_column("users", sa.Column("primary_department_id", sa.Integer(), nullable=True))
op.create_index("ix_users_primary_department_id", "users", ["primary_department_id"], unique=False)
op.add_column("groups", sa.Column("department_id", sa.Integer(), nullable=True))
op.create_index("ix_groups_department_id", "groups", ["department_id"], unique=False)
op.create_table(
"user_department_access",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False),
sa.Column("department_id", sa.Integer(), sa.ForeignKey("departments.id"), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.UniqueConstraint("user_id", "department_id", name="uq_user_department_access"),
)
op.create_index("ix_user_department_access_user_id", "user_department_access", ["user_id"], unique=False)
op.create_index("ix_user_department_access_department_id", "user_department_access", ["department_id"], unique=False)
op.execute(
sa.text(
"INSERT INTO departments (name, description) VALUES (:name, :description)"
).bindparams(name=DEFAULT_DEPARTMENT_NAME, description="系统默认部门")
)
op.execute("UPDATE users SET primary_department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1)")
op.execute("UPDATE groups SET department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1)")
op.execute(
"""
INSERT INTO user_department_access (user_id, department_id)
SELECT id, primary_department_id FROM users
WHERE primary_department_id IS NOT NULL
"""
)
op.create_foreign_key("fk_users_primary_department_id", "users", "departments", ["primary_department_id"], ["id"])
op.create_foreign_key("fk_groups_department_id", "groups", "departments", ["department_id"], ["id"])
op.alter_column("users", "primary_department_id", nullable=False)
op.alter_column("groups", "department_id", nullable=False)
op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin' AND lower(username) <> 'admin'")
op.execute("UPDATE users SET role = 'super_admin' WHERE lower(username) = 'admin'")
def downgrade() -> None:
op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin'")
op.drop_constraint("fk_groups_department_id", "groups", type_="foreignkey")
op.drop_constraint("fk_users_primary_department_id", "users", type_="foreignkey")
op.drop_index("ix_user_department_access_department_id", table_name="user_department_access")
op.drop_index("ix_user_department_access_user_id", table_name="user_department_access")
op.drop_table("user_department_access")
op.drop_index("ix_groups_department_id", table_name="groups")
op.drop_column("groups", "department_id")
op.drop_index("ix_users_primary_department_id", table_name="users")
op.drop_column("users", "primary_department_id")
op.drop_index("ix_departments_name", table_name="departments")
op.drop_table("departments")
@@ -1,93 +0,0 @@
"""remove default department bootstrap
Revision ID: 20260329_0005
Revises: 20260329_0004
Create Date: 2026-03-29 17:10:00
"""
from alembic import op
import sqlalchemy as sa
revision = "20260329_0005"
down_revision = "20260329_0004"
branch_labels = None
depends_on = None
LEGACY_DEFAULT_DEPARTMENT_NAMES = ("默认部门", "榛樿閮ㄩ棬")
def upgrade() -> None:
op.alter_column("users", "primary_department_id", nullable=True)
op.alter_column("groups", "department_id", nullable=True)
for name in LEGACY_DEFAULT_DEPARTMENT_NAMES:
op.execute(
sa.text(
"""
DELETE FROM user_department_access
WHERE department_id IN (SELECT id FROM departments WHERE name = :name)
"""
).bindparams(name=name)
)
op.execute(
sa.text(
"""
UPDATE users
SET primary_department_id = NULL
WHERE primary_department_id IN (SELECT id FROM departments WHERE name = :name)
"""
).bindparams(name=name)
)
op.execute(
sa.text(
"""
UPDATE groups
SET department_id = NULL
WHERE department_id IN (SELECT id FROM departments WHERE name = :name)
"""
).bindparams(name=name)
)
op.execute(sa.text("DELETE FROM departments WHERE name = :name").bindparams(name=name))
def downgrade() -> None:
op.execute(
sa.text(
"""
INSERT INTO departments (name, description)
SELECT :name, :description
WHERE NOT EXISTS (SELECT 1 FROM departments WHERE name = :name)
"""
).bindparams(name="默认部门", description="系统默认部门")
)
op.execute(
"""
UPDATE users
SET primary_department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1)
WHERE primary_department_id IS NULL
"""
)
op.execute(
"""
UPDATE groups
SET department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1)
WHERE department_id IS NULL
"""
)
op.execute(
"""
INSERT INTO user_department_access (user_id, department_id)
SELECT id, primary_department_id
FROM users
WHERE primary_department_id IS NOT NULL
AND NOT EXISTS (
SELECT 1
FROM user_department_access uda
WHERE uda.user_id = users.id AND uda.department_id = users.primary_department_id
)
"""
)
op.alter_column("groups", "department_id", nullable=False)
op.alter_column("users", "primary_department_id", nullable=False)
@@ -1,27 +0,0 @@
"""make group names unique per department
Revision ID: 20260401_0006
Revises: 20260329_0005
Create Date: 2026-04-01 18:40:00
"""
from alembic import op
import sqlalchemy as sa
revision = "20260401_0006"
down_revision = "20260329_0005"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.drop_index("ix_groups_name", table_name="groups")
op.create_index("ix_groups_name", "groups", ["name"], unique=False)
op.create_unique_constraint("uq_groups_department_name", "groups", ["department_id", "name"])
def downgrade() -> None:
op.drop_constraint("uq_groups_department_name", "groups", type_="unique")
op.drop_index("ix_groups_name", table_name="groups")
op.create_index("ix_groups_name", "groups", ["name"], unique=True)
@@ -1,41 +0,0 @@
"""require a department on groups
Revision ID: 20260401_0007
Revises: 20260401_0006
Create Date: 2026-04-01 21:10:00
"""
from alembic import op
import sqlalchemy as sa
revision = "20260401_0007"
down_revision = "20260401_0006"
branch_labels = None
depends_on = None
def upgrade() -> None:
bind = op.get_bind()
bind.execute(
sa.text(
"""
UPDATE groups
SET department_id = users.primary_department_id
FROM users
WHERE groups.department_id IS NULL
AND groups.created_by_id = users.id
AND users.primary_department_id IS NOT NULL
"""
)
)
null_group_count = bind.execute(sa.text("SELECT COUNT(*) FROM groups WHERE department_id IS NULL")).scalar_one()
if null_group_count:
raise RuntimeError(
f"Cannot require group departments while {null_group_count} knowledge base(s) still have no department."
)
op.alter_column("groups", "department_id", existing_type=sa.Integer(), nullable=False)
def downgrade() -> None:
op.alter_column("groups", "department_id", existing_type=sa.Integer(), nullable=True)
-28
View File
@@ -1,28 +0,0 @@
fastapi==0.116.1
uvicorn[standard]==0.35.0
sqlalchemy==2.0.43
alembic==1.16.5
pydantic==2.11.9
pydantic-settings==2.10.1
python-multipart==0.0.20
python-jose[cryptography]==3.5.0
passlib[bcrypt]==1.7.4
requests==2.32.5
rq==2.6.0
redis==6.4.0
psycopg[binary]==3.2.11
PyYAML==6.0.2
networkx==3.5
openpyxl==3.1.5
python-docx==1.2.0
rapidocr-onnxruntime==1.4.4
pillow==11.3.0
numpy==2.3.3
pypdf==6.1.0
pypdfium2==5.0.0
python-pptx==1.0.2
beautifulsoup4==4.14.2
lxml==6.0.2
typer==0.17.4
pytest==8.4.2
httpx==0.28.1
-114
View File
@@ -1,114 +0,0 @@
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
os.environ["DATABASE_URL"] = "sqlite:///./test_document_cleaning.db"
os.environ["DATA_ROOT"] = "./test_data"
os.environ["PUBLIC_BASE_URL"] = "http://testserver"
os.environ["INTEGRATION_API_KEY"] = "integration-secret"
os.environ["INTEGRATION_DOWNLOAD_SECRET"] = "integration-download-secret"
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.config import get_settings # noqa: E402
from app.database import Base, get_db # noqa: E402
from app.main import app # noqa: E402
from app.models import Department, SystemSetting, User # noqa: E402
from app.security import hash_password # noqa: E402
TEST_DB = Path("./test_document_cleaning.db")
TEST_DATA_ROOT = Path("./test_data")
if TEST_DB.exists():
TEST_DB.unlink()
if TEST_DATA_ROOT.exists():
shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True)
TEST_DATA_ROOT.mkdir(parents=True, exist_ok=True)
engine = create_engine("sqlite:///./test_document_cleaning.db", connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
@pytest.fixture
def initialized_db():
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True)
get_settings().ensure_data_dirs()
db = TestingSessionLocal()
db.add(
Department(
id=1,
name="测试部门",
description="测试部门",
)
)
db.add(
SystemSetting(
id=1,
dify_permission="all_team_members",
indexing_technique="high_quality",
search_method="hybrid_search",
doc_form="text_model",
top_k=5,
score_threshold_enabled=True,
score_threshold="0.35",
)
)
db.add(
User(
username="admin",
full_name="System Admin",
password_hash=hash_password("admin123456"),
role="super_admin",
is_active=True,
primary_department_id=1,
)
)
db.add(
User(
username="adam",
full_name="Adam",
password_hash=hash_password("admin123456"),
role="admin",
is_active=True,
primary_department_id=1,
)
)
db.commit()
db.close()
yield
shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True)
@pytest.fixture
def client(initialized_db):
with TestClient(app) as test_client:
yield test_client
@pytest.fixture
def db_session(initialized_db):
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
-119
View File
@@ -1,119 +0,0 @@
from __future__ import annotations
import uuid
from pathlib import Path
from app.database import SessionLocal
from app.models import Department, Document, DocumentVersion, Group, User, UserDepartmentAccess
from app.security import hash_password
def _token(client, username: str, password: str):
response = client.post("/api/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
def _headers(client, username: str, password: str):
return {"Authorization": f"Bearer {_token(client, username, password)}"}
def _seed_access_fixture() -> tuple[int, int]:
db = SessionLocal()
try:
super_admin = db.query(User).filter(User.username == "admin").first()
assert super_admin is not None
blocked_department = Department(name=f"blocked-dept-{uuid.uuid4().hex[:6]}", description="blocked")
db.add(blocked_department)
db.commit()
db.refresh(blocked_department)
scoped_user = User(
username="scoped-user",
full_name="Scoped User",
password_hash=hash_password("scoped123"),
role="user",
is_active=True,
primary_department_id=1,
)
db.add(scoped_user)
db.commit()
db.refresh(scoped_user)
allowed_group = Group(name=f"allowed-{uuid.uuid4().hex[:8]}", created_by_id=super_admin.id, department_id=1)
blocked_group = Group(
name=f"blocked-{uuid.uuid4().hex[:8]}",
created_by_id=super_admin.id,
department_id=blocked_department.id,
)
db.add_all([allowed_group, blocked_group])
db.commit()
db.refresh(allowed_group)
db.refresh(blocked_group)
db.add(UserDepartmentAccess(user_id=scoped_user.id, department_id=1))
db.commit()
allowed_document = Document(group_id=allowed_group.id, title="allowed-doc", created_by_id=super_admin.id, is_deleted=False)
blocked_document = Document(group_id=blocked_group.id, title="blocked-doc", created_by_id=super_admin.id, is_deleted=False)
db.add_all([allowed_document, blocked_document])
db.commit()
db.refresh(allowed_document)
db.refresh(blocked_document)
db.add_all(
[
DocumentVersion(
document_id=allowed_document.id,
version_no=1,
is_current=True,
source_filename="allowed.docx",
source_ext=".docx",
source_path=str(Path("allowed.docx")),
source_sha256=uuid.uuid4().hex,
file_size=12,
uploader_id=super_admin.id,
convert_status="success",
sync_status="unsynced",
),
DocumentVersion(
document_id=blocked_document.id,
version_no=1,
is_current=True,
source_filename="blocked.docx",
source_ext=".docx",
source_path=str(Path("blocked.docx")),
source_sha256=uuid.uuid4().hex,
file_size=12,
uploader_id=super_admin.id,
convert_status="success",
sync_status="unsynced",
),
]
)
db.commit()
return allowed_group.id, blocked_group.id
finally:
db.close()
def test_groups_and_files_are_scoped_by_user_access(client):
allowed_group_id, blocked_group_id = _seed_access_fixture()
headers = _headers(client, "scoped-user", "scoped123")
groups_response = client.get("/api/groups", headers=headers)
assert groups_response.status_code == 200
groups = groups_response.json()["data"]
assert len(groups) == 1
assert groups[0]["id"] == allowed_group_id
summary_response = client.get("/api/groups/summary", headers=headers)
assert summary_response.status_code == 200
assert summary_response.json()["knowledge_base_count"] == 1
assert summary_response.json()["file_count"] == 1
allowed_files = client.get(f"/api/groups/{allowed_group_id}/files", headers=headers)
blocked_files = client.get(f"/api/groups/{blocked_group_id}/files", headers=headers)
assert allowed_files.status_code == 200
assert len(allowed_files.json()["data"]) == 1
assert blocked_files.status_code == 403
-699
View File
@@ -1,699 +0,0 @@
from __future__ import annotations
import json
import uuid
from datetime import timedelta
from app.config import get_settings
from app.database import SessionLocal
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess
from app.security import hash_password
from app.services.bootstrap_service import ensure_defaults
from app.time_utils import utc_now
def _token(client, username: str = "admin", password: str = "admin123456"):
response = client.post("/api/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
def _headers(client, username: str = "admin", password: str = "admin123456"):
return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"}
def _create_user(*, username: str, password: str, role: str = "user", full_name: str = "User") -> int:
db = SessionLocal()
try:
user = User(
username=username,
full_name=full_name,
password_hash=hash_password(password),
role=role,
is_active=True,
primary_department_id=1,
)
db.add(user)
db.commit()
db.refresh(user)
return user.id
finally:
db.close()
def _create_group(*, name: str) -> int:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=name, created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
return group.id
finally:
db.close()
def _create_department(*, name: str, description: str = "test department") -> int:
db = SessionLocal()
try:
department = Department(name=name, description=description)
db.add(department)
db.commit()
db.refresh(department)
return department.id
finally:
db.close()
def _create_stale_syncing_document() -> tuple[int, str]:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"health-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="stale-health", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="stale.docx",
source_ext=".docx",
source_path="/tmp/stale.docx",
source_sha256=uuid.uuid4().hex,
file_size=128,
uploader_id=admin_id,
convert_status="success",
sync_status="syncing",
)
db.add(version)
db.commit()
db.refresh(version)
old_time = utc_now() - timedelta(minutes=20)
job = Job(
id=str(uuid.uuid4()),
job_type="sync",
status="running",
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
started_at=old_time,
)
db.add(job)
db.commit()
record = DifySyncRecord(
version_id=version.id,
dataset_id="dataset-health",
remote_document_id="remote-health",
batch="batch-health",
status="syncing",
created_at=old_time,
updated_at=old_time,
)
db.add(record)
db.commit()
return version.id, job.id
finally:
db.close()
def _create_stale_convert_document() -> tuple[int, str]:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"convert-health-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="convert-stale-health", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
old_time = utc_now() - timedelta(minutes=20)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="convert-stale.docx",
source_ext=".docx",
source_path="/tmp/convert-stale.docx",
source_sha256=uuid.uuid4().hex,
file_size=128,
uploader_id=admin_id,
convert_status="queued",
sync_status="unsynced",
uploaded_at=old_time,
)
db.add(version)
db.commit()
db.refresh(version)
job = Job(
id=str(uuid.uuid4()),
job_type="convert",
status="queued",
queue_job_id="missing-convert-job",
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
)
db.add(job)
db.commit()
return version.id, job.id
finally:
db.close()
def test_admin_can_create_and_update_users(client):
group_id = _create_group(name=f"access-{uuid.uuid4().hex[:8]}")
create_response = client.post(
"/api/admin/users",
json={
"username": "operator",
"password": "operator123",
"full_name": "Ops User",
"role": "user",
"primary_department_id": 1,
"accessible_department_ids": [1],
},
headers=_headers(client),
)
assert create_response.status_code == 200
assert create_response.json()["username"] == "operator"
assert create_response.json()["accessible_department_ids"] == [1]
db = SessionLocal()
try:
user = db.query(User).filter(User.username == "operator").first()
assert user is not None
user_id = user.id
finally:
db.close()
update_response = client.patch(
f"/api/admin/users/{user_id}",
json={
"full_name": "Operations User",
"role": "admin",
"is_active": False,
"primary_department_id": 1,
"accessible_department_ids": [1],
},
headers=_headers(client),
)
assert update_response.status_code == 200
body = update_response.json()
assert body["full_name"] == "Operations User"
assert body["role"] == "admin"
assert body["is_active"] is False
assert body["accessible_department_ids"] == [1]
def test_admin_can_delete_user_and_clear_created_by_references(client):
user_id = _create_user(username=f"delete-user-{uuid.uuid4().hex[:8]}", password="delete123", role="user", full_name="Delete User")
db = SessionLocal()
try:
user = db.query(User).filter(User.id == user_id).first()
admin = db.query(User).filter(User.username == "admin").first()
assert user is not None
assert admin is not None
group = Group(name=f"delete-user-group-{uuid.uuid4().hex[:8]}", created_by_id=user_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title=f"delete-user-doc-{uuid.uuid4().hex[:8]}", created_by_id=user_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="delete-user.docx",
source_ext=".docx",
source_path="/tmp/delete-user.docx",
source_sha256=uuid.uuid4().hex,
file_size=128,
uploader_id=user_id,
convert_status="success",
sync_status="unsynced",
)
db.add(version)
db.add(Job(id=str(uuid.uuid4()), job_type="convert", status="success", created_by_id=user_id, document_id=document.id, version_id=version.id))
db.commit()
group_id = group.id
document_id = document.id
version_id = version.id
finally:
db.close()
response = client.delete(f"/api/admin/users/{user_id}", headers=_headers(client))
assert response.status_code == 200
assert response.json()["deleted_user_id"] == user_id
db = SessionLocal()
try:
assert db.query(User).filter(User.id == user_id).first() is None
group = db.query(Group).filter(Group.id == group_id).first()
document = db.query(Document).filter(Document.id == document_id).first()
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.document_id == document_id).first()
assert group is not None and group.created_by_id is None
assert document is not None and document.created_by_id is None
assert version is not None and version.uploader_id is None
assert job is not None and job.created_by_id is None
finally:
db.close()
def test_admin_delete_protects_primary_super_admin_and_self(client):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
finally:
db.close()
delete_admin = client.delete(f"/api/admin/users/{admin_id}", headers=_headers(client))
assert delete_admin.status_code == 400
assert "cannot be deleted" in delete_admin.json()["detail"]
username = f"self-delete-{uuid.uuid4().hex[:8]}"
user_id = _create_user(username=username, password="self123", role="admin", full_name="Self Delete")
self_delete = client.delete(
f"/api/admin/users/{user_id}",
headers=_headers(client, username=username, password="self123"),
)
assert self_delete.status_code == 400
assert "cannot delete your own account" in self_delete.json()["detail"].lower()
def test_only_admin_can_hold_super_admin_role(client):
create_response = client.post(
"/api/admin/users",
json={
"username": "other-super",
"password": "operator123",
"full_name": "Other Super",
"role": "super_admin",
"primary_department_id": 1,
"accessible_department_ids": [],
},
headers=_headers(client),
)
assert create_response.status_code == 400
assert "Only admin can be a super admin" in create_response.json()["detail"]
db = SessionLocal()
try:
admin_user = db.query(User).filter(User.username == "admin").first()
operator = User(
username="operator-promote",
full_name="Operator Promote",
password_hash=hash_password("operator123"),
role="admin",
is_active=True,
primary_department_id=1,
)
db.add(operator)
db.commit()
db.refresh(operator)
assert admin_user is not None
operator_id = operator.id
admin_id = admin_user.id
finally:
db.close()
promote_response = client.patch(
f"/api/admin/users/{operator_id}",
json={"role": "super_admin"},
headers=_headers(client),
)
assert promote_response.status_code == 400
assert "Only admin can be a super admin" in promote_response.json()["detail"]
demote_admin = client.patch(
f"/api/admin/users/{admin_id}",
json={"role": "admin"},
headers=_headers(client),
)
assert demote_admin.status_code == 400
assert "admin must remain a super admin" in demote_admin.json()["detail"]
def test_bootstrap_keeps_admin_as_unique_super_admin():
db = SessionLocal()
try:
rogue = User(
username="legacy-super",
full_name="Legacy Super",
password_hash=hash_password("legacy123"),
role="super_admin",
is_active=True,
primary_department_id=None,
)
db.add(rogue)
db.commit()
ensure_defaults(db)
admin = db.query(User).filter(User.username == "admin").first()
legacy = db.query(User).filter(User.username == "legacy-super").first()
adam = db.query(User).filter(User.username == "adam").first()
assert admin is not None
assert admin.role == "super_admin"
assert legacy is not None
assert legacy.role == "admin"
assert legacy.primary_department_id is None
assert adam is not None
assert adam.role == "admin"
finally:
db.close()
def test_admin_can_read_and_update_settings(client):
initial = client.get("/api/admin/settings", headers=_headers(client))
assert initial.status_code == 200
assert initial.json()["search_method"] == "hybrid_search"
updated = client.patch(
"/api/admin/settings",
json={
"search_method": "semantic_search",
"top_k": 8,
"score_threshold_enabled": False,
"score_threshold": 0.4,
"embedding_model_provider": "langgenius/siliconflow/siliconflow",
"embedding_model": "Qwen/Qwen3-Embedding-8B",
"reranking_model_provider": "langgenius/siliconflow/siliconflow",
"reranking_model": "Qwen/Qwen3-Reranker-8B",
},
headers=_headers(client),
)
assert updated.status_code == 200
body = updated.json()
assert body["search_method"] == "semantic_search"
assert body["top_k"] == 8
assert body["score_threshold_enabled"] is False
assert body["score_threshold"] == 0.4
assert body["embedding_model_provider"] == "langgenius/siliconflow/siliconflow"
assert body["embedding_model"] == "Qwen/Qwen3-Embedding-8B"
assert body["reranking_model_provider"] == "langgenius/siliconflow/siliconflow"
assert body["reranking_model"] == "Qwen/Qwen3-Reranker-8B"
def test_empty_department_can_be_deleted(client):
department_id = _create_department(name=f"empty-dept-{uuid.uuid4().hex[:8]}")
response = client.request(
"DELETE",
f"/api/admin/departments/{department_id}",
headers=_headers(client),
json={"target_department_id": None},
)
assert response.status_code == 200
assert response.json()["deleted_department_id"] == department_id
db = SessionLocal()
try:
assert db.query(Department).filter(Department.id == department_id).first() is None
finally:
db.close()
def test_department_delete_requires_migration_when_department_is_in_use(client):
source_department_id = _create_department(name=f"source-dept-{uuid.uuid4().hex[:8]}")
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"in-use-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id)
db.add(group)
db.commit()
finally:
db.close()
response = client.request(
"DELETE",
f"/api/admin/departments/{source_department_id}",
headers=_headers(client),
json={"target_department_id": None},
)
assert response.status_code == 400
assert "Choose another department to migrate first" in response.json()["detail"]
def test_department_delete_can_migrate_knowledge_bases_and_user_access(client):
source_department_id = _create_department(name=f"source-migrate-{uuid.uuid4().hex[:8]}")
target_department_id = _create_department(name=f"target-migrate-{uuid.uuid4().hex[:8]}")
operator_id = _create_user(username=f"dept-user-{uuid.uuid4().hex[:8]}", password="operator123", role="user", full_name="Dept User")
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
operator = db.query(User).filter(User.id == operator_id).first()
assert admin is not None
assert operator is not None
admin.primary_department_id = target_department_id
operator.primary_department_id = source_department_id
db.add(UserDepartmentAccess(user_id=admin.id, department_id=source_department_id))
group = Group(name=f"migrate-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id)
db.add(group)
db.commit()
db.refresh(group)
group_id = group.id
admin_id = admin.id
finally:
db.close()
response = client.request(
"DELETE",
f"/api/admin/departments/{source_department_id}",
headers=_headers(client),
json={"target_department_id": target_department_id},
)
assert response.status_code == 200
payload = response.json()
assert payload["migrated_to_department_id"] == target_department_id
assert payload["knowledge_base_count"] == 1
assert payload["primary_user_count"] == 1
assert payload["extra_user_count"] == 1
db = SessionLocal()
try:
assert db.query(Department).filter(Department.id == source_department_id).first() is None
group = db.query(Group).filter(Group.id == group_id).first()
operator = db.query(User).filter(User.id == operator_id).first()
admin = db.query(User).filter(User.id == admin_id).first()
assert group is not None
assert operator is not None
assert admin is not None
assert group.department_id == target_department_id
assert operator.primary_department_id == target_department_id
assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == source_department_id).first() is None
assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == target_department_id).first() is None
finally:
db.close()
def test_admin_can_read_available_dify_models(client, monkeypatch):
class FakeDifyService:
def list_available_embedding_models(self):
return [
type("Model", (), {"provider": "provider-a", "model": "embed-a", "label": "Provider A / embed-a"})()
]
def list_available_rerank_models(self):
return [
type("Model", (), {"provider": "provider-b", "model": "rerank-b", "label": "Provider B / rerank-b"})()
]
def resolve_embedding_model_choice(self, *, provider=None, model=None):
return ("provider-a", "embed-a")
def resolve_rerank_model_choice(self, *, provider=None, model=None):
return ("provider-b", "rerank-b")
monkeypatch.setattr("app.api.admin.DifyService", FakeDifyService)
response = client.get("/api/admin/dify-models", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["embedding_models"][0]["model"] == "embed-a"
assert payload["rerank_models"][0]["model"] == "rerank-b"
assert payload["automatic_defaults"] == {
"embedding_model_provider": "provider-a",
"embedding_model": "embed-a",
"reranking_model_provider": "provider-b",
"reranking_model": "rerank-b",
}
def test_admin_endpoints_require_admin_and_job_list_scopes_by_user(client):
user_id = _create_user(username="viewer", password="viewer123", role="user", full_name="Viewer")
admin_id = _create_user(username="ops-admin", password="ops123456", role="admin", full_name="Ops Admin")
admin_headers = _headers(client)
user_headers = _headers(client, username="viewer", password="viewer123")
ops_headers = _headers(client, username="ops-admin", password="ops123456")
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"ops-scope-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
db.add(UserDepartmentAccess(user_id=admin_id, department_id=1))
db.add_all(
[
Job(
id=str(uuid.uuid4()),
job_type="convert",
status="success",
created_by_id=admin.id,
group_id=group.id,
payload={"owner": "admin"},
),
Job(
id=str(uuid.uuid4()),
job_type="sync",
status="queued",
created_by_id=user_id,
payload={"owner": "viewer"},
),
Job(
id=str(uuid.uuid4()),
job_type="sync",
status="queued",
created_by_id=admin_id,
group_id=group.id,
payload={"owner": "ops-admin"},
),
]
)
db.commit()
finally:
db.close()
forbidden_users = client.get("/api/admin/users", headers=user_headers)
forbidden_settings = client.get("/api/admin/settings", headers=user_headers)
allowed_user_admin = client.get("/api/admin/users", headers=ops_headers)
allowed_health_admin = client.get("/api/admin/dify-health", headers=ops_headers)
assert forbidden_users.status_code == 403
assert forbidden_settings.status_code == 403
assert allowed_user_admin.status_code == 200
assert allowed_health_admin.status_code == 200
admin_jobs = client.get("/api/jobs", headers=admin_headers)
assert admin_jobs.status_code == 200
assert len(admin_jobs.json()["data"]) == 3
user_jobs = client.get("/api/jobs", headers=user_headers)
assert user_jobs.status_code == 200
assert len(user_jobs.json()["data"]) == 1
assert user_jobs.json()["data"][0]["payload"] == {"owner": "viewer"}
ops_jobs = client.get("/api/jobs", headers=ops_headers)
assert ops_jobs.status_code == 200
assert len(ops_jobs.json()["data"]) == 2
def test_admin_dify_health_reads_snapshot_and_local_summary(client):
path = get_settings().data_root / "watchdog" / "dify-health.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(
{
"status": "ok",
"queue_lengths": {"priority_dataset": 1},
"worker": {"concurrency": 2},
}
),
encoding="utf-8",
)
_create_stale_syncing_document()
response = client.get("/api/admin/dify-health", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["watchdog_snapshot"]["worker"]["concurrency"] == 2
assert payload["local_convert_health"]["pending_versions"] == 0
assert payload["local_sync_health"]["stale_candidates"] == 1
assert payload["dify_api_configured"] is False
def test_admin_can_recover_stale_syncs(client):
version_id, job_id = _create_stale_syncing_document()
response = client.post("/api/admin/recover-stale-syncs", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["recovered_versions"] == 1
assert payload["recovered_jobs"] == 1
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
finally:
db.close()
def test_admin_can_recover_stale_converts(client, monkeypatch):
version_id, job_id = _create_stale_convert_document()
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set())
response = client.post("/api/admin/recover-stale-converts", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["recovered_versions"] == 1
assert payload["recovered_jobs"] == 1
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "failed"
assert job.status == "failed"
finally:
db.close()
-24
View File
@@ -1,24 +0,0 @@
from app.config import Settings
def test_settings_default_to_sqlite_when_no_database_url_override():
settings = Settings(database_url="", database_backend="sqlite")
assert settings.database_url == "sqlite:///./document_cleaning.db"
def test_settings_select_postgres_url_from_backend_choice():
settings = Settings(
database_url="",
database_backend="postgres",
postgres_database_url="postgresql://postgres:difyai123456@localhost:5432/doccleaning_db",
)
assert settings.database_url == "postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db"
def test_settings_keep_database_url_override_highest_priority():
settings = Settings(
database_backend="sqlite",
database_url="postgresql://postgres:difyai123456@localhost:5432/doccleaning_db",
sqlite_database_url="sqlite:///./other.db",
)
assert settings.database_url == "postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db"
-238
View File
@@ -1,238 +0,0 @@
from __future__ import annotations
import uuid
from pathlib import Path
from types import SimpleNamespace
from app.config import get_settings
from app.database import SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
from app.services.storage_service import version_dir
def _token(client, username: str = "admin", password: str = "admin123456"):
response = client.post("/api/auth/login", json={"username": username, "password": password})
return response.json()["access_token"]
def _headers(client, username: str = "admin", password: str = "admin123456"):
return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"}
def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, Path, Path, Path]:
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"delete-{uuid.uuid4().hex[:8]}", description="Delete coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
markdown_root = version_dir("markdown", group.id, document.id, 1)
assets_root = version_dir("assets", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
markdown_root.mkdir(parents=True, exist_ok=True)
assets_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / "manual.docx"
markdown_path = markdown_root / "document.md"
asset_path = assets_root / "img_001.png"
source_path.write_bytes(b"source")
markdown_path.write_text("# Manual", encoding="utf-8")
asset_path.write_bytes(b"png")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="manual.docx",
source_ext=".docx",
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
md_public_url="http://testserver/storage/markdown/document.md",
asset_dir=str(assets_root.relative_to(settings.data_root)),
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status="success",
sync_status="synced" if with_remote_sync else "unsynced",
)
db.add(version)
db.commit()
db.refresh(version)
if with_remote_sync:
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-001",
remote_document_id="remote-001",
status="synced",
)
)
db.commit()
return document.id, source_root, markdown_root, assets_root
finally:
db.close()
def test_delete_file_marks_document_deleted_and_enqueues_cleanup(client, monkeypatch):
document_id, source_root, markdown_root, assets_root = _seed_document_for_delete(with_remote_sync=False)
enqueue_calls: list[tuple[str, tuple[object, ...]]] = []
class FakeQueue:
def enqueue(self, task_name: str, *args, **kwargs):
enqueue_calls.append((task_name, args))
return SimpleNamespace(id="queued-delete-job")
monkeypatch.setattr("app.api.files.get_queue", lambda: FakeQueue())
response = client.delete(f"/api/files/{document_id}?delete_dify=false", headers=_headers(client))
assert response.status_code == 200
assert response.json() == {"deleted": True}
db = SessionLocal()
try:
document = db.query(Document).filter(Document.id == document_id).first()
job = db.query(Job).filter(Job.document_id == document_id, Job.job_type == "delete").first()
assert document is not None
assert job is not None
assert document.is_deleted is True
assert "__deleted__" in document.title
finally:
db.close()
assert enqueue_calls
assert enqueue_calls[0][0] == "app.tasks.run_delete_document_job"
assert enqueue_calls[0][1][1] == document_id
assert source_root.exists()
assert markdown_root.exists()
assert assets_root.exists()
def test_batch_markdown_download_returns_zip_file(client):
document_id, source_root, markdown_root, assets_root = _seed_document_for_delete(with_remote_sync=False)
response = client.post(
"/api/files/download-batch",
json={"document_ids": [document_id], "kind": "md"},
headers=_headers(client),
)
assert response.status_code == 200
assert "zip" in response.headers["content-type"]
assert len(response.content) > 0
def test_sync_endpoint_rejects_already_synced_current_version(client):
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"sync-{uuid.uuid4().hex[:8]}", description="Sync coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="already-synced", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
markdown_root = version_dir("markdown", group.id, document.id, 1)
markdown_root.mkdir(parents=True, exist_ok=True)
markdown_path = markdown_root / "document.md"
markdown_path.write_text("# Synced", encoding="utf-8")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="already-synced.docx",
source_ext=".docx",
source_path=str(settings.data_root / "tmp" / "already-synced.docx"),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add(version)
db.commit()
db.refresh(version)
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-001",
remote_document_id="remote-001",
status="synced",
)
)
db.commit()
file_id = document.id
finally:
db.close()
response = client.post(f"/api/files/{file_id}/sync-dify", headers=_headers(client))
assert response.status_code == 409
assert response.json()["detail"] == "Current version is already synced to Dify."
def test_sync_endpoint_rejects_current_version_already_syncing(client):
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"syncing-{uuid.uuid4().hex[:8]}", description="Sync coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="already-syncing", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
markdown_root = version_dir("markdown", group.id, document.id, 1)
markdown_root.mkdir(parents=True, exist_ok=True)
markdown_path = markdown_root / "document.md"
markdown_path.write_text("# Syncing", encoding="utf-8")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="already-syncing.docx",
source_ext=".docx",
source_path=str(settings.data_root / "tmp" / "already-syncing.docx"),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="syncing",
)
db.add(version)
db.commit()
db.refresh(version)
file_id = document.id
finally:
db.close()
response = client.post(f"/api/files/{file_id}/sync-dify", headers=_headers(client))
assert response.status_code == 409
assert response.json()["detail"] == "Current version is already syncing to Dify."
-266
View File
@@ -1,266 +0,0 @@
from __future__ import annotations
import uuid
from app.config import get_settings
from app.database import Base, SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, User
from app.services.storage_service import version_dir
def _integration_headers() -> dict[str, str]:
return {"X-Integration-Key": "integration-secret"}
def _seed_integration_document() -> tuple[int, int]:
settings = get_settings()
db = SessionLocal()
try:
Base.metadata.create_all(bind=db.get_bind())
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(
name=f"integration-group-{uuid.uuid4().hex[:8]}",
description="Integration coverage",
created_by_id=admin.id,
department_id=1,
dify_dataset_id="dataset-integration",
)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="integration-file", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
markdown_root = version_dir("markdown", group.id, document.id, 1)
assets_root = version_dir("assets", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
markdown_root.mkdir(parents=True, exist_ok=True)
assets_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / "integration-file.docx"
markdown_path = markdown_root / "document.md"
source_path.write_bytes(b"source")
markdown_path.write_text("# Integration", encoding="utf-8")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="integration-file.docx",
source_ext=".docx",
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
md_public_url=f"{settings.public_base_url}/storage/{markdown_path.relative_to(settings.data_root).as_posix()}",
asset_dir=str(assets_root.relative_to(settings.data_root)),
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add(version)
db.commit()
db.refresh(version)
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-integration",
remote_document_id="remote-integration",
status="synced",
)
)
db.commit()
return group.id, document.id
finally:
db.close()
def test_integration_api_requires_service_key(client):
response = client.get("/api/integration/knowledge-bases")
assert response.status_code == 401
def test_integration_api_requires_download_secret(client):
settings = get_settings()
previous_key = settings.integration_api_key
previous_secret = settings.integration_download_secret
settings.integration_api_key = "integration-secret"
settings.integration_download_secret = ""
try:
_seed_integration_document()
response = client.get("/api/integration/files/1", headers=_integration_headers())
assert response.status_code == 503
assert response.json()["detail"] == "Integration download secret is not configured."
finally:
settings.integration_api_key = previous_key
settings.integration_download_secret = previous_secret
def test_integration_api_lists_knowledge_bases_and_files(client, monkeypatch):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
group_id, document_id = _seed_integration_document()
knowledge_bases = client.get("/api/integration/knowledge-bases", headers=_integration_headers())
assert knowledge_bases.status_code == 200
kb_payload = knowledge_bases.json()["data"]
assert len(kb_payload) == 1
assert kb_payload[0]["id"] == group_id
assert kb_payload[0]["dify_dataset_id"] == "dataset-integration"
files = client.get(f"/api/integration/knowledge-bases/{group_id}/files", headers=_integration_headers())
assert files.status_code == 200
file_payload = files.json()["data"]
assert len(file_payload) == 1
assert file_payload[0]["document_id"] == document_id
assert file_payload[0]["source_filename"] == "integration-file.docx"
assert "/api/integration/download?version_id=" in file_payload[0]["source_download_url"]
assert file_payload[0]["markdown_download_url"] is not None
assert file_payload[0]["queried_at"] is not None
assert file_payload[0]["download_url_expires_at"] is not None
detail = client.get(f"/api/integration/files/{document_id}", headers=_integration_headers())
assert detail.status_code == 200
detail_payload = detail.json()
assert detail_payload["knowledge_base"]["id"] == group_id
assert detail_payload["dify"]["remote_document_id"] == "remote-integration"
finally:
settings.integration_api_key = previous_key
def test_integration_api_downloads_source_and_markdown(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
_, document_id = _seed_integration_document()
detail = client.get(f"/api/integration/files/{document_id}", headers=_integration_headers())
assert detail.status_code == 200
payload = detail.json()
source_download = client.get(payload["source_download_url"].replace("http://testserver", ""))
assert source_download.status_code == 200
assert "integration-file.docx" in source_download.headers["content-disposition"]
markdown_download = client.get(payload["markdown_download_url"].replace("http://testserver", ""))
assert markdown_download.status_code == 200
assert "integration-file.md" in markdown_download.headers["content-disposition"]
finally:
settings.integration_api_key = previous_key
def test_integration_api_can_lookup_local_file_by_dify_ids(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
group_id, document_id = _seed_integration_document()
response = client.get(
"/api/integration/dify-file?dataset_id=dataset-integration&remote_document_id=remote-integration",
headers=_integration_headers(),
)
assert response.status_code == 200
payload = response.json()
assert payload["document_id"] == document_id
assert payload["knowledge_base"]["id"] == group_id
assert payload["dify"]["dataset_id"] == "dataset-integration"
assert payload["dify"]["remote_document_id"] == "remote-integration"
assert "version_id=" in payload["source_download_url"]
finally:
settings.integration_api_key = previous_key
def test_integration_api_lookup_by_dify_ids_uses_matched_version_not_unsynced_current_version(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
_, document_id = _seed_integration_document()
db = SessionLocal()
try:
document = db.query(Document).filter(Document.id == document_id).first()
assert document is not None
current_version = document.versions[0]
current_version.is_current = False
new_root = version_dir("original", document.group_id, document.id, 2)
new_root.mkdir(parents=True, exist_ok=True)
new_source = new_root / "integration-file-v2.docx"
new_source.write_bytes(b"new-source")
new_version = DocumentVersion(
document_id=document.id,
version_no=2,
is_current=True,
source_filename="integration-file-v2.docx",
source_ext=".docx",
source_path=str(new_source),
source_sha256=uuid.uuid4().hex,
file_size=new_source.stat().st_size,
uploader_id=document.created_by_id,
convert_status="success",
sync_status="unsynced",
)
db.add(new_version)
db.commit()
finally:
db.close()
response = client.get(
"/api/integration/dify-file?dataset_id=dataset-integration&remote_document_id=remote-integration",
headers=_integration_headers(),
)
assert response.status_code == 200
payload = response.json()
assert payload["source_filename"] == "integration-file.docx"
assert payload["dify"]["remote_document_id"] == "remote-integration"
assert "version_id=1" in payload["source_download_url"]
finally:
settings.integration_api_key = previous_key
def test_integration_api_can_batch_resolve_by_dify_ids(client):
settings = get_settings()
previous_key = settings.integration_api_key
settings.integration_api_key = "integration-secret"
try:
_, document_id = _seed_integration_document()
response = client.post(
"/api/integration/dify-files/resolve",
headers=_integration_headers(),
json={
"items": [
{"dataset_id": "dataset-integration", "remote_document_id": "remote-integration"},
{"dataset_id": "dataset-integration", "remote_document_id": "remote-missing"},
{"remote_document_id": "remote-integration"},
]
},
)
assert response.status_code == 200
payload = response.json()["data"]
assert len(payload) == 3
assert payload[0]["request"]["remote_document_id"] == "remote-integration"
assert payload[0]["found"] is True
assert payload[0]["document"]["document_id"] == document_id
assert payload[1]["request"]["remote_document_id"] == "remote-missing"
assert payload[1]["found"] is False
assert payload[1]["document"] is None
assert payload[2]["request"]["dataset_id"] is None
assert payload[2]["found"] is True
assert payload[2]["document"]["dify"]["remote_document_id"] == "remote-integration"
finally:
settings.integration_api_key = previous_key
-937
View File
@@ -1,937 +0,0 @@
from __future__ import annotations
import base64
import uuid
from pathlib import Path
from types import SimpleNamespace
import pytest
import app.tasks as task_module
from app.config import get_settings
from app.database import SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
from app.services.dify_service import DifyError
from app.services.storage_service import version_dir
def _seed_document_version(
*,
source_filename: str = "policy.docx",
title: str = "policy",
convert_status: str = "queued",
sync_status: str = "unsynced",
markdown_text: str | None = None,
) -> tuple[int, int, int, int]:
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name=f"group-{uuid.uuid4().hex[:8]}", description="Task coverage", created_by_id=admin.id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title=title, created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / source_filename
source_path.write_bytes(b"source document")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename=source_filename,
source_ext=Path(source_filename).suffix.lower(),
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status=convert_status,
sync_status=sync_status,
)
db.add(version)
db.commit()
db.refresh(version)
if markdown_text is not None:
markdown_root = version_dir("markdown", group.id, document.id, version.version_no)
markdown_root.mkdir(parents=True, exist_ok=True)
markdown_path = markdown_root / "document.md"
markdown_path.write_text(markdown_text, encoding="utf-8")
version.md_path = str(markdown_path)
db.commit()
return group.id, document.id, version.id, admin.id
finally:
db.close()
def _seed_job(
*,
job_type: str,
group_id: int,
document_id: int,
version_id: int,
created_by_id: int,
) -> str:
db = SessionLocal()
try:
job = Job(
id=str(uuid.uuid4()),
job_type=job_type,
status="queued",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=created_by_id,
payload={},
)
db.add(job)
db.commit()
return job.id
finally:
db.close()
def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, int, int, int, Path, Path, Path]:
settings = get_settings()
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(
name=f"delete-{uuid.uuid4().hex[:8]}",
description="Delete coverage",
created_by_id=admin.id,
department_id=1,
)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=True)
db.add(document)
db.commit()
db.refresh(document)
source_root = version_dir("original", group.id, document.id, 1)
markdown_root = version_dir("markdown", group.id, document.id, 1)
assets_root = version_dir("assets", group.id, document.id, 1)
source_root.mkdir(parents=True, exist_ok=True)
markdown_root.mkdir(parents=True, exist_ok=True)
assets_root.mkdir(parents=True, exist_ok=True)
source_path = source_root / "manual.docx"
markdown_path = markdown_root / "document.md"
asset_path = assets_root / "img_001.png"
source_path.write_bytes(b"source")
markdown_path.write_text("# Manual", encoding="utf-8")
asset_path.write_bytes(b"png")
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="manual.docx",
source_ext=".docx",
source_path=str(source_path),
source_sha256=uuid.uuid4().hex,
md_path=str(markdown_path),
md_public_url="http://testserver/storage/markdown/document.md",
asset_dir=str(assets_root.relative_to(settings.data_root)),
file_size=source_path.stat().st_size,
uploader_id=admin.id,
convert_status="success",
sync_status="synced" if with_remote_sync else "unsynced",
)
db.add(version)
db.commit()
db.refresh(version)
if with_remote_sync:
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-001",
remote_document_id="remote-001",
status="synced",
)
)
db.commit()
return group.id, document.id, version.id, admin.id, source_root, markdown_root, assets_root
finally:
db.close()
def test_convert_job_success_updates_version_and_job(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version()
job_id = _seed_job(
job_type="convert",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
def fake_build_knowledge(source_path, output_dir, config, cache_dir):
generated_dir = output_dir / "generated"
generated_dir.mkdir(parents=True, exist_ok=True)
(generated_dir / "document.md").write_text("# Policy\n\nConverted content", encoding="utf-8")
return [{"status": "success"}]
monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge)
task_module.run_convert_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "success"
assert version.sync_status == "unsynced"
assert version.md_path is not None
assert Path(version.md_path).exists()
assert Path(version.md_path).read_text(encoding="utf-8") == "# Policy\n\nConverted content"
assert version.word_count == 4
assert version.warnings_json == [{"message": "embedded_images=0"}]
assert job.status == "success"
assert job.message == "Conversion completed"
assert job.result == {
"md_path": version.md_path,
"md_public_url": version.md_public_url,
"image_count": 0,
}
finally:
db.close()
def test_convert_job_success_rewrites_embedded_images_to_local_asset_urls(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version()
job_id = _seed_job(
job_type="convert",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
def fake_build_knowledge(source_path, output_dir, config, cache_dir):
generated_dir = output_dir / "generated"
generated_dir.mkdir(parents=True, exist_ok=True)
image_bytes = base64.b64encode(b"fake-image").decode("ascii")
markdown = f"# Policy\n\n![image-1](data:image/png;base64,{image_bytes})"
(generated_dir / "document.md").write_text(markdown, encoding="utf-8")
return [{"status": "success"}]
monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge)
task_module.run_convert_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
assert version is not None
assert version.asset_dir is not None
assert version.md_path is not None
markdown = Path(version.md_path).read_text(encoding="utf-8")
assert "http://testserver/storage/assets/" in markdown
assert "data:image" not in markdown
finally:
db.close()
def test_convert_job_failure_marks_job_and_version_failed(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version()
job_id = _seed_job(
job_type="convert",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object()))
monkeypatch.setattr(
task_module,
"build_knowledge",
lambda source_path, output_dir, config, cache_dir: [{"status": "failed", "error": "converter exploded"}],
)
with pytest.raises(RuntimeError, match="converter exploded"):
task_module.run_convert_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "failed"
assert version.failed_reason == "converter exploded"
assert job.status == "failed"
assert job.message == "Conversion failed"
assert job.error == "converter exploded"
finally:
db.close()
def test_sync_job_success_creates_sync_record_and_marks_document_synced(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
assert dataset_id == "dataset-001"
assert name == "policy"
assert "Ready for sync" in text
assert indexing_technique == "high_quality"
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
raise AssertionError("update_document_by_text should not be called for a first sync")
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert batch == "batch-001"
return {"indexing_status": "completed"}
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called when batch exists")
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
group = db.query(Group).filter(Group.id == group_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert group is not None
assert job is not None
assert group.dify_dataset_id == "dataset-001"
assert version.sync_status == "synced"
assert len(records) == 1
assert records[0].remote_document_id == "remote-001"
assert records[0].status == "synced"
assert records[0].last_indexing_status == "completed"
assert job.status == "success"
assert job.message == "Dify sync completed"
assert job.result == {
"dataset_id": "dataset-001",
"remote_document_id": "remote-001",
"batch": "batch-001",
"indexing_status": "completed",
}
finally:
db.close()
def test_sync_job_success_without_batch_waits_for_document_completion(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
assert dataset_id == "dataset-001"
assert name == "policy"
return {"document": {"id": "remote-001"}}
def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert document_id == "remote-001"
return {"indexing_status": "completed"}
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called directly in no-batch mode")
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
record = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).first()
assert version is not None
assert job is not None
assert record is not None
assert version.sync_status == "synced"
assert record.status == "synced"
assert record.batch is None
assert record.last_indexing_status == "completed"
assert job.status == "success"
finally:
db.close()
def test_sync_job_reuses_existing_no_batch_sync_record_and_waits_for_completion(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="syncing",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
db = SessionLocal()
try:
db.add(
DifySyncRecord(
version_id=version_id,
dataset_id="dataset-001",
remote_document_id="remote-existing",
batch=None,
status="syncing",
)
)
db.commit()
finally:
db.close()
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(self, **kwargs) -> dict:
raise AssertionError("create_document_by_text should not be called when an in-flight sync record exists")
def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert document_id == "remote-existing"
return {"indexing_status": "completed_with_warning"}
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
record = (
db.query(DifySyncRecord)
.filter(DifySyncRecord.version_id == version_id)
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
.first()
)
assert version is not None
assert job is not None
assert record is not None
assert version.sync_status == "synced"
assert record.status == "synced"
assert record.last_indexing_status == "completed_with_warning"
assert job.status == "success"
assert job.result["remote_document_id"] == "remote-existing"
finally:
db.close()
def test_delete_document_job_removes_local_storage_and_remote_dify_document(db_session, monkeypatch):
group_id, document_id, version_id, admin_id, source_root, markdown_root, assets_root = _seed_document_for_delete(
with_remote_sync=True
)
job_id = _seed_job(
job_type="delete",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
db = SessionLocal()
try:
job = db.query(Job).filter(Job.id == job_id).first()
assert job is not None
job.payload = {"delete_dify": True}
db.commit()
finally:
db.close()
delete_calls: list[tuple[str, str]] = []
class FakeDifyService:
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
delete_calls.append((dataset_id, document_id))
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_delete_document_job(job_id, document_id)
db = SessionLocal()
try:
job = db.query(Job).filter(Job.id == job_id).first()
assert job is not None
assert job.status == "success"
assert job.message == "Document delete completed"
assert job.result == {"deleted": True, "delete_dify": True, "remote_document_count": 1}
finally:
db.close()
assert delete_calls == [("dataset-001", "remote-001")]
assert not source_root.exists()
assert not markdown_root.exists()
assert not assets_root.exists()
def test_sync_job_failure_marks_existing_sync_record_failed(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
raise AssertionError("update_document_by_text should not be called for a first sync")
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
raise DifyError("Indexing failed with status=failed")
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
assert dataset_id == "dataset-001"
assert batch == "batch-001"
return [{"indexing_status": "failed", "display_status": "error"}]
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called when batch exists")
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
with pytest.raises(DifyError, match="status=failed"):
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert job is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
assert job.message == "Dify sync failed"
assert "status=failed" in job.error
assert len(records) == 1
assert records[0].status == "sync_failed"
assert "status=failed" in records[0].error
assert records[0].last_indexing_status == "failed"
finally:
db.close()
def test_sync_job_keeps_local_asset_urls_when_syncing_to_dify(db_session, monkeypatch):
local_asset_url = (
f"http://testserver/storage/assets/group_{1:04d}/document_{1:06d}/v001/img_001_deadbeef.jpg"
)
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text=f"# Policy\n\n![image-1]({local_asset_url})",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(self, *, dataset_id, name, text, doc_form, indexing_technique):
assert local_asset_url in text
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def wait_for_indexing(self, *, dataset_id, batch, timeout_seconds=300):
return {"indexing_status": "completed"}
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
task_module.run_sync_job(job_id, version_id)
def test_sync_job_recreates_remote_document_when_previous_sync_record_exists(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="sync_failed",
markdown_text="# Policy\n\nReady for resync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
db = SessionLocal()
try:
db.add(
DifySyncRecord(
version_id=version_id,
dataset_id="dataset-001",
remote_document_id="remote-old",
status="sync_failed",
)
)
db.commit()
finally:
db.close()
class FakeDifyService:
def __init__(self):
self.deleted: list[tuple[str, str]] = []
def ensure_dataset(self, **kwargs):
return "dataset-001"
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
self.deleted.append((dataset_id, document_id))
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
assert dataset_id == "dataset-001"
assert name == "policy"
assert "Ready for resync" in text
return {"document": {"id": "remote-new"}, "batch": "batch-new"}
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
raise AssertionError("update_document_by_text should not be called during resync")
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
assert dataset_id == "dataset-001"
assert batch == "batch-new"
return {"indexing_status": "completed"}
def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict:
raise AssertionError("get_document_detail should not be called when batch exists")
service = FakeDifyService()
monkeypatch.setattr(task_module, "DifyService", lambda: service)
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).order_by(DifySyncRecord.id).all()
assert version is not None
assert job is not None
assert version.sync_status == "synced"
assert service.deleted == [("dataset-001", "remote-old")]
assert len(records) == 2
assert records[-1].remote_document_id == "remote-new"
assert records[-1].status == "synced"
assert job.status == "success"
assert job.result == {
"dataset_id": "dataset-001",
"remote_document_id": "remote-new",
"batch": "batch-new",
"indexing_status": "completed",
}
finally:
db.close()
def test_sync_job_retryable_dify_error_requeues_instead_of_failing(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class SettingsStub:
task_execution_mode = "rq"
dify_sync_max_retries = 4
dify_sync_cooldown_seconds = 20
@staticmethod
def dify_sync_retry_delays():
return [15, 30, 60]
class FakeQueue:
def __init__(self):
self.calls: list[tuple[int, str, tuple]] = []
def enqueue_in(self, delay, task_name, *args, **kwargs):
self.calls.append((int(delay.total_seconds()), task_name, args))
return SimpleNamespace(id="rq-retry-1")
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
raise DifyError("FATAL: sorry, too many clients already")
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
return [{"indexing_status": "waiting", "display_status": "queuing"}]
queue = FakeQueue()
cooldowns: list[tuple[str, int]] = []
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
monkeypatch.setattr(task_module, "get_queue", lambda: queue)
monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub())
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0)
monkeypatch.setattr(task_module, "set_delay_gate", lambda name, ttl: cooldowns.append((name, ttl)))
task_module.run_sync_job(job_id, version_id)
assert queue.calls == [(15, "app.tasks.run_sync_job", (job_id, version_id))]
assert cooldowns == [(task_module.DIFY_SYNC_COOLDOWN_GATE, 20)]
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert job is not None
assert version.sync_status == "syncing"
assert job.status == "queued"
assert job.queue_job_id == "rq-retry-1"
assert job.payload["sync_retry_count"] == 1
assert job.payload["sync_retry_after_seconds"] == 15
assert "too many clients already" in job.payload["sync_last_error"]
assert job.message == "Dify busy, retrying in 15s (attempt 1/4)."
assert job.error is None
assert len(records) == 1
assert records[0].status == "syncing"
assert "too many clients already" in records[0].error
finally:
db.close()
def test_sync_job_retryable_dify_error_fails_cleanly_in_sync_mode(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="unsynced",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class SettingsStub:
task_execution_mode = "sync"
dify_sync_max_retries = 4
dify_sync_cooldown_seconds = 20
@staticmethod
def dify_sync_retry_delays():
return [15, 30, 60]
class FakeDifyService:
def ensure_dataset(self, **kwargs):
return "dataset-001"
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
doc_form: str,
indexing_technique: str,
) -> dict:
return {"document": {"id": "remote-001"}, "batch": "batch-001"}
def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict:
raise DifyError("FATAL: sorry, too many clients already")
def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]:
return [{"indexing_status": "waiting", "display_status": "queuing"}]
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub())
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0)
with pytest.raises(DifyError, match="too many clients already"):
task_module.run_sync_job(job_id, version_id)
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all()
assert version is not None
assert job is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
assert job.queue_job_id is None
assert job.error is not None and "too many clients already" in job.error
assert len(records) == 1
assert records[0].status == "sync_failed"
finally:
db.close()
def test_sync_job_defers_during_dify_cooldown_without_calling_dify(db_session, monkeypatch):
group_id, document_id, version_id, admin_id = _seed_document_version(
convert_status="success",
sync_status="syncing",
markdown_text="# Policy\n\nReady for sync",
)
job_id = _seed_job(
job_type="sync",
group_id=group_id,
document_id=document_id,
version_id=version_id,
created_by_id=admin_id,
)
class FakeQueue:
def __init__(self):
self.calls: list[tuple[int, str, tuple]] = []
def enqueue_in(self, delay, task_name, *args, **kwargs):
self.calls.append((int(delay.total_seconds()), task_name, args))
return SimpleNamespace(id="rq-retry-2")
invoked = {"count": 0}
class FakeDifyService:
def __init__(self):
invoked["count"] += 1
queue = FakeQueue()
monkeypatch.setattr(task_module, "DifyService", FakeDifyService)
monkeypatch.setattr(task_module, "get_queue", lambda: queue)
monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 45)
task_module.run_sync_job(job_id, version_id)
assert invoked["count"] == 0
assert queue.calls == [(45, "app.tasks.run_sync_job", (job_id, version_id))]
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.sync_status == "syncing"
assert job.status == "queued"
assert job.queue_job_id == "rq-retry-2"
assert job.message == "Dify cooldown active, retrying in 45s."
finally:
db.close()
-660
View File
@@ -1,660 +0,0 @@
from __future__ import annotations
from datetime import date, timedelta
from app.database import SessionLocal
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess
def _token(client):
response = client.post("/api/auth/login", json={"username": "admin", "password": "admin123456"})
return response.json()["access_token"]
def _headers(client):
return {"Authorization": f"Bearer {_token(client)}"}
def test_duplicate_upload_is_detected(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "quality", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
first = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
assert len(first.json()["created"]) == 1
second = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
assert len(second.json()["duplicates"]) == 1
def test_upload_rejects_more_than_500_files(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "bulk-limit", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", (f"sample-{index}.pdf", b"pdf", "application/pdf")) for index in range(501)]
response = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
assert response.status_code == 400
assert response.json()["detail"] == "Batch upload accepts at most 500 files at a time."
def test_same_title_creates_new_version(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "risk", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
first_file = [("files", ("policy.docx", b"abc", "application/octet-stream"))]
second_file = [("files", ("policy.docx", b"abcd", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=first_file, headers=_headers(client))
client.post("/api/files/upload", data=payload, files=second_file, headers=_headers(client))
db = SessionLocal()
try:
document = db.query(Document).filter(Document.group_id == 1, Document.title == "policy").first()
assert document is not None
versions = db.query(DocumentVersion).filter(DocumentVersion.document_id == document.id).all()
assert len(versions) == 2
finally:
db.close()
def test_group_rename_endpoint(client):
client.post("/api/groups", json={"name": "safety", "description": "", "department_id": 1}, headers=_headers(client))
response = client.patch("/api/groups/1", json={"name": "EHS", "rename_dify": False}, headers=_headers(client))
assert response.status_code == 200
assert response.json()["name"] == "EHS"
def test_group_name_can_repeat_in_different_departments(client):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
department = Department(name="second-dept", description="secondary")
db.add(department)
db.commit()
db.refresh(department)
db.add(UserDepartmentAccess(user_id=admin.id, department_id=department.id))
db.commit()
finally:
db.close()
first = client.post(
"/api/groups",
json={"name": "shared-name", "description": "", "department_id": 1},
headers=_headers(client),
)
assert first.status_code == 200
second = client.post(
"/api/groups",
json={"name": "shared-name", "description": "", "department_id": 2},
headers=_headers(client),
)
assert second.status_code == 200
assert second.json()["department_id"] == 2
def test_group_rename_returns_conflict_within_same_department(client):
first = client.post("/api/groups", json={"name": "dept-a", "description": "", "department_id": 1}, headers=_headers(client))
second = client.post("/api/groups", json={"name": "dept-b", "description": "", "department_id": 1}, headers=_headers(client))
assert first.status_code == 200
assert second.status_code == 200
response = client.patch("/api/groups/2", json={"name": "dept-a", "rename_dify": False}, headers=_headers(client))
assert response.status_code == 409
assert response.json()["detail"] == "Group already exists."
def test_group_delete_endpoint(client):
client.post("/api/groups", json={"name": "archive", "description": "", "department_id": 1}, headers=_headers(client))
response = client.delete("/api/groups/1", headers=_headers(client))
assert response.status_code == 200
listed = client.get("/api/groups", headers=_headers(client))
assert listed.status_code == 200
assert listed.json()["data"] == []
def test_group_delete_with_documents_and_dify(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
deleted = {}
def fake_delete_dataset(self, *, dataset_id: str):
deleted["dataset_id"] = dataset_id
monkeypatch.setattr("app.api.groups.DifyService.delete_dataset", fake_delete_dataset)
client.post("/api/groups", json={"name": "cleanup", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
db = SessionLocal()
try:
group = db.query(Document).filter(Document.group_id == 1).first().group
group.dify_dataset_id = "dataset-123"
job = db.query(Job).filter(Job.group_id == 1).first()
job.status = "success"
db.commit()
finally:
db.close()
response = client.delete("/api/groups/1?delete_dify=true", headers=_headers(client))
assert response.status_code == 200
assert deleted["dataset_id"] == "dataset-123"
db = SessionLocal()
try:
assert db.query(Document).count() == 0
finally:
db.close()
def test_group_delete_rejects_running_jobs(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "active", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
response = client.delete("/api/groups/1", headers=_headers(client))
assert response.status_code == 409
def test_group_list_includes_document_count(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "filled", "description": "", "department_id": 1}, headers=_headers(client))
client.post("/api/groups", json={"name": "empty", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
response = client.get("/api/groups", headers=_headers(client))
assert response.status_code == 200
counts = {item["name"]: item["document_count"] for item in response.json()["data"]}
assert counts["filled"] == 1
assert counts["empty"] == 0
def test_group_dify_diff_reports_local_remote_and_attention(client, monkeypatch):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name="diff-group", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-123")
db.add(group)
db.commit()
db.refresh(group)
local_only = Document(group_id=group.id, title="local only", created_by_id=admin.id, is_deleted=False)
attention = Document(group_id=group.id, title="attention", created_by_id=admin.id, is_deleted=False)
synced = Document(group_id=group.id, title="matched", created_by_id=admin.id, is_deleted=False)
db.add_all([local_only, attention, synced])
db.commit()
db.refresh(local_only)
db.refresh(attention)
db.refresh(synced)
local_only_version = DocumentVersion(
document_id=local_only.id,
version_no=1,
is_current=True,
source_filename="local only.docx",
source_ext=".docx",
source_path="local-only.docx",
source_sha256="hash-local",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="unsynced",
)
attention_version = DocumentVersion(
document_id=attention.id,
version_no=1,
is_current=True,
source_filename="attention.docx",
source_ext=".docx",
source_path="attention.docx",
source_sha256="hash-attention",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="sync_failed",
)
synced_version = DocumentVersion(
document_id=synced.id,
version_no=1,
is_current=True,
source_filename="matched.docx",
source_ext=".docx",
source_path="matched.docx",
source_sha256="hash-matched",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add_all([local_only_version, attention_version, synced_version])
db.commit()
db.refresh(attention_version)
db.refresh(synced_version)
db.add_all(
[
DifySyncRecord(
version_id=attention_version.id,
dataset_id="dataset-123",
remote_document_id="remote-attention",
status="sync_failed",
),
DifySyncRecord(
version_id=synced_version.id,
dataset_id="dataset-123",
remote_document_id="remote-matched",
status="synced",
),
]
)
db.commit()
finally:
db.close()
class FakeRemote:
def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True):
self.id = document_id
self.name = name
self.indexing_status = indexing_status
self.display_status = display_status
self.enabled = enabled
class FakeDifyService:
def list_documents(self, *, dataset_id: str, limit: int = 100):
assert dataset_id == "dataset-123"
assert limit == 100
return [
FakeRemote("remote-attention", "attention", "indexing"),
FakeRemote("remote-matched", "matched", "completed"),
FakeRemote("remote-only", "remote only", "completed"),
]
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.get("/api/groups/1/dify-diff", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 1, "attention": 1}
rows = {row["display_name"]: row for row in payload["rows"]}
assert rows["local only"]["status"] == "local_only"
assert rows["remote only"]["status"] == "dify_only"
assert rows["attention"]["status"] == "attention"
assert rows["matched"]["status"] == "matched"
def test_group_dify_diff_keeps_multiple_remote_documents_with_same_stem(client, monkeypatch):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
group = Group(name="duplicate-stem", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-stem")
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="policy", created_by_id=admin.id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="policy.docx",
source_ext=".docx",
source_path="policy.docx",
source_sha256="hash-policy",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add(version)
db.commit()
db.refresh(version)
db.add(
DifySyncRecord(
version_id=version.id,
dataset_id="dataset-stem",
remote_document_id="remote-policy-docx",
status="synced",
)
)
db.commit()
finally:
db.close()
class FakeRemote:
def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True):
self.id = document_id
self.name = name
self.indexing_status = indexing_status
self.display_status = display_status
self.enabled = enabled
class FakeDifyService:
def list_documents(self, *, dataset_id: str, limit: int = 100):
assert dataset_id == "dataset-stem"
return [
FakeRemote("remote-policy-docx", "policy.docx", "completed"),
FakeRemote("remote-policy-pdf", "policy.pdf", "completed"),
]
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.get("/api/groups/1/dify-diff", headers=_headers(client))
assert response.status_code == 200
payload = response.json()
assert payload["summary"] == {"matched": 1, "local_only": 0, "dify_only": 1, "attention": 0}
assert len(payload["rows"]) == 2
rows = {(row["display_name"], row["status"]) for row in payload["rows"]}
assert ("policy", "matched") in rows
assert ("policy.pdf", "dify_only") in rows
def test_global_dashboard_summary_and_dify_diff(client, monkeypatch):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
blocked_department = Department(name="blocked-global", description="hidden")
db.add(blocked_department)
db.commit()
db.refresh(blocked_department)
linked_group = Group(name="kb-linked", description="", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-linked")
local_only_group = Group(name="kb-local", description="", created_by_id=admin.id, department_id=1)
hidden_group = Group(
name="kb-hidden",
description="",
created_by_id=admin.id,
department_id=blocked_department.id,
dify_dataset_id="dataset-hidden",
)
db.add_all([linked_group, local_only_group, hidden_group])
db.commit()
db.refresh(linked_group)
db.refresh(local_only_group)
db.refresh(hidden_group)
linked_document = Document(group_id=linked_group.id, title="alpha", created_by_id=admin.id, is_deleted=False)
running_document = Document(group_id=local_only_group.id, title="beta", created_by_id=admin.id, is_deleted=False)
hidden_document = Document(group_id=hidden_group.id, title="secret", created_by_id=admin.id, is_deleted=False)
db.add_all([linked_document, running_document, hidden_document])
db.commit()
db.refresh(linked_document)
db.refresh(running_document)
db.refresh(hidden_document)
linked_version = DocumentVersion(
document_id=linked_document.id,
version_no=1,
is_current=True,
source_filename="alpha.docx",
source_ext=".docx",
source_path="alpha.docx",
source_sha256="hash-alpha",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
running_version = DocumentVersion(
document_id=running_document.id,
version_no=1,
is_current=True,
source_filename="beta.docx",
source_ext=".docx",
source_path="beta.docx",
source_sha256="hash-beta",
file_size=1,
uploader_id=admin.id,
convert_status="running",
sync_status="unsynced",
)
hidden_version = DocumentVersion(
document_id=hidden_document.id,
version_no=1,
is_current=True,
source_filename="secret.docx",
source_ext=".docx",
source_path="secret.docx",
source_sha256="hash-secret",
file_size=1,
uploader_id=admin.id,
convert_status="success",
sync_status="synced",
)
db.add_all([linked_version, running_version, hidden_version])
db.commit()
db.refresh(linked_version)
db.refresh(hidden_version)
db.add_all(
[
DifySyncRecord(
version_id=linked_version.id,
dataset_id="dataset-linked",
remote_document_id="remote-alpha",
status="synced",
),
DifySyncRecord(
version_id=hidden_version.id,
dataset_id="dataset-hidden",
remote_document_id="remote-secret",
status="synced",
),
]
)
db.commit()
finally:
db.close()
class FakeDataset:
def __init__(self, dataset_id: str, name: str):
self.id = dataset_id
self.name = name
class FakeRemote:
def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True):
self.id = document_id
self.name = name
self.indexing_status = indexing_status
self.display_status = display_status
self.enabled = enabled
class FakeDifyService:
def list_datasets(self):
return [
FakeDataset("dataset-linked", "kb-linked"),
FakeDataset("dataset-hidden", "kb-hidden"),
FakeDataset("dataset-remote", "kb-remote"),
]
def list_documents(self, *, dataset_id: str, limit: int = 100):
if dataset_id == "dataset-linked":
return [FakeRemote("remote-alpha", "alpha", "completed")]
if dataset_id == "dataset-hidden":
return [FakeRemote("remote-secret", "secret", "completed")]
if dataset_id == "dataset-remote":
return [FakeRemote("remote-gamma", "gamma", "completed")]
return []
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
summary_response = client.get("/api/groups/summary", headers=_headers(client))
assert summary_response.status_code == 200
assert summary_response.json() == {
"knowledge_base_count": 2,
"file_count": 2,
"running_count": 1,
}
diff_response = client.get("/api/groups/dify-diff-global", headers=_headers(client))
assert diff_response.status_code == 200
payload = diff_response.json()
assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 0, "attention": 0}
rows = {(row["knowledge_base"]["name"], row["display_name"]): row for row in payload["rows"]}
assert rows[("kb-linked", "alpha")]["status"] == "matched"
assert rows[("kb-local", "beta")]["status"] == "local_only"
assert ("kb-remote", "gamma") not in rows
assert ("kb-hidden", "secret") not in rows
def test_import_dify_document_into_existing_group(client, monkeypatch):
client.post("/api/groups", json={"name": "imports", "description": "", "department_id": 1}, headers=_headers(client))
class FakeSegment:
def __init__(self, content: str, position: int):
self.content = content
self.position = position
class FakeDifyService:
def get_document_detail(self, *, dataset_id: str, document_id: str):
assert dataset_id == "dataset-import"
assert document_id == "remote-1"
return {"name": "policy.docx", "indexing_status": "completed"}
def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100):
assert limit == 100
return [FakeSegment("hello world", 1), FakeSegment("from dify", 2)]
def get_upload_file(self, *, dataset_id: str, document_id: str):
return None
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.post(
"/api/groups/import-dify-document",
json={
"group_id": 1,
"dataset_id": "dataset-import",
"remote_document_id": "remote-1",
"knowledge_base_name": "imports",
},
headers=_headers(client),
)
assert response.status_code == 200
payload = response.json()
assert payload["group_id"] == 1
assert payload["document"]["title"] == "policy"
assert payload["document"]["current_version"]["sync_status"] == "synced"
assert payload["document"]["current_version"]["convert_status"] == "success"
assert payload["document"]["current_version"]["source_ext"] == ".md"
db = SessionLocal()
try:
group = db.query(Group).filter(Group.id == 1).first()
assert group is not None
assert group.dify_dataset_id == "dataset-import"
sync_record = db.query(DifySyncRecord).first()
assert sync_record is not None
assert sync_record.remote_document_id == "remote-1"
assert sync_record.status == "synced"
finally:
db.close()
def test_import_dify_document_creates_group_for_remote_only_dataset(client, monkeypatch):
class FakeSegment:
def __init__(self, content: str, position: int):
self.content = content
self.position = position
class FakeDifyService:
def get_document_detail(self, *, dataset_id: str, document_id: str):
assert dataset_id == "dataset-remote-only"
return {"name": "remote-only.md", "indexing_status": "completed"}
def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100):
return [FakeSegment("# Remote\n\nbody", 1)]
def get_upload_file(self, *, dataset_id: str, document_id: str):
return None
monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService)
response = client.post(
"/api/groups/import-dify-document",
json={
"dataset_id": "dataset-remote-only",
"remote_document_id": "remote-doc",
"knowledge_base_name": "remote-only-kb",
},
headers=_headers(client),
)
assert response.status_code == 200
payload = response.json()
assert payload["group_name"] == "remote-only-kb"
assert payload["document"]["title"] == "remote-only"
db = SessionLocal()
try:
group = db.query(Group).filter(Group.name == "remote-only-kb").first()
assert group is not None
document = db.query(Document).filter(Document.group_id == group.id, Document.title == "remote-only").first()
assert document is not None
finally:
db.close()
def test_import_dify_document_requires_department_when_admin_has_no_primary_department(client):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin.primary_department_id = None
db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id).delete()
db.commit()
finally:
db.close()
response = client.post(
"/api/groups/import-dify-document",
json={
"dataset_id": "dataset-remote-only",
"remote_document_id": "remote-doc",
"knowledge_base_name": "remote-only-kb",
},
headers=_headers(client),
)
assert response.status_code == 400
assert response.json()["detail"] == "Department is required for Dify import."
def test_group_files_include_uploader_and_date_filter(client, monkeypatch):
monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job)
client.post("/api/groups", json={"name": "ops", "description": "", "department_id": 1}, headers=_headers(client))
payload = {"group_id": "1"}
files = [("files", ("sample.docx", b"abc", "application/octet-stream"))]
client.post("/api/files/upload", data=payload, files=files, headers=_headers(client))
baseline = client.get("/api/groups/1/files", headers=_headers(client))
assert baseline.status_code == 200
uploaded_at = baseline.json()["data"][0]["current_version"]["uploaded_at"]
actual_date = uploaded_at.split("T")[0]
tomorrow = (date.fromisoformat(actual_date) + timedelta(days=1)).isoformat()
listed = client.get(
f"/api/groups/1/files?uploaded_from={actual_date}&uploaded_to={actual_date}&file_type=.docx",
headers=_headers(client),
)
assert listed.status_code == 200
row = listed.json()["data"][0]
assert row["current_version"]["uploaded_by"]["username"] == "admin"
future = client.get(f"/api/groups/1/files?uploaded_from={tomorrow}", headers=_headers(client))
assert future.status_code == 200
assert future.json()["data"] == []
-254
View File
@@ -1,254 +0,0 @@
from __future__ import annotations
import json
import uuid
from datetime import timedelta
from app.config import get_settings
from app.database import SessionLocal
from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User
from app.services.watchdog_service import (
local_convert_health_summary,
local_sync_health_summary,
read_watchdog_snapshot,
recover_stale_converts,
recover_stale_syncs,
)
from app.time_utils import utc_now
def _seed_stale_sync_version():
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"watchdog-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="watchdog-policy", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="watchdog.docx",
source_ext=".docx",
source_path="/tmp/watchdog.docx",
source_sha256=uuid.uuid4().hex,
file_size=2048,
uploader_id=admin_id,
convert_status="success",
sync_status="syncing",
)
db.add(version)
db.commit()
db.refresh(version)
old_time = utc_now() - timedelta(minutes=20)
job = Job(
id=str(uuid.uuid4()),
job_type="sync",
status="running",
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
started_at=old_time,
message="Syncing document to Dify",
)
db.add(job)
db.commit()
record = DifySyncRecord(
version_id=version.id,
dataset_id="dataset-watchdog",
remote_document_id="remote-watchdog",
batch="batch-watchdog",
status="syncing",
created_at=old_time,
updated_at=old_time,
)
db.add(record)
db.commit()
return version.id, job.id, record.id
finally:
db.close()
def _seed_stale_convert_version(*, queue_job_id: str | None = "rq-convert-stale", status: str = "queued"):
db = SessionLocal()
try:
admin = db.query(User).filter(User.username == "admin").first()
assert admin is not None
admin_id = admin.id
group = Group(name=f"convert-watchdog-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1)
db.add(group)
db.commit()
db.refresh(group)
document = Document(group_id=group.id, title="convert-watchdog", created_by_id=admin_id, is_deleted=False)
db.add(document)
db.commit()
db.refresh(document)
old_time = utc_now() - timedelta(minutes=20)
version = DocumentVersion(
document_id=document.id,
version_no=1,
is_current=True,
source_filename="convert-watchdog.docx",
source_ext=".docx",
source_path="/tmp/convert-watchdog.docx",
source_sha256=uuid.uuid4().hex,
file_size=1024,
uploader_id=admin_id,
convert_status=status,
sync_status="unsynced",
uploaded_at=old_time,
)
db.add(version)
db.commit()
db.refresh(version)
job = Job(
id=str(uuid.uuid4()),
job_type="convert",
status=status,
queue_job_id=queue_job_id,
group_id=group.id,
document_id=document.id,
version_id=version.id,
created_by_id=admin_id,
created_at=old_time,
started_at=old_time if status == "running" else None,
message="Converting source document",
)
db.add(job)
db.commit()
return version.id, job.id
finally:
db.close()
def test_recover_stale_syncs_marks_versions_jobs_and_records_failed(db_session):
version_id, job_id, record_id = _seed_stale_sync_version()
db = SessionLocal()
try:
result = recover_stale_syncs(db, timeout_seconds=900)
assert result["recovered_versions"] == 1
assert result["recovered_jobs"] == 1
assert result["recovered_records"] == 1
finally:
db.close()
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
record = db.query(DifySyncRecord).filter(DifySyncRecord.id == record_id).first()
assert version is not None
assert job is not None
assert record is not None
assert version.sync_status == "sync_failed"
assert job.status == "failed"
assert "watchdog timeout" in (job.error or "")
assert record.status == "sync_failed"
assert "watchdog timeout" in (record.error or "")
finally:
db.close()
def test_local_sync_health_summary_reports_stale_candidates(db_session):
_seed_stale_sync_version()
db = SessionLocal()
try:
payload = local_sync_health_summary(db, timeout_seconds=900)
assert payload["syncing_versions"] == 1
assert payload["active_sync_jobs"] == 1
assert payload["stale_candidates"] == 1
assert payload["stale_versions"][0]["remote_document_id"] == "remote-watchdog"
finally:
db.close()
def test_recover_stale_converts_marks_versions_and_jobs_failed_when_queue_job_is_missing(db_session, monkeypatch):
version_id, job_id = _seed_stale_convert_version()
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set())
db = SessionLocal()
try:
result = recover_stale_converts(db, timeout_seconds=900, orphan_grace_seconds=120)
assert result["recovered_versions"] == 1
assert result["recovered_jobs"] == 1
finally:
db.close()
db = SessionLocal()
try:
version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first()
job = db.query(Job).filter(Job.id == job_id).first()
assert version is not None
assert job is not None
assert version.convert_status == "failed"
assert "watchdog" in (version.failed_reason or "")
assert job.status == "failed"
assert "missing from Redis queue" in (job.error or "")
finally:
db.close()
def test_local_convert_health_summary_reports_stale_candidates(db_session, monkeypatch):
_seed_stale_convert_version()
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set())
db = SessionLocal()
try:
payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120)
assert payload["pending_versions"] == 1
assert payload["active_convert_jobs"] == 1
assert payload["stale_candidates"] == 1
assert payload["stale_versions"][0]["reason"].startswith("Convert job is missing")
finally:
db.close()
def test_local_convert_health_summary_keeps_live_queue_jobs_out_of_stale_candidates(db_session, monkeypatch):
_seed_stale_convert_version(queue_job_id="rq-convert-live")
monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: {"rq-convert-live"})
db = SessionLocal()
try:
payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120)
assert payload["pending_versions"] == 1
assert payload["stale_candidates"] == 0
finally:
db.close()
def test_read_watchdog_snapshot_reads_json_from_data_root(db_session):
path = get_settings().data_root / "watchdog" / "dify-health.json"
path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"status": "ok",
"worker": {"concurrency": 2},
"queue_lengths": {"priority_dataset": 0},
}
path.write_text(json.dumps(payload), encoding="utf-8")
loaded = read_watchdog_snapshot()
assert loaded is not None
assert loaded["available"] is True
assert loaded["worker"]["concurrency"] == 2
-14
View File
@@ -1,14 +0,0 @@
from redis import Redis
from rq import Worker
from app.config import get_settings
settings = get_settings()
if __name__ == "__main__":
connection = Redis.from_url(settings.redis_url)
worker = Worker([settings.rq_queue_name], connection=connection)
worker.work()
-101
View File
@@ -1,101 +0,0 @@
services:
postgres:
image: postgres:17-alpine
container_name: doc-cleaning-postgres
restart: always
environment:
POSTGRES_DB: document_cleaning
POSTGRES_USER: document_cleaning
POSTGRES_PASSWORD: document_cleaning
volumes:
- doc_cleaning_pg:/var/lib/postgresql/data
networks:
- doc-cleaning
redis:
image: redis:7-alpine
container_name: doc-cleaning-redis
restart: always
networks:
- doc-cleaning
api:
build:
context: ./backend
dockerfile: Dockerfile
container_name: doc-cleaning-api
restart: always
environment:
DATABASE_BACKEND: ${DATABASE_BACKEND:-postgres}
DATABASE_URL: ${DATABASE_URL:-}
SQLITE_DATABASE_URL: ${SQLITE_DATABASE_URL:-sqlite:///./document_cleaning.db}
POSTGRES_DATABASE_URL: ${POSTGRES_DATABASE_URL:-postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning}
REDIS_URL: redis://redis:6379/0
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://192.168.100.230:8891}
DIFY_BASE_URL: ${DIFY_BASE_URL:-https://api.dify.ai/v1}
DIFY_API_KEY: ${DIFY_API_KEY:-}
INTEGRATION_API_KEY: ${INTEGRATION_API_KEY:-}
INTEGRATION_DOWNLOAD_SECRET: ${INTEGRATION_DOWNLOAD_SECRET:-}
JWT_SECRET: ${JWT_SECRET:-change-me}
DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME:-admin}
DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-admin123456}
TASK_EXECUTION_MODE: ${TASK_EXECUTION_MODE:-rq}
depends_on:
- postgres
- redis
volumes:
- doc_cleaning_data:/app/data
networks:
- doc-cleaning
worker:
build:
context: ./backend
dockerfile: Dockerfile
container_name: doc-cleaning-worker
restart: always
command: ["python", "worker.py"]
environment:
DATABASE_BACKEND: ${DATABASE_BACKEND:-postgres}
DATABASE_URL: ${DATABASE_URL:-}
SQLITE_DATABASE_URL: ${SQLITE_DATABASE_URL:-sqlite:///./document_cleaning.db}
POSTGRES_DATABASE_URL: ${POSTGRES_DATABASE_URL:-postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning}
REDIS_URL: redis://redis:6379/0
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://192.168.100.230:8891}
DIFY_BASE_URL: ${DIFY_BASE_URL:-https://api.dify.ai/v1}
DIFY_API_KEY: ${DIFY_API_KEY:-}
INTEGRATION_API_KEY: ${INTEGRATION_API_KEY:-}
INTEGRATION_DOWNLOAD_SECRET: ${INTEGRATION_DOWNLOAD_SECRET:-}
JWT_SECRET: ${JWT_SECRET:-change-me}
DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME:-admin}
DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-admin123456}
TASK_EXECUTION_MODE: ${TASK_EXECUTION_MODE:-rq}
depends_on:
- postgres
- redis
volumes:
- doc_cleaning_data:/app/data
networks:
- doc-cleaning
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
container_name: doc-cleaning-frontend
restart: always
depends_on:
- api
ports:
- "8891:80"
networks:
- doc-cleaning
networks:
doc-cleaning:
name: doc-cleaning
driver: bridge
volumes:
doc_cleaning_pg:
doc_cleaning_data:
-13
View File
@@ -1,13 +0,0 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
-13
View File
@@ -1,13 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document Cleaning</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
-43
View File
@@ -1,43 +0,0 @@
server {
listen 80;
server_name _;
resolver 127.0.0.11 ipv6=off valid=10s;
client_max_body_size 200m;
root /usr/share/nginx/html;
index index.html;
location /api/ {
set $api_upstream api:8000;
proxy_pass http://$api_upstream$request_uri;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /storage/ {
set $api_upstream api:8000;
proxy_pass http://$api_upstream$request_uri;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /index.html {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always;
add_header Pragma "no-cache" always;
add_header Expires "0" always;
try_files $uri =404;
}
location / {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always;
add_header Pragma "no-cache" always;
add_header Expires "0" always;
try_files $uri $uri/ /index.html;
}
}
-2668
View File
File diff suppressed because it is too large. Load diff
-29
View File
@@ -1,29 +0,0 @@
{
"name": "document-cleaning-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@uppy/core": "^4.5.2",
"@uppy/dashboard": "^4.4.2",
"@uppy/xhr-upload": "^4.3.3",
"vue": "^3.5.25",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@types/node": "^24.10.1",
"@vitejs/plugin-vue": "^6.0.2",
"@vue/tsconfig": "^0.8.1",
"autoprefixer": "^10.4.24",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "~5.9.3",
"vite": "^8.0.0-beta.13",
"vue-tsc": "^3.1.5"
}
}
-7
View File
@@ -1,7 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
}
-5
View File
@@ -1,5 +0,0 @@
<template>
<div class="app-shell">
<router-view />
</div>
</template>
@@ -1,359 +0,0 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { apiFetch } from '@/lib/api'
import { localeCode, useI18n } from '@/lib/i18n'
type WatchdogTask = {
id: string
name: string
runtime_seconds?: number | null
delivery_info?: {
routing_key?: string | null
} | null
}
type WatchdogAction = {
type: string
at?: string | null
reason?: string | null
}
type WatchdogSnapshot = {
available?: boolean
status?: string
checked_at?: string | null
last_restart_at?: string | null
worker?: {
online?: boolean
command?: string | null
concurrency?: number | null
} | null
api?: {
configured?: boolean
reachable?: boolean
base_url?: string | null
dataset_count?: number | null
error?: string | null
} | null
queue_lengths?: Record<string, number>
shared_postgres?: {
available?: boolean
max_connections?: number | null
active_connections?: number | null
usage_ratio?: number | null
error?: string | null
} | null
active_tasks?: WatchdogTask[]
reserved_tasks?: WatchdogTask[]
actions?: WatchdogAction[]
issues?: string[]
} | null
type LocalSyncHealth = {
timeout_seconds: number
syncing_versions: number
sync_failed_versions: number
active_sync_jobs: number
stale_candidates: number
active_jobs: Array<{ id: string }>
recent_failures: Array<{ id: string }>
stale_versions: Array<{
document_id: number
version_id: number
age_seconds: number
reason: string
}>
}
type DifyHealthPayload = {
dify_base_url: string
dify_api_configured: boolean
watchdog_snapshot: WatchdogSnapshot
local_sync_health: LocalSyncHealth
}
const props = defineProps<{
open: boolean
}>()
const emit = defineEmits<{
close: []
toast: [message: string]
error: [message: string]
}>()
const { locale, t } = useI18n()
const loading = ref(false)
const recoveryBusy = ref(false)
const payload = ref<DifyHealthPayload | null>(null)
const snapshot = computed(() => payload.value?.watchdog_snapshot || null)
const localHealth = computed<LocalSyncHealth>(() => {
return (
payload.value?.local_sync_health || {
timeout_seconds: 0,
syncing_versions: 0,
sync_failed_versions: 0,
active_sync_jobs: 0,
stale_candidates: 0,
active_jobs: [],
recent_failures: [],
stale_versions: [],
}
)
})
const queueEntries = computed(() => Object.entries(snapshot.value?.queue_lengths || {}))
const totalPending = computed(() => queueEntries.value.reduce((sum, [, count]) => sum + count, 0))
const activeTasks = computed(() => snapshot.value?.active_tasks || [])
const watchdogIssues = computed(() => snapshot.value?.issues || [])
const watchdogActions = computed(() => snapshot.value?.actions || [])
const sharedPostgres = computed(() => snapshot.value?.shared_postgres || null)
const sharedPostgresUsagePercent = computed(() => {
const ratio = sharedPostgres.value?.usage_ratio
if (typeof ratio !== 'number' || Number.isNaN(ratio)) return null
return Math.round(ratio * 100)
})
const sharedPostgresUsageLabel = computed(() => {
if (!sharedPostgres.value?.available) return t('admin.sharedPostgresUnavailable')
if (sharedPostgresUsagePercent.value === null) return '--'
return `${sharedPostgresUsagePercent.value}%`
})
const sharedPostgresUsageHint = computed(() => {
if (!sharedPostgres.value?.available) return sharedPostgres.value?.error || t('common.none')
return `${sharedPostgres.value?.active_connections ?? '--'} / ${sharedPostgres.value?.max_connections ?? '--'}`
})
const healthGuide = computed(() => {
if (locale.value === 'zh') {
return [
{ label: 'Watchdog 状态', text: '表示服务器自动巡检和自愈最近一次执行的结果。' },
{ label: 'Dify API', text: '表示当前系统能否访问 Dify 接口。' },
{ label: 'Worker 并发', text: '表示 Dify 后台当前最多能同时处理多少个任务。' },
{ label: '待处理队列', text: '表示 Dify 队列里还未被消费的任务总量。' },
{ label: '卡住同步', text: '表示本地已经卡住、等待回收的同步记录数量。' },
{ label: '本地同步健康', text: '表示本地同步中、失败和卡住候选的汇总情况。' },
]
}
return [
{ label: 'Watchdog Status', text: 'Latest self-healing result from the watchdog.' },
{ label: 'Dify API', text: 'Whether this system can reach the Dify API.' },
{ label: 'Worker Concurrency', text: 'How many Dify background jobs can run at the same time.' },
{ label: 'Pending Queue', text: 'How many jobs are still waiting inside Dify queues.' },
{ label: 'Stuck Syncs', text: 'How many local sync records are stuck and waiting to be reclaimed.' },
{ label: 'Local Sync Health', text: 'Overview of local syncing, failures, and stale candidates.' },
]
})
function close() {
emit('close')
}
function formatDate(value?: string | null) {
if (!value) return t('common.none')
return new Date(value).toLocaleString(localeCode(locale.value))
}
function formatRuntime(seconds?: number | null) {
if (!seconds || seconds < 1) return '0s'
if (seconds < 60) return `${seconds}s`
const minutes = Math.floor(seconds / 60)
const remain = seconds % 60
return `${minutes}m ${remain}s`
}
function statusLabel(status?: string | null) {
switch (status) {
case 'ok':
return t('admin.statusOk')
case 'restarted':
return t('admin.statusRestarted')
case 'warning':
return t('admin.statusWarning')
default:
return t('admin.healthUnavailable')
}
}
async function loadHealth() {
loading.value = true
try {
payload.value = await apiFetch('/api/admin/dify-health')
} catch (err) {
emit('error', err instanceof Error ? err.message : t('admin.failedToLoadDifyHealth'))
} finally {
loading.value = false
}
}
async function recoverStuckSyncs() {
recoveryBusy.value = true
try {
const result = await apiFetch('/api/admin/recover-stale-syncs', { method: 'POST' })
const message =
result.recovered_versions > 0
? t('admin.staleSyncRecovered', { count: result.recovered_versions })
: t('admin.noStaleSyncsFound')
emit('toast', message)
await loadHealth()
} catch (err) {
emit('error', err instanceof Error ? err.message : t('admin.failedToRecoverStaleSyncs'))
} finally {
recoveryBusy.value = false
}
}
watch(
() => props.open,
(open) => {
if (open) {
void loadHealth()
}
}
)
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="close"
>
<div class="panel w-full max-w-6xl px-6 py-6" @click.stop>
<div class="flex items-start justify-between gap-4">
<div>
<p class="text-xs font-semibold uppercase tracking-[0.22em] text-surge">{{ t('admin.difyHealth') }}</p>
<h3 class="mt-2 text-2xl font-bold text-ink">{{ t('admin.difyHealthTitle') }}</h3>
<p class="mt-2 text-sm text-dusk">{{ t('admin.difyHealthHint') }}</p>
</div>
<div class="flex items-center gap-3">
<button class="btn-ghost" :disabled="recoveryBusy" @click="recoverStuckSyncs">{{ t('admin.recoverStaleSyncs') }}</button>
<button class="btn-ghost flex h-12 w-12 items-center justify-center rounded-2xl px-0" @click="close" aria-label="Close">
<svg aria-hidden="true" class="h-5 w-5" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M5 5l10 10M15 5L5 15" />
</svg>
</button>
</div>
</div>
<div v-if="loading" class="py-16 text-center text-dusk">{{ t('common.loading') }}</div>
<template v-else>
<div class="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.7fr)]">
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-6">
<div class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.healthStatus') }}</p>
<span class="tag mt-3 inline-flex" :class="snapshot?.status === 'ok' ? 'bg-emerald-100 text-emerald-700' : snapshot?.status === 'restarted' ? 'bg-amber-100 text-amber-700' : 'bg-rose-100 text-rose-700'">
{{ statusLabel(snapshot?.status) }}
</span>
<p class="mt-3 text-xs text-dusk">{{ t('admin.lastCheckedAt') }}: {{ formatDate(snapshot?.checked_at) }}</p>
</div>
<div class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.difyApi') }}</p>
<p class="mt-3 text-2xl font-semibold text-ink">{{ snapshot?.api?.reachable ? t('common.yes') : t('common.no') }}</p>
<p class="mt-3 break-all text-xs text-dusk">{{ payload?.dify_base_url || t('common.none') }}</p>
</div>
<div class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.workerConcurrency') }}</p>
<p class="mt-3 text-2xl font-semibold text-ink">{{ snapshot?.worker?.concurrency ?? '--' }}</p>
<p class="mt-3 text-xs text-dusk">{{ t('admin.lastRestartAt') }}: {{ formatDate(snapshot?.last_restart_at) }}</p>
</div>
<div class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.sharedPostgresUsage') }}</p>
<p class="mt-3 text-2xl font-semibold text-ink">{{ sharedPostgresUsageLabel }}</p>
<p class="mt-3 break-all text-xs text-dusk">{{ sharedPostgresUsageHint }}</p>
</div>
<div class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.pendingQueue') }}</p>
<p class="mt-3 text-2xl font-semibold text-ink">{{ totalPending }}</p>
<p class="mt-3 text-xs text-dusk">{{ queueEntries.map(([name, count]) => `${name}:${count}`).join(' · ') || t('common.none') }}</p>
</div>
<div class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.staleCandidates') }}</p>
<p class="mt-3 text-2xl font-semibold text-ink">{{ localHealth.stale_candidates }}</p>
<p class="mt-3 text-xs text-dusk">{{ t('admin.activeSyncJobs') }}: {{ localHealth.active_sync_jobs }}</p>
</div>
</div>
<div class="rounded-3xl border border-slate-200 bg-mist/40 px-5 py-5">
<p class="rounded-2xl border border-slate-200 bg-white px-3 py-3 text-sm text-dusk">
{{ t('admin.recoverStaleSyncsHint') }}
</p>
<p class="mt-5 text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.watchdogIssues') }}</p>
<div class="mt-3 space-y-2">
<p v-if="watchdogIssues.length === 0" class="text-sm text-dusk">{{ t('admin.noWatchdogIssues') }}</p>
<p v-for="issue in watchdogIssues" :key="issue" class="rounded-2xl border border-slate-200 bg-white px-3 py-3 text-sm text-ink">
{{ issue }}
</p>
</div>
<p class="mt-5 text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.watchdogActions') }}</p>
<div class="mt-3 space-y-2">
<p v-if="watchdogActions.length === 0" class="text-sm text-dusk">{{ t('admin.noWatchdogActions') }}</p>
<div
v-for="action in watchdogActions.slice(0, 5)"
:key="`${action.type}-${action.at}`"
class="rounded-2xl border border-slate-200 bg-white px-3 py-3 text-sm text-ink"
>
<p class="font-medium">{{ action.type }}</p>
<p v-if="action.reason" class="mt-1 text-xs text-dusk">{{ action.reason }}</p>
<p v-if="action.at" class="mt-1 text-xs text-dusk">{{ formatDate(action.at) }}</p>
</div>
</div>
</div>
</div>
<div class="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<div class="rounded-3xl border border-slate-200 bg-white px-5 py-5">
<div class="flex items-center justify-between gap-3">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.activeTasks') }}</p>
<span class="text-xs text-dusk">{{ activeTasks.length }}</span>
</div>
<div class="mt-4 space-y-3">
<p v-if="activeTasks.length === 0" class="text-sm text-dusk">{{ t('admin.noneRunning') }}</p>
<div v-for="task in activeTasks.slice(0, 6)" :key="task.id" class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<div class="flex items-start justify-between gap-3">
<div>
<p class="font-medium text-ink">{{ task.name }}</p>
<p class="mt-1 text-xs text-dusk">{{ t('admin.routingKey') }}: {{ task.delivery_info?.routing_key || t('common.none') }}</p>
</div>
<span class="tag bg-sky-100 text-sky-700">{{ formatRuntime(task.runtime_seconds) }}</span>
</div>
</div>
</div>
</div>
<div class="rounded-3xl border border-slate-200 bg-white px-5 py-5">
<div class="flex items-center justify-between gap-3">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.localSyncHealth') }}</p>
<span class="text-xs text-dusk">{{ t('admin.timeoutSeconds') }}: {{ localHealth.timeout_seconds }}</span>
</div>
<div class="mt-4 grid gap-3 sm:grid-cols-3">
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('status.syncing') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ localHealth.syncing_versions }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('status.sync_failed') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ localHealth.sync_failed_versions }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('admin.staleCandidates') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ localHealth.stale_candidates }}</p>
</div>
</div>
</div>
</div>
<div class="mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
<div v-for="item in healthGuide" :key="item.label" class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<p class="font-semibold text-ink">{{ item.label }}</p>
<p class="mt-2 text-sm leading-6 text-dusk">{{ item.text }}</p>
</div>
</div>
</template>
</div>
</div>
</template>
@@ -1,281 +0,0 @@
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { apiFetch } from '@/lib/api'
import { useI18n } from '@/lib/i18n'
type DifyModelOption = {
provider: string
model: string
label: string
}
type DifyModelCatalog = {
embedding_models: DifyModelOption[]
rerank_models: DifyModelOption[]
automatic_defaults: {
embedding_model_provider?: string | null
embedding_model?: string | null
reranking_model_provider?: string | null
reranking_model?: string | null
}
}
const props = defineProps<{
open: boolean
}>()
const emit = defineEmits<{
close: []
saved: [message: string]
error: [message: string]
}>()
const { t } = useI18n()
const loading = ref(false)
const saving = ref(false)
const errorMessage = ref('')
const settings = reactive({
dify_permission: 'all_team_members',
indexing_technique: 'high_quality',
search_method: 'hybrid_search',
doc_form: 'text_model',
embedding_model_provider: '',
embedding_model: '',
reranking_model_provider: '',
reranking_model: '',
top_k: 5,
score_threshold_enabled: true,
score_threshold: 0.35
})
const difyModels = reactive<DifyModelCatalog>({
embedding_models: [],
rerank_models: [],
automatic_defaults: {
embedding_model_provider: '',
embedding_model: '',
reranking_model_provider: '',
reranking_model: ''
}
})
function close() {
emit('close')
}
function modelValue(provider?: string | null, model?: string | null) {
return provider && model ? `${provider}::${model}` : ''
}
function applyModelValue(value: string, kind: 'embedding' | 'rerank') {
const [provider = '', model = ''] = value.split('::')
if (kind === 'embedding') {
settings.embedding_model_provider = provider
settings.embedding_model = model
return
}
settings.reranking_model_provider = provider
settings.reranking_model = model
}
const embeddingOptions = computed(() => [
{ value: '', label: t('admin.automaticChoice') },
...difyModels.embedding_models.map((item) => ({
value: modelValue(item.provider, item.model),
label: item.label
}))
])
const rerankOptions = computed(() => [
{ value: '', label: t('admin.automaticChoice') },
...difyModels.rerank_models.map((item) => ({
value: modelValue(item.provider, item.model),
label: item.label
}))
])
const selectedEmbeddingValue = computed({
get: () => modelValue(settings.embedding_model_provider, settings.embedding_model),
set: (value: string) => applyModelValue(value, 'embedding')
})
const selectedRerankValue = computed({
get: () => modelValue(settings.reranking_model_provider, settings.reranking_model),
set: (value: string) => applyModelValue(value, 'rerank')
})
function resolveModelLabel(kind: 'embedding' | 'rerank', provider?: string | null, model?: string | null) {
const collection = kind === 'embedding' ? difyModels.embedding_models : difyModels.rerank_models
const matched = collection.find((item) => item.provider === provider && item.model === model)
if (matched) return matched.label
return provider && model ? `${provider} / ${model}` : t('admin.automaticChoice')
}
const automaticEmbeddingLabel = computed(() =>
resolveModelLabel(
'embedding',
difyModels.automatic_defaults.embedding_model_provider,
difyModels.automatic_defaults.embedding_model
)
)
const automaticRerankLabel = computed(() =>
resolveModelLabel(
'rerank',
difyModels.automatic_defaults.reranking_model_provider,
difyModels.automatic_defaults.reranking_model
)
)
async function loadData() {
loading.value = true
errorMessage.value = ''
try {
const [settingsData, difyModelsData] = await Promise.all([
apiFetch('/api/admin/settings'),
apiFetch('/api/admin/dify-models')
])
Object.assign(settings, settingsData)
Object.assign(difyModels, difyModelsData)
} catch (err) {
const message = err instanceof Error ? err.message : t('admin.failedToLoadAdminData')
errorMessage.value = message
emit('error', message)
} finally {
loading.value = false
}
}
async function saveSettings() {
saving.value = true
errorMessage.value = ''
try {
await apiFetch('/api/admin/settings', {
method: 'PATCH',
body: JSON.stringify(settings)
})
emit('saved', t('admin.difyDefaultsSaved'))
close()
} catch (err) {
const message = err instanceof Error ? err.message : t('admin.failedToSaveSettings')
errorMessage.value = message
emit('error', message)
} finally {
saving.value = false
}
}
watch(
() => props.open,
(open) => {
if (open) {
loadData()
}
}
)
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="close"
>
<div class="panel w-full max-w-5xl px-6 py-6" @click.stop>
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-2xl font-bold text-ink">{{ t('admin.settingsDialogTitle') }}</h3>
<p class="mt-2 max-w-3xl text-sm leading-6 text-dusk">{{ t('admin.automaticSummary') }}</p>
</div>
<button class="btn-ghost flex h-12 w-12 items-center justify-center rounded-2xl px-0" @click="close" aria-label="Close">
<svg aria-hidden="true" class="h-5 w-5" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M5 5l10 10M15 5L5 15" />
</svg>
</button>
</div>
<p v-if="errorMessage" class="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
{{ errorMessage }}
</p>
<div v-if="loading" class="py-16 text-center text-dusk">{{ t('common.loading') }}</div>
<template v-else>
<div class="mt-5 grid gap-4 rounded-3xl border border-slate-100 bg-mist/40 p-4 md:grid-cols-2">
<div class="rounded-2xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.embeddingModel') }}</p>
<p class="mt-2 text-sm text-ink">{{ t('admin.currentAutomaticEmbedding', { value: automaticEmbeddingLabel }) }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-white px-4 py-4">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-dusk">{{ t('admin.rerankModel') }}</p>
<p class="mt-2 text-sm text-ink">{{ t('admin.currentAutomaticRerank', { value: automaticRerankLabel }) }}</p>
</div>
</div>
<div class="mt-5 grid gap-4 md:grid-cols-2">
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.difyPermission') }}</span>
<select v-model="settings.dify_permission" class="input">
<option value="all_team_members">all_team_members</option>
<option value="only_me">only_me</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.indexingTechnique') }}</span>
<select v-model="settings.indexing_technique" class="input">
<option value="high_quality">high_quality</option>
<option value="economy">economy</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.searchMethod') }}</span>
<select v-model="settings.search_method" class="input">
<option value="hybrid_search">hybrid_search</option>
<option value="semantic_search">semantic_search</option>
<option value="full_text_search">full_text_search</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.docForm') }}</span>
<select v-model="settings.doc_form" class="input">
<option value="text_model">text_model</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.embeddingModel') }}</span>
<select v-model="selectedEmbeddingValue" class="input">
<option v-for="option in embeddingOptions" :key="option.value || 'auto-embedding'" :value="option.value">{{ option.label }}</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.rerankModel') }}</span>
<select v-model="selectedRerankValue" class="input" :disabled="settings.search_method !== 'hybrid_search'">
<option v-for="option in rerankOptions" :key="option.value || 'auto-rerank'" :value="option.value">{{ option.label }}</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.topK') }}</span>
<input v-model.number="settings.top_k" class="input" type="number" min="1" />
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.scoreThreshold') }}</span>
<input v-model.number="settings.score_threshold" class="input" type="number" min="0" max="1" step="0.05" />
</label>
</div>
<label class="mt-4 inline-flex items-center gap-2 text-sm text-dusk">
<input v-model="settings.score_threshold_enabled" type="checkbox" />
{{ t('admin.enableScoreThreshold') }}
</label>
<div class="mt-6 flex flex-wrap justify-end gap-3">
<button class="btn-ghost" @click="close">{{ t('common.cancel') }}</button>
<button class="btn-primary" :disabled="saving" @click="saveSettings">{{ t('common.save') }}</button>
</div>
</template>
</div>
</div>
</template>
@@ -1,26 +0,0 @@
<script setup lang="ts">
import { useI18n, type Locale } from '@/lib/i18n'
const { locale, setLocale, t } = useI18n()
const options: Array<{ value: Locale; label: string }> = [
{ value: 'en', label: 'EN' },
{ value: 'zh', label: '中文' }
]
function handleLocaleChange(event: Event) {
const target = event.target as HTMLSelectElement
setLocale(target.value as Locale)
}
</script>
<template>
<label class="select-shell">
<span class="select-label">{{ t('common.language') }}</span>
<select class="select-control" :value="locale" @change="handleLocaleChange">
<option v-for="option in options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
</label>
</template>
-28
View File
@@ -1,28 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from '@/lib/i18n'
const props = defineProps<{
status: string
kind?: 'convert' | 'sync'
}>()
const { t } = useI18n()
const klass = computed(() => {
const status = props.status || 'unknown'
if (status === 'success' || status === 'synced') return 'bg-emerald-100 text-emerald-700'
if (status === 'running' || status === 'syncing') return 'bg-sky-100 text-sky-700'
if (status === 'failed' || status === 'sync_failed') return 'bg-rose-100 text-rose-700'
if (status === 'queued' || status === 'unsynced' || status === 'stale') return 'bg-slate-100 text-slate-700'
return 'bg-slate-100 text-slate-700'
})
const label = computed(() => {
return t(`status.${props.status === 'stale' ? 'unsynced' : props.status}`)
})
</script>
<template>
<span class="tag" :class="klass">{{ label }}</span>
</template>
-28
View File
@@ -1,28 +0,0 @@
<script setup lang="ts">
defineProps<{
toasts: Array<{
id: number
tone?: 'success' | 'error'
message: string
}>
}>()
</script>
<template>
<div class="pointer-events-none fixed left-1/2 top-20 z-[70] flex w-[min(34rem,calc(100vw-2rem))] -translate-x-1/2 flex-col gap-3">
<transition-group name="toast">
<div
v-for="toast in toasts"
:key="toast.id"
class="rounded-2xl border px-4 py-3 text-center text-sm shadow-soft backdrop-blur-xl"
:class="
toast.tone === 'error'
? 'border-rose-200 bg-rose-50/95 text-rose-700'
: 'border-emerald-200 bg-emerald-50/95 text-emerald-700'
"
>
{{ toast.message }}
</div>
</transition-group>
</div>
</template>
-76
View File
@@ -1,76 +0,0 @@
import { authState, clearSession } from './auth'
type RequestOptions = RequestInit & {
skipAuth?: boolean
}
export async function apiFetch(path: string, options: RequestOptions = {}) {
const headers = new Headers(options.headers || {})
if (!options.skipAuth && authState.token) {
headers.set('Authorization', `Bearer ${authState.token}`)
}
if (!(options.body instanceof FormData) && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json')
}
const response = await fetch(path, { ...options, headers })
if (response.status === 401) {
clearSession()
window.location.href = '/login'
throw new Error('Unauthorized')
}
if (!response.ok) {
let detail = response.statusText
try {
const data = await response.json()
detail = data.detail || JSON.stringify(data)
} catch {
detail = await response.text()
}
throw new Error(detail)
}
if (response.status === 204) {
return null
}
const contentType = response.headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return response.json()
}
return response
}
export async function downloadBlob(path: string, options: RequestOptions = {}, filename?: string) {
const headers = new Headers(options.headers || {})
if (authState.token) {
headers.set('Authorization', `Bearer ${authState.token}`)
}
const response = await fetch(path, { ...options, headers })
if (!response.ok) {
throw new Error(await response.text())
}
const blob = await response.blob()
const disposition = response.headers.get('content-disposition') || ''
const utf8Match = disposition.match(/filename\*\s*=\s*UTF-8''([^;]+)/i)
const quotedMatch = disposition.match(/filename\s*=\s*"([^"]+)"/i)
const plainMatch = disposition.match(/filename\s*=\s*([^;]+)/i)
const resolvedFilename =
filename ||
(utf8Match?.[1]
? (() => {
try {
return decodeURIComponent(utf8Match[1].trim())
} catch {
return utf8Match[1].trim()
}
})()
: quotedMatch?.[1] || plainMatch?.[1]?.trim()) ||
'download.bin'
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = resolvedFilename
link.style.display = 'none'
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(url)
}
-39
View File
@@ -1,39 +0,0 @@
import { reactive } from 'vue'
type SessionUser = {
id: number
username: string
full_name?: string | null
role: string
accessible_group_ids?: number[]
primary_department_id?: number | null
primary_department_name?: string | null
accessible_department_ids?: number[]
}
type SessionState = {
token: string
user: SessionUser | null
}
const storedToken = localStorage.getItem('dc_token') || ''
const storedUser = localStorage.getItem('dc_user')
export const authState = reactive<SessionState>({
token: storedToken,
user: storedUser ? JSON.parse(storedUser) : null
})
export function setSession(token: string, user: SessionUser) {
authState.token = token
authState.user = user
localStorage.setItem('dc_token', token)
localStorage.setItem('dc_user', JSON.stringify(user))
}
export function clearSession() {
authState.token = ''
authState.user = null
localStorage.removeItem('dc_token')
localStorage.removeItem('dc_user')
}
File diff suppressed because it is too large. Load diff
-7
View File
@@ -1,7 +0,0 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './style.css'
createApp(App).use(router).mount('#app')
-45
View File
@@ -1,45 +0,0 @@
import { createRouter, createWebHistory } from 'vue-router'
import { authState } from '@/lib/auth'
import LoginView from '@/views/LoginView.vue'
import WorkspaceView from '@/views/WorkspaceView.vue'
import AdminView from '@/views/AdminView.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
redirect: '/workspace'
},
{
path: '/login',
component: LoginView,
meta: { guestOnly: true }
},
{
path: '/workspace',
component: WorkspaceView,
meta: { requiresAuth: true }
},
{
path: '/admin',
component: AdminView,
meta: { requiresAuth: true, adminOnly: true }
}
]
})
router.beforeEach((to) => {
if (to.meta.requiresAuth && !authState.token) {
return '/login'
}
if (to.meta.guestOnly && authState.token) {
return '/workspace'
}
if (to.meta.adminOnly && !['super_admin', 'admin'].includes(authState.user?.role || '')) {
return '/workspace'
}
return true
})
export default router
-395
View File
@@ -1,395 +0,0 @@
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&family=Noto+Sans+SC:wght@400;500;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
color: #122033;
background:
radial-gradient(circle at 12% 14%, rgba(21, 115, 255, 0.18), transparent 30%),
radial-gradient(circle at 86% 18%, rgba(255, 113, 71, 0.12), transparent 24%),
radial-gradient(circle at 78% 88%, rgba(31, 195, 154, 0.14), transparent 28%),
linear-gradient(180deg, #f6f8fc 0%, #ecf1f7 100%);
font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
position: relative;
color: #122033;
}
body::before {
content: '';
position: fixed;
inset: 0;
pointer-events: none;
background-image:
linear-gradient(rgba(18, 32, 51, 0.035) 1px, transparent 1px),
linear-gradient(90deg, rgba(18, 32, 51, 0.035) 1px, transparent 1px);
background-size: 32px 32px;
mask-image: linear-gradient(180deg, rgba(0, 0, 0, 0.9), rgba(0, 0, 0, 0.22));
}
body::after {
content: '';
position: fixed;
right: -10rem;
top: 8rem;
width: 28rem;
height: 28rem;
border-radius: 9999px;
pointer-events: none;
background: radial-gradient(circle, rgba(21, 115, 255, 0.18) 0%, rgba(21, 115, 255, 0) 70%);
filter: blur(8px);
}
#app {
min-height: 100vh;
}
.app-shell {
min-height: 100vh;
}
.panel {
@apply rounded-panel border border-slate-300/90 bg-white/80 shadow-soft backdrop-blur-xl;
position: relative;
box-shadow:
0 18px 50px rgba(18, 32, 51, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.72);
}
.panel::before {
content: '';
position: absolute;
inset: 0 0 auto 0;
height: 3px;
background: linear-gradient(90deg, rgba(21, 115, 255, 0.92), rgba(31, 195, 154, 0.72), rgba(255, 113, 71, 0.72));
}
.input {
@apply w-full rounded-2xl border border-slate-300 bg-white px-4 py-3 text-sm text-ink outline-none transition focus:border-surge focus:ring-4 focus:ring-surge/10;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.7),
0 1px 2px rgba(18, 32, 51, 0.04);
}
.btn {
@apply inline-flex items-center justify-center gap-2 rounded-2xl px-4 py-2.5 text-sm font-medium transition;
}
.btn-primary {
@apply btn border border-transparent bg-ink text-white hover:-translate-y-0.5 hover:bg-slate-800;
box-shadow: 0 12px 24px rgba(18, 32, 51, 0.18);
}
.btn-ghost {
@apply btn border border-slate-300 bg-white text-ink hover:-translate-y-0.5 hover:border-surge hover:text-surge;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.7),
0 1px 2px rgba(18, 32, 51, 0.05);
}
.dialog-static-btn,
.dialog-static-btn:hover,
.dialog-static-btn:focus-visible,
.dialog-static-btn:active {
transform: none !important;
}
.dialog-static-btn {
transition:
border-color 140ms ease,
color 140ms ease,
background-color 140ms ease,
box-shadow 140ms ease !important;
}
.icon-btn {
@apply inline-flex h-8 w-8 items-center justify-center rounded-full border border-slate-300 bg-white transition hover:-translate-y-0.5 hover:border-surge hover:text-surge disabled:cursor-not-allowed disabled:opacity-60;
}
.group-card .group-card-actions {
opacity: 0;
pointer-events: none;
transition:
opacity 160ms ease,
transform 160ms ease,
border-color 180ms ease,
background-color 180ms ease,
color 180ms ease;
transform: translateY(-50%) scale(0.96);
}
.group-card .group-card-status-dot {
opacity: 1;
transition: opacity 160ms ease;
}
.group-card:hover .group-card-actions,
.group-card .group-card-actions:focus-within {
opacity: 1;
pointer-events: auto;
transform: translateY(-50%) scale(1);
}
.group-card:hover .group-card-status-dot {
opacity: 0;
}
@media (hover: none) {
.group-card .group-card-actions {
opacity: 1;
pointer-events: auto;
transform: translateY(-50%) scale(1);
}
.group-card .group-card-status-dot {
opacity: 0;
}
}
.tag {
@apply inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold;
letter-spacing: 0.02em;
}
.select-shell {
@apply inline-flex items-center gap-2 rounded-2xl border border-slate-300 bg-white px-3 py-2 text-sm shadow-soft backdrop-blur-xl;
}
.select-label {
@apply text-xs font-semibold uppercase tracking-[0.18em] text-dusk;
}
.select-control {
@apply rounded-xl border-0 bg-transparent py-1 pl-1 pr-7 text-sm font-semibold text-ink outline-none;
}
.menu-shell {
position: relative;
}
.menu-trigger {
@apply inline-flex cursor-pointer items-center gap-2 rounded-full px-3 py-2 text-sm font-semibold text-ink transition hover:bg-white/80 hover:text-surge;
list-style: none;
user-select: none;
}
.menu-trigger::-webkit-details-marker {
display: none;
}
.menu-trigger-icon {
@apply h-4 w-4 text-dusk transition;
}
.menu-shell[open] .menu-trigger {
@apply border-surge text-surge;
}
.menu-shell[open] .menu-trigger-icon {
transform: rotate(180deg);
}
.menu-popover {
@apply absolute right-0 top-[calc(100%+0.5rem)] z-40 rounded-2xl border border-slate-200 bg-white/95 p-1 shadow-soft backdrop-blur-xl;
}
.menu-item {
@apply flex w-full items-center justify-center rounded-xl px-4 py-2 text-center text-sm font-medium text-ink transition hover:bg-mist hover:text-surge;
}
.user-menu {
@apply relative inline-flex items-center outline-none;
}
.user-menu::after {
content: '';
position: absolute;
left: -0.5rem;
right: -0.5rem;
top: 100%;
height: 10px;
}
.user-menu-trigger {
@apply inline-flex items-center gap-1 rounded-xl px-1.5 py-1 text-[15px] font-semibold text-ink transition;
}
.user-menu:hover .user-menu-trigger,
.user-menu:focus-within .user-menu-trigger {
@apply text-surge;
}
.user-menu-panel {
@apply absolute left-1/2 top-[calc(100%+0.45rem)] z-50 min-w-[132px] rounded-2xl border border-slate-300 bg-white p-1 shadow-soft backdrop-blur-xl;
opacity: 0;
pointer-events: none;
visibility: hidden;
transform: translate(-50%, 4px);
transition:
opacity 160ms ease,
transform 160ms ease;
}
.user-menu:hover .user-menu-panel,
.user-menu:focus-within .user-menu-panel {
opacity: 1;
pointer-events: auto;
visibility: visible;
transform: translate(-50%, 0);
}
.user-menu-name {
@apply max-w-[156px] truncate text-[15px] font-semibold text-current;
}
.user-menu-icon {
@apply h-3.5 w-3.5 text-dusk transition;
}
.user-menu:hover .user-menu-icon,
.user-menu:focus-within .user-menu-icon {
@apply text-surge;
transform: rotate(180deg);
}
.date-range-shell {
@apply flex items-center rounded-2xl border border-slate-300 bg-white px-3 py-2;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
}
.date-range-input {
@apply min-w-0 flex-1 border-0 bg-transparent px-1 py-1 text-sm text-ink outline-none;
}
.date-range-divider {
@apply px-2 text-sm font-semibold text-dusk;
}
.file-title-link {
@apply block max-w-[8em] truncate text-left font-semibold text-surge underline decoration-surge/80 underline-offset-4 transition hover:text-blue-700;
}
.file-title-text {
@apply block max-w-[8em] truncate font-semibold text-ink;
}
.datetime-stack {
@apply flex flex-col leading-tight text-ink;
}
.datetime-subtle {
@apply mt-1 text-xs text-dusk;
}
.table-actions {
@apply flex flex-nowrap items-center gap-2 overflow-x-auto;
}
.table-actions .btn-ghost {
transform: none !important;
transition:
border-color 140ms ease,
color 140ms ease,
background-color 140ms ease,
box-shadow 140ms ease !important;
}
.table-actions .btn-ghost:hover,
.table-actions .btn-ghost:focus-visible,
.table-actions .btn-ghost:active {
transform: none !important;
}
.table-action-btn {
@apply shrink-0 whitespace-nowrap justify-center rounded-xl px-3 py-2 text-xs;
transform: none !important;
transition:
border-color 140ms ease,
color 140ms ease,
background-color 140ms ease,
box-shadow 140ms ease;
}
.table-action-btn:hover,
.table-action-btn:focus-visible {
transform: none !important;
}
.status-toggle {
@apply inline-flex min-w-[132px] items-center justify-center gap-3 rounded-full border px-3 py-2 text-sm font-medium transition;
}
.status-toggle:disabled {
@apply cursor-not-allowed opacity-60;
}
.status-toggle-track {
@apply relative h-6 w-11 rounded-full border border-transparent transition;
}
.status-toggle-thumb {
@apply absolute left-0.5 top-0.5 rounded-full bg-white shadow-sm transition;
height: 1.125rem;
width: 1.125rem;
}
.status-toggle-label {
@apply whitespace-nowrap;
}
.status-toggle--on {
@apply border-emerald-200 bg-emerald-50 text-emerald-700;
}
.status-toggle--on .status-toggle-track {
@apply bg-emerald-500;
}
.status-toggle--on .status-toggle-thumb {
transform: translateX(1.25rem);
}
.status-toggle--off {
@apply border-slate-200 bg-slate-100 text-slate-600;
}
.status-toggle--off .status-toggle-track {
@apply bg-slate-300;
}
.uppy-compact .uppy-Dashboard-inner,
.uppy-compact .uppy-Dashboard-innerWrap {
min-height: 220px !important;
}
.uppy-compact .uppy-Dashboard-inner {
width: 100% !important;
border: 1px dashed rgba(148, 163, 184, 0.45);
border-radius: 1.5rem;
background: linear-gradient(180deg, rgba(248, 250, 252, 0.82), rgba(255, 255, 255, 0.94));
}
.file-table {
table-layout: auto;
}
.diff-table {
table-layout: fixed;
min-width: 960px;
}
.file-table th,
.file-table td {
vertical-align: middle;
}
-769
View File
@@ -1,769 +0,0 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import DifyHealthDialog from '@/components/DifyHealthDialog.vue'
import DifySettingsDialog from '@/components/DifySettingsDialog.vue'
import LocaleSwitcher from '@/components/LocaleSwitcher.vue'
import ToastStack from '@/components/ToastStack.vue'
import { apiFetch } from '@/lib/api'
import { authState, clearSession } from '@/lib/auth'
import { useI18n } from '@/lib/i18n'
type DepartmentRow = {
id: number
name: string
description?: string | null
user_count?: number
knowledge_base_count?: number
}
type UserRow = {
id: number
username: string
full_name?: string | null
role: string
is_primary_super_admin?: boolean
is_active: boolean
primary_department_id: number | null
primary_department_name?: string | null
accessible_department_ids: number[]
extra_department_ids: number[]
}
type EditableUser = {
id: number | null
username: string
full_name: string
password: string
role: string
is_active: boolean
primary_department_id: number | null
extra_department_ids: number[]
}
const router = useRouter()
const { t } = useI18n()
const loading = ref(false)
const error = ref('')
const users = ref<UserRow[]>([])
const departments = ref<DepartmentRow[]>([])
const settingsDialogOpen = ref(false)
const healthDialogOpen = ref(false)
const userMenuOpen = ref(false)
const togglingUserId = ref<number | null>(null)
const toasts = ref<Array<{ id: number; tone?: 'success' | 'error'; message: string }>>([])
const departmentDialog = reactive({
open: false,
mode: 'create' as 'create' | 'edit',
id: null as number | null,
name: '',
description: '',
})
const departmentDeleteDialog = reactive({
open: false,
id: null as number | null,
name: '',
user_count: 0,
knowledge_base_count: 0,
target_department_id: null as number | null,
})
const userDialog = reactive({
open: false,
mode: 'create' as 'create' | 'edit',
})
const userDeleteDialog = reactive({
open: false,
id: null as number | null,
username: '',
})
const editableUser = reactive<EditableUser>({
id: null,
username: '',
full_name: '',
password: '',
role: 'user',
is_active: true,
primary_department_id: null,
extra_department_ids: [],
})
const isAdmin = computed(() => ['super_admin', 'admin'].includes(authState.user?.role || ''))
const currentUserLabel = computed(() => authState.user?.full_name || authState.user?.username || t('common.unknown'))
const currentUserId = computed(() => authState.user?.id ?? null)
const sortedUsers = computed(() => [...users.value].sort((left, right) => left.username.localeCompare(right.username)))
const departmentOptions = computed(() => departments.value.map((item) => ({ value: item.id, label: item.name })))
const hasDepartments = computed(() => departments.value.length > 0)
const departmentDeleteOptions = computed(() =>
departments.value.filter((item) => item.id !== departmentDeleteDialog.id).map((item) => ({ value: item.id, label: item.name })),
)
const departmentDeleteNeedsMigration = computed(
() => departmentDeleteDialog.user_count > 0 || departmentDeleteDialog.knowledge_base_count > 0,
)
const roleOptions = computed(() => [
{ value: 'admin', label: t('roles.admin') },
{ value: 'user', label: t('roles.user') },
])
const userDepartmentIds = computed(() => {
const ids = [editableUser.primary_department_id, ...editableUser.extra_department_ids].filter(
(value): value is number => value !== null,
)
return [...new Set(ids)]
})
function pushToast(message: string, tone: 'success' | 'error' = 'success') {
const id = Date.now() + Math.floor(Math.random() * 1000)
toasts.value.push({ id, tone, message })
window.setTimeout(() => {
toasts.value = toasts.value.filter((item) => item.id !== id)
}, 3000)
}
function logout() {
clearSession()
router.push('/login')
}
function closeMenus() {
userMenuOpen.value = false
}
function resetDepartmentDialog() {
departmentDialog.open = false
departmentDialog.mode = 'create'
departmentDialog.id = null
departmentDialog.name = ''
departmentDialog.description = ''
}
function resetDepartmentDeleteDialog() {
departmentDeleteDialog.open = false
departmentDeleteDialog.id = null
departmentDeleteDialog.name = ''
departmentDeleteDialog.user_count = 0
departmentDeleteDialog.knowledge_base_count = 0
departmentDeleteDialog.target_department_id = null
}
function resetUserDialog() {
userDialog.open = false
userDialog.mode = 'create'
editableUser.id = null
editableUser.username = ''
editableUser.full_name = ''
editableUser.password = ''
editableUser.role = 'user'
editableUser.is_active = true
editableUser.primary_department_id = departments.value[0]?.id ?? null
editableUser.extra_department_ids = []
}
function resetUserDeleteDialog() {
userDeleteDialog.open = false
userDeleteDialog.id = null
userDeleteDialog.username = ''
}
function setUserDepartmentIds(departmentIds: number[]) {
const uniqueIds = [...new Set(departmentIds)]
editableUser.primary_department_id = uniqueIds[0] ?? null
editableUser.extra_department_ids = uniqueIds.slice(1)
}
function normalizeExtraDepartments(primaryDepartmentId: number | null, departmentIds: number[]) {
if (!primaryDepartmentId) return [...new Set(departmentIds)]
return [...new Set(departmentIds)].filter((item) => item !== primaryDepartmentId)
}
function openCreateDepartmentDialog() {
resetDepartmentDialog()
departmentDialog.open = true
departmentDialog.mode = 'create'
}
function openEditDepartmentDialog(row: DepartmentRow) {
departmentDialog.open = true
departmentDialog.mode = 'edit'
departmentDialog.id = row.id
departmentDialog.name = row.name
departmentDialog.description = row.description || ''
}
function openDeleteDepartmentDialog(row: DepartmentRow) {
departmentDeleteDialog.open = true
departmentDeleteDialog.id = row.id
departmentDeleteDialog.name = row.name
departmentDeleteDialog.user_count = row.user_count ?? 0
departmentDeleteDialog.knowledge_base_count = row.knowledge_base_count ?? 0
departmentDeleteDialog.target_department_id = departments.value.find((item) => item.id !== row.id)?.id ?? null
}
function openCreateUserDialog() {
if (!hasDepartments.value) {
pushToast(t('admin.createDepartmentFirst'), 'error')
return
}
resetUserDialog()
userDialog.open = true
userDialog.mode = 'create'
}
function openEditUserDialog(row: UserRow) {
userDialog.open = true
userDialog.mode = 'edit'
editableUser.id = row.id
editableUser.username = row.username
editableUser.full_name = row.full_name || ''
editableUser.password = ''
editableUser.role = row.is_primary_super_admin ? 'super_admin' : row.role
editableUser.is_active = row.is_active
setUserDepartmentIds(row.accessible_department_ids)
}
function canDeleteUser(row: UserRow) {
return row.username !== 'admin' && !row.is_primary_super_admin && row.id !== currentUserId.value
}
function openDeleteUserDialog(row: UserRow) {
if (!canDeleteUser(row)) return
userDeleteDialog.open = true
userDeleteDialog.id = row.id
userDeleteDialog.username = row.username
}
function toggleUserDepartment(departmentId: number, checked: boolean) {
const nextIds = [...userDepartmentIds.value]
if (checked) {
if (!nextIds.includes(departmentId)) nextIds.push(departmentId)
} else {
const index = nextIds.indexOf(departmentId)
if (index >= 0) nextIds.splice(index, 1)
}
setUserDepartmentIds(nextIds)
}
async function loadAll() {
loading.value = true
error.value = ''
try {
const [departmentData, userData] = await Promise.all([
apiFetch('/api/admin/departments'),
apiFetch('/api/admin/users'),
])
departments.value = departmentData.data || []
users.value = userData.data || []
if (!editableUser.primary_department_id) {
editableUser.primary_department_id = departments.value[0]?.id ?? null
}
} catch (err) {
error.value = err instanceof Error ? err.message : t('admin.failedToLoadAdminData')
} finally {
loading.value = false
}
}
async function saveDepartment() {
error.value = ''
try {
const payload = {
name: departmentDialog.name.trim(),
description: departmentDialog.description.trim() || null,
}
if (departmentDialog.mode === 'create') {
await apiFetch('/api/admin/departments', {
method: 'POST',
body: JSON.stringify(payload),
})
pushToast(t('admin.departmentCreated'))
} else {
await apiFetch(`/api/admin/departments/${departmentDialog.id}`, {
method: 'PATCH',
body: JSON.stringify(payload),
})
pushToast(t('admin.departmentUpdated'))
}
resetDepartmentDialog()
await loadAll()
} catch (err) {
error.value = err instanceof Error ? err.message : t('admin.failedToSaveDepartment')
}
}
async function deleteDepartment() {
error.value = ''
if (!departmentDeleteDialog.id) return
if (departmentDeleteNeedsMigration.value && !departmentDeleteDialog.target_department_id) {
error.value = t('admin.deleteDepartmentTargetRequired')
return
}
try {
await apiFetch(`/api/admin/departments/${departmentDeleteDialog.id}`, {
method: 'DELETE',
body: JSON.stringify({
target_department_id: departmentDeleteNeedsMigration.value ? departmentDeleteDialog.target_department_id : null,
}),
})
pushToast(departmentDeleteNeedsMigration.value ? t('admin.departmentDeletedWithMigration') : t('admin.departmentDeleted'))
resetDepartmentDeleteDialog()
await loadAll()
} catch (err) {
error.value = err instanceof Error ? err.message : t('admin.failedToDeleteDepartment')
}
}
async function saveUser() {
error.value = ''
if (userDepartmentIds.value.length === 0) {
error.value = t('admin.primaryDepartmentRequired')
return
}
const orderedDepartmentIds = userDepartmentIds.value
const payload = {
username: editableUser.username.trim(),
password: editableUser.password || undefined,
full_name: editableUser.full_name.trim() || null,
role: editableUser.role,
is_active: editableUser.is_active,
primary_department_id: orderedDepartmentIds[0] ?? null,
accessible_department_ids: normalizeExtraDepartments(orderedDepartmentIds[0] ?? null, orderedDepartmentIds.slice(1)),
}
try {
if (userDialog.mode === 'create') {
await apiFetch('/api/admin/users', {
method: 'POST',
body: JSON.stringify({
...payload,
password: editableUser.password,
}),
})
pushToast(t('admin.userCreated'))
} else {
await apiFetch(`/api/admin/users/${editableUser.id}`, {
method: 'PATCH',
body: JSON.stringify(payload),
})
pushToast(t('admin.userSaved', { username: editableUser.username }))
}
resetUserDialog()
await loadAll()
} catch (err) {
error.value = err instanceof Error ? err.message : t(userDialog.mode === 'create' ? 'admin.failedToCreateUser' : 'admin.failedToUpdateUser')
}
}
function departmentSummary(user: UserRow) {
const names = departments.value
.filter((item) => user.accessible_department_ids.includes(item.id))
.map((item) => item.name)
return names.join('、') || t('common.none')
}
function extraDepartmentSummary(user: UserRow) {
const names = departments.value
.filter((item) => user.extra_department_ids.includes(item.id))
.map((item) => item.name)
return names.join('、') || t('common.none')
}
function departmentPermissionSummary(user: UserRow) {
const names = departments.value
.filter((item) => user.accessible_department_ids.includes(item.id))
.map((item) => item.name)
return names.join('、') || t('common.none')
}
function renderDepartmentPermissionSummary(user: UserRow) {
const names = departments.value
.filter((item) => user.accessible_department_ids.includes(item.id))
.map((item) => item.name)
return names.join('、') || t('common.none')
}
async function toggleUserActive(user: UserRow) {
if (user.username === 'admin' || user.is_primary_super_admin || togglingUserId.value === user.id) return
error.value = ''
togglingUserId.value = user.id
try {
await apiFetch(`/api/admin/users/${user.id}`, {
method: 'PATCH',
body: JSON.stringify({
is_active: !user.is_active,
}),
})
user.is_active = !user.is_active
pushToast(t('admin.userStatusUpdated'))
} catch (err) {
error.value = err instanceof Error ? err.message : t('admin.failedToToggleUserStatus')
} finally {
togglingUserId.value = null
}
}
async function deleteUser() {
error.value = ''
if (!userDeleteDialog.id) return
try {
await apiFetch(`/api/admin/users/${userDeleteDialog.id}`, {
method: 'DELETE',
})
pushToast(t('admin.userDeleted'))
resetUserDeleteDialog()
await loadAll()
} catch (err) {
error.value = err instanceof Error ? err.message : t('admin.failedToDeleteUser')
}
}
watch(
() => t('admin.permissionsPageTitle'),
(value) => {
document.title = value
},
{ immediate: true },
)
onMounted(() => {
if (!isAdmin.value) {
router.push('/workspace')
return
}
void loadAll()
})
</script>
<template>
<main class="min-h-screen px-4 py-6 md:px-8" @click="closeMenus">
<ToastStack :toasts="toasts" />
<div class="mx-auto max-w-[1680px] space-y-6">
<header class="panel relative z-20 overflow-visible flex flex-col gap-4 px-6 py-4 xl:flex-row xl:items-center xl:justify-between">
<div>
<h1 class="text-3xl font-bold text-ink">{{ t('admin.permissionsPageTitle') }}</h1>
</div>
<div class="flex flex-wrap items-center justify-end gap-3">
<LocaleSwitcher />
<button class="btn-ghost" @click="router.push('/workspace')">{{ t('admin.backToWorkspace') }}</button>
<div class="user-menu" tabindex="0" @click.stop>
<button class="user-menu-trigger" type="button" @click="userMenuOpen = !userMenuOpen">
<span class="user-menu-name" :title="currentUserLabel">{{ currentUserLabel }}</span>
<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" class="user-menu-icon">
<path d="m5 7 5 5 5-5" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</button>
<div v-if="userMenuOpen" class="user-menu-panel min-w-[180px]">
<button class="menu-item" @click="settingsDialogOpen = true">{{ t('admin.openDifySettings') }}</button>
<button class="menu-item" @click="healthDialogOpen = true">{{ t('admin.difyHealth') }}</button>
<button class="menu-item" @click="logout">{{ t('common.signOut') }}</button>
</div>
</div>
</div>
</header>
<p v-if="error" class="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{{ error }}</p>
<section class="grid gap-6 xl:grid-cols-[360px_minmax(0,1fr)]">
<div class="panel px-5 py-5">
<div class="flex items-start justify-between gap-3">
<div>
<h2 class="text-2xl font-bold text-ink">{{ t('admin.departmentsTitle') }}</h2>
</div>
<button class="btn-ghost" @click="openCreateDepartmentDialog">{{ t('admin.createDepartment') }}</button>
</div>
<div class="mt-5 space-y-3">
<article v-for="department in departments" :key="department.id" class="rounded-3xl border border-slate-200 bg-white px-4 py-4">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<p class="truncate text-base font-semibold text-ink">{{ department.name }}</p>
<p v-if="department.description" class="mt-1 text-sm text-dusk">{{ department.description }}</p>
</div>
<div class="flex items-center gap-2">
<button class="btn-ghost px-3 py-2" @click="openEditDepartmentDialog(department)">{{ t('common.edit') }}</button>
<button class="btn-ghost px-3 py-2" @click="openDeleteDepartmentDialog(department)">{{ t('workspace.delete') }}</button>
</div>
</div>
<div class="mt-4 grid grid-cols-2 gap-3">
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('admin.userCount') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ department.user_count ?? 0 }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('admin.groups') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ department.knowledge_base_count ?? 0 }}</p>
</div>
</div>
</article>
</div>
</div>
<div class="panel px-5 py-5">
<div class="flex flex-wrap items-center justify-end gap-3">
<button class="btn-ghost" :disabled="!hasDepartments" @click="openCreateUserDialog">{{ t('admin.createUser') }}</button>
</div>
<p v-if="!hasDepartments" class="mt-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
{{ t('admin.createDepartmentFirst') }}
</p>
<div class="mt-5 overflow-hidden rounded-3xl border border-slate-200 bg-white">
<table class="file-table w-full min-w-[920px] text-left text-sm">
<thead class="bg-mist/70 text-dusk">
<tr>
<th class="px-4 py-3">{{ t('admin.username') }}</th>
<th class="px-4 py-3">{{ t('admin.fullName') }}</th>
<th class="px-4 py-3">{{ t('admin.role') }}</th>
<th class="px-4 py-3">{{ t('admin.departmentPermissions') }}</th>
<th class="px-4 py-3">{{ t('admin.active') }}</th>
<th class="px-4 py-3">{{ t('admin.action') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="user in sortedUsers" :key="user.id" class="border-t border-slate-100">
<td class="px-4 py-4 font-semibold text-ink">{{ user.username }}</td>
<td class="px-4 py-4 text-ink">{{ user.full_name || '-' }}</td>
<td class="px-4 py-4 text-ink">{{ t(`roles.${user.role}`) }}</td>
<td class="px-4 py-4 text-dusk">{{ renderDepartmentPermissionSummary(user) }}</td>
<td class="px-4 py-4">
<button
class="status-toggle"
:class="user.is_active ? 'status-toggle--on' : 'status-toggle--off'"
:disabled="user.username === 'admin' || user.is_primary_super_admin || togglingUserId === user.id"
@click="toggleUserActive(user)"
>
<span class="status-toggle-track" aria-hidden="true">
<span class="status-toggle-thumb"></span>
</span>
<span class="status-toggle-label">
{{ user.is_active ? t('admin.enabled') : t('admin.disabled') }}
</span>
</button>
</td>
<td class="px-4 py-4">
<div class="flex flex-wrap items-center gap-2">
<button class="btn-ghost px-3 py-2" @click="openEditUserDialog(user)">{{ t('common.edit') }}</button>
<button
v-if="canDeleteUser(user)"
class="btn-ghost px-3 py-2"
@click="openDeleteUserDialog(user)"
>
{{ t('workspace.delete') }}
</button>
</div>
</td>
</tr>
<tr v-if="!loading && sortedUsers.length === 0">
<td colspan="6" class="px-4 py-10 text-center text-dusk">{{ t('admin.noUsers') }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<div
v-if="departmentDialog.open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="resetDepartmentDialog"
>
<div class="panel w-full max-w-xl px-6 py-6" @click.stop>
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-2xl font-bold text-ink">
{{ departmentDialog.mode === 'create' ? t('admin.createDepartment') : t('admin.editDepartment') }}
</h3>
</div>
<button class="btn-ghost flex h-12 w-12 items-center justify-center rounded-2xl px-0" @click="resetDepartmentDialog" aria-label="Close">
<svg aria-hidden="true" class="h-5 w-5" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M5 5l10 10M15 5L5 15" />
</svg>
</button>
</div>
<div class="mt-5 space-y-4">
<input v-model="departmentDialog.name" class="input" :placeholder="t('admin.departmentName')" />
<textarea v-model="departmentDialog.description" class="input min-h-[140px] resize-none" :placeholder="t('admin.departmentDescription')"></textarea>
</div>
<div class="mt-6 flex flex-wrap justify-end gap-3">
<button class="btn-ghost" @click="resetDepartmentDialog">{{ t('common.cancel') }}</button>
<button class="btn-primary" @click="saveDepartment">{{ t('common.save') }}</button>
</div>
</div>
</div>
<div
v-if="departmentDeleteDialog.open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="resetDepartmentDeleteDialog"
>
<div class="panel w-full max-w-xl px-6 py-6" @click.stop>
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-2xl font-bold text-ink">{{ t('admin.deleteDepartment') }}</h3>
<p class="mt-2 text-sm text-dusk">{{ departmentDeleteDialog.name }}</p>
</div>
<button class="btn-ghost flex h-12 w-12 items-center justify-center rounded-2xl px-0" @click="resetDepartmentDeleteDialog" aria-label="Close">
<svg aria-hidden="true" class="h-5 w-5" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M5 5l10 10M15 5L5 15" />
</svg>
</button>
</div>
<div class="mt-5 grid grid-cols-2 gap-3">
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('admin.userCount') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ departmentDeleteDialog.user_count }}</p>
</div>
<div class="rounded-2xl border border-slate-200 bg-mist/40 px-3 py-3">
<p class="text-xs text-dusk">{{ t('admin.groups') }}</p>
<p class="mt-2 text-xl font-semibold text-ink">{{ departmentDeleteDialog.knowledge_base_count }}</p>
</div>
</div>
<div v-if="departmentDeleteNeedsMigration" class="mt-5 rounded-3xl border border-amber-200 bg-amber-50 px-4 py-4">
<p class="text-sm font-semibold text-amber-900">{{ t('admin.deleteDepartmentNeedsMigration') }}</p>
<p class="mt-2 text-sm text-amber-800">{{ t('admin.deleteDepartmentNeedsMigrationHint') }}</p>
<select v-model="departmentDeleteDialog.target_department_id" class="input mt-4">
<option :value="null">{{ t('admin.selectMigrationDepartment') }}</option>
<option v-for="option in departmentDeleteOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
</div>
<p v-else class="mt-5 rounded-3xl border border-slate-200 bg-mist/40 px-4 py-4 text-sm text-dusk">
{{ t('admin.deleteDepartmentEmptyHint') }}
</p>
<div class="mt-6 flex flex-wrap justify-end gap-3">
<button class="btn-ghost" @click="resetDepartmentDeleteDialog">{{ t('common.cancel') }}</button>
<button
class="btn-primary"
:disabled="departmentDeleteNeedsMigration && !departmentDeleteDialog.target_department_id"
@click="deleteDepartment"
>
{{ t('admin.deleteDepartment') }}
</button>
</div>
</div>
</div>
<div
v-if="userDialog.open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="resetUserDialog"
>
<div class="panel w-full max-w-3xl px-6 py-6" @click.stop>
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-2xl font-bold text-ink">
{{ userDialog.mode === 'create' ? t('admin.createUser') : t('admin.editUser') }}
</h3>
</div>
<button class="btn-ghost flex h-12 w-12 items-center justify-center rounded-2xl px-0" @click="resetUserDialog" aria-label="Close">
<svg aria-hidden="true" class="h-5 w-5" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M5 5l10 10M15 5L5 15" />
</svg>
</button>
</div>
<div class="mt-5 grid gap-4 md:grid-cols-2">
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.username') }}</span>
<input v-model="editableUser.username" class="input" :disabled="userDialog.mode === 'edit'" />
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.fullName') }}</span>
<input v-model="editableUser.full_name" class="input" />
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.password') }}</span>
<input v-model="editableUser.password" class="input" type="password" :placeholder="userDialog.mode === 'edit' ? t('admin.passwordOptional') : t('admin.password')" />
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-dusk">{{ t('admin.role') }}</span>
<select v-model="editableUser.role" class="input" :disabled="editableUser.username === 'admin'">
<option v-if="editableUser.username === 'admin'" value="super_admin">{{ t('roles.super_admin') }}</option>
<option v-for="option in roleOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
</label>
</div>
<div class="mt-5 rounded-3xl border border-slate-200 bg-mist/40 px-4 py-4">
<p class="text-sm font-semibold text-ink">{{ t('admin.departmentPermissions') }}</p>
<p class="mt-2 text-sm text-dusk">{{ t('admin.departmentAccessHint') }}</p>
<div v-if="hasDepartments" class="mt-4 grid gap-2 md:grid-cols-2">
<label
v-for="department in departments"
:key="department.id"
class="flex items-center gap-3 rounded-2xl border border-slate-200 bg-white px-3 py-3 text-sm text-ink"
>
<input
class="h-4 w-4 accent-surge"
type="checkbox"
:checked="userDepartmentIds.includes(department.id)"
@change="toggleUserDepartment(department.id, ($event.target as HTMLInputElement).checked)"
/>
<span class="truncate">{{ department.name }}</span>
</label>
</div>
<input
v-else
class="input mt-4"
:value="t('admin.noDepartmentPlaceholder')"
disabled
readonly
/>
</div>
<div class="mt-6 flex flex-wrap justify-end gap-3">
<button class="btn-ghost" @click="resetUserDialog">{{ t('common.cancel') }}</button>
<button class="btn-primary" @click="saveUser">{{ t('common.save') }}</button>
</div>
</div>
</div>
<div
v-if="userDeleteDialog.open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="resetUserDeleteDialog"
>
<div class="panel w-full max-w-lg px-6 py-6" @click.stop>
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-2xl font-bold text-ink">{{ t('admin.deleteUser') }}</h3>
<p class="mt-2 text-sm text-dusk">{{ t('admin.deleteUserPrompt', { username: userDeleteDialog.username }) }}</p>
</div>
<button class="btn-ghost flex h-12 w-12 items-center justify-center rounded-2xl px-0" @click="resetUserDeleteDialog" aria-label="Close">
<svg aria-hidden="true" class="h-5 w-5" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M5 5l10 10M15 5L5 15" />
</svg>
</button>
</div>
<div class="mt-6 flex flex-wrap justify-end gap-3">
<button class="btn-ghost" @click="resetUserDeleteDialog">{{ t('common.cancel') }}</button>
<button class="btn-primary" @click="deleteUser">{{ t('workspace.delete') }}</button>
</div>
</div>
</div>
<DifySettingsDialog
:open="settingsDialogOpen"
@close="settingsDialogOpen = false"
@saved="pushToast($event)"
@error="pushToast($event, 'error')"
/>
<DifyHealthDialog
:open="healthDialogOpen"
@close="healthDialogOpen = false"
@toast="pushToast($event)"
@error="pushToast($event, 'error')"
/>
</div>
</main>
</template>
-100
View File
@@ -1,100 +0,0 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import LocaleSwitcher from '@/components/LocaleSwitcher.vue'
import { setSession } from '@/lib/auth'
import { apiFetch } from '@/lib/api'
import { useI18n } from '@/lib/i18n'
const router = useRouter()
const { t } = useI18n()
const username = ref('admin')
const password = ref('admin123456')
const loading = ref(false)
const error = ref('')
const cards = computed(() => [
{
title: t('login.cards.batchUploadTitle'),
body: t('login.cards.batchUploadBody')
},
{
title: t('login.cards.queuedConversionTitle'),
body: t('login.cards.queuedConversionBody')
},
{
title: t('login.cards.difyMappingTitle'),
body: t('login.cards.difyMappingBody')
}
])
async function submit() {
loading.value = true
error.value = ''
try {
const data = await apiFetch('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ username: username.value, password: password.value }),
skipAuth: true
})
setSession(data.access_token, data.user)
router.push('/workspace')
} catch (err) {
error.value = err instanceof Error ? err.message : t('login.loginFailed')
} finally {
loading.value = false
}
}
</script>
<template>
<main class="min-h-screen px-6 py-10 md:px-10">
<div class="mx-auto max-w-6xl">
<div class="mb-6 flex justify-end">
<LocaleSwitcher />
</div>
</div>
<div class="mx-auto grid min-h-[calc(100vh-8rem)] max-w-6xl gap-8 lg:grid-cols-[1.15fr_0.85fr]">
<section class="panel relative overflow-hidden px-8 py-10 md:px-12">
<div class="absolute inset-x-0 top-0 h-1.5 bg-gradient-to-r from-surge via-cyan-400 to-mint"></div>
<p class="text-sm font-semibold uppercase tracking-[0.32em] text-surge">{{ t('login.productName') }}</p>
<h1 class="mt-6 max-w-xl text-4xl font-bold leading-tight text-ink md:text-6xl">
{{ t('login.heading') }}
</h1>
<p class="mt-6 max-w-2xl text-base leading-8 text-dusk md:text-lg">
{{ t('login.description') }}
</p>
<div class="mt-10 grid gap-4 md:grid-cols-3">
<div v-for="card in cards" :key="card.title" class="rounded-3xl border border-slate-200 bg-mist/80 p-5">
<p class="text-sm font-semibold text-ink">{{ card.title }}</p>
<p class="mt-2 text-sm leading-6 text-dusk">{{ card.body }}</p>
</div>
</div>
</section>
<section class="panel flex items-center px-8 py-10 md:px-10">
<form class="w-full space-y-5" @submit.prevent="submit">
<div>
<p class="text-sm font-semibold uppercase tracking-[0.24em] text-dusk">{{ t('login.signInLabel') }}</p>
<h2 class="mt-3 text-3xl font-bold text-ink">{{ t('login.enterWorkspace') }}</h2>
</div>
<label class="block space-y-2">
<span class="text-sm text-dusk">{{ t('login.username') }}</span>
<input v-model="username" class="input" placeholder="admin" />
</label>
<label class="block space-y-2">
<span class="text-sm text-dusk">{{ t('login.password') }}</span>
<input v-model="password" class="input" type="password" :placeholder="t('login.passwordPlaceholder')" />
</label>
<p v-if="error" class="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
{{ error }}
</p>
<button class="btn-primary w-full py-3 text-base" :disabled="loading">
{{ loading ? t('login.signingIn') : t('login.signInContinue') }}
</button>
</form>
</section>
</div>
</main>
</template>
File diff suppressed because it is too large. Load diff
-2
View File
@@ -1,2 +0,0 @@
/// <reference types="vite/client" />
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more