Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
137d9508ae | ||
|
|
888e8f3054 | ||
|
|
c7871c94b5 | ||
|
|
efae286f5c | ||
|
|
fafcdfe742 | ||
|
|
7475828c63 | ||
|
|
29bd60a24b | ||
|
|
f6a23c9534 | ||
|
|
514c3d01be | ||
|
|
20271ada61 | ||
|
|
42e29fd747 | ||
|
|
35f650720f | ||
|
|
e06d5f7e01 | ||
|
|
5e8ea03b6c | ||
|
|
605317c2b2 | ||
|
|
639b0944db | ||
|
|
4d5a9942c2 | ||
|
|
df7beb2189 | ||
|
|
24da604727 | ||
|
|
a0c8721fbb | ||
|
|
b48f1e592a | ||
|
|
3a6e82bb03 | ||
|
|
9ccfb97fa9 | ||
|
|
b3e233bf76 | ||
|
|
f18b6ce2df | ||
|
|
2b8a0010ef | ||
|
|
2ece8a2ca0 | ||
|
|
abb3efe114 |
No files matched your search
@@ -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
|
|
||||||
Executable
+33
@@ -0,0 +1,33 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||||
|
cd "${ROOT_DIR}"
|
||||||
|
|
||||||
|
STAGED_FILES="$(git diff --cached --name-only --diff-filter=ACMR || true)"
|
||||||
|
if [[ -z "${STAGED_FILES}" ]]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
MODELS_CHANGED=0
|
||||||
|
MIGRATION_CHANGED=0
|
||||||
|
|
||||||
|
if echo "${STAGED_FILES}" | grep -Eq '^backend/app/models\.py$'; then
|
||||||
|
MODELS_CHANGED=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if echo "${STAGED_FILES}" | grep -Eq '^backend/migrations/versions/.*\.py$'; then
|
||||||
|
MIGRATION_CHANGED=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "${MODELS_CHANGED}" -eq 1 && "${MIGRATION_CHANGED}" -eq 0 ]]; then
|
||||||
|
echo "[pre-commit] 检测到 backend/app/models.py 已暂存,但未检测到 migration 文件暂存。"
|
||||||
|
echo "[pre-commit] 请先执行:"
|
||||||
|
echo " cd backend"
|
||||||
|
echo " venv/bin/flask --app manage.py db migrate -m \"your_change\""
|
||||||
|
echo " venv/bin/flask --app manage.py db upgrade"
|
||||||
|
echo " git add backend/migrations/versions/*.py"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 0
|
||||||
+58
-65
@@ -1,75 +1,68 @@
|
|||||||
# =========================
|
# Environments
|
||||||
# Secrets / env
|
deploy.sh
|
||||||
# =========================
|
deploy_docker_rsync.sh
|
||||||
|
docs/
|
||||||
|
venv/
|
||||||
|
backend/venv/
|
||||||
|
env/
|
||||||
.env
|
.env
|
||||||
.env.*
|
.venv
|
||||||
!.env.example
|
build/
|
||||||
backend.env
|
develop-eggs/
|
||||||
backend.env.*
|
dist/
|
||||||
!backend.env.example
|
downloads/
|
||||||
*.key
|
eggs/
|
||||||
*.pem
|
.eggs/
|
||||||
*secret*
|
lib/
|
||||||
*token*
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
# =========================
|
# Python
|
||||||
# OS / IDE
|
__pycache__/
|
||||||
# =========================
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
frontend/node_modules/
|
||||||
|
# frontend/dist/ <-- Commented out to allow committing dist
|
||||||
|
frontend/.DS_Store
|
||||||
|
frontend/.env.local
|
||||||
|
frontend/.env.*.local
|
||||||
|
|
||||||
|
# IDEs
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# Runtime files
|
||||||
|
.run/
|
||||||
|
|
||||||
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
.idea/
|
|
||||||
.vscode/
|
|
||||||
|
|
||||||
# =========================
|
# Runtime files
|
||||||
# Python
|
.run/
|
||||||
# =========================
|
|
||||||
__pycache__/
|
|
||||||
*.pyc
|
|
||||||
*.pyo
|
|
||||||
*.pyd
|
|
||||||
.pytest_cache/
|
|
||||||
.venv/
|
|
||||||
venv/
|
|
||||||
python/
|
|
||||||
|
|
||||||
# =========================
|
docker-compose.yml
|
||||||
# Node
|
nginx.conf
|
||||||
# =========================
|
deploy_docker_rsync.sh
|
||||||
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
|
|
||||||
|
|
||||||
# =========================
|
gunicorn_config.py
|
||||||
# Databases (不要提交测试数据/本地库)
|
hxops_menu.sh
|
||||||
# =========================
|
|
||||||
*.db
|
|
||||||
*.sqlite
|
|
||||||
*.sqlite3
|
|
||||||
|
|
||||||
# =========================
|
nginx.conf
|
||||||
# Archives / bundles (不要提交打包产物)
|
docker-compose.yml
|
||||||
# =========================
|
gunicorn_config.py
|
||||||
*.zip
|
hxops_menu.sh
|
||||||
*.tar.gz
|
|
||||||
*.tgz
|
|
||||||
|
|
||||||
# =========================
|
|
||||||
# Optional: staging deploy output (如果是生成物就忽略)
|
|
||||||
# =========================
|
|
||||||
.deploy-stage/
|
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
* Serving Flask app 'app'
|
||||||
|
* Debug mode: on
|
||||||
|
[31m[1mWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.[0m
|
||||||
|
* Running on all addresses (0.0.0.0)
|
||||||
|
* Running on http://127.0.0.1:5002
|
||||||
|
* Running on http://192.168.31.48:5002
|
||||||
|
[33mPress CTRL+C to quit[0m
|
||||||
|
* Restarting with stat
|
||||||
|
* Debugger is active!
|
||||||
|
* Debugger PIN: 679-745-431
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:45:02] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:45:08] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:45:37] "[35m[1mPOST /api/admin/agents HTTP/1.1[0m" 201 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:47:50] "[31m[1mGET /api/admin/agents HTTP/1.1[0m" 403 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:47:55] "[31m[1mGET /api/admin/agents HTTP/1.1[0m" 403 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:48:02] "GET /api/admin/agents HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:00] "GET /api/agents/public HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:10] "[31m[1mPOST /api/user/login HTTP/1.1[0m" 401 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:17] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:18] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:20] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:20] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:30] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:30] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:50:02] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:50:45] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:50:51] "GET /api/user/home HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/home HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:32] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/home HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:32] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:34] "GET /api/agents/public HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:43] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:43] "GET /api/user/home HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:46] "GET /api/user/profile HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:57] "POST /api/user/change-password HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:59] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:55:59] "GET /api/user/home HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:02] "GET /api/agents/public HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:07] "POST /api/user/login HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:07] "GET /api/user/home HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/agents HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/permission-requests HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/reports/usage HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/departments HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/users HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/reports/feedback HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:16] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:17] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:17] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:27] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||||
|
127.0.0.1 - - [28/Mar/2026 23:57:28] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
4903
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
|
||||||
|
> frontend@0.0.0 dev
|
||||||
|
> vite
|
||||||
|
|
||||||
|
|
||||||
|
VITE v8.0.0-beta.15 ready in 118 ms
|
||||||
|
|
||||||
|
➜ Local: http://localhost:8881/
|
||||||
|
➜ Network: use --host to expose
|
||||||
|
11:51:45 PM [vite] (client) page reload src/main.ts
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
4917
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
2026-03-28 23:44:52.265 CST [4865] LOG: starting PostgreSQL 18.1 (Homebrew) on aarch64-apple-darwin25.2.0, compiled by Apple clang version 17.0.0 (clang-1700.6.3.2), 64-bit
|
||||||
|
2026-03-28 23:44:52.267 CST [4865] LOG: listening on IPv6 address "::1", port 5432
|
||||||
|
2026-03-28 23:44:52.267 CST [4865] LOG: listening on IPv4 address "127.0.0.1", port 5432
|
||||||
|
2026-03-28 23:44:52.267 CST [4865] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"
|
||||||
|
2026-03-28 23:44:52.275 CST [4872] LOG: database system was shut down at 2026-03-28 23:37:09 CST
|
||||||
|
2026-03-28 23:44:52.277 CST [4865] LOG: database system is ready to accept connections
|
||||||
|
2026-03-28 23:49:52.269 CST [4870] LOG: checkpoint starting: time
|
||||||
|
2026-03-28 23:49:53.685 CST [4870] LOG: checkpoint complete: wrote 14 buffers (0.1%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=1.414 s, sync=0.002 s, total=1.416 s; sync files=16, longest=0.001 s, average=0.001 s; distance=40 kB, estimate=40 kB; lsn=0/3994578, redo lsn=0/39944E8
|
||||||
|
2026-03-28 23:54:52.680 CST [4870] LOG: checkpoint starting: time
|
||||||
|
2026-03-28 23:54:53.185 CST [4870] LOG: checkpoint complete: wrote 5 buffers (0.0%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.505 s, sync=0.001 s, total=0.506 s; sync files=6, longest=0.001 s, average=0.001 s; distance=11 kB, estimate=37 kB; lsn=0/3997280, redo lsn=0/3997228
|
||||||
|
2026-03-28 23:59:52.181 CST [4870] LOG: checkpoint starting: time
|
||||||
|
2026-03-28 23:59:52.687 CST [4870] LOG: checkpoint complete: wrote 5 buffers (0.0%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.505 s, sync=0.001 s, total=0.507 s; sync files=6, longest=0.001 s, average=0.001 s; distance=12 kB, estimate=34 kB; lsn=0/399A400, redo lsn=0/399A3A8
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
4865
|
||||||
@@ -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 文档在文档清洗系统中没有本地文件映射。
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
# Document Cleaning
|
|
||||||
|
|
||||||
Independent internal web system for document cleaning, version tracking, batch download, and manual sync into Dify datasets.
|
|
||||||
|
|
||||||
## 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`
|
|
||||||
|
|
||||||
## Local Run
|
|
||||||
|
|
||||||
1. Copy `.env.example` to `.env` and fill in `DIFY_API_KEY`.
|
|
||||||
2. Start services:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose up --build -d
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Open `http://localhost:8891`.
|
|
||||||
|
|
||||||
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
|
|
||||||
```
|
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# WeCom Integration Checklist
|
||||||
|
|
||||||
|
## 1) Backend Environment Variables
|
||||||
|
|
||||||
|
Set these on the backend runtime:
|
||||||
|
|
||||||
|
- `WECOM_ENABLED=true`
|
||||||
|
- `WECOM_CORP_ID=<your_corp_id>`
|
||||||
|
- `WECOM_AGENT_ID=<your_agent_id>`
|
||||||
|
- `WECOM_SECRET=<your_app_secret>`
|
||||||
|
- `WECOM_REDIRECT_URI=https://<your-domain>/workspace`
|
||||||
|
- `WECOM_AUTO_CREATE_USER=true` (or `false` if you require manual admin binding)
|
||||||
|
|
||||||
|
## 2) Database Migration
|
||||||
|
|
||||||
|
Run migrations after deployment:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
flask db upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
This applies:
|
||||||
|
|
||||||
|
- WeCom user binding fields in `users`
|
||||||
|
- Login audit table `login_audits`
|
||||||
|
|
||||||
|
## 3) WeCom Console Configuration
|
||||||
|
|
||||||
|
In WeCom admin console (自建应用):
|
||||||
|
|
||||||
|
1. Configure application homepage URL to your HTTPS domain.
|
||||||
|
2. Configure OAuth trusted redirect domain.
|
||||||
|
3. Ensure callback URL matches `WECOM_REDIRECT_URI`.
|
||||||
|
4. Ensure users/groups are visible to the app.
|
||||||
|
|
||||||
|
## 4) Frontend Checks
|
||||||
|
|
||||||
|
1. Open `/workspace`.
|
||||||
|
2. Verify `企业微信登录 / Login with WeCom` button is shown.
|
||||||
|
3. Trigger login in WeCom and confirm redirect back to `/workspace`.
|
||||||
|
4. Verify session is stored and user enters workspace.
|
||||||
|
|
||||||
|
## 5) Admin Operations
|
||||||
|
|
||||||
|
Available admin APIs:
|
||||||
|
|
||||||
|
- `GET /api/admin/wecom/bindings`
|
||||||
|
- `POST /api/admin/wecom/bind`
|
||||||
|
- `POST /api/admin/wecom/unbind`
|
||||||
|
- `GET /api/admin/wecom/login-audits`
|
||||||
|
|
||||||
|
## 6) Smoke Tests
|
||||||
|
|
||||||
|
1. Password login still works.
|
||||||
|
2. WeCom login success creates an audit record.
|
||||||
|
3. Invalid/expired state is rejected.
|
||||||
|
4. Disabled user cannot login via WeCom.
|
||||||
|
|
||||||
+15
-11
@@ -1,20 +1,24 @@
|
|||||||
FROM python:3.12-slim
|
FROM python:3.12-slim
|
||||||
|
|
||||||
ENV PYTHONDONTWRITEBYTECODE=1
|
|
||||||
ENV PYTHONUNBUFFERED=1
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
RUN apt-get update \
|
# Install system dependencies
|
||||||
&& apt-get install -y --no-install-recommends libreoffice fonts-noto-cjk curl \
|
# libpq-dev is required for psycopg2
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
gcc \
|
||||||
|
libpq-dev \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
COPY requirements.txt /app/requirements.txt
|
# Install Python dependencies
|
||||||
RUN pip install --no-cache-dir -r /app/requirements.txt
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
COPY . /app
|
# Copy application code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
EXPOSE 8000
|
# Expose port 5000
|
||||||
|
EXPOSE 5000
|
||||||
CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
|
|
||||||
|
|
||||||
|
# Start Gunicorn
|
||||||
|
# Using the config file we created earlier
|
||||||
|
CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"]
|
||||||
@@ -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
|
|
||||||
|
|
||||||
+38
-1
@@ -1 +1,38 @@
|
|||||||
"""Document Cleaning backend package."""
|
|
||||||
|
"""
|
||||||
|
backend/app/__init__.py
|
||||||
|
应用工厂
|
||||||
|
"""
|
||||||
|
from flask import Flask
|
||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
from flask_cors import CORS
|
||||||
|
from app.config import config
|
||||||
|
|
||||||
|
db = SQLAlchemy()
|
||||||
|
migrate = Migrate()
|
||||||
|
|
||||||
|
def create_app(config_name='default'):
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config.from_object(config[config_name])
|
||||||
|
|
||||||
|
db.init_app(app)
|
||||||
|
migrate.init_app(app, db)
|
||||||
|
CORS(app) # 允许跨域
|
||||||
|
|
||||||
|
# 注册 Blueprints
|
||||||
|
from app.api.chat import chat_bp
|
||||||
|
from app.api.admin import admin_bp
|
||||||
|
from app.api.agents import agents_bp
|
||||||
|
from app.api.user import user_bp
|
||||||
|
|
||||||
|
# 聊天相关接口
|
||||||
|
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||||
|
# 管理员相关接口
|
||||||
|
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||||
|
# 普通用户可见的 Agent 列表接口
|
||||||
|
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||||
|
# 当前用户相关接口(首页、常用问题等)
|
||||||
|
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||||
|
|
||||||
|
return app
|
||||||
@@ -1 +0,0 @@
|
|||||||
from app.api import admin, auth, files, groups, integration, jobs
|
|
||||||
+820
-432
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/agents.py
|
||||||
|
文件用途:普通用户可见的 Agent 列表接口
|
||||||
|
引用文件:flask, models, decorators
|
||||||
|
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||||
|
"""
|
||||||
|
from flask import Blueprint, jsonify, g
|
||||||
|
from app.models import Agent, User
|
||||||
|
from app.decorators import _get_current_user # 内部工具函数
|
||||||
|
|
||||||
|
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||||
|
agents_bp = Blueprint('agents', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@agents_bp.route('', methods=['GET'])
|
||||||
|
def list_user_agents():
|
||||||
|
"""
|
||||||
|
获取当前用户可见的 Agent 列表
|
||||||
|
用途:Workspace 页面展示应用网格
|
||||||
|
"""
|
||||||
|
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||||
|
user: User = _get_current_user()
|
||||||
|
|
||||||
|
# 管理员:返回所有激活的 Agent
|
||||||
|
if user.role == 'admin':
|
||||||
|
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||||
|
else:
|
||||||
|
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||||
|
agents = [a for a in user.agents if a.is_active]
|
||||||
|
|
||||||
|
# 序列化为前端所需字段
|
||||||
|
|
||||||
|
@agents_bp.route('/public', methods=['GET'])
|
||||||
|
def list_public_agents():
|
||||||
|
"""
|
||||||
|
获取公开的 Agent 列表 (无需登录)
|
||||||
|
用途:登录页面展示
|
||||||
|
"""
|
||||||
|
# 返回所有激活的 Agent,包含基本信息
|
||||||
|
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||||
|
|
||||||
|
data = [
|
||||||
|
{
|
||||||
|
'id': a.id,
|
||||||
|
'name': a.name,
|
||||||
|
'description': a.description,
|
||||||
|
'icon_url': a.icon_url,
|
||||||
|
}
|
||||||
|
for a in agents
|
||||||
|
]
|
||||||
|
return jsonify(data)
|
||||||
|
|
||||||
|
|
||||||
@@ -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))
|
|
||||||
|
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
backend/app/api/chat.py
|
||||||
|
文件用途:定义聊天相关 API 路由
|
||||||
|
引用文件:flask, services.dify, decorators, models
|
||||||
|
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
|
||||||
|
"""
|
||||||
|
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
|
||||||
|
from sqlalchemy import func, desc
|
||||||
|
from app.services.dify import DifyService
|
||||||
|
from app.decorators import require_agent_permission
|
||||||
|
from app.models import Agent, ChatLog, Feedback
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||||
|
chat_bp = Blueprint('chat', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/sessions', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_chat_sessions():
|
||||||
|
"""
|
||||||
|
获取当前用户与当前 Agent 的历史会话列表
|
||||||
|
"""
|
||||||
|
user = getattr(g, 'current_user', None)
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
|
||||||
|
if user is None or agent is None:
|
||||||
|
return jsonify({'error': 'Missing context'}), 500
|
||||||
|
|
||||||
|
# 聚合查询:按 conversation_id 分组,获取最新时间
|
||||||
|
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
|
||||||
|
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
|
||||||
|
# 更严谨的做法是先查出 conversation_ids,再查详情。
|
||||||
|
# 这里为了简单,我们假设 query 不为空
|
||||||
|
|
||||||
|
# 修正逻辑:先查出最近的 20 个 conversation_id
|
||||||
|
subquery = db.session.query(
|
||||||
|
ChatLog.conversation_id,
|
||||||
|
func.max(ChatLog.created_at).label('last_active')
|
||||||
|
).filter_by(
|
||||||
|
user_id=user.id,
|
||||||
|
agent_id=agent.id
|
||||||
|
).group_by(ChatLog.conversation_id).subquery()
|
||||||
|
|
||||||
|
# 联表查询获取详细信息,按时间倒序
|
||||||
|
results = db.session.query(
|
||||||
|
subquery.c.conversation_id,
|
||||||
|
subquery.c.last_active,
|
||||||
|
ChatLog.query
|
||||||
|
).join(
|
||||||
|
ChatLog,
|
||||||
|
(ChatLog.conversation_id == subquery.c.conversation_id) &
|
||||||
|
(ChatLog.created_at == subquery.c.last_active)
|
||||||
|
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||||
|
|
||||||
|
sessions = []
|
||||||
|
for row in results:
|
||||||
|
if not row.conversation_id:
|
||||||
|
continue
|
||||||
|
sessions.append({
|
||||||
|
'id': 0, # 前端需要 id key
|
||||||
|
'conversation_id': row.conversation_id,
|
||||||
|
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
|
||||||
|
'created_at': row.last_active.isoformat()
|
||||||
|
})
|
||||||
|
|
||||||
|
return jsonify(sessions)
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/messages', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_chat_messages():
|
||||||
|
"""
|
||||||
|
获取指定会话的消息记录
|
||||||
|
"""
|
||||||
|
conversation_id = request.args.get('conversation_id')
|
||||||
|
if not conversation_id:
|
||||||
|
return jsonify([])
|
||||||
|
|
||||||
|
logs = db.session.query(ChatLog).filter_by(
|
||||||
|
conversation_id=conversation_id
|
||||||
|
).order_by(ChatLog.created_at.asc()).all()
|
||||||
|
|
||||||
|
messages = []
|
||||||
|
for log in logs:
|
||||||
|
messages.append({'role': 'user', 'content': log.query})
|
||||||
|
messages.append({'role': 'assistant', 'content': log.answer})
|
||||||
|
|
||||||
|
return jsonify(messages)
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/completions', methods=['POST'])
|
||||||
|
@require_agent_permission
|
||||||
|
def chat_completions():
|
||||||
|
"""
|
||||||
|
SSE 流式聊天接口
|
||||||
|
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
|
||||||
|
核心逻辑:
|
||||||
|
1. 从请求体中读取 query / agent_id / conversation_id
|
||||||
|
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
|
||||||
|
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
|
||||||
|
传入参数:
|
||||||
|
无(从 request.json 读取)
|
||||||
|
返回值:
|
||||||
|
Flask Response 对象,mimetype=text/event-stream
|
||||||
|
"""
|
||||||
|
# 解析 JSON 请求体
|
||||||
|
data = request.get_json() or {}
|
||||||
|
# 提取用户提问内容
|
||||||
|
query = data.get('query')
|
||||||
|
# 提取会话 ID(可选)
|
||||||
|
conversation_id = data.get('conversation_id')
|
||||||
|
|
||||||
|
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
|
||||||
|
user = getattr(g, 'current_user', None)
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
|
||||||
|
# 安全兜底:如果装饰器未正确注入,返回错误
|
||||||
|
if user is None or agent is None:
|
||||||
|
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||||
|
|
||||||
|
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||||
|
return Response(
|
||||||
|
stream_with_context(
|
||||||
|
DifyService.stream_chat(query, user.id, agent, conversation_id)
|
||||||
|
),
|
||||||
|
mimetype='text/event-stream',
|
||||||
|
headers={
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
|
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
||||||
|
'X-Accel-Buffering': 'no'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/feedback', methods=['POST'])
|
||||||
|
@require_agent_permission
|
||||||
|
def submit_feedback():
|
||||||
|
"""
|
||||||
|
提交对回答的评分与评论
|
||||||
|
用途:在对话结束后,由前端发送评分(1~5)和文字意见
|
||||||
|
核心逻辑:
|
||||||
|
1. 从请求体中读取 score/comment/conversation_id
|
||||||
|
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
|
||||||
|
3. 为该 ChatLog 创建或更新 Feedback 记录
|
||||||
|
"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
score = data.get('score')
|
||||||
|
comment = data.get('comment') or ''
|
||||||
|
conversation_id = data.get('conversation_id')
|
||||||
|
|
||||||
|
if not current_app.config.get('FEEDBACK_ENABLED', True):
|
||||||
|
return jsonify({'error': 'feedback is disabled'}), 403
|
||||||
|
|
||||||
|
if score is None:
|
||||||
|
return jsonify({'error': 'score is required'}), 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
score_value = int(score)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return jsonify({'error': 'score must be an integer'}), 400
|
||||||
|
|
||||||
|
if score_value < 1 or score_value > 5:
|
||||||
|
return jsonify({'error': 'score must be between 1 and 5'}), 400
|
||||||
|
|
||||||
|
user = getattr(g, 'current_user', None)
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
if user is None or agent is None:
|
||||||
|
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||||
|
|
||||||
|
# 构造查询:限定在当前用户和 Agent 范围内
|
||||||
|
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
|
||||||
|
if conversation_id:
|
||||||
|
query = query.filter_by(conversation_id=conversation_id)
|
||||||
|
|
||||||
|
# 取最新一条对话日志
|
||||||
|
chat_log = query.order_by(ChatLog.created_at.desc()).first()
|
||||||
|
if not chat_log:
|
||||||
|
return jsonify({'error': 'ChatLog not found'}), 404
|
||||||
|
|
||||||
|
# 如果已存在反馈,则更新;否则新建
|
||||||
|
if chat_log.feedback:
|
||||||
|
chat_log.feedback.score = score_value
|
||||||
|
chat_log.feedback.comment = comment
|
||||||
|
else:
|
||||||
|
fb = Feedback(
|
||||||
|
chat_log_id=chat_log.id,
|
||||||
|
score=score_value,
|
||||||
|
comment=comment,
|
||||||
|
)
|
||||||
|
db.session.add(fb)
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
@@ -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]}
|
|
||||||
@@ -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}
|
|
||||||
@@ -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}
|
|
||||||
@@ -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)
|
|
||||||
@@ -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)
|
|
||||||
@@ -0,0 +1,729 @@
|
|||||||
|
from flask import Blueprint, request, jsonify, current_app, url_for
|
||||||
|
from app import db
|
||||||
|
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit
|
||||||
|
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
import uuid
|
||||||
|
import requests
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
user_bp = Blueprint('user', __name__)
|
||||||
|
|
||||||
|
_WECOM_ACCESS_TOKEN_CACHE = {
|
||||||
|
'token': None,
|
||||||
|
'expires_at': None,
|
||||||
|
}
|
||||||
|
_WECOM_STATE_CACHE = {}
|
||||||
|
|
||||||
|
def _write_login_audit(
|
||||||
|
source: str,
|
||||||
|
status: str,
|
||||||
|
user: User = None,
|
||||||
|
username: str = None,
|
||||||
|
reason: str = None,
|
||||||
|
wecom_userid: str = None
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
audit = LoginAudit(
|
||||||
|
user_id=user.id if user else None,
|
||||||
|
username=username or (user.username if user else None),
|
||||||
|
source=source,
|
||||||
|
status=status,
|
||||||
|
reason=reason,
|
||||||
|
wecom_userid=wecom_userid,
|
||||||
|
ip=request.headers.get('X-Forwarded-For', request.remote_addr),
|
||||||
|
user_agent=(request.user_agent.string or '')[:255]
|
||||||
|
)
|
||||||
|
db.session.add(audit)
|
||||||
|
except Exception:
|
||||||
|
# Do not break auth flow because of audit logging.
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _get_current_user():
|
||||||
|
"""
|
||||||
|
Helper to get current user from headers
|
||||||
|
"""
|
||||||
|
user_id = request.headers.get('X-User-Id')
|
||||||
|
if not user_id:
|
||||||
|
return None
|
||||||
|
return db.session.get(User, int(user_id))
|
||||||
|
|
||||||
|
def _is_wecom_configured():
|
||||||
|
return all([
|
||||||
|
current_app.config.get('WECOM_ENABLED'),
|
||||||
|
current_app.config.get('WECOM_CORP_ID'),
|
||||||
|
current_app.config.get('WECOM_AGENT_ID'),
|
||||||
|
current_app.config.get('WECOM_SECRET'),
|
||||||
|
])
|
||||||
|
|
||||||
|
def _cleanup_wecom_state_cache():
|
||||||
|
now = datetime.utcnow()
|
||||||
|
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
||||||
|
for k in expired:
|
||||||
|
_WECOM_STATE_CACHE.pop(k, None)
|
||||||
|
|
||||||
|
def _issue_wecom_state():
|
||||||
|
_cleanup_wecom_state_cache()
|
||||||
|
state = f"hxops_wecom_{uuid.uuid4().hex}"
|
||||||
|
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
|
||||||
|
return state
|
||||||
|
|
||||||
|
def _consume_wecom_state(state: str):
|
||||||
|
if not state:
|
||||||
|
return False
|
||||||
|
_cleanup_wecom_state_cache()
|
||||||
|
exp = _WECOM_STATE_CACHE.pop(state, None)
|
||||||
|
return bool(exp and exp > datetime.utcnow())
|
||||||
|
|
||||||
|
def _get_wecom_access_token():
|
||||||
|
now = datetime.utcnow()
|
||||||
|
token = _WECOM_ACCESS_TOKEN_CACHE.get('token')
|
||||||
|
expires_at = _WECOM_ACCESS_TOKEN_CACHE.get('expires_at')
|
||||||
|
|
||||||
|
if token and expires_at and now < expires_at:
|
||||||
|
return token
|
||||||
|
|
||||||
|
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||||
|
secret = current_app.config.get('WECOM_SECRET')
|
||||||
|
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
|
||||||
|
resp = requests.get(token_url, params={'corpid': corp_id, 'corpsecret': secret}, timeout=8)
|
||||||
|
data = resp.json()
|
||||||
|
|
||||||
|
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||||
|
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
||||||
|
|
||||||
|
_WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
||||||
|
_WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||||
|
return data['access_token']
|
||||||
|
|
||||||
|
def _build_login_payload(user: User, source: str = 'password'):
|
||||||
|
return {
|
||||||
|
'id': user.id,
|
||||||
|
'username': user.username,
|
||||||
|
'role': user.role,
|
||||||
|
'default_agent_id': user.default_agent_id,
|
||||||
|
'source': source,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _sync_or_create_user_from_wecom(wecom_user: dict) -> User:
|
||||||
|
userid = wecom_user.get('userid')
|
||||||
|
email = wecom_user.get('email')
|
||||||
|
mobile = wecom_user.get('mobile')
|
||||||
|
unionid = wecom_user.get('unionid')
|
||||||
|
name = wecom_user.get('name') or userid or 'wecom_user'
|
||||||
|
|
||||||
|
user = None
|
||||||
|
if userid:
|
||||||
|
user = db.session.query(User).filter_by(wecom_userid=userid).first()
|
||||||
|
if not user and email:
|
||||||
|
user = db.session.query(User).filter_by(email=email).first()
|
||||||
|
if not user and mobile:
|
||||||
|
user = db.session.query(User).filter_by(phone_number=mobile).first()
|
||||||
|
|
||||||
|
if user:
|
||||||
|
if userid and not user.wecom_userid:
|
||||||
|
user.wecom_userid = userid
|
||||||
|
if unionid and not user.wecom_unionid:
|
||||||
|
user.wecom_unionid = unionid
|
||||||
|
if name and not user.real_name:
|
||||||
|
user.real_name = name
|
||||||
|
if email and not user.email:
|
||||||
|
user.email = email
|
||||||
|
if mobile and not user.phone_number:
|
||||||
|
user.phone_number = mobile
|
||||||
|
return user
|
||||||
|
|
||||||
|
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
|
||||||
|
raise PermissionError('No linked account found. Contact admin to bind WeCom account.')
|
||||||
|
|
||||||
|
# Ensure unique username for auto-created user
|
||||||
|
base_username = (userid or email or mobile or f"wecom_{uuid.uuid4().hex[:8]}").replace('@', '_')
|
||||||
|
candidate = base_username
|
||||||
|
suffix = 1
|
||||||
|
while db.session.query(User).filter_by(username=candidate).first():
|
||||||
|
candidate = f"{base_username}_{suffix}"
|
||||||
|
suffix += 1
|
||||||
|
|
||||||
|
safe_email = email or f"{candidate}@wecom.local"
|
||||||
|
if db.session.query(User).filter_by(email=safe_email).first():
|
||||||
|
safe_email = f"{candidate}_{uuid.uuid4().hex[:6]}@wecom.local"
|
||||||
|
|
||||||
|
user = User(
|
||||||
|
username=candidate,
|
||||||
|
email=safe_email,
|
||||||
|
role='user',
|
||||||
|
status='active',
|
||||||
|
real_name=name,
|
||||||
|
phone_number=mobile,
|
||||||
|
wecom_userid=userid,
|
||||||
|
wecom_unionid=unionid,
|
||||||
|
)
|
||||||
|
# Set random password to make local password login explicit.
|
||||||
|
user.set_password(uuid.uuid4().hex)
|
||||||
|
db.session.add(user)
|
||||||
|
return user
|
||||||
|
|
||||||
|
@user_bp.route('/register', methods=['POST'])
|
||||||
|
def register():
|
||||||
|
"""
|
||||||
|
User registration
|
||||||
|
"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
|
||||||
|
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
|
||||||
|
for field in required_fields:
|
||||||
|
if not data.get(field):
|
||||||
|
return jsonify({'error': f'{field} is required'}), 400
|
||||||
|
|
||||||
|
if db.session.query(User).filter_by(username=data['username']).first():
|
||||||
|
return jsonify({'error': 'Username already exists'}), 400
|
||||||
|
if db.session.query(User).filter_by(email=data['email']).first():
|
||||||
|
return jsonify({'error': 'Email already exists'}), 400
|
||||||
|
if db.session.query(User).filter_by(employee_id=data['employee_id']).first():
|
||||||
|
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
user = User(
|
||||||
|
username=data['username'],
|
||||||
|
email=data['email'],
|
||||||
|
real_name=data['real_name'],
|
||||||
|
employee_id=data['employee_id'],
|
||||||
|
phone_number=data['phone_number'],
|
||||||
|
department=data.get('department'),
|
||||||
|
role='user',
|
||||||
|
status='active'
|
||||||
|
)
|
||||||
|
user.set_password(data['password'])
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return jsonify({'message': 'Registration successful', 'id': user.id}), 201
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/login', methods=['POST'])
|
||||||
|
def login():
|
||||||
|
"""
|
||||||
|
User login with detailed error messages
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = request.get_json() or {}
|
||||||
|
username = data.get('username')
|
||||||
|
password = data.get('password')
|
||||||
|
|
||||||
|
if not username or not password:
|
||||||
|
_write_login_audit('password', 'failed', username=username, reason='missing_credentials')
|
||||||
|
return jsonify({'error': 'Username and password are required'}), 400
|
||||||
|
|
||||||
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': 'User not found'}), 404
|
||||||
|
|
||||||
|
if not user.check_password(password):
|
||||||
|
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': 'Incorrect password'}), 401
|
||||||
|
|
||||||
|
if user.status != 'active':
|
||||||
|
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': 'Account is disabled'}), 403
|
||||||
|
_write_login_audit('password', 'success', user=user)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(_build_login_payload(user, 'password'))
|
||||||
|
except OperationalError as e:
|
||||||
|
print(f"Database connection error: {e}")
|
||||||
|
return jsonify({'error': 'Database connection failed'}), 503
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
print(f"Login error: {e}")
|
||||||
|
return jsonify({'error': 'Internal server error'}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/wecom/authorize-url', methods=['GET'])
|
||||||
|
def wecom_authorize_url():
|
||||||
|
if not _is_wecom_configured():
|
||||||
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
||||||
|
|
||||||
|
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
|
||||||
|
if not redirect_uri:
|
||||||
|
return jsonify({'error': 'redirect_uri is required'}), 400
|
||||||
|
|
||||||
|
state = _issue_wecom_state()
|
||||||
|
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||||
|
agent_id = current_app.config.get('WECOM_AGENT_ID')
|
||||||
|
|
||||||
|
url = (
|
||||||
|
"https://open.weixin.qq.com/connect/oauth2/authorize"
|
||||||
|
f"?appid={corp_id}"
|
||||||
|
f"&redirect_uri={quote(redirect_uri, safe='')}"
|
||||||
|
"&response_type=code"
|
||||||
|
f"&scope=snsapi_base&state={quote(state, safe='')}"
|
||||||
|
f"&agentid={agent_id}#wechat_redirect"
|
||||||
|
)
|
||||||
|
return jsonify({'url': url, 'state': state})
|
||||||
|
|
||||||
|
@user_bp.route('/wecom/login', methods=['POST'])
|
||||||
|
def wecom_login():
|
||||||
|
if not _is_wecom_configured():
|
||||||
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
||||||
|
|
||||||
|
data = request.get_json() or {}
|
||||||
|
code = data.get('code')
|
||||||
|
state = data.get('state')
|
||||||
|
if not code:
|
||||||
|
_write_login_audit('wecom', 'failed', reason='missing_code')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': 'code is required'}), 400
|
||||||
|
if not _consume_wecom_state(state):
|
||||||
|
_write_login_audit('wecom', 'failed', reason='invalid_state')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': 'Invalid or expired WeCom state'}), 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
access_token = _get_wecom_access_token()
|
||||||
|
info_resp = requests.get(
|
||||||
|
'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo',
|
||||||
|
params={'access_token': access_token, 'code': code},
|
||||||
|
timeout=8
|
||||||
|
)
|
||||||
|
info = info_resp.json()
|
||||||
|
if info.get('errcode') != 0 or not info.get('UserId'):
|
||||||
|
_write_login_audit('wecom', 'failed', reason=f"auth_failed:{info.get('errmsg')}")
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': f"WeCom auth failed: {info.get('errmsg', 'unknown error')}"}), 401
|
||||||
|
|
||||||
|
user_resp = requests.get(
|
||||||
|
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
|
||||||
|
params={'access_token': access_token, 'userid': info['UserId']},
|
||||||
|
timeout=8
|
||||||
|
)
|
||||||
|
wecom_user = user_resp.json()
|
||||||
|
if wecom_user.get('errcode') != 0:
|
||||||
|
_write_login_audit('wecom', 'failed', reason=f"user_fetch_failed:{wecom_user.get('errmsg')}", wecom_userid=info.get('UserId'))
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}"}), 401
|
||||||
|
|
||||||
|
user = _sync_or_create_user_from_wecom(wecom_user)
|
||||||
|
if user.status != 'active':
|
||||||
|
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=wecom_user.get('userid'))
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': 'Account is disabled'}), 403
|
||||||
|
_write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_user.get('userid'))
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(_build_login_payload(user, 'wecom'))
|
||||||
|
except PermissionError as e:
|
||||||
|
db.session.rollback()
|
||||||
|
_write_login_audit('wecom', 'failed', reason='bind_required')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': str(e)}), 403
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'error': f'WeCom login failed: {str(e)}'}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/wecom/binding', methods=['GET'])
|
||||||
|
def get_wecom_binding():
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
return jsonify({
|
||||||
|
'bound': bool(user.wecom_userid),
|
||||||
|
'wecom_userid': user.wecom_userid,
|
||||||
|
'wecom_unionid': user.wecom_unionid,
|
||||||
|
})
|
||||||
|
|
||||||
|
@user_bp.route('/wecom/unbind', methods=['POST'])
|
||||||
|
def unbind_wecom_self():
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
user.wecom_userid = None
|
||||||
|
user.wecom_unionid = None
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||||
|
|
||||||
|
@user_bp.route('/home', methods=['GET'])
|
||||||
|
def home():
|
||||||
|
"""
|
||||||
|
Get user homepage data
|
||||||
|
"""
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
# Get all agents available to user (including public ones)
|
||||||
|
if user.role == 'admin':
|
||||||
|
agents = db.session.query(Agent).filter_by(is_active=True).all()
|
||||||
|
else:
|
||||||
|
# User permissions
|
||||||
|
agents = user.agents
|
||||||
|
|
||||||
|
# Favorites
|
||||||
|
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||||
|
favorite_ids = [f.agent_id for f in favorites]
|
||||||
|
|
||||||
|
# Quick Questions (Global + User specific)
|
||||||
|
qqs = db.session.query(QuickQuestion).filter(
|
||||||
|
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
||||||
|
).all()
|
||||||
|
|
||||||
|
# Layout
|
||||||
|
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||||
|
layout = layout_config.layout if layout_config else {}
|
||||||
|
|
||||||
|
# Embedded agents
|
||||||
|
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||||
|
embedded_agents = []
|
||||||
|
for rel in embedded_rel:
|
||||||
|
agent = db.session.get(Agent, rel.agent_id)
|
||||||
|
if agent:
|
||||||
|
embedded_agents.append({
|
||||||
|
'id': agent.id,
|
||||||
|
'name': agent.name,
|
||||||
|
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
|
||||||
|
})
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'user': {
|
||||||
|
'id': user.id,
|
||||||
|
'username': user.username,
|
||||||
|
'role': user.role,
|
||||||
|
'default_agent_id': user.default_agent_id,
|
||||||
|
'language': user.language,
|
||||||
|
'theme_preference': user.theme_preference or 'system',
|
||||||
|
},
|
||||||
|
'agents': [{
|
||||||
|
'id': a.id,
|
||||||
|
'name': a.name,
|
||||||
|
'description': a.description,
|
||||||
|
'icon_url': a.icon_url
|
||||||
|
} for a in agents],
|
||||||
|
'favorite_agent_ids': favorite_ids,
|
||||||
|
'quick_questions': [{
|
||||||
|
'id': q.id,
|
||||||
|
'title': q.title,
|
||||||
|
'question': q.question,
|
||||||
|
'agent_id': q.agent_id
|
||||||
|
} for q in qqs],
|
||||||
|
'embedded_agents': embedded_agents,
|
||||||
|
'layout': layout
|
||||||
|
})
|
||||||
|
|
||||||
|
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||||
|
def toggle_favorite(agent_id: int):
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
if request.method == 'POST':
|
||||||
|
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||||
|
if not exists:
|
||||||
|
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||||
|
db.session.add(fav)
|
||||||
|
else:
|
||||||
|
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
@user_bp.route('/quick-questions', methods=['POST'])
|
||||||
|
def add_quick_question():
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
data = request.get_json() or {}
|
||||||
|
if not data.get('title') or not data.get('question') or not data.get('agent_id'):
|
||||||
|
return jsonify({'error': 'Missing fields'}), 400
|
||||||
|
|
||||||
|
qq = QuickQuestion(
|
||||||
|
user_id=user.id,
|
||||||
|
title=data['title'],
|
||||||
|
question=data['question'],
|
||||||
|
agent_id=data['agent_id']
|
||||||
|
)
|
||||||
|
db.session.add(qq)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': 'Added', 'id': qq.id}), 201
|
||||||
|
|
||||||
|
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
||||||
|
def update_quick_question(qq_id: int):
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||||||
|
if not qq:
|
||||||
|
return jsonify({"error": "QuickQuestion not found or permission denied"}), 404
|
||||||
|
|
||||||
|
if request.method == 'DELETE':
|
||||||
|
db.session.delete(qq)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
data = request.get_json() or {}
|
||||||
|
if 'title' in data:
|
||||||
|
qq.title = data['title']
|
||||||
|
if 'question' in data:
|
||||||
|
qq.question = data['question']
|
||||||
|
if 'agent_id' in data:
|
||||||
|
qq.agent_id = data['agent_id']
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({"status": "ok"})
|
||||||
|
|
||||||
|
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||||
|
def update_layout():
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
data = request.get_json() or {}
|
||||||
|
layout = data.get('layout', {})
|
||||||
|
|
||||||
|
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||||
|
if not config:
|
||||||
|
config = UserHomepageConfig(user_id=user.id, layout=layout)
|
||||||
|
db.session.add(config)
|
||||||
|
else:
|
||||||
|
config.layout = layout
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
@user_bp.route('/profile', methods=['GET', 'PUT'])
|
||||||
|
def user_profile():
|
||||||
|
"""
|
||||||
|
User profile management
|
||||||
|
GET: Get details
|
||||||
|
PUT: Update basic info
|
||||||
|
"""
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
if request.method == 'GET':
|
||||||
|
return jsonify({
|
||||||
|
'id': user.id,
|
||||||
|
'username': user.username,
|
||||||
|
'real_name': user.real_name,
|
||||||
|
'email': user.email,
|
||||||
|
'phone_number': user.phone_number,
|
||||||
|
'employee_id': user.employee_id,
|
||||||
|
'department': user.department,
|
||||||
|
'role': user.role,
|
||||||
|
'language': user.language,
|
||||||
|
'theme_preference': user.theme_preference or 'system',
|
||||||
|
})
|
||||||
|
|
||||||
|
# PUT
|
||||||
|
data = request.get_json() or {}
|
||||||
|
|
||||||
|
if 'real_name' in data:
|
||||||
|
user.real_name = data['real_name']
|
||||||
|
if 'phone_number' in data:
|
||||||
|
user.phone_number = data['phone_number']
|
||||||
|
if 'language' in data:
|
||||||
|
user.language = data['language']
|
||||||
|
if 'theme_preference' in data:
|
||||||
|
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||||||
|
return jsonify({'error': 'Invalid theme preference'}), 400
|
||||||
|
user.theme_preference = data['theme_preference']
|
||||||
|
|
||||||
|
# Allow editing email, employee_id, department
|
||||||
|
if 'email' in data:
|
||||||
|
# Check uniqueness
|
||||||
|
if data['email']:
|
||||||
|
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||||
|
if existing and existing.id != user.id:
|
||||||
|
return jsonify({'error': 'Email already exists'}), 400
|
||||||
|
user.email = data['email']
|
||||||
|
|
||||||
|
if 'employee_id' in data:
|
||||||
|
# Check uniqueness
|
||||||
|
if data['employee_id']:
|
||||||
|
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||||
|
if existing and existing.id != user.id:
|
||||||
|
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||||
|
user.employee_id = data['employee_id']
|
||||||
|
|
||||||
|
if 'department' in data:
|
||||||
|
user.department = data['department']
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': 'Profile updated successfully'})
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/change-password', methods=['POST'])
|
||||||
|
def change_password():
|
||||||
|
"""
|
||||||
|
Change password
|
||||||
|
"""
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
data = request.get_json() or {}
|
||||||
|
|
||||||
|
current_password = data.get('current_password')
|
||||||
|
new_password = data.get('new_password')
|
||||||
|
|
||||||
|
if not current_password or not new_password:
|
||||||
|
return jsonify({'error': 'Current and new password are required'}), 400
|
||||||
|
|
||||||
|
if not user.check_password(current_password):
|
||||||
|
return jsonify({'error': 'Incorrect current password'}), 403
|
||||||
|
|
||||||
|
try:
|
||||||
|
user.set_password(new_password)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': 'Password changed successfully'})
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/reset-password-by-email', methods=['POST'])
|
||||||
|
def reset_password_request():
|
||||||
|
"""
|
||||||
|
Request password reset via email
|
||||||
|
"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
email = data.get('email')
|
||||||
|
|
||||||
|
if not email:
|
||||||
|
return jsonify({'error': 'Email is required'}), 400
|
||||||
|
|
||||||
|
user = db.session.query(User).filter_by(email=email).first()
|
||||||
|
if not user:
|
||||||
|
# For security, don't reveal if email exists
|
||||||
|
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||||
|
|
||||||
|
# Generate token
|
||||||
|
token = str(uuid.uuid4())
|
||||||
|
user.reset_token = token
|
||||||
|
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# Mock send email
|
||||||
|
reset_link = f"http://localhost:5173/reset-password?token={token}"
|
||||||
|
print(f"============================================")
|
||||||
|
print(f"MOCK EMAIL TO: {email}")
|
||||||
|
print(f"SUBJECT: Password Reset Request")
|
||||||
|
print(f"LINK: {reset_link}")
|
||||||
|
print(f"============================================")
|
||||||
|
|
||||||
|
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||||
|
|
||||||
|
@user_bp.route('/reset-password-confirm', methods=['POST'])
|
||||||
|
def reset_password_confirm():
|
||||||
|
"""
|
||||||
|
Reset password with token
|
||||||
|
"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
token = data.get('token')
|
||||||
|
new_password = data.get('new_password')
|
||||||
|
|
||||||
|
if not token or not new_password:
|
||||||
|
return jsonify({'error': 'Token and new password are required'}), 400
|
||||||
|
|
||||||
|
user = db.session.query(User).filter_by(reset_token=token).first()
|
||||||
|
|
||||||
|
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||||
|
return jsonify({'error': 'Invalid or expired token'}), 400
|
||||||
|
|
||||||
|
try:
|
||||||
|
user.set_password(new_password)
|
||||||
|
user.reset_token = None
|
||||||
|
user.reset_token_expiry = None
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': 'Password has been reset successfully'})
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/agents/<int:id>', methods=['GET'])
|
||||||
|
def get_agent_details(id):
|
||||||
|
"""
|
||||||
|
Get agent details with permission check
|
||||||
|
"""
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 401
|
||||||
|
|
||||||
|
agent = db.session.get(Agent, id)
|
||||||
|
if not agent:
|
||||||
|
return jsonify({'error': 'Not found'}), 404
|
||||||
|
|
||||||
|
# Check permission
|
||||||
|
# Admin can access all
|
||||||
|
if user.role != 'admin':
|
||||||
|
has_permission = agent in user.agents
|
||||||
|
if not has_permission:
|
||||||
|
return jsonify({'error': 'Access denied'}), 403
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'id': agent.id,
|
||||||
|
'name': agent.name,
|
||||||
|
'description': agent.description,
|
||||||
|
'icon_url': agent.extra_config.get('icon_url') if agent.extra_config else None,
|
||||||
|
'welcome_message': agent.extra_config.get('welcome_message') if agent.extra_config else None,
|
||||||
|
'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []
|
||||||
|
})
|
||||||
|
|
||||||
|
@user_bp.route('/announcements', methods=['GET'])
|
||||||
|
def get_announcements():
|
||||||
|
"""
|
||||||
|
Get active announcements (Public)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
|
||||||
|
return jsonify([{
|
||||||
|
'id': a.id,
|
||||||
|
'title': a.title,
|
||||||
|
'content': a.content,
|
||||||
|
'created_at': a.created_at.isoformat()
|
||||||
|
} for a in anns])
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'error': str(e)}), 500
|
||||||
|
|
||||||
|
@user_bp.route('/announcements', methods=['POST'])
|
||||||
|
def create_announcement():
|
||||||
|
"""
|
||||||
|
Create announcement (Admin only)
|
||||||
|
"""
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user or user.role != 'admin':
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 403
|
||||||
|
|
||||||
|
data = request.get_json() or {}
|
||||||
|
if not data.get('title') or not data.get('content'):
|
||||||
|
return jsonify({'error': 'Missing fields'}), 400
|
||||||
|
|
||||||
|
ann = Announcement(
|
||||||
|
title=data['title'],
|
||||||
|
content=data['content'],
|
||||||
|
is_active=True
|
||||||
|
)
|
||||||
|
db.session.add(ann)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': 'Created', 'id': ann.id}), 201
|
||||||
|
|
||||||
|
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||||
|
def delete_announcement(id):
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user or user.role != 'admin':
|
||||||
|
return jsonify({'error': 'Unauthorized'}), 403
|
||||||
|
|
||||||
|
ann = db.session.get(Announcement, id)
|
||||||
|
if ann:
|
||||||
|
db.session.delete(ann)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'message': 'Deleted'})
|
||||||
+56
-105
@@ -1,112 +1,63 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from functools import lru_cache
|
"""
|
||||||
from pathlib import Path
|
backend/app/config.py
|
||||||
from typing import Literal
|
配置类,区分开发/生产环境
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
|
||||||
from pydantic import Field, model_validator
|
class Config:
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
|
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
|
||||||
|
# 数据库连接池配置
|
||||||
|
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||||
|
'pool_size': 20,
|
||||||
|
'max_overflow': 10,
|
||||||
|
'pool_recycle': 3600,
|
||||||
|
'pool_pre_ping': True
|
||||||
|
}
|
||||||
|
# Dify 网关配置
|
||||||
|
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
|
||||||
|
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||||
|
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||||
|
REDIS_URL = os.getenv('REDIS_URL', 'redis://:difyai123456@localhost:6379/0')
|
||||||
|
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||||
|
HR_WORKFLOW_IFRAME_URL = os.getenv(
|
||||||
|
'HR_WORKFLOW_IFRAME_URL',
|
||||||
|
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
|
||||||
|
)
|
||||||
|
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
|
||||||
|
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||||
|
# WeCom (企业微信) 登录配置
|
||||||
|
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||||
|
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||||
|
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||||
|
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||||
|
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||||
|
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||||
|
|
||||||
|
class DevelopmentConfig(Config):
|
||||||
class Settings(BaseSettings):
|
DEBUG = True
|
||||||
model_config = SettingsConfigDict(
|
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
|
||||||
env_file=".env",
|
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||||
env_file_encoding="utf-8",
|
'DATABASE_URL',
|
||||||
extra="ignore",
|
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
|
||||||
)
|
)
|
||||||
|
|
||||||
app_name: str = "Document Cleaning"
|
class ProductionConfig(Config):
|
||||||
api_prefix: str = "/api"
|
DEBUG = False
|
||||||
jwt_secret: str = "change-me-in-production"
|
# 服务器 Ubuntu PostgreSQL 配置
|
||||||
jwt_algorithm: str = "HS256"
|
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
|
||||||
access_token_expire_minutes: int = 720
|
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
|
||||||
|
|
||||||
database_backend: Literal["sqlite", "postgres"] = "sqlite"
|
class TestingConfig(Config):
|
||||||
database_url: str = ""
|
TESTING = True
|
||||||
sqlite_database_url: str = "sqlite:///./document_cleaning.db"
|
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||||
postgres_database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/document_cleaning"
|
WTF_CSRF_ENABLED = False
|
||||||
redis_url: str = "redis://redis:6379/0"
|
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||||
|
|
||||||
data_root: Path = Field(default=Path("./data"))
|
config = {
|
||||||
public_base_url: str = "http://192.168.100.230:8891"
|
'development': DevelopmentConfig,
|
||||||
allowed_origins: str = "http://192.168.100.230:8891,http://localhost:5173"
|
'testing': TestingConfig,
|
||||||
|
'production': ProductionConfig,
|
||||||
dify_base_url: str = "https://api.dify.ai/v1"
|
'default': DevelopmentConfig
|
||||||
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
|
|
||||||
@@ -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()
|
|
||||||
|
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
backend/app/decorators.py
|
||||||
|
文件用途:权限控制装饰器集合
|
||||||
|
引用文件:flask, functools, models, db
|
||||||
|
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||||
|
"""
|
||||||
|
from functools import wraps
|
||||||
|
from flask import request, jsonify, g
|
||||||
|
from app import db
|
||||||
|
from app.models import Agent, User
|
||||||
|
|
||||||
|
|
||||||
|
def _get_current_user() -> User:
|
||||||
|
"""
|
||||||
|
内部工具函数:获取当前登录用户
|
||||||
|
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
|
||||||
|
"""
|
||||||
|
user_id = request.headers.get('X-User-Id')
|
||||||
|
username = request.headers.get('X-Username')
|
||||||
|
role = request.headers.get('X-Role', 'user')
|
||||||
|
|
||||||
|
user = None
|
||||||
|
if user_id:
|
||||||
|
try:
|
||||||
|
user = User.query.get(int(user_id))
|
||||||
|
except ValueError:
|
||||||
|
user = None
|
||||||
|
if user is None and username:
|
||||||
|
user = User.query.filter_by(username=username).first()
|
||||||
|
if not user:
|
||||||
|
if user_id:
|
||||||
|
safe_id = int(user_id)
|
||||||
|
user = User(
|
||||||
|
id=safe_id,
|
||||||
|
username=username or f'user_{safe_id}',
|
||||||
|
email=f'{username or f"user_{safe_id}"}@example.com',
|
||||||
|
department='IT',
|
||||||
|
role=role,
|
||||||
|
)
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
elif username:
|
||||||
|
user = User(
|
||||||
|
username=username,
|
||||||
|
email=f'{username}@example.com',
|
||||||
|
department='IT',
|
||||||
|
role=role,
|
||||||
|
)
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
else:
|
||||||
|
# Check if guest user exists
|
||||||
|
user = User.query.filter_by(username='guest').first()
|
||||||
|
if not user:
|
||||||
|
user = User(
|
||||||
|
username='guest',
|
||||||
|
email='guest@example.com',
|
||||||
|
department='',
|
||||||
|
role='guest',
|
||||||
|
)
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
g.current_user = user
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def require_agent_permission(f):
|
||||||
|
"""
|
||||||
|
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||||
|
核心逻辑:
|
||||||
|
1. 从请求体中读取 agent_id
|
||||||
|
2. 获取当前用户 (临时固定为 ID=1)
|
||||||
|
3. 如果用户是 admin,则放行
|
||||||
|
4. 否则检查 user.agents 是否包含该 agent
|
||||||
|
传入参数:
|
||||||
|
f: 被装饰的视图函数
|
||||||
|
返回值:
|
||||||
|
包装后的视图函数
|
||||||
|
"""
|
||||||
|
|
||||||
|
@wraps(f)
|
||||||
|
def decorated_function(*args, **kwargs):
|
||||||
|
# 从 JSON 请求体中解析数据
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
# 获取 agent_id (优先从 Body,其次从 Query)
|
||||||
|
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||||
|
|
||||||
|
# 如果未提供 agent_id,则返回 400 错误
|
||||||
|
if not agent_id:
|
||||||
|
return jsonify({'error': 'agent_id is required'}), 400
|
||||||
|
|
||||||
|
# 获取当前用户(此处固定为 admin 用户,用于演示)
|
||||||
|
user = _get_current_user()
|
||||||
|
|
||||||
|
# 查询目标 Agent 是否存在
|
||||||
|
agent = Agent.query.get(agent_id)
|
||||||
|
if not agent:
|
||||||
|
return jsonify({'error': 'Agent not found'}), 404
|
||||||
|
|
||||||
|
# 将 agent 对象挂在 g 上,方便下游使用
|
||||||
|
g.current_agent = agent
|
||||||
|
|
||||||
|
# 如果用户是管理员,跳过权限检查直接放行
|
||||||
|
if user.role == 'admin':
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
# 非管理员:检查多对多关联表中是否存在权限
|
||||||
|
if agent not in user.agents:
|
||||||
|
return jsonify({'error': 'Permission denied for this agent'}), 403
|
||||||
|
|
||||||
|
# 鉴权通过,调用原始视图函数
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
return decorated_function
|
||||||
|
|
||||||
|
|
||||||
|
def require_admin(f):
|
||||||
|
"""
|
||||||
|
装饰器:限制只有管理员角色才能访问的接口
|
||||||
|
核心逻辑:
|
||||||
|
1. 获取当前用户
|
||||||
|
2. 判断 user.role 是否为 'admin'
|
||||||
|
"""
|
||||||
|
|
||||||
|
@wraps(f)
|
||||||
|
def decorated_function(*args, **kwargs):
|
||||||
|
# 获取当前用户(自动创建 admin)
|
||||||
|
user = _get_current_user()
|
||||||
|
# 如果不是管理员,则返回 403
|
||||||
|
if user.role != 'admin':
|
||||||
|
return jsonify({'error': 'Admin privilege required'}), 403
|
||||||
|
# 是管理员则放行
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
return decorated_function
|
||||||
@@ -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
|
|
||||||
@@ -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"}
|
|
||||||
+250
-216
@@ -1,243 +1,277 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from typing import Optional, List
|
||||||
from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
|
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
from app import db
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
|
|
||||||
from app.database import Base
|
class Base(db.Model):
|
||||||
from app.time_utils import utc_now
|
"""
|
||||||
|
基础模型类,设置为抽象基类
|
||||||
|
"""
|
||||||
|
__abstract__ = True
|
||||||
|
|
||||||
|
# RBAC 关联表:用户与 Agent 的多对多关系
|
||||||
|
# 用于存储用户拥有哪些 Agent 的访问权限
|
||||||
|
user_agent_permissions = db.Table(
|
||||||
|
'user_agent_permissions',
|
||||||
|
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
|
||||||
|
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
class ZlLanguage(Base):
|
||||||
|
"""
|
||||||
|
多语言配置表
|
||||||
|
用途:存储系统支持的语言列表
|
||||||
|
"""
|
||||||
|
__tablename__ = 'zl_languages'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
|
||||||
|
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
|
||||||
|
is_active: Mapped[bool] = mapped_column(default=True)
|
||||||
|
|
||||||
class Department(Base):
|
class Department(Base):
|
||||||
__tablename__ = "departments"
|
"""
|
||||||
|
部门表
|
||||||
|
用途:存储公司部门列表
|
||||||
|
"""
|
||||||
|
__tablename__ = 'departments'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||||
|
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
|
||||||
|
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
|
||||||
|
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
class UserHomepageConfig(Base):
|
||||||
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()
|
"""
|
||||||
)
|
__tablename__ = 'user_homepage_configs'
|
||||||
updated_at: Mapped[datetime] = mapped_column(
|
|
||||||
DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now()
|
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||||
)
|
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
|
||||||
|
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
|
||||||
|
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
users: Mapped[list["User"]] = relationship(back_populates="primary_department")
|
class UserFavoriteAgent(Base):
|
||||||
user_accesses: Mapped[list["UserDepartmentAccess"]] = relationship(
|
"""
|
||||||
back_populates="department", cascade="all, delete-orphan"
|
用户收藏 Agent 表
|
||||||
)
|
用途:存储用户收藏的 Agent
|
||||||
groups: Mapped[list["Group"]] = relationship(back_populates="department")
|
"""
|
||||||
|
__tablename__ = 'user_favorite_agents'
|
||||||
|
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||||
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
|
||||||
|
class UserDefaultAgent(Base):
|
||||||
|
"""
|
||||||
|
用户默认 Agent 表 (嵌入首页)
|
||||||
|
用途:存储用户设置的默认嵌入 Agent (最多2个)
|
||||||
|
"""
|
||||||
|
__tablename__ = 'user_default_agents'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||||
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
|
||||||
class User(Base):
|
class User(Base):
|
||||||
__tablename__ = "users"
|
"""
|
||||||
|
用户表
|
||||||
|
用途:存储系统用户信息
|
||||||
|
核心逻辑:包含部门、角色等字段,关联 Agent 权限
|
||||||
|
"""
|
||||||
|
__tablename__ = 'users'
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
# 主键 ID
|
||||||
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
full_name: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
# 用户名,唯一且带索引
|
||||||
password_hash: Mapped[str] = mapped_column(String(255))
|
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
||||||
role: Mapped[str] = mapped_column(String(16), default="user")
|
# 邮箱,唯一
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
email: Mapped[str] = mapped_column(String(100), unique=True)
|
||||||
primary_department_id: Mapped[int | None] = mapped_column(ForeignKey("departments.id"), index=True, nullable=True)
|
# 部门信息
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||||
DateTime(timezone=True), default=utc_now, server_default=func.now()
|
# 角色:admin 或 user
|
||||||
|
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||||
|
# 账号状态:active (正常), pending (待审批), disabled (禁用)
|
||||||
|
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||||
|
# 密码哈希
|
||||||
|
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||||
|
# 首选语言
|
||||||
|
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||||
|
# 主题偏好: light / dark / system
|
||||||
|
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
|
||||||
|
# 企业微信关联字段
|
||||||
|
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||||
|
wecom_unionid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||||
|
|
||||||
|
# 真实姓名
|
||||||
|
real_name: Mapped[Optional[str]] = mapped_column(String(50))
|
||||||
|
# 公司工号,唯一
|
||||||
|
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||||
|
# 手机号,唯一
|
||||||
|
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
|
||||||
|
|
||||||
|
# 默认嵌入的 Agent ID (忽略权限检查)
|
||||||
|
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
|
||||||
|
|
||||||
|
# 关系:用户拥有的 Agent 权限 (多对多)
|
||||||
|
agents: Mapped[List["Agent"]] = relationship(
|
||||||
|
secondary=user_agent_permissions,
|
||||||
|
back_populates="users"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 密码重置 Token
|
||||||
|
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
|
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
def set_password(self, password):
|
||||||
|
self.password_hash = generate_password_hash(password)
|
||||||
|
|
||||||
|
def check_password(self, password):
|
||||||
|
if not self.password_hash:
|
||||||
|
return False
|
||||||
|
return check_password_hash(self.password_hash, password)
|
||||||
|
|
||||||
|
class Agent(Base):
|
||||||
|
"""
|
||||||
|
AI 应用配置表
|
||||||
|
用途:存储接入的 Dify Agent 配置信息
|
||||||
|
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
|
||||||
|
"""
|
||||||
|
__tablename__ = 'agents'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
# 应用名称
|
||||||
|
name: Mapped[str] = mapped_column(String(100))
|
||||||
|
# 应用描述
|
||||||
|
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
|
# 图标 URL
|
||||||
|
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||||
|
|
||||||
|
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
|
||||||
|
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
|
||||||
|
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
|
||||||
|
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
|
|
||||||
|
# 类型:api (默认) 或 iframe
|
||||||
|
type: Mapped[str] = mapped_column(String(20), default='api')
|
||||||
|
# 自定义 API Base URL (覆盖全局配置)
|
||||||
|
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||||
|
# 额外配置 (JSON),用于存储 iframe_url 等
|
||||||
|
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||||
|
|
||||||
|
# 是否激活
|
||||||
|
is_active: Mapped[bool] = mapped_column(default=True)
|
||||||
|
# 创建时间
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
|
||||||
|
# 关系:拥有该应用权限的用户 (多对多)
|
||||||
|
users: Mapped[List["User"]] = relationship(
|
||||||
|
secondary=user_agent_permissions,
|
||||||
|
back_populates="agents"
|
||||||
)
|
)
|
||||||
|
|
||||||
primary_department: Mapped[Department | None] = relationship(back_populates="users")
|
class ChatLog(Base):
|
||||||
department_accesses: Mapped[list["UserDepartmentAccess"]] = relationship(
|
"""
|
||||||
back_populates="user", cascade="all, delete-orphan"
|
对话日志表
|
||||||
)
|
用途:存储用户与 Agent 的对话记录
|
||||||
groups_created: Mapped[list["Group"]] = relationship(back_populates="created_by")
|
"""
|
||||||
group_accesses: Mapped[list["UserGroupAccess"]] = relationship(
|
__tablename__ = 'chat_logs'
|
||||||
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")
|
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||||
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||||
|
query: Mapped[str] = mapped_column(Text)
|
||||||
|
answer: Mapped[str] = mapped_column(Text)
|
||||||
|
latency: Mapped[int] = mapped_column(default=0)
|
||||||
|
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||||
|
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
|
||||||
|
# 关联 Feedback
|
||||||
|
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
|
||||||
|
|
||||||
class SystemSetting(Base):
|
class Feedback(Base):
|
||||||
__tablename__ = "system_settings"
|
"""
|
||||||
|
反馈表
|
||||||
|
用途:存储用户对回答的评分与评价
|
||||||
|
"""
|
||||||
|
__tablename__ = 'feedbacks'
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
dify_permission: Mapped[str] = mapped_column(String(32), default="all_team_members")
|
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
|
||||||
indexing_technique: Mapped[str] = mapped_column(String(32), default="high_quality")
|
score: Mapped[int] = mapped_column(Integer) # 1-5
|
||||||
search_method: Mapped[str] = mapped_column(String(32), default="hybrid_search")
|
comment: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
doc_form: Mapped[str] = mapped_column(String(32), default="text_model")
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
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()
|
|
||||||
)
|
|
||||||
|
|
||||||
|
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||||
|
|
||||||
class Group(Base):
|
class PermissionRequest(Base):
|
||||||
__tablename__ = "groups"
|
"""
|
||||||
__table_args__ = (UniqueConstraint("department_id", "name", name="uq_groups_department_name"),)
|
权限申请表
|
||||||
|
用途:存储用户的权限申请记录
|
||||||
|
"""
|
||||||
|
__tablename__ = 'permission_requests'
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||||
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
|
reason: Mapped[str] = mapped_column(Text)
|
||||||
dify_dataset_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
|
||||||
dify_sync_policy: Mapped[str] = mapped_column(String(32), default="manual")
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
indexing_technique: Mapped[str] = mapped_column(String(32), default="high_quality")
|
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||||
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")
|
class QuickQuestion(Base):
|
||||||
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")
|
__tablename__ = 'quick_questions'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||||
|
title: Mapped[str] = mapped_column(String(100))
|
||||||
|
question: Mapped[str] = mapped_column(Text)
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
|
||||||
class UserDepartmentAccess(Base):
|
class Announcement(Base):
|
||||||
__tablename__ = "user_department_access"
|
"""
|
||||||
__table_args__ = (UniqueConstraint("user_id", "department_id", name="uq_user_department_access"),)
|
公告表
|
||||||
|
用途:存储系统公告
|
||||||
|
"""
|
||||||
|
__tablename__ = 'announcements'
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
title: Mapped[str] = mapped_column(String(200))
|
||||||
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True)
|
content: Mapped[str] = mapped_column(Text)
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
is_active: Mapped[bool] = mapped_column(default=True)
|
||||||
DateTime(timezone=True), default=utc_now, server_default=func.now()
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
)
|
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
user: Mapped[User] = relationship(back_populates="department_accesses")
|
class LoginAudit(Base):
|
||||||
department: Mapped[Department] = relationship(back_populates="user_accesses")
|
"""
|
||||||
|
登录审计表
|
||||||
|
用途:记录密码登录与企业微信登录结果,便于排障与审计
|
||||||
|
"""
|
||||||
|
__tablename__ = 'login_audits'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
class UserGroupAccess(Base):
|
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
__tablename__ = "user_group_access"
|
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||||
__table_args__ = (UniqueConstraint("user_id", "group_id", name="uq_user_group_access"),)
|
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
|
||||||
|
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
group_id: Mapped[int] = mapped_column(ForeignKey("groups.id"), index=True)
|
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||||
DateTime(timezone=True), default=utc_now, server_default=func.now()
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
)
|
|
||||||
|
|
||||||
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")
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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,
|
|
||||||
}
|
|
||||||
@@ -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()
|
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
backend/app/services/dify.py
|
||||||
|
文件用途:Dify API 集成服务
|
||||||
|
引用文件:requests, json, models, config
|
||||||
|
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
|
||||||
|
"""
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from flask import current_app
|
||||||
|
from app.models import ChatLog, db
|
||||||
|
from app.config import Config
|
||||||
|
|
||||||
|
class DifyService:
|
||||||
|
"""
|
||||||
|
Dify 服务类
|
||||||
|
用途:封装与 Dify API 的交互逻辑
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
||||||
|
"""
|
||||||
|
生成器函数:向 Dify 发起请求并流式返回
|
||||||
|
用途:处理 /v1/chat-messages 接口的流式响应
|
||||||
|
核心逻辑:
|
||||||
|
1. 构造请求头与 Payload
|
||||||
|
2. 使用 requests.post(stream=True) 发起请求
|
||||||
|
3. 逐行读取 SSE 数据
|
||||||
|
4. 解析 'data: ' 开头的行,透传给前端
|
||||||
|
5. 在 'message_end' 事件中记录完整日志到数据库
|
||||||
|
参数:
|
||||||
|
query: 用户提问内容
|
||||||
|
user_id: 当前用户 ID
|
||||||
|
agent: Agent 模型对象,包含 API Key
|
||||||
|
conversation_id: 会话 ID (可选)
|
||||||
|
输出:
|
||||||
|
Yields SSE 格式字符串 "data: {...}\n\n"
|
||||||
|
"""
|
||||||
|
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
|
||||||
|
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||||
|
# 移除末尾斜杠以避免双斜杠问题
|
||||||
|
base_url = base_url.rstrip('/')
|
||||||
|
url = f"{base_url}/chat-messages"
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
}
|
||||||
|
payload = {
|
||||||
|
"inputs": {},
|
||||||
|
"query": query,
|
||||||
|
"response_mode": "streaming",
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
"user": str(user_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
# 记录开始时间,用于计算耗时
|
||||||
|
start_time = time.time()
|
||||||
|
# 用于收集流式片段拼接完整回答
|
||||||
|
full_answer = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
# stream=True 关键参数,建立长连接
|
||||||
|
# 设置连接超时为 5 秒,读取超时为 60 秒
|
||||||
|
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
# 逐行迭代响应内容
|
||||||
|
for line in response.iter_lines():
|
||||||
|
if line:
|
||||||
|
decoded_line = line.decode('utf-8')
|
||||||
|
# 识别 SSE 数据行
|
||||||
|
if decoded_line.startswith('data: '):
|
||||||
|
json_str = decoded_line[6:]
|
||||||
|
try:
|
||||||
|
data = json.loads(json_str)
|
||||||
|
event = data.get('event')
|
||||||
|
|
||||||
|
# 核心:将 Dify 的原始数据透传给前端
|
||||||
|
yield f"data: {json_str}\n\n"
|
||||||
|
|
||||||
|
# 收集完整回答用于日志
|
||||||
|
if event == 'message':
|
||||||
|
full_answer.append(data.get('answer', ''))
|
||||||
|
elif event == 'message_end':
|
||||||
|
# 对话结束,记录日志
|
||||||
|
latency = int((time.time() - start_time) * 1000)
|
||||||
|
metadata = data.get('metadata', {})
|
||||||
|
usage = metadata.get('usage', {})
|
||||||
|
|
||||||
|
# 显式使用应用上下文
|
||||||
|
with current_app.app_context():
|
||||||
|
DifyService._log_chat(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent.id,
|
||||||
|
conversation_id=data.get('conversation_id') or conversation_id,
|
||||||
|
query=query,
|
||||||
|
answer="".join(full_answer),
|
||||||
|
tokens=usage.get('total_tokens', 0),
|
||||||
|
latency=latency
|
||||||
|
)
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
# 处理 keep-alive 等其他行
|
||||||
|
pass
|
||||||
|
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
# 异常处理:返回标准错误格式给前端
|
||||||
|
error_msg = json.dumps({"event": "error", "message": str(e)})
|
||||||
|
yield f"data: {error_msg}\n\n"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _log_chat(user_id, agent_id, conversation_id, query, answer, tokens, latency):
|
||||||
|
"""
|
||||||
|
内部方法:写入数据库日志
|
||||||
|
用途:将对话详情持久化到 ChatLog 表
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 确保在应用上下文中
|
||||||
|
chat_log = ChatLog(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
query=query,
|
||||||
|
answer=answer,
|
||||||
|
tokens_used=tokens or 0,
|
||||||
|
latency=latency or 0
|
||||||
|
)
|
||||||
|
db.session.add(chat_log)
|
||||||
|
db.session.commit()
|
||||||
|
except Exception as e:
|
||||||
|
# Re-acquire logger from current_app as it might be detached
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.error(f"Failed to log chat: {e}")
|
||||||
|
db.session.rollback()
|
||||||
@@ -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}")
|
|
||||||
@@ -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)
|
|
||||||
@@ -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""
|
|
||||||
|
|
||||||
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
|
|
||||||
@@ -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,
|
|
||||||
}
|
|
||||||
@@ -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()
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
|
|
||||||
def utc_now() -> datetime:
|
|
||||||
return datetime.now(timezone.utc)
|
|
||||||
@@ -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
|
|
||||||
@@ -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()
|
|
||||||
@@ -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
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from app import create_app, db
|
||||||
|
from app.models import ChatLog, User
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
app = create_app('development')
|
||||||
|
with app.app_context():
|
||||||
|
print('=== 数据库中的用户 ===')
|
||||||
|
users = db.session.query(User).all()
|
||||||
|
for u in users:
|
||||||
|
print(f'id={u.id}, username={u.username}, role={u.role}')
|
||||||
|
|
||||||
|
print()
|
||||||
|
print('=== 各用户对 Agent 3 的会话统计 ===')
|
||||||
|
for uid in [1, 2, 3, 4, 5]:
|
||||||
|
count = db.session.query(func.count(ChatLog.id)).filter(
|
||||||
|
ChatLog.user_id == uid,
|
||||||
|
ChatLog.agent_id == 3
|
||||||
|
).scalar()
|
||||||
|
print(f'user_id={uid}: {count} logs')
|
||||||
|
|
||||||
|
print()
|
||||||
|
print('=== ChatLog 样本 (Agent 3) ===')
|
||||||
|
logs = db.session.query(ChatLog).filter(ChatLog.agent_id == 3).order_by(ChatLog.created_at.desc()).limit(5).all()
|
||||||
|
for log in logs:
|
||||||
|
print(f'user_id={log.user_id}, conv_id={log.conversation_id}, query={log.query[:40]}...')
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from app import create_app, db
|
||||||
|
from app.models import Agent, User
|
||||||
|
|
||||||
|
app = create_app('development')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
agents = Agent.query.all()
|
||||||
|
print("--- Agents ---")
|
||||||
|
for a in agents:
|
||||||
|
print(f"ID: {a.id}, Name: {a.name}, Key: {a.dify_api_key}, URL: {a.api_base_url}")
|
||||||
|
|
||||||
|
users = User.query.all()
|
||||||
|
print("\n--- Users ---")
|
||||||
|
for u in users:
|
||||||
|
print(f"ID: {u.id}, Username: {u.username}, Role: {u.role}")
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
|
||||||
|
from app import create_app, db
|
||||||
|
from app.models import User
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
with app.app_context():
|
||||||
|
users = User.query.all()
|
||||||
|
for u in users:
|
||||||
|
print(f"ID: {u.id}, User: {u.username}, Role: {u.role}")
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
gunicorn_config.py
|
||||||
|
Gunicorn 生产环境配置文件
|
||||||
|
"""
|
||||||
|
import multiprocessing
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 绑定地址
|
||||||
|
bind = "127.0.0.1:5000"
|
||||||
|
|
||||||
|
# 工作模式
|
||||||
|
# 使用 gevent 处理高并发和长连接 (SSE)
|
||||||
|
worker_class = "gevent"
|
||||||
|
|
||||||
|
# 进程数
|
||||||
|
# 公式: 2 * CPU核心数 + 1
|
||||||
|
workers = multiprocessing.cpu_count() * 2 + 1
|
||||||
|
|
||||||
|
# 每个 Worker 的最大并发连接数
|
||||||
|
worker_connections = 1000
|
||||||
|
|
||||||
|
# 超时设置 (秒)
|
||||||
|
# SSE 流式响应通常需要较长的超时时间
|
||||||
|
timeout = 120
|
||||||
|
keepalive = 5
|
||||||
|
|
||||||
|
# 日志
|
||||||
|
# 在 Docker 环境中,推荐输出到 stdout/stderr
|
||||||
|
accesslog = "-"
|
||||||
|
errorlog = "-"
|
||||||
|
loglevel = "info"
|
||||||
|
|
||||||
|
# 守护进程模式 (由 Supervisor 管理时通常设为 False)
|
||||||
|
daemon = False
|
||||||
|
|
||||||
|
# 进程名称
|
||||||
|
proc_name = "hxops_backend"
|
||||||
|
|
||||||
|
# 预加载应用 (加快启动速度)
|
||||||
|
preload_app = True
|
||||||
@@ -1 +0,0 @@
|
|||||||
"""Enterprise KB Skill System orchestrator package."""
|
|
||||||
@@ -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()
|
|
||||||
@@ -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)
|
|
||||||
@@ -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]
|
|
||||||
@@ -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
|
|
||||||
@@ -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 +0,0 @@
|
|||||||
"""Atomic skills for enterprise KB pipeline."""
|
|
||||||
@@ -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
@@ -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"")
|
|
||||||
else:
|
|
||||||
lines.append(f"")
|
|
||||||
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)
|
|
||||||
@@ -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}
|
|
||||||
@@ -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""
|
|
||||||
|
|
||||||
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""
|
|
||||||
|
|
||||||
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}
|
|
||||||
@@ -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,
|
|
||||||
)
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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"
|
|
||||||
@@ -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))
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
|
||||||
|
from app import create_app, db
|
||||||
|
from app.models import User
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
with app.app_context():
|
||||||
|
# Check for admin user
|
||||||
|
admin = User.query.filter_by(username='admin').first()
|
||||||
|
if admin:
|
||||||
|
print(f"Found admin user. Current role: {admin.role}")
|
||||||
|
if admin.role != 'admin':
|
||||||
|
admin.role = 'admin'
|
||||||
|
print("Updated admin user role to 'admin'")
|
||||||
|
# Always update password to ensure it's set correctly
|
||||||
|
admin.set_password('Hxit@54321')
|
||||||
|
db.session.commit()
|
||||||
|
print("Updated admin user password to 'Hxit@54321'")
|
||||||
|
else:
|
||||||
|
print("Admin user not found. Creating...")
|
||||||
|
admin = User(username='admin', email='admin@example.com', role='admin')
|
||||||
|
admin.set_password('Hxit@54321')
|
||||||
|
db.session.add(admin)
|
||||||
|
db.session.commit()
|
||||||
|
print("Created admin user with role 'admin' and password 'Hxit@54321'")
|
||||||
|
|
||||||
|
# Also check if there are other users that should be admin but aren't
|
||||||
|
users = User.query.all()
|
||||||
|
for u in users:
|
||||||
|
print(f"User: {u.username}, Role: {u.role}")
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
fix_agent_permission.py
|
||||||
|
文件用途:修复 Agent 权限问题
|
||||||
|
关键逻辑:
|
||||||
|
1. 根据 username 或 user_id 获取用户
|
||||||
|
2. 给用户分配指定的 agent 权限
|
||||||
|
3. 支持批量分配和查看当前权限
|
||||||
|
语法实现:使用 SQLAlchemy relationship 操作多对多关联
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
from app import create_app, db
|
||||||
|
from app.models import User, Agent
|
||||||
|
|
||||||
|
|
||||||
|
def grant_agent_permission(username=None, user_id=None, agent_ids=None, grant_all=False):
|
||||||
|
"""
|
||||||
|
给用户分配 Agent 权限
|
||||||
|
|
||||||
|
参数:
|
||||||
|
username: 用户名
|
||||||
|
user_id: 用户 ID
|
||||||
|
agent_ids: 要分配的 Agent ID 列表,如 [1, 2, 3]
|
||||||
|
grant_all: 是否授予所有 Agent 的权限
|
||||||
|
"""
|
||||||
|
env = os.getenv('FLASK_ENV', 'production')
|
||||||
|
app = create_app(env)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
user = None
|
||||||
|
if user_id:
|
||||||
|
user = User.query.get(int(user_id))
|
||||||
|
elif username:
|
||||||
|
user = User.query.filter_by(username=username).first()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
print(f"❌ 用户不存在: username={username}, user_id={user_id}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
print(f"✅ 找到用户: {user.username} (ID: {user.id}, Role: {user.role})")
|
||||||
|
|
||||||
|
if grant_all:
|
||||||
|
agents = Agent.query.all()
|
||||||
|
agent_ids = [a.id for a in agents]
|
||||||
|
print(f"📋 所有可用 Agent: {agent_ids}")
|
||||||
|
|
||||||
|
if not agent_ids:
|
||||||
|
print("⚠️ 未指定 agent_ids,使用 --grant-all 授予所有权限")
|
||||||
|
agents = Agent.query.all()
|
||||||
|
user.agents = agents
|
||||||
|
else:
|
||||||
|
agents = Agent.query.filter(Agent.id.in_(agent_ids)).all()
|
||||||
|
if not agents:
|
||||||
|
print(f"❌ 未找到 ID 为 {agent_ids} 的 Agent")
|
||||||
|
return False
|
||||||
|
user.agents = agents
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
print(f"✅ 权限授予成功!用户 {user.username} 现在可以访问 Agent: {[a.id for a in user.agents]}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def list_user_permissions(username=None, user_id=None):
|
||||||
|
"""查看用户的 Agent 权限"""
|
||||||
|
env = os.getenv('FLASK_ENV', 'production')
|
||||||
|
app = create_app(env)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
user = None
|
||||||
|
if user_id:
|
||||||
|
user = User.query.get(int(user_id))
|
||||||
|
elif username:
|
||||||
|
user = User.query.filter_by(username=username).first()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
print(f"❌ 用户不存在: username={username}, user_id={user_id}")
|
||||||
|
return
|
||||||
|
|
||||||
|
print(f"\n👤 用户: {user.username} (ID: {user.id}, Role: {user.role})")
|
||||||
|
print(f"📋 当前可访问的 Agent: {[a.id for a in user.agents]}")
|
||||||
|
print("\n📋 所有 Agent 列表:")
|
||||||
|
all_agents = Agent.query.all()
|
||||||
|
for a in all_agents:
|
||||||
|
has_access = a in user.agents
|
||||||
|
print(f" [{a.id}] {a.name} - {'✅ 有权限' if has_access else '❌ 无权限'}")
|
||||||
|
|
||||||
|
|
||||||
|
def list_all_users():
|
||||||
|
"""列出所有用户及其权限"""
|
||||||
|
env = os.getenv('FLASK_ENV', 'production')
|
||||||
|
app = create_app(env)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
users = User.query.all()
|
||||||
|
print("\n👥 所有用户列表:")
|
||||||
|
for u in users:
|
||||||
|
print(f" [{u.id}] {u.username} (Role: {u.role}) - Agents: {[a.id for a in u.agents]}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description='修复 Agent 权限')
|
||||||
|
parser.add_argument('--username', '-u', type=str, help='用户名')
|
||||||
|
parser.add_argument('--user-id', '-i', type=int, help='用户 ID')
|
||||||
|
parser.add_argument('--agent-ids', '-a', type=int, nargs='+', help='Agent ID 列表,如: 1 2 3')
|
||||||
|
parser.add_argument('--grant-all', '-g', action='store_true', help='授予所有 Agent 权限')
|
||||||
|
parser.add_argument('--list', '-l', action='store_true', help='查看用户权限')
|
||||||
|
parser.add_argument('--list-users', action='store_true', help='列出所有用户')
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.list_users:
|
||||||
|
list_all_users()
|
||||||
|
elif args.list:
|
||||||
|
list_user_permissions(username=args.username, user_id=args.user_id)
|
||||||
|
elif args.grant_all or args.agent_ids:
|
||||||
|
grant_agent_permission(
|
||||||
|
username=args.username,
|
||||||
|
user_id=args.user_id,
|
||||||
|
agent_ids=args.agent_ids,
|
||||||
|
grant_all=args.grant_all
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
parser.print_help()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
backend/gunicorn_config.py
|
||||||
|
生产环境 Gunicorn 配置 (支持高并发)
|
||||||
|
"""
|
||||||
|
import multiprocessing
|
||||||
|
|
||||||
|
# 绑定地址
|
||||||
|
bind = "0.0.0.0:8000"
|
||||||
|
|
||||||
|
# 核心:使用 Gevent 异步 Worker
|
||||||
|
worker_class = "gevent"
|
||||||
|
|
||||||
|
# Worker 数量:通常 CPU 核数 * 2 + 1
|
||||||
|
workers = multiprocessing.cpu_count() * 2 + 1
|
||||||
|
|
||||||
|
# 核心:每个 Worker 最大并发连接数
|
||||||
|
# Gevent 下这个值可以设置得很高,支持海量 SSE 连接
|
||||||
|
worker_connections = 2000
|
||||||
|
|
||||||
|
# 超时设置 (SSE 长连接需要较长超时)
|
||||||
|
timeout = 120
|
||||||
|
keepalive = 5
|
||||||
|
|
||||||
|
# 日志
|
||||||
|
accesslog = "-"
|
||||||
|
errorlog = "-"
|
||||||
|
loglevel = "info"
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"""
|
||||||
|
backend/init_db.py
|
||||||
|
文件用途:初始化 PostgreSQL 数据库 hxops_db 并创建所有表
|
||||||
|
引用文件:psycopg2, urllib.parse, app
|
||||||
|
逻辑关系:
|
||||||
|
1. 从配置中解析 SQLALCHEMY_DATABASE_URI
|
||||||
|
2. 连接 postgres 系统库,检查 hxops_db 是否存在,不存在则创建
|
||||||
|
3. 使用 Flask 应用上下文调用 db.create_all() 创建所有表结构
|
||||||
|
使用方式:
|
||||||
|
在项目根目录下执行:
|
||||||
|
cd backend
|
||||||
|
python init_db.py
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
import psycopg2
|
||||||
|
|
||||||
|
from app import create_app, db
|
||||||
|
|
||||||
|
def _parse_db_url(url: str):
|
||||||
|
"""
|
||||||
|
解析 SQLAlchemy 风格的数据库 URL
|
||||||
|
输入示例: postgresql://user:password@localhost:5432/hxops_db
|
||||||
|
输出:字典包含 user/password/host/port/dbname
|
||||||
|
"""
|
||||||
|
# 使用 urllib.parse 解析 URL
|
||||||
|
parsed = urllib.parse.urlparse(url)
|
||||||
|
# 从 netloc 中解析用户名和密码
|
||||||
|
if parsed.username:
|
||||||
|
user = urllib.parse.unquote(parsed.username)
|
||||||
|
else:
|
||||||
|
user = 'postgres'
|
||||||
|
if parsed.password:
|
||||||
|
password = urllib.parse.unquote(parsed.password)
|
||||||
|
else:
|
||||||
|
password = ''
|
||||||
|
host = parsed.hostname or 'localhost'
|
||||||
|
port = parsed.port or 5432
|
||||||
|
# 去掉路径前导斜杠得到数据库名
|
||||||
|
dbname = parsed.path.lstrip('/') or 'postgres'
|
||||||
|
return {
|
||||||
|
'user': user,
|
||||||
|
'password': password,
|
||||||
|
'host': host,
|
||||||
|
'port': port,
|
||||||
|
'dbname': dbname,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_database():
|
||||||
|
"""
|
||||||
|
确保数据库存在
|
||||||
|
核心逻辑:
|
||||||
|
1. 获取当前环境配置的 SQLALCHEMY_DATABASE_URI
|
||||||
|
2. 使用 psycopg2 连接到 postgres 系统数据库
|
||||||
|
3. 查询 pg_database,如果不存在则执行 CREATE DATABASE
|
||||||
|
"""
|
||||||
|
# 获取当前环境
|
||||||
|
env = os.getenv('FLASK_ENV', 'development')
|
||||||
|
app = create_app(env)
|
||||||
|
|
||||||
|
# 从应用配置中获取数据库 URL
|
||||||
|
url = app.config['SQLALCHEMY_DATABASE_URI']
|
||||||
|
print(f"Checking database for environment '{env}': {url}")
|
||||||
|
|
||||||
|
info = _parse_db_url(url)
|
||||||
|
target_db = info['dbname']
|
||||||
|
|
||||||
|
# 连接系统数据库 postgres
|
||||||
|
conn = psycopg2.connect(
|
||||||
|
dbname='postgres',
|
||||||
|
user=info['user'],
|
||||||
|
password=info['password'],
|
||||||
|
host=info['host'],
|
||||||
|
port=info['port'],
|
||||||
|
)
|
||||||
|
conn.autocommit = True
|
||||||
|
try:
|
||||||
|
cur = conn.cursor()
|
||||||
|
# 查询目标数据库是否已存在
|
||||||
|
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (target_db,))
|
||||||
|
exists = cur.fetchone() is not None
|
||||||
|
if not exists:
|
||||||
|
# 创建数据库
|
||||||
|
cur.execute(f'CREATE DATABASE "{target_db}"')
|
||||||
|
print(f'Created database {target_db}')
|
||||||
|
else:
|
||||||
|
print(f'Database {target_db} already exists')
|
||||||
|
cur.close()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_tables():
|
||||||
|
"""
|
||||||
|
在 hxops_db 中创建所有表结构
|
||||||
|
核心逻辑:
|
||||||
|
1. 创建 Flask 应用实例
|
||||||
|
2. 在应用上下文中调用 db.create_all()
|
||||||
|
"""
|
||||||
|
env = os.getenv('FLASK_ENV', 'development')
|
||||||
|
app = create_app(env)
|
||||||
|
with app.app_context():
|
||||||
|
db.create_all()
|
||||||
|
print(f'All tables created in {app.config["SQLALCHEMY_DATABASE_URI"]}')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
ensure_database()
|
||||||
|
create_tables()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 第一步:确保数据库存在
|
||||||
|
ensure_database()
|
||||||
|
# 第二步:创建所有表
|
||||||
|
create_tables()
|
||||||
|
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# Add backend directory to path
|
||||||
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
# Force SQLite for local testing BEFORE importing app
|
||||||
|
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'local_test.db')
|
||||||
|
os.environ['DATABASE_URL'] = f'sqlite:///{db_path}'
|
||||||
|
print(f"Setting DATABASE_URL to: {os.environ['DATABASE_URL']}")
|
||||||
|
|
||||||
|
from app import create_app, db
|
||||||
|
from app.models import User, Agent
|
||||||
|
|
||||||
|
app = create_app('development')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
print(f"Creating database tables at {db_path}...")
|
||||||
|
db.create_all()
|
||||||
|
print("Tables created successfully.")
|
||||||
|
|
||||||
|
# Check if we need to seed data
|
||||||
|
user = User.query.filter_by(username='admin').first()
|
||||||
|
if user is None:
|
||||||
|
print("Seeding initial user 'admin'...")
|
||||||
|
user = User(username='admin', email='admin@example.com', role='admin')
|
||||||
|
user.set_password('Hxit@54321')
|
||||||
|
db.session.add(user)
|
||||||
|
else:
|
||||||
|
# Update password if user exists
|
||||||
|
print("Updating admin password to 'Hxit@54321'...")
|
||||||
|
user.set_password('Hxit@54321')
|
||||||
|
|
||||||
|
if Agent.query.first() is None:
|
||||||
|
print("Seeding initial agent 'Demo Agent'...")
|
||||||
|
agent = Agent(
|
||||||
|
name='Demo Agent',
|
||||||
|
description='A test agent for local verification',
|
||||||
|
type='api',
|
||||||
|
dify_api_key='test-key',
|
||||||
|
is_active=True
|
||||||
|
)
|
||||||
|
db.session.add(agent)
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
print("Database seeded successfully.")
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
|
||||||
|
from app import create_app, db
|
||||||
|
from app.models import Agent
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
# 1. 方式一:嵌入到网站中 (Iframe)
|
||||||
|
# <iframe src=" http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg " style="width: 100%; height: 100%; min-height: 700px" frameborder="0" allow="microphone"> </iframe>
|
||||||
|
|
||||||
|
agent_iframe = Agent.query.filter_by(name='人事规章(网页版)').first()
|
||||||
|
if not agent_iframe:
|
||||||
|
agent_iframe = Agent(
|
||||||
|
name='人事规章(网页版)',
|
||||||
|
description='嵌入式人事规章助手',
|
||||||
|
dify_app_id=str(uuid.uuid4()), # Placeholder unique ID
|
||||||
|
dify_api_key='placeholder',
|
||||||
|
type='iframe',
|
||||||
|
extra_config={'iframe_url': 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'},
|
||||||
|
icon_url='ri-article-line'
|
||||||
|
)
|
||||||
|
db.session.add(agent_iframe)
|
||||||
|
print("Added Iframe Agent")
|
||||||
|
else:
|
||||||
|
agent_iframe.type = 'iframe'
|
||||||
|
agent_iframe.extra_config = {'iframe_url': 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'}
|
||||||
|
agent_iframe.icon_url = 'ri-article-line'
|
||||||
|
print("Updated Iframe Agent")
|
||||||
|
|
||||||
|
# 2. 方式二:API
|
||||||
|
# 基础URL: http://127.0.0.1:5001/v1
|
||||||
|
# API密钥:app-xdiejQibWQy8ZQWXcdxJjS9I
|
||||||
|
|
||||||
|
agent_api = Agent.query.filter_by(name='人事规章(API版)').first()
|
||||||
|
if not agent_api:
|
||||||
|
agent_api = Agent(
|
||||||
|
name='人事规章(API版)',
|
||||||
|
description='API调用人事规章助手',
|
||||||
|
dify_app_id=str(uuid.uuid4()), # Placeholder unique ID
|
||||||
|
dify_api_key='app-xdiejQibWQy8ZQWXcdxJjS9I',
|
||||||
|
type='api',
|
||||||
|
api_base_url='http://127.0.0.1:5001/v1',
|
||||||
|
icon_url='ri-robot-line'
|
||||||
|
)
|
||||||
|
db.session.add(agent_api)
|
||||||
|
print("Added API Agent")
|
||||||
|
else:
|
||||||
|
agent_api.type = 'api'
|
||||||
|
agent_api.dify_api_key = 'app-xdiejQibWQy8ZQWXcdxJjS9I'
|
||||||
|
agent_api.api_base_url = 'http://127.0.0.1:5001/v1'
|
||||||
|
agent_api.icon_url = 'ri-robot-line'
|
||||||
|
print("Updated API Agent")
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
Binary file not shown.
@@ -0,0 +1,15 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
backend/manage.py
|
||||||
|
数据库迁移管理脚本
|
||||||
|
"""
|
||||||
|
from app import create_app, db
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
|
||||||
|
app = create_app('development')
|
||||||
|
migrate = Migrate(app, db)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 仅作为 CLI 入口
|
||||||
|
# 使用: flask --app manage db init/migrate/upgrade
|
||||||
|
pass
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Single-database configuration for Flask.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# template used to generate migration files
|
||||||
|
# file_template = %%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic,flask_migrate
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[logger_flask_migrate]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = flask_migrate
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
+91
-27
@@ -1,44 +1,108 @@
|
|||||||
from __future__ import annotations
|
import logging
|
||||||
|
|
||||||
from logging.config import fileConfig
|
from logging.config import fileConfig
|
||||||
from pathlib import Path
|
|
||||||
import sys
|
from flask import current_app
|
||||||
|
|
||||||
from alembic import context
|
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
|
|
||||||
|
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
config = context.config
|
config = context.config
|
||||||
settings = get_settings()
|
|
||||||
config.set_main_option("sqlalchemy.url", settings.database_url)
|
|
||||||
|
|
||||||
if config.config_file_name is not None:
|
# Interpret the config file for Python logging.
|
||||||
fileConfig(config.config_file_name)
|
# This line sets up loggers basically.
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
target_metadata = Base.metadata
|
logger = logging.getLogger('alembic.env')
|
||||||
|
|
||||||
|
|
||||||
def run_migrations_offline() -> None:
|
def get_engine():
|
||||||
|
try:
|
||||||
|
# this works with Flask-SQLAlchemy<3 and Alchemical
|
||||||
|
return current_app.extensions['migrate'].db.get_engine()
|
||||||
|
except (TypeError, AttributeError):
|
||||||
|
# this works with Flask-SQLAlchemy>=3
|
||||||
|
return current_app.extensions['migrate'].db.engine
|
||||||
|
|
||||||
|
|
||||||
|
def get_engine_url():
|
||||||
|
try:
|
||||||
|
return get_engine().url.render_as_string(hide_password=False).replace(
|
||||||
|
'%', '%%')
|
||||||
|
except AttributeError:
|
||||||
|
return str(get_engine().url).replace('%', '%%')
|
||||||
|
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
config.set_main_option('sqlalchemy.url', get_engine_url())
|
||||||
|
target_db = current_app.extensions['migrate'].db
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def get_metadata():
|
||||||
|
if hasattr(target_db, 'metadatas'):
|
||||||
|
return target_db.metadatas[None]
|
||||||
|
return target_db.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline():
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
url = config.get_main_option("sqlalchemy.url")
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
|
context.configure(
|
||||||
|
url=url, target_metadata=get_metadata(), literal_binds=True
|
||||||
|
)
|
||||||
|
|
||||||
with context.begin_transaction():
|
with context.begin_transaction():
|
||||||
context.run_migrations()
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
def run_migrations_online() -> None:
|
def run_migrations_online():
|
||||||
connectable = engine_from_config(
|
"""Run migrations in 'online' mode.
|
||||||
config.get_section(config.config_ini_section, {}),
|
|
||||||
prefix="sqlalchemy.",
|
In this scenario we need to create an Engine
|
||||||
poolclass=pool.NullPool,
|
and associate a connection with the context.
|
||||||
)
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
# this callback is used to prevent an auto-migration from being generated
|
||||||
|
# when there are no changes to the schema
|
||||||
|
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
|
||||||
|
def process_revision_directives(context, revision, directives):
|
||||||
|
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||||
|
script = directives[0]
|
||||||
|
if script.upgrade_ops.is_empty():
|
||||||
|
directives[:] = []
|
||||||
|
logger.info('No changes in schema detected.')
|
||||||
|
|
||||||
|
conf_args = current_app.extensions['migrate'].configure_args
|
||||||
|
if conf_args.get("process_revision_directives") is None:
|
||||||
|
conf_args["process_revision_directives"] = process_revision_directives
|
||||||
|
|
||||||
|
connectable = get_engine()
|
||||||
|
|
||||||
with connectable.connect() as connection:
|
with connectable.connect() as connection:
|
||||||
context.configure(connection=connection, target_metadata=target_metadata)
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=get_metadata(),
|
||||||
|
**conf_args
|
||||||
|
)
|
||||||
|
|
||||||
with context.begin_transaction():
|
with context.begin_transaction():
|
||||||
context.run_migrations()
|
context.run_migrations()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""add phone_number to user
|
||||||
|
|
||||||
|
Revision ID: 08f34c125a73
|
||||||
|
Revises: 5b797d05f412
|
||||||
|
Create Date: 2026-02-23 17:10:37.613505
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '08f34c125a73'
|
||||||
|
down_revision = '5b797d05f412'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('phone_number', sa.String(length=20), nullable=True))
|
||||||
|
batch_op.create_unique_constraint(None, ['phone_number'])
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint(None, type_='unique')
|
||||||
|
batch_op.drop_column('phone_number')
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Add Announcement table
|
||||||
|
|
||||||
|
Revision ID: 1a79b14cffa5
|
||||||
|
Revises: cae76a195dec
|
||||||
|
Create Date: 2026-03-04 09:42:16.200197
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '1a79b14cffa5'
|
||||||
|
down_revision = 'cae76a195dec'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('announcements',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=200), nullable=False),
|
||||||
|
sa.Column('content', sa.Text(), nullable=False),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table('announcements')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -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)
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""add theme preference to user
|
||||||
|
|
||||||
|
Revision ID: 2f8d9d4ce4aa
|
||||||
|
Revises: 1a79b14cffa5
|
||||||
|
Create Date: 2026-03-28 10:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2f8d9d4ce4aa'
|
||||||
|
down_revision = '1a79b14cffa5'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(
|
||||||
|
sa.Column('theme_preference', sa.String(length=10), nullable=False, server_default='system')
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('theme_preference')
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""add_tokens_used_to_chatlog
|
||||||
|
|
||||||
|
Revision ID: 439e501ac52b
|
||||||
|
Revises: 7797942bfa85
|
||||||
|
Create Date: 2026-02-24 08:51:08.086113
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '439e501ac52b'
|
||||||
|
down_revision = '7797942bfa85'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('tokens_used', sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('tokens_used')
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Add default_agent_id to User
|
||||||
|
|
||||||
|
Revision ID: 48f1ca8fa73a
|
||||||
|
Revises: 08f34c125a73
|
||||||
|
Create Date: 2026-02-23 20:39:30.511482
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '48f1ca8fa73a'
|
||||||
|
down_revision = '08f34c125a73'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('default_agent_id', sa.Integer(), nullable=True))
|
||||||
|
batch_op.create_foreign_key(None, 'agents', ['default_agent_id'], ['id'])
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint(None, type_='foreignkey')
|
||||||
|
batch_op.drop_column('default_agent_id')
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 510db8a4f806
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-02-23 11:16:09.218508
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '510db8a4f806'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('agents', schema=None) as batch_op:
|
||||||
|
batch_op.alter_column('type',
|
||||||
|
existing_type=sa.VARCHAR(length=20),
|
||||||
|
nullable=False,
|
||||||
|
existing_server_default=sa.text("'api'::character varying"))
|
||||||
|
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.alter_column('status',
|
||||||
|
existing_type=sa.VARCHAR(length=20),
|
||||||
|
nullable=False,
|
||||||
|
existing_server_default=sa.text("'active'::character varying"))
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.alter_column('status',
|
||||||
|
existing_type=sa.VARCHAR(length=20),
|
||||||
|
nullable=True,
|
||||||
|
existing_server_default=sa.text("'active'::character varying"))
|
||||||
|
|
||||||
|
with op.batch_alter_table('agents', schema=None) as batch_op:
|
||||||
|
batch_op.alter_column('type',
|
||||||
|
existing_type=sa.VARCHAR(length=20),
|
||||||
|
nullable=True,
|
||||||
|
existing_server_default=sa.text("'api'::character varying"))
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Add real_name and employee_id
|
||||||
|
|
||||||
|
Revision ID: 5b797d05f412
|
||||||
|
Revises: 80382a78c530
|
||||||
|
Create Date: 2026-02-23 12:43:47.707814
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '5b797d05f412'
|
||||||
|
down_revision = '80382a78c530'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('real_name', sa.String(length=50), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('employee_id', sa.String(length=50), nullable=True))
|
||||||
|
batch_op.create_unique_constraint(None, ['employee_id'])
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint(None, type_='unique')
|
||||||
|
batch_op.drop_column('employee_id')
|
||||||
|
batch_op.drop_column('real_name')
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
Loaded 100 of 275 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user