Commit dd9cc291 by 黄南光

加入批量摄出,批量终止功能

ppt支持预览,多模态摄入
1 parent ac76562d
...@@ -9,13 +9,16 @@ RUN sed -i 's/deb.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.li ...@@ -9,13 +9,16 @@ RUN sed -i 's/deb.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.li
&& sed -i 's/deb.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list 2>/dev/null || true \ && sed -i 's/deb.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list 2>/dev/null || true \
&& sed -i 's/security.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list 2>/dev/null || true && sed -i 's/security.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list 2>/dev/null || true
# 安装必要的系统依赖,包括 mysqlclient 和 PyMuPDF 可能需要的库 # 安装必要的系统依赖,包括 mysqlclient、PyMuPDF 可能需要的库,以及 PPT/PPTX 转 PDF 所需的 LibreOffice
RUN apt-get update && apt-get install -y --no-install-recommends \ RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \ build-essential \
default-libmysqlclient-dev \ default-libmysqlclient-dev \
pkg-config \ pkg-config \
libgl1 \ libgl1 \
libglib2.0-0 \ libglib2.0-0 \
libreoffice-impress \
fonts-noto-cjk \
fontconfig \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
COPY requirements.txt . COPY requirements.txt .
......
...@@ -50,6 +50,11 @@ interface TreeFile { ...@@ -50,6 +50,11 @@ interface TreeFile {
path: string; path: string;
} }
const canIframePreview = (name: string) => {
const lowerName = name.toLowerCase();
return lowerName.endsWith(".pdf") || lowerName.endsWith(".ppt") || lowerName.endsWith(".pptx");
};
const buildTree = (links: string[]) => { const buildTree = (links: string[]) => {
const root: TreeFolder = { name: "root", type: "folder", children: {} }; const root: TreeFolder = { name: "root", type: "folder", children: {} };
...@@ -453,6 +458,79 @@ export default function EnterpriseWiki() { ...@@ -453,6 +458,79 @@ export default function EnterpriseWiki() {
} }
}; };
const handleBatchEgress = async () => {
const ids = Array.from(selectedIds);
const toEgress = ids.filter(id => {
const file = files.find(f => f.id === id);
return file && file.status === "Indexed";
});
if (toEgress.length === 0) {
alert("请先选择已索引的文件");
return;
}
const skippedCount = ids.length - toEgress.length;
const confirmMsg = skippedCount > 0
? `选中的项目中,有 ${skippedCount} 个文件不是“已索引”状态,无法摄出。\n确定摄出其余 ${toEgress.length} 个文件吗?`
: `确定摄出选中的 ${toEgress.length} 个文件吗?`;
if (!confirm(confirmMsg)) return;
try {
const res = await fetch(`${API_BASE}/wiki/batch_egress`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: toEgress }),
});
if (!res.ok) {
const error = await res.json().catch(() => ({ detail: "批量摄出失败" }));
alert(error.detail || "批量摄出失败");
return;
}
setSelectedIds(new Set());
await fetchFiles();
if (selectedFileId && toEgress.includes(selectedFileId)) {
setWikiContent("");
setViewMode("wiki_tree");
}
} catch {
alert("批量摄出请求发生错误");
await fetchFiles();
}
};
const handleBatchCancelIngest = async () => {
const toCancel = Array.from(selectedIds).filter(id => {
const file = files.find(f => f.id === id);
return file && file.status === "Ingesting";
});
if (toCancel.length === 0) {
alert("请先选择正在摄入的文件");
return;
}
if (!confirm(`确定终止选中的 ${toCancel.length} 个摄入任务吗?终止后状态会回到“待处理”。`)) return;
setFiles(prev => prev.map(f => toCancel.includes(f.id) ? { ...f, status: "Pending" } : f));
try {
const res = await fetch(`${API_BASE}/wiki/ingest/cancel`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: toCancel }),
});
if (!res.ok) {
const error = await res.json().catch(() => ({ detail: "批量终止失败" }));
alert(error.detail || "批量终止失败");
}
setSelectedIds(new Set());
await fetchFiles();
} catch {
alert("批量终止请求发生错误");
await fetchFiles();
}
};
const viewWiki = async (name: string) => { const viewWiki = async (name: string) => {
setWikiContent("正在调取 AI 摘要..."); setWikiContent("正在调取 AI 摘要...");
try { try {
...@@ -470,7 +548,7 @@ export default function EnterpriseWiki() { ...@@ -470,7 +548,7 @@ export default function EnterpriseWiki() {
const fetchPreview = async (id: string) => { const fetchPreview = async (id: string) => {
const targetFile = files.find(f => f.id === id); const targetFile = files.find(f => f.id === id);
if (targetFile?.name.toLowerCase().endsWith(".pdf")) return; if (targetFile && canIframePreview(targetFile.name)) return;
setIsPreviewLoading(true); setIsPreviewLoading(true);
setPreviewContent("正在加载预览..."); setPreviewContent("正在加载预览...");
...@@ -1072,6 +1150,18 @@ export default function EnterpriseWiki() { ...@@ -1072,6 +1150,18 @@ export default function EnterpriseWiki() {
<Zap className="w-3.5 h-3.5" /> 批量摄入 <Zap className="w-3.5 h-3.5" /> 批量摄入
</button> </button>
<button <button
onClick={handleBatchEgress}
className="text-xs font-bold bg-amber-50 text-amber-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-amber-100 transition"
>
<Eject className="w-3.5 h-3.5 rotate-180" /> 批量摄出
</button>
<button
onClick={handleBatchCancelIngest}
className="text-xs font-bold bg-rose-50 text-rose-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-rose-100 transition"
>
<Square className="w-3.5 h-3.5 fill-current" /> 批量终止
</button>
<button
onClick={async () => { onClick={async () => {
const ids = Array.from(selectedIds); const ids = Array.from(selectedIds);
const toDelete = ids.filter(id => { const toDelete = ids.filter(id => {
...@@ -1453,7 +1543,7 @@ export default function EnterpriseWiki() { ...@@ -1453,7 +1543,7 @@ export default function EnterpriseWiki() {
{viewMode === "raw" ? ( {viewMode === "raw" ? (
<div className="flex w-full h-full"> <div className="flex w-full h-full">
<div className="flex-1 w-full h-full p-8"> <div className="flex-1 w-full h-full p-8">
{selectedFileObj?.name?.toLowerCase().endsWith(".pdf") ? ( {selectedFileObj && canIframePreview(selectedFileObj.name) ? (
<iframe <iframe
key={selectedFileId} key={selectedFileId}
src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`} src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`}
......
...@@ -17,7 +17,12 @@ from src.database.session import AsyncSessionLocal ...@@ -17,7 +17,12 @@ from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog from src.database.models import WikiFile, WikiFilePage, WikiOperationLog
from src.database.schemas import UploadInitRequest from src.database.schemas import UploadInitRequest
from config import RAW_DIR from config import RAW_DIR
from src.tools.document_parser import extract_text_from_file from src.tools.document_parser import (
delete_office_preview_pdf,
extract_text_from_file,
get_or_create_office_preview_pdf,
is_presentation_file,
)
router = APIRouter() router = APIRouter()
...@@ -217,6 +222,9 @@ async def upload_file_chunk(file_id: str, file: UploadFile = File(...)): ...@@ -217,6 +222,9 @@ async def upload_file_chunk(file_id: str, file: UploadFile = File(...)):
file_size = os.path.getsize(file_path) file_size = os.path.getsize(file_path)
word_count = 0 word_count = 0
if is_presentation_file(file_path):
logger.info(f"Skip PPT/PPTX upload word count to avoid converting during upload: {file.filename}")
else:
try: try:
text = extract_text_from_file(file_path) text = extract_text_from_file(file_path)
pure_text = re.sub(r'\s+', '', text) pure_text = re.sub(r'\s+', '', text)
...@@ -258,6 +266,8 @@ async def delete_file(file_id: str): ...@@ -258,6 +266,8 @@ async def delete_file(file_id: str):
file_path = os.path.join(file_dir, name) file_path = os.path.join(file_dir, name)
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
if os.path.splitext(name)[1].lower() in (".ppt", ".pptx"):
delete_office_preview_pdf(file_path, file_id)
if os.path.exists(file_dir) and not os.listdir(file_dir): if os.path.exists(file_dir) and not os.listdir(file_dir):
os.rmdir(file_dir) os.rmdir(file_dir)
...@@ -303,6 +313,8 @@ async def batch_delete_files(data: dict = Body(...)): ...@@ -303,6 +313,8 @@ async def batch_delete_files(data: dict = Body(...)):
file_path = os.path.join(file_dir, db_file.name) file_path = os.path.join(file_dir, db_file.name)
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
if os.path.splitext(db_file.name)[1].lower() in (".ppt", ".pptx"):
delete_office_preview_pdf(file_path, fid)
if os.path.exists(file_dir) and not os.listdir(file_dir): if os.path.exists(file_dir) and not os.listdir(file_dir):
os.rmdir(file_dir) os.rmdir(file_dir)
...@@ -338,12 +350,38 @@ async def view_file(file_id: str): ...@@ -338,12 +350,38 @@ async def view_file(file_id: str):
raise HTTPException(status_code=404, detail="File not found") raise HTTPException(status_code=404, detail="File not found")
file_path = os.path.join(RAW_DIR, db_file.format.lower(), db_file.name) file_path = os.path.join(RAW_DIR, db_file.format.lower(), db_file.name)
logger.info(
"[Preview] 原始文件预览请求: file_id=%s, name=%s, path=%s",
file_id,
db_file.name,
file_path,
)
if not os.path.exists(file_path): if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found on disk") raise HTTPException(status_code=404, detail="File not found on disk")
ext = os.path.splitext(db_file.name)[1].lower() ext = os.path.splitext(db_file.name)[1].lower()
if ext == '.pdf': if ext == '.pdf':
logger.info("[Preview] 返回 PDF 原文件: file_id=%s, media_type=application/pdf", file_id)
return FileResponse(file_path, media_type='application/pdf') return FileResponse(file_path, media_type='application/pdf')
if ext in ('.ppt', '.pptx'):
try:
preview_pdf_path = await run_in_threadpool(get_or_create_office_preview_pdf, file_path, file_id)
logger.info(
"[Preview] 返回 PPT/PPTX PDF 预览: file_id=%s, cache_path=%s, media_type=application/pdf",
file_id,
preview_pdf_path,
)
return FileResponse(preview_pdf_path, media_type='application/pdf')
except Exception as e:
logger.error(
"[Preview] PPT/PPTX PDF 预览失败: file_id=%s, name=%s, path=%s, error=%s",
file_id,
db_file.name,
file_path,
e,
exc_info=True,
)
raise HTTPException(status_code=500, detail=f"PPT/PPTX 预览生成失败: {str(e)}")
try: try:
content = extract_text_from_file(file_path) content = extract_text_from_file(file_path)
......
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
MODELS = ROOT / "src" / "database" / "models.py"
CREATE_TABLES = ROOT / "src" / "database" / "sql" / "create_tables.sql"
UUID_ID_SNIPPETS = (
"id = Column(String(36), primary_key=True, default=uuid_str",
"`id` VARCHAR(36) NOT NULL PRIMARY KEY",
)
REMOVED_SNIPPETS = (
"autoincrement=True",
"AUTO_INCREMENT",
"idx_rag_chunks_content_kind",
"idx_rag_chunks_business",
"idx_rag_chunks_brand",
"idx_rag_chunks_source_loc",
)
EXPECTED_MODEL_INDEXES = (
"idx_wiki_files_name",
"idx_wiki_files_status",
"idx_wiki_files_created_at",
"idx_wiki_file_pages_file",
"uq_wiki_file_pages_file_path",
"idx_wiki_operation_logs_file_created",
"idx_wiki_operation_logs_operation_created",
"idx_wiki_query_logs_session_created",
"idx_wiki_query_logs_status_created",
"idx_rag_documents_status",
"idx_rag_documents_hash",
"idx_rag_documents_name_status",
"idx_rag_documents_created_at",
"idx_rag_chunks_document_level_status",
"idx_rag_chunks_document_level_index",
"idx_rag_chunks_parent",
"idx_rag_chunks_status",
"idx_rag_index_runs_document_created",
"idx_rag_index_runs_status_created",
"idx_rag_query_logs_session_status_created",
"idx_rag_query_logs_status_created",
)
def test_models_use_uuid_primary_keys_and_expected_indexes():
text = MODELS.read_text(encoding="utf-8")
assert text.count(UUID_ID_SNIPPETS[0]) == 8
for snippet in REMOVED_SNIPPETS:
assert snippet not in text
for index_name in EXPECTED_MODEL_INDEXES:
assert index_name in text
def test_create_tables_sql_matches_fresh_uuid_schema():
text = CREATE_TABLES.read_text(encoding="utf-8")
assert text.count(UUID_ID_SNIPPETS[1]) == 8
for snippet in REMOVED_SNIPPETS:
assert snippet not in text
for index_name in EXPECTED_MODEL_INDEXES:
assert index_name in text
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!