files.py
12.1 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
import os
import shutil
import re
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
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 extract_text_from_file
router = APIRouter()
@router.get("/files")
async def list_files(page: int = 1, page_size: int = 10, search: str = ""):
"""从数据库获取原始文件列表及其状态。
状态包括:Pending(待处理)、Ingesting(摄入中)、Indexed(已完成索引)、Failed(失败)。
"""
logger.info(f"获取文件列表: page={page}, page_size={page_size}, search='{search}'")
async with AsyncSessionLocal() as session:
query = select(WikiFile)
if search:
query = query.where(WikiFile.name.ilike(f"%{search}%"))
count_query = select(func.count()).select_from(query.subquery())
total_result = await session.execute(count_query)
total_count = total_result.scalar() or 0
query = query.order_by(WikiFile.created_at.desc()).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,
"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
}
@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
try:
text = extract_text_from_file(file_path)
pure_text = re.sub(r'\s+', '', text)
word_count = len(pure_text)
except Exception as e:
logger.warning(f"计算字数失败 [{file.filename}]: {e}")
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"}
@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.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.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)
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':
return FileResponse(file_path, media_type='application/pdf')
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}