files.py
17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import os
import shutil
import json
from datetime import datetime
from urllib.parse import quote
import logging
logger = logging.getLogger(__name__)
from fastapi import APIRouter, HTTPException, UploadFile, File, Body, Query
from fastapi.responses import FileResponse
from fastapi.concurrency import run_in_threadpool
from sqlalchemy import select, func, delete
from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog
from src.database.schemas import UploadInitRequest
from config import RAW_DIR
from src.tools.document_parser import (
delete_office_preview_pdf,
extract_text_from_file,
get_existing_office_preview_pdf,
)
router = APIRouter()
FILE_LIST_SORT_COLUMNS = {
"time": WikiFile.created_at,
"name": WikiFile.name,
"size": WikiFile.size,
"status": WikiFile.status,
"format": WikiFile.format,
"id": WikiFile.id,
"word_count": func.coalesce(WikiFile.word_count, 0),
# 「Token 消耗」按总消耗(LLM + VLM)排序,与列展示的 overall 口径一致;
# coalesce 兜底 NULL,避免旧数据在 desc 排序时把空值顶到前面。
"token": (func.coalesce(WikiFile.total_tokens, 0) + func.coalesce(WikiFile.vlm_total_tokens, 0)),
}
FILE_LIST_STATUSES = {"All", "Indexed", "Pending", "Ingesting", "Uploading", "Failed"}
def _normalize_file_list_options(
sort_by: str = "time",
sort_order: str = "desc",
status: str = "All",
file_format: str = "All",
) -> tuple[str, str, str, str]:
normalized_sort_by = sort_by if sort_by in FILE_LIST_SORT_COLUMNS else "time"
normalized_sort_order = sort_order.lower() if sort_order and sort_order.lower() in {"asc", "desc"} else "desc"
normalized_status = status if status in FILE_LIST_STATUSES else "All"
normalized_format = file_format.strip() if file_format and file_format.strip() else "All"
return normalized_sort_by, normalized_sort_order, normalized_status, normalized_format
def _apply_file_list_filters(query, search: str = "", status: str = "All", file_format: str = "All"):
if search:
query = query.where(WikiFile.name.ilike(f"%{search}%"))
if status != "All":
query = query.where(WikiFile.status == status)
if file_format != "All":
query = query.where(WikiFile.format == file_format)
return query
def _file_list_order_by(sort_by: str = "time", sort_order: str = "desc"):
sort_column = FILE_LIST_SORT_COLUMNS.get(sort_by, WikiFile.created_at)
if sort_order == "asc":
order_by = [sort_column.asc()]
stability_order = WikiFile.id.asc()
else:
order_by = [sort_column.desc()]
stability_order = WikiFile.id.desc()
if sort_by != "id":
order_by.append(stability_order)
return order_by
@router.get("/files")
async def list_files(
page: int = 1,
page_size: int = 10,
search: str = "",
sort_by: str = "time",
sort_order: str = "desc",
status: str = "All",
file_format: str = Query("All", alias="format"),
):
"""从数据库获取原始文件列表及其状态。
状态包括:Pending(待处理)、Ingesting(摄入中)、Indexed(已完成索引)、Failed(失败)。
"""
sort_by, sort_order, status, file_format = _normalize_file_list_options(
sort_by=sort_by,
sort_order=sort_order,
status=status,
file_format=file_format,
)
logger.info(
"获取文件列表: page=%s, page_size=%s, search='%s', sort_by=%s, sort_order=%s, status=%s, format=%s",
page,
page_size,
search,
sort_by,
sort_order,
status,
file_format,
)
async with AsyncSessionLocal() as session:
query = _apply_file_list_filters(select(WikiFile), search, status, file_format)
count_query = select(func.count()).select_from(query.subquery())
total_result = await session.execute(count_query)
total_count = total_result.scalar() or 0
formats_query = _apply_file_list_filters(
select(WikiFile.format).distinct(),
search=search,
status=status,
file_format="All",
).order_by(WikiFile.format.asc())
formats_result = await session.execute(formats_query)
format_options = [fmt for fmt in formats_result.scalars().all() if fmt]
query = query.order_by(*_file_list_order_by(sort_by, sort_order)).offset((page - 1) * page_size).limit(page_size)
result = await session.execute(query)
db_files = result.scalars().all()
files_list = []
for db_file in db_files:
name = db_file.name
ext = db_file.format or (os.path.splitext(name)[1].lstrip(".").upper() or "TXT")
size_raw = db_file.size or 0
if size_raw < 1024 * 1024:
size_str = f"{size_raw / 1024:.1f} KB"
else:
size_str = f"{size_raw / (1024*1024):.1f} MB"
frontend_meta = {}
if db_file.status == "Indexed" and db_file.ingest_time:
frontend_meta = {
"total_tokens": db_file.total_tokens or 0,
"input_tokens": db_file.input_tokens or 0,
"output_tokens": db_file.output_tokens or 0,
"cached_input_tokens": db_file.cached_input_tokens or 0,
"vlm_total_tokens": db_file.vlm_total_tokens or 0,
# 前端「Token 消耗」列展示口径:LLM + VLM 总消耗。
"overall_total_tokens": (db_file.total_tokens or 0) + (db_file.vlm_total_tokens or 0),
"ingest_mode": db_file.ingest_mode or "",
"ingest_duration": str(db_file.ingest_duration or "0"),
"ingest_time": db_file.ingest_time.strftime("%Y-%m-%d %H:%M:%S") if db_file.ingest_time else ""
}
created_at = db_file.created_at or datetime.now()
files_list.append({
"id": db_file.id,
"name": name,
"time": created_at.strftime("%Y-%m-%d"),
"full_time": created_at.strftime("%Y-%m-%d %H:%M:%S"),
"format": ext,
"size": size_str,
"size_raw": size_raw,
"word_count": db_file.word_count or 0,
"status": db_file.status,
"error_message": db_file.error_message,
"meta": frontend_meta,
})
return {
"files": files_list,
"total": total_count,
"page": page,
"page_size": page_size,
"filter_options": {
"formats": format_options,
},
}
@router.post("/upload/init")
async def upload_init(payload: UploadInitRequest):
"""分步上传第一步:批量分配 UUID 并进行同名拦截。"""
logger.info(f"初始化文件上传,共 {len(payload.files)} 个文件")
mapping = {}
errors = {}
async with AsyncSessionLocal() as session:
for f in payload.files:
result = await session.execute(
select(WikiFile).where(WikiFile.name == f.name)
)
existing = result.scalars().first()
if existing:
errors[f.name] = "文件已存在,请勿重复上传。"
continue
ext = os.path.splitext(f.name)[1].lstrip(".").upper() or "TXT"
db_file = WikiFile(
name=f.name,
format=ext,
size=0,
word_count=0,
status="Uploading",
)
session.add(db_file)
await session.flush()
mapping[f.name] = db_file.id
await session.commit()
return {"mapping": mapping, "errors": errors}
@router.post("/upload/{file_id}")
async def upload_file_chunk(file_id: str, file: UploadFile = File(...)):
"""分步上传第二步:根据 UUID 传输具体文件,异步流式落盘。"""
logger.info(f"接收文件上传: file_id={file_id}, filename={file.filename}")
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
raise HTTPException(status_code=404, detail="File init record not found.")
if db_file.status != "Uploading":
raise HTTPException(status_code=400, detail="File is not in Uploading state.")
file_dir = os.path.join(RAW_DIR, db_file.format.lower())
os.makedirs(file_dir, exist_ok=True)
file_path = os.path.join(file_dir, file.filename)
def save_upload_file(upload_file, path):
with open(path, "wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)
await run_in_threadpool(save_upload_file, file, file_path)
file_size = os.path.getsize(file_path)
word_count = 0
logger.info(
"[Upload] File saved; skip upload-time text extraction: file_id=%s, name=%s, size=%s",
file_id,
file.filename,
file_size,
)
db_file.size = file_size
db_file.word_count = word_count
db_file.status = "Pending"
log = WikiOperationLog(
file_id=file_id,
file_name=file.filename,
operation="UPLOAD_COMPLETED",
details=json.dumps({"size": file_size, "word_count": word_count}, ensure_ascii=False)
)
session.add(log)
await session.commit()
logger.info(f"文件上传完成: {file.filename}, size={file_size}, word_count={word_count}")
return {
"status": "success",
"file_id": file_id,
"file_status": "Pending",
"size": file_size,
"word_count": word_count,
}
@router.delete("/files/{file_id}")
async def delete_file(file_id: str):
"""根据 ID 从数据库和磁盘彻底删除文件。"""
logger.info(f"请求删除文件: file_id={file_id}")
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
raise HTTPException(status_code=404, detail="File not found")
if db_file.status not in ["Pending", "Failed"]:
raise HTTPException(status_code=400, detail="只有待处理或失败的文件才能删除!")
name = db_file.name
file_dir = os.path.join(RAW_DIR, db_file.format.lower())
file_path = os.path.join(file_dir, name)
if os.path.exists(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):
os.rmdir(file_dir)
# 先写入 DELETE 日志(WikiFile 删除后 ON DELETE SET NULL 会将日志的 file_id 置为 NULL)
log = WikiOperationLog(
file_id=file_id,
file_name=name,
operation="DELETE",
details=json.dumps({"deleted_from": "disk and db"}, ensure_ascii=False)
)
session.add(log)
# 显式删除关联 pages(ForeignKey CASCADE 会处理,显式删除保证兼容性)
await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == file_id))
await session.delete(db_file)
await session.commit()
logger.info(f"文件已删除: {name} (id={file_id})")
return {"status": "success"}
@router.post("/files/batch_delete")
async def batch_delete_files(data: dict = Body(...)):
"""根据 ids 批量从数据库和磁盘彻底删除文件。"""
ids = data.get("ids", [])
if not ids:
raise HTTPException(status_code=400, detail="ids 不能为空")
logger.info(f"请求批量删除文件: ids={ids}")
deleted_count = 0
errors = []
async with AsyncSessionLocal() as session:
for fid in ids:
result = await session.execute(select(WikiFile).where(WikiFile.id == fid))
db_file = result.scalar_one_or_none()
if not db_file:
errors.append(f"id={fid}: 未找到")
continue
if db_file.status not in ["Pending", "Failed"]:
errors.append(f"{db_file.name}: 只有待处理或失败的文件才能删除")
continue
try:
file_dir = os.path.join(RAW_DIR, db_file.format.lower())
file_path = os.path.join(file_dir, db_file.name)
if os.path.exists(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):
os.rmdir(file_dir)
log = WikiOperationLog(
file_id=fid,
file_name=db_file.name,
operation="DELETE",
details=json.dumps({"batch": True}, ensure_ascii=False)
)
session.add(log)
await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == fid))
await session.delete(db_file)
deleted_count += 1
logger.info(f"批量删除: 已删除文件 {db_file.name} (id={fid})")
except Exception as e:
logger.error(f"批量删除文件失败 [{db_file.name}]: {e}")
errors.append(f"{db_file.name}: 删除失败 {str(e)}")
await session.commit()
if errors and deleted_count == 0:
raise HTTPException(status_code=400, detail="批量删除失败: " + "; ".join(errors))
return {"status": "success", "deleted_count": deleted_count, "errors": errors or None}
@router.get("/files/view/{file_id}")
async def view_file(file_id: str):
"""根据 ID 预览本地原始文件内容。"""
logger.info(f"请求预览本地原始文件: file_id={file_id}")
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
raise HTTPException(status_code=404, detail="File not found")
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):
raise HTTPException(status_code=404, detail="File not found on disk")
ext = os.path.splitext(db_file.name)[1].lower()
if ext == '.pdf':
logger.info("[Preview] 返回 PDF 原文件: file_id=%s, media_type=application/pdf", file_id)
return FileResponse(file_path, media_type='application/pdf')
if ext in ('.ppt', '.pptx'):
preview_pdf_path = get_existing_office_preview_pdf(file_path, file_id)
if not preview_pdf_path:
logger.info(
"[Preview] PPT/PPTX preview PDF missing: file_id=%s, name=%s, path=%s",
file_id,
db_file.name,
file_path,
)
raise HTTPException(
status_code=202,
detail={
"type": "preview_status",
"preview_status": "missing",
"message": "预览 PDF 尚未生成,请稍后刷新或先发起摄入。",
},
)
logger.info(
"[Preview] Return cached PPT/PPTX PDF preview: file_id=%s, cache_path=%s, media_type=application/pdf",
file_id,
preview_pdf_path,
)
return FileResponse(preview_pdf_path, media_type='application/pdf')
if ext in ('.xlsx', '.xls'):
media_type = (
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
if ext == '.xlsx' else 'application/vnd.ms-excel'
)
logger.info("[Preview] 返回 Excel 原文件: file_id=%s, media_type=%s", file_id, media_type)
return FileResponse(file_path, media_type=media_type)
try:
content = extract_text_from_file(file_path)
return {"type": "text_preview", "content": content}
except Exception as e:
logger.error(f"提取文件内容失败 [{db_file.name}]: {e}")
return {"type": "text_preview", "content": f"无法提取文件内容: {str(e)}"}
@router.get("/files/download/{file_id}")
async def download_file(file_id: str):
"""根据 ID 下载本地原始文件。"""
logger.info(f"请求下载本地原始文件: file_id={file_id}")
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
raise HTTPException(status_code=404, detail="File not found")
file_path = os.path.join(RAW_DIR, db_file.format.lower(), db_file.name)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found on disk")
headers = {
"Content-Disposition": f"attachment; filename={quote(db_file.name)}; filename*=utf-8''{quote(db_file.name)}"
}
return FileResponse(file_path, headers=headers)
@router.get("/files/{file_id}/wiki_links")
async def get_file_wiki_links(file_id: str):
"""查询指定文件生成的 Wiki 页面路径列表。"""
logger.info(f"查询文件关联的 Wiki 链接: file_id={file_id}")
async with AsyncSessionLocal() as session:
result = await session.execute(
select(WikiFilePage).where(WikiFilePage.file_id == file_id)
)
pages = result.scalars().all()
links = [p.page_path for p in pages]
return {"links": links}