excel.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from fastapi import APIRouter, File, UploadFile, Depends
  2. from fastapi.responses import JSONResponse, FileResponse
  3. from fastapi.exceptions import HTTPException
  4. from sqlalchemy.orm import Session
  5. from starlette.websockets import WebSocket, WebSocketDisconnect
  6. from werkzeug.utils import secure_filename
  7. from app.api import get_current_user_websocket
  8. from app.models.agent_model import AgentModel, AgentType
  9. from app.models.base_model import get_db
  10. from app.models.user_model import UserModel
  11. from app.utils.excelmerge.conformity import run_conformity
  12. import shutil
  13. import os
  14. router = APIRouter()
  15. ALLOWED_EXTENSIONS = {'xlsx'}
  16. EXCEL_FILES_PATH = 'data/output'
  17. SOURCE_FILES_PATH = 'data/source'
  18. output_path_value = None
  19. def allowed_file(filename):
  20. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  21. def create_dir_if_not_exists(path):
  22. if not os.path.exists(path):
  23. os.makedirs(path)
  24. @router.post('/excel/upload')
  25. async def upload_file(files: list[UploadFile] = File(...)):
  26. if not any(file.filename for file in files):
  27. return JSONResponse(content={"error": "没有文件部分"}, status_code=400)
  28. create_dir_if_not_exists(SOURCE_FILES_PATH)
  29. # 清空SOURCE_FILES_PATH目录
  30. for filename in os.listdir(SOURCE_FILES_PATH):
  31. file_path = os.path.join(SOURCE_FILES_PATH, filename)
  32. try:
  33. if os.path.isfile(file_path) or os.path.islink(file_path):
  34. os.unlink(file_path)
  35. elif os.path.isdir(file_path):
  36. shutil.rmtree(file_path)
  37. except Exception as e:
  38. return JSONResponse(content={"error": "文件处理出错"}, status_code=500)
  39. save_path_list = []
  40. for file in files:
  41. if file.filename == '':
  42. return JSONResponse(content={"error": "没有选择文件"}, status_code=400)
  43. if file and allowed_file(file.filename):
  44. filename = secure_filename(file.filename)
  45. save_path = os.path.join(SOURCE_FILES_PATH, filename)
  46. with open(save_path, 'wb') as buffer:
  47. shutil.copyfileobj(file.file, buffer)
  48. save_path_list.append(save_path)
  49. else:
  50. return JSONResponse(content={"error": "不允许的文件类型"}, status_code=400)
  51. return JSONResponse(content={"message": "文件上传成功", "paths": save_path_list}, status_code=201)
  52. @router.post('/excel/conformity')
  53. async def run_conformity_api():
  54. global output_path_value # 声明全局变量
  55. try:
  56. create_dir_if_not_exists(EXCEL_FILES_PATH)
  57. # 清空EXCEL_FILES_PATH目录
  58. for filename in os.listdir(EXCEL_FILES_PATH):
  59. file_path = os.path.join(EXCEL_FILES_PATH, filename)
  60. try:
  61. if os.path.isfile(file_path) or os.path.islink(file_path):
  62. os.unlink(file_path)
  63. elif os.path.isdir(file_path):
  64. shutil.rmtree(file_path)
  65. except Exception as e:
  66. return JSONResponse(content={"error": "文件处理出错"}, status_code=500)
  67. # 运行方法
  68. output_path = run_conformity()
  69. output_path_value = output_path
  70. return JSONResponse(content={"message": "conformity.py 运行成功", "output_path": str(output_path)},
  71. status_code=200)
  72. except Exception as e:
  73. return JSONResponse(content={"error": str(e)}, status_code=500)
  74. @router.get('/excel/file/status')
  75. async def get_file_status():
  76. try:
  77. return JSONResponse(content={"output_path": str(output_path_value)}, status_code=200)
  78. except Exception as e:
  79. return JSONResponse(content={"error": str(e)}, status_code=500)
  80. @router.get('/excel/download_excel')
  81. async def download_excel():
  82. try:
  83. files = os.listdir(EXCEL_FILES_PATH)
  84. first_file = files[0]
  85. return FileResponse(os.path.join(EXCEL_FILES_PATH, first_file), filename=first_file,
  86. media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  87. except FileNotFoundError:
  88. raise HTTPException(status_code=404, detail="文件不存在")
  89. except Exception as e:
  90. raise HTTPException(status_code=500, detail="服务器错误")
  91. @router.websocket("/ws/{agent_id}/{chat_id}")
  92. async def excel_chat(websocket: WebSocket,
  93. agent_id: str,
  94. chat_id: str,
  95. db: Session = Depends(get_db)):
  96. agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
  97. if not agent:
  98. ret = {"message": "Agent not found", "type": "close"}
  99. return websocket.send_json(ret)
  100. agent_type = agent.agent_type
  101. if chat_id == "" or chat_id == "0":
  102. ret = {"message": "Chat ID not found", "type": "close"}
  103. return websocket.send_json(ret)
  104. if agent_type != AgentType.BASIC:
  105. ret = {"message": "agent type error", "type": "close"}
  106. return websocket.send_json(ret)
  107. await websocket.accept()
  108. try:
  109. while True:
  110. message = await websocket.receive_json()
  111. print(message) # 打印接收到的消息
  112. result = {"message": "已生成文件", "type": "file", "url": "ip/download?id=xxxx"}
  113. # 发送响应
  114. await websocket.send_json(result)
  115. except WebSocketDisconnect as e:
  116. print(f"Client {chat_id} disconnected")