-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
752 lines (595 loc) · 28.3 KB
/
api_server.py
File metadata and controls
752 lines (595 loc) · 28.3 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import os
import sys
import uuid
import shutil
from pathlib import Path
import json
from datetime import datetime, timedelta
import asyncio
from typing import Dict, Optional, List
import time
import glob
import re
# 禁用 Windows 控制台快速编辑模式 + 设置编码
if sys.platform == 'win32':
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-10), 0x0080)
# 修复中文乱码
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
os.system('chcp 65001 >nul 2>&1')
# 获取基础路径(兼容打包后的exe)
if getattr(sys, 'frozen', False):
BASE_DIR = Path(sys._MEIPASS)
else:
BASE_DIR = Path(__file__).parent
STATIC_DIR = BASE_DIR / "static"
# 导入 pdf_craft 转换功能
try:
from pdf_craft import transform_markdown
except ImportError as e:
print(f"Error importing pdf_craft: {e}")
transform_markdown = None
# 导入 PDF 处理功能
try:
from pdf_processor import PDFProcessor
pdf_processor = PDFProcessor()
except ImportError as e:
print(f"Error importing pdf_processor: {e}")
pdf_processor = None
# 导入 OpenCC 繁简转换功能
try:
import opencc
opencc_converter = opencc.OpenCC('t2s')
except ImportError as e:
print(f"Error importing opencc: {e}")
opencc_converter = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
try:
if transform_markdown:
print("PDF转换功能已准备就绪")
else:
print("警告: pdf_craft 模块未正确导入")
cleanup_temp_files()
asyncio.create_task(periodic_cleanup())
except Exception as e:
print(f"初始化错误: {e}")
yield
print("应用关闭中...")
app = FastAPI(
title="PDF 文档处理平台",
description="提供 PDF 转换、处理和格式转换等全方位服务",
lifespan=lifespan
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
UPLOAD_DIR = Path("temp_uploads")
OUTPUT_DIR = Path("temp_outputs")
UPLOAD_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)
task_status: Dict[str, Dict] = {}
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
@app.get("/")
async def read_root():
from fastapi.responses import RedirectResponse
return RedirectResponse(url="/pdf-tools", status_code=302)
@app.get("/home", response_class=HTMLResponse)
async def read_home():
with open(STATIC_DIR / "index.html", "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read())
@app.get("/pdf-tools", response_class=HTMLResponse)
async def read_pdf_tools():
with open(STATIC_DIR / "pdf-tools.html", "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read())
@app.post("/api/upload")
async def upload_pdf(file: UploadFile = File(...)):
if not file.filename.endswith('.pdf'):
raise HTTPException(status_code=400, detail="只能上传PDF文件")
task_id = str(uuid.uuid4())
file_path = UPLOAD_DIR / f"{task_id}_{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
task_status[task_id] = {
"status": "uploaded",
"filename": file.filename,
"file_path": str(file_path),
"created_at": datetime.now().isoformat(),
"progress": 0
}
return {"task_id": task_id, "message": "文件上传成功"}
@app.post("/api/convert/{task_id}")
async def convert_pdf(task_id: str, background_tasks: BackgroundTasks):
if task_id not in task_status:
raise HTTPException(status_code=404, detail="任务不存在")
if task_status[task_id]["status"] not in ["uploaded", "failed"]:
raise HTTPException(status_code=400, detail="任务状态不允许转换")
if not transform_markdown:
raise HTTPException(status_code=500, detail="PDF转换功能不可用")
task_status[task_id]["status"] = "processing"
task_status[task_id]["progress"] = 10
background_tasks.add_task(process_pdf_conversion, task_id)
return {"task_id": task_id, "message": "转换任务已开始"}
async def process_pdf_conversion(task_id: str):
try:
task_info = task_status[task_id]
file_path = task_info["file_path"]
original_filename = task_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
output_filename = f"{filename_without_ext}.md"
output_path = OUTPUT_DIR / f"{task_id}_{output_filename}"
task_status[task_id]["progress"] = 30
transform_markdown(
pdf_path=file_path,
markdown_path=str(output_path),
models_cache_path="models",
local_only=True
)
task_status[task_id]["status"] = "completed"
task_status[task_id]["progress"] = 100
task_status[task_id]["output_path"] = str(output_path)
task_status[task_id]["completed_at"] = datetime.now().isoformat()
task_status[task_id]["download_filename"] = output_filename
except Exception as e:
task_status[task_id]["status"] = "failed"
task_status[task_id]["error"] = str(e)
task_status[task_id]["failed_at"] = datetime.now().isoformat()
@app.get("/api/status/{task_id}")
async def get_task_status(task_id: str):
if task_id not in task_status:
raise HTTPException(status_code=404, detail="任务不存在")
return task_status[task_id]
@app.get("/api/download/{task_id}")
async def download_result(task_id: str):
if task_id not in task_status:
raise HTTPException(status_code=404, detail="任务不存在")
task_info = task_status[task_id]
if task_info["status"] != "completed":
raise HTTPException(status_code=400, detail="任务尚未完成")
output_path = task_info.get("output_path")
if not output_path or not os.path.exists(output_path):
raise HTTPException(status_code=404, detail="结果文件不存在")
if "is_single_file" in task_info:
is_single_file = task_info["is_single_file"]
else:
is_single_file = not output_path.lower().endswith('.zip')
if is_single_file:
if "download_filename" in task_info:
filename = task_info["download_filename"]
elif "filename" in task_info:
original_filename = task_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
file_ext = os.path.splitext(output_path)[1]
filename = f"{filename_without_ext}{file_ext}"
else:
filename = os.path.basename(output_path).replace(f"{task_id}_", "")
if filename.lower().endswith('.pdf'):
media_type = "application/pdf"
elif filename.lower().endswith('.docx'):
media_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
elif filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg'):
media_type = "image/jpeg"
elif filename.lower().endswith('.png'):
media_type = "image/png"
elif filename.lower().endswith('.md'):
media_type = "text/markdown"
else:
media_type = "application/octet-stream"
else:
if "files" in task_info and len(task_info["files"]) > 0:
first_file = task_info["files"][0]["filename"]
base_name = os.path.splitext(first_file)[0]
operation_name = task_info.get("operation", "processed")
filename = f"{base_name}_{operation_name}.zip"
else:
operation_name = task_info.get("operation", "processed")
filename = f"{operation_name}_files.zip"
media_type = "application/zip"
return FileResponse(
path=output_path,
media_type=media_type,
filename=filename
)
@app.get("/api/tasks")
async def list_tasks():
return task_status
@app.delete("/api/tasks/{task_id}")
async def delete_task(task_id: str):
if task_id not in task_status:
raise HTTPException(status_code=404, detail="任务不存在")
task_info = task_status[task_id]
try:
if "file_path" in task_info and os.path.exists(task_info["file_path"]):
os.remove(task_info["file_path"])
except Exception as e:
print(f"删除上传文件时出错: {e}")
try:
output_path = task_info.get("output_path")
if output_path and os.path.exists(output_path):
if os.path.isdir(output_path):
shutil.rmtree(output_path)
else:
os.remove(output_path)
except Exception as e:
print(f"删除输出文件时出错: {e}")
try:
for dir_path in glob.glob(str(OUTPUT_DIR / f"{task_id}_*")):
if os.path.isdir(dir_path):
shutil.rmtree(dir_path)
except Exception as e:
print(f"删除任务输出目录时出错: {e}")
del task_status[task_id]
return {"message": "任务已删除"}
@app.post("/api/pdf/upload-multiple")
async def upload_multiple_files(files: List[UploadFile] = File(...)):
if not pdf_processor:
raise HTTPException(status_code=500, detail="PDF处理功能不可用")
task_id = str(uuid.uuid4())
uploaded_files = []
for file in files:
if not file.filename:
continue
file_path = UPLOAD_DIR / f"{task_id}_{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
file_info_result = pdf_processor.get_file_info(str(file_path))
uploaded_files.append({
"filename": file.filename,
"file_path": str(file_path),
"file_info": file_info_result.get("file_info", {})
})
task_status[task_id] = {
"status": "uploaded",
"files": uploaded_files,
"task_type": "batch_process",
"created_at": datetime.now().isoformat(),
"progress": 0
}
return {"task_id": task_id, "files": uploaded_files}
@app.post("/api/pdf/process/{task_id}")
async def process_pdf(task_id: str, operation: str, background_tasks: BackgroundTasks):
if task_id not in task_status:
raise HTTPException(status_code=404, detail="任务不存在")
if task_status[task_id]["status"] not in ["uploaded", "failed"]:
raise HTTPException(status_code=400, detail="任务状态不允许处理")
if not pdf_processor:
raise HTTPException(status_code=500, detail="PDF处理功能不可用")
task_status[task_id]["status"] = "processing"
task_status[task_id]["progress"] = 10
task_status[task_id]["operation"] = operation
background_tasks.add_task(process_pdf_operation, task_id, operation)
return {"task_id": task_id, "message": f"开始执行 {operation} 操作"}
async def process_pdf_operation(task_id: str, operation: str):
try:
task_info = task_status[task_id]
task_info["progress"] = 30
output_dir = OUTPUT_DIR / f"{task_id}_{operation}"
output_dir.mkdir(exist_ok=True)
results = []
if operation == "pdf_to_md":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] == ".pdf":
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
output_md_path = output_dir / f"{filename_without_ext}.md"
transform_markdown(
pdf_path=file_info["file_path"],
markdown_path=str(output_md_path),
models_cache_path="models",
local_only=True
)
results.append({
"success": True,
"message": f"成功将 {file_info['filename']} 转换为 Markdown",
"output_path": str(output_md_path)
})
elif operation == "traditional_to_simplified":
if not opencc_converter:
raise Exception("繁简转换功能不可用,请检查OpenCC库")
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] in [".doc", ".docx"]:
import docx
from docx import Document
doc = Document(file_info["file_path"])
for paragraph in doc.paragraphs:
if paragraph.text:
paragraph.text = opencc_converter.convert(paragraph.text)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
if cell.text:
cell.text = opencc_converter.convert(cell.text)
original_filename = file_info["filename"]
output_path = output_dir / original_filename
doc.save(str(output_path))
results.append({
"success": True,
"message": f"成功将 {file_info['filename']} 从繁体转换为简体",
"output_path": str(output_path)
})
elif operation == "pdf_to_docx":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] == ".pdf":
result = pdf_processor.pdf_to_docx(file_info["file_path"], str(output_dir))
if result.get("success") and "output_file" in result:
output_file_path = result["output_file"]
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
new_output_path = os.path.join(output_dir, f"{filename_without_ext}.docx")
os.rename(output_file_path, new_output_path)
result["output_file"] = new_output_path
results.append(result)
elif operation == "pdf_to_jpg":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] == ".pdf":
result = pdf_processor.pdf_to_jpg(file_info["file_path"], str(output_dir))
if result.get("success") and "output_files" in result:
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
new_output_files = []
for output_file in result["output_files"]:
output_name = os.path.basename(output_file)
match = re.search(r'_p(\d+)', output_name)
if match:
page_num = match.group(1)
new_name = f"{filename_without_ext}_p{page_num}.jpg"
else:
new_name = f"{filename_without_ext}.jpg"
new_path = os.path.join(output_dir, new_name)
os.rename(output_file, new_path)
new_output_files.append(new_path)
result["output_files"] = new_output_files
results.append(result)
elif operation == "split_pdf":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] == ".pdf":
result = pdf_processor.split_pdf(file_info["file_path"], str(output_dir))
if result.get("success") and "output_files" in result:
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
new_output_files = []
for output_file in result["output_files"]:
output_name = os.path.basename(output_file)
match = re.search(r'_p(\d+)', output_name)
if match:
page_num = match.group(1)
new_name = f"{filename_without_ext}_p{page_num}.pdf"
else:
new_name = f"{filename_without_ext}.pdf"
new_path = os.path.join(output_dir, new_name)
os.rename(output_file, new_path)
new_output_files.append(new_path)
result["output_files"] = new_output_files
results.append(result)
elif operation == "compress_pdf":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] == ".pdf":
result = pdf_processor.compress_pdf(file_info["file_path"], str(output_dir))
if result.get("success") and "output_file" in result:
output_file_path = result["output_file"]
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
new_output_path = os.path.join(output_dir, f"{filename_without_ext}_compressed.pdf")
os.rename(output_file_path, new_output_path)
result["output_file"] = new_output_path
results.append(result)
elif operation == "merge_pdfs":
pdf_files = [f["file_path"] for f in task_info["files"]
if f["file_info"]["extension"] == ".pdf"]
if pdf_files:
result = pdf_processor.merge_pdfs(pdf_files, str(output_dir))
if result.get("success") and "output_file" in result:
output_file_path = result["output_file"]
first_filename = task_info["files"][0]["filename"]
filename_without_ext = os.path.splitext(first_filename)[0]
new_output_path = os.path.join(output_dir, f"{filename_without_ext}_merged.pdf")
os.rename(output_file_path, new_output_path)
result["output_file"] = new_output_path
results.append(result)
elif operation == "images_to_pdf":
image_files = [f["file_path"] for f in task_info["files"]
if f["file_info"]["extension"] in ['.jpg', '.jpeg', '.png', '.bmp']]
if image_files:
result = pdf_processor.images_to_pdf(image_files, str(output_dir))
if result.get("success") and "output_file" in result:
output_file_path = result["output_file"]
first_filename = task_info["files"][0]["filename"]
filename_without_ext = os.path.splitext(first_filename)[0]
new_output_path = os.path.join(output_dir, f"{filename_without_ext}_converted.pdf")
os.rename(output_file_path, new_output_path)
result["output_file"] = new_output_path
results.append(result)
elif operation == "word_to_pdf":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] in ['.doc', '.docx']:
result = pdf_processor.word_to_pdf(file_info["file_path"], str(output_dir))
if result.get("success") and "output_file" in result:
output_file_path = result["output_file"]
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
new_output_path = os.path.join(output_dir, f"{filename_without_ext}.pdf")
os.rename(output_file_path, new_output_path)
result["output_file"] = new_output_path
results.append(result)
elif operation == "excel_to_pdf":
for file_info in task_info["files"]:
if file_info["file_info"]["extension"] in ['.xls', '.xlsx']:
result = pdf_processor.excel_to_pdf(file_info["file_path"], str(output_dir))
if result.get("success") and "output_file" in result:
output_file_path = result["output_file"]
original_filename = file_info["filename"]
filename_without_ext = os.path.splitext(original_filename)[0]
new_output_path = os.path.join(output_dir, f"{filename_without_ext}.pdf")
os.rename(output_file_path, new_output_path)
result["output_file"] = new_output_path
results.append(result)
task_info["progress"] = 90
if not output_dir.exists() or not any(output_dir.iterdir()):
raise Exception("没有生成任何输出文件")
output_files = list(output_dir.glob('*'))
if len(output_files) == 1:
task_info["status"] = "completed"
task_info["progress"] = 100
task_info["output_path"] = str(output_files[0])
task_info["results"] = results
task_info["completed_at"] = datetime.now().isoformat()
task_info["is_single_file"] = True
else:
if len(task_info["files"]) > 0:
first_file_name = task_info["files"][0]["filename"]
base_name = os.path.splitext(first_file_name)[0]
zip_filename = f"{base_name}_{operation}"
else:
zip_filename = f"{operation}_files"
zip_path = OUTPUT_DIR / f"{task_id}_{zip_filename}.zip"
shutil.make_archive(str(zip_path.with_suffix('')), 'zip', str(output_dir))
task_info["status"] = "completed"
task_info["progress"] = 100
task_info["output_path"] = str(zip_path)
task_info["results"] = results
task_info["completed_at"] = datetime.now().isoformat()
task_info["is_single_file"] = False
except Exception as e:
task_status[task_id]["status"] = "failed"
task_status[task_id]["error"] = str(e)
task_status[task_id]["failed_at"] = datetime.now().isoformat()
@app.get("/api/pdf/operations")
async def get_available_operations():
if not pdf_processor:
raise HTTPException(status_code=500, detail="PDF处理功能不可用")
operations = [
{"id": "pdf_to_md", "name": "PDF → Markdown", "description": "将PDF文件转换为Markdown文档",
"supported_formats": [".pdf"]},
{"id": "pdf_to_docx", "name": "PDF → DOCX", "description": "将PDF文件转换为Word文档",
"supported_formats": [".pdf"]},
{"id": "pdf_to_jpg", "name": "PDF → JPG", "description": "将PDF文件转换为图片", "supported_formats": [".pdf"]},
{"id": "traditional_to_simplified", "name": "繁体 → 简体", "description": "将Word文档从繁体中文转换为简体中文",
"supported_formats": [".doc", ".docx"]},
{"id": "split_pdf", "name": "拆分PDF", "description": "将PDF文件按页面拆分为多个文件",
"supported_formats": [".pdf"]},
{"id": "compress_pdf", "name": "压缩PDF", "description": "优化PDF文件大小", "supported_formats": [".pdf"]},
{"id": "merge_pdfs", "name": "合并PDF", "description": "将多个PDF文件合并为一个", "supported_formats": [".pdf"],
"min_files": 2},
{"id": "images_to_pdf", "name": "图片 → PDF", "description": "将图片合并为PDF文件",
"supported_formats": [".jpg", ".jpeg", ".png", ".bmp"], "min_files": 1},
{"id": "word_to_pdf", "name": "Word → PDF", "description": "将Word文档转换为PDF",
"supported_formats": [".doc", ".docx"], "platform": "windows"},
{"id": "excel_to_pdf", "name": "Excel → PDF", "description": "将Excel表格转换为PDF",
"supported_formats": [".xls", ".xlsx"], "platform": "windows"}
]
return {"operations": operations}
@app.post("/api/cleanup")
async def manual_cleanup():
try:
cleanup_temp_files()
return {"message": "临时文件清理完成"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"清理失败: {str(e)}")
@app.post("/api/cleanup/all")
async def clear_all_temp_files():
try:
cleared_files = 0
if UPLOAD_DIR.exists():
for file_path in UPLOAD_DIR.glob("*"):
if file_path.is_file():
file_path.unlink()
cleared_files += 1
elif file_path.is_dir():
shutil.rmtree(file_path)
cleared_files += 1
if OUTPUT_DIR.exists():
for file_path in OUTPUT_DIR.glob("*"):
if file_path.is_file():
file_path.unlink()
cleared_files += 1
elif file_path.is_dir():
shutil.rmtree(file_path)
cleared_files += 1
task_count = len(task_status)
task_status.clear()
return {
"message": f"已清空所有临时文件和任务状态",
"files_cleared": cleared_files,
"tasks_cleared": task_count
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"清空失败: {str(e)}")
def cleanup_temp_files():
try:
current_time = time.time()
expiration_time = 24 * 60 * 60
for file_path in glob.glob(str(UPLOAD_DIR / "*")):
if os.path.isfile(file_path):
file_age = current_time - os.path.getmtime(file_path)
if file_age > expiration_time:
os.remove(file_path)
for file_path in glob.glob(str(OUTPUT_DIR / "*")):
if os.path.isfile(file_path):
file_age = current_time - os.path.getmtime(file_path)
if file_age > expiration_time:
os.remove(file_path)
elif os.path.isdir(file_path):
dir_age = current_time - os.path.getmtime(file_path)
if dir_age > expiration_time:
shutil.rmtree(file_path)
expired_tasks = []
for task_id, task_info in task_status.items():
created_time = datetime.fromisoformat(task_info["created_at"])
if datetime.now() - created_time > timedelta(hours=24):
expired_tasks.append(task_id)
for task_id in expired_tasks:
del task_status[task_id]
except Exception as e:
print(f"清理临时文件时出错: {e}")
async def periodic_cleanup():
while True:
await asyncio.sleep(6 * 60 * 60)
cleanup_temp_files()
if __name__ == "__main__":
import uvicorn
import webbrowser
import threading
import time
def open_browser():
"""打开浏览器,兼容exe文件"""
try:
# 延迟打开浏览器,等服务器启动
time.sleep(1.5)
url = "http://localhost:8000"
# 判断是否为打包后的exe环境
if getattr(sys, 'frozen', False):
# Windows下使用start命令打开默认浏览器
if sys.platform == 'win32':
import os
os.system(f'start "" "{url}"')
# macOS下使用open命令
elif sys.platform == 'darwin':
import os
os.system(f'open "{url}"')
# Linux下使用xdg-open命令
else:
import os
os.system(f'xdg-open "{url}"')
else:
# 开发环境直接使用webbrowser模块
webbrowser.open(url)
except Exception as e:
print(f"打开浏览器失败: {e}")
print(f"请手动访问: {url}")
# 在新线程中打开浏览器,避免阻塞服务器启动
browser_thread = threading.Thread(target=open_browser)
browser_thread.daemon = True
browser_thread.start()
uvicorn.run(app, host="0.0.0.0", port=8000)