From a77073fec80037072df84fc6a58e0f3be7e43b14 Mon Sep 17 00:00:00 2001
From: zhangxiao <898441624@qq.com>
Date: 星期四, 17 十月 2024 17:19:31 +0800
Subject: [PATCH] 改为websocket 脚本运行。(功能有待优化)
---
app/api/excel.py | 137 +++++++++++++++++----------------------------
1 files changed, 52 insertions(+), 85 deletions(-)
diff --git a/app/api/excel.py b/app/api/excel.py
index 1ff4741..4110527 100644
--- a/app/api/excel.py
+++ b/app/api/excel.py
@@ -4,7 +4,6 @@
from sqlalchemy.orm import Session
from starlette.websockets import WebSocket, WebSocketDisconnect
from werkzeug.utils import secure_filename
-
from app.api import get_current_user_websocket
from app.models.agent_model import AgentModel, AgentType
from app.models.base_model import get_db
@@ -18,8 +17,6 @@
ALLOWED_EXTENSIONS = {'xlsx'}
EXCEL_FILES_PATH = 'data/output'
SOURCE_FILES_PATH = 'data/source'
-output_path_value = None
-
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@@ -30,23 +27,29 @@
os.makedirs(path)
-@router.post('/excel/upload')
-async def upload_file(files: list[UploadFile] = File(...)):
- if not any(file.filename for file in files):
- return JSONResponse(content={"error": "娌℃湁鏂囦欢閮ㄥ垎"}, status_code=400)
-
- create_dir_if_not_exists(SOURCE_FILES_PATH)
-
- # 娓呯┖SOURCE_FILES_PATH鐩綍
- for filename in os.listdir(SOURCE_FILES_PATH):
- file_path = os.path.join(SOURCE_FILES_PATH, filename)
+# 娓呯悊鍑芥暟
+def clear_directory(path):
+ for filename in os.listdir(path):
+ file_path = os.path.join(path, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
- return JSONResponse(content={"error": "鏂囦欢澶勭悊鍑洪敊"}, status_code=500)
+ return {"error": "娓呯┖鍑洪敊"}
+ return {"message": "鐩綍宸叉竻绌�"}
+
+
+@router.post('/excel/upload')
+async def upload_file(files: list[UploadFile] = File(...)):
+ if not any(file.filename for file in files):
+ return JSONResponse(content={"error": "娌℃湁鏂囦欢閮ㄥ垎"}, status_code=400)
+
+ create_dir_if_not_exists(SOURCE_FILES_PATH)
+ create_dir_if_not_exists(EXCEL_FILES_PATH)
+ clear_directory(SOURCE_FILES_PATH)
+ clear_directory(EXCEL_FILES_PATH)
save_path_list = []
for file in files:
@@ -63,79 +66,43 @@
return JSONResponse(content={"message": "鏂囦欢涓婁紶鎴愬姛", "paths": save_path_list}, status_code=201)
-@router.post('/excel/conformity')
-async def run_conformity_api():
- global output_path_value # 澹版槑鍏ㄥ眬鍙橀噺
+# ws://localhost:9201/api/document/ws/excel
+@router.websocket("/ws/excel")
+async def ws_excel(websocket: WebSocket):
+ await websocket.accept()
+ while True:
+ data = await websocket.receive_json()
+ action = data.get("action")
+ try:
+ if action == "process":
+ clear_directory(EXCEL_FILES_PATH)
+ output_file_path = run_conformity()
+ await websocket.send_json({"step_message": "寮�濮嬪悎骞�"})
+ elif action == "inquire":
+ files = os.listdir(EXCEL_FILES_PATH)
+ if not files:
+ await websocket.send_json({"step_message": "姝e湪鍚堝苟涓�"})
+ else:
+ await websocket.send_json({"step_message": "鏂囨。鍚堝苟鎴愬姛锛�"})
+ elif action == "download":
+ files = os.listdir(EXCEL_FILES_PATH)
+ if not files:
+ await websocket.send_json({"error": "鐩綍涓嬫病鏈夌敓鎴愮殑鏂囦欢"})
+ else:
+ first_file = files[0]
+ await websocket.send_json({"step_message": "鍚堝苟鏂囦欢宸茬敓鎴�", "download_url": f"/download/{first_file}"})
+ else:
+ await websocket.send_json({"error": "鏈煡鎸囦护"})
+ except Exception as e:
+ await websocket.send_json({"error": str(e)})
+
+
+@router.get("/download/{filename}")
+async def download_file(filename: str):
try:
- create_dir_if_not_exists(EXCEL_FILES_PATH)
-
- # 娓呯┖EXCEL_FILES_PATH鐩綍
- for filename in os.listdir(EXCEL_FILES_PATH):
- file_path = os.path.join(EXCEL_FILES_PATH, filename)
- try:
- if os.path.isfile(file_path) or os.path.islink(file_path):
- os.unlink(file_path)
- elif os.path.isdir(file_path):
- shutil.rmtree(file_path)
- except Exception as e:
- return JSONResponse(content={"error": "鏂囦欢澶勭悊鍑洪敊"}, status_code=500)
-
- # 杩愯鏂规硶
- output_path = run_conformity()
- output_path_value = output_path
- return JSONResponse(content={"message": "conformity.py 杩愯鎴愬姛", "output_path": str(output_path)},
- status_code=200)
- except Exception as e:
- return JSONResponse(content={"error": str(e)}, status_code=500)
-
-
-@router.get('/excel/file/status')
-async def get_file_status():
- try:
- return JSONResponse(content={"output_path": str(output_path_value)}, status_code=200)
- except Exception as e:
- return JSONResponse(content={"error": str(e)}, status_code=500)
-
-
-@router.get('/excel/download_excel')
-async def download_excel():
- try:
- files = os.listdir(EXCEL_FILES_PATH)
- first_file = files[0]
- return FileResponse(os.path.join(EXCEL_FILES_PATH, first_file), filename=first_file,
+ return FileResponse(os.path.join(EXCEL_FILES_PATH, filename), filename=filename,
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
except FileNotFoundError:
raise HTTPException(status_code=404, detail="鏂囦欢涓嶅瓨鍦�")
except Exception as e:
- raise HTTPException(status_code=500, detail="鏈嶅姟鍣ㄩ敊璇�")
-
-
-@router.websocket("/ws/{agent_id}/{chat_id}")
-async def excel_chat(websocket: WebSocket,
- agent_id: str,
- chat_id: str,
- db: Session = Depends(get_db)):
- agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
- if not agent:
- ret = {"message": "Agent not found", "type": "close"}
- return websocket.send_json(ret)
- agent_type = agent.agent_type
- if chat_id == "" or chat_id == "0":
- ret = {"message": "Chat ID not found", "type": "close"}
- return websocket.send_json(ret)
-
- if agent_type != AgentType.BASIC:
- ret = {"message": "agent type error", "type": "close"}
- return websocket.send_json(ret)
-
- await websocket.accept()
- try:
- while True:
- message = await websocket.receive_json()
- print(message) # 鎵撳嵃鎺ユ敹鍒扮殑娑堟伅
- result = {"message": "宸茬敓鎴愭枃浠�", "type": "file", "url": "ip/download?id=xxxx"}
- # 鍙戦�佸搷搴�
- await websocket.send_json(result)
- except WebSocketDisconnect as e:
-
- print(f"Client {chat_id} disconnected")
+ raise HTTPException(status_code=500, detail="鏈嶅姟鍣ㄩ敊璇�")
\ No newline at end of file
--
Gitblit v1.8.0