api.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. from natsort.natsort import order_by_index
  2. from sqlalchemy import func
  3. from models import *
  4. import requests
  5. import json
  6. from logger import logger
  7. from serial.tools import list_ports
  8. from model import PhotoRecord
  9. import settings
  10. import pandas as pd
  11. from utils.hlm_http_request import forward_request
  12. from utils.utils_func import check_path
  13. from sockets.socket_client import socket_manager
  14. from mcu.DeviceControl import DeviceControl
  15. import time, shutil
  16. from sqlalchemy import and_, asc, desc
  17. from functools import partial
  18. from service.deal_image import DealImage
  19. from databases import DeviceConfig, SqlQuery, CRUD, select
  20. from service.run_main import RunMain
  21. import importlib
  22. from service.auto_deal_pics.upload_pic import UploadPic
  23. from service.OnePicTest import OnePicTest
  24. # from service.AutoDealPics import AutoDealPics
  25. # for plugin in settings.plugins:
  26. # module_path, class_name = plugin.rsplit(".", 1)
  27. # print("module_path", module_path, class_name)
  28. # module = importlib.import_module(module_path)
  29. # getattr(module, class_name)
  30. @app.get("/")
  31. async def index():
  32. # await socket_manager.send_message(msg="测试")
  33. return {"message": "Hello World"}
  34. @app.get("/send_test")
  35. async def index():
  36. data = {"data1": 1, "data2": 2, "data3": 3, "data4": 4}
  37. await socket_manager.send_message(msg="测试", data=data)
  38. return {"message": "Hello World"}
  39. @app.get("/scan_serials", description="扫描可用的设备端口")
  40. async def scanSerials():
  41. """扫描串口"""
  42. ports = list_ports.comports()
  43. print("Scanning", ports)
  44. return {"message": "Hello World"}
  45. @app.get("/test_conndevice")
  46. def test_conndevice():
  47. device_control = DeviceControl()
  48. p_list = []
  49. temp_ports_dict = {}
  50. # while 1:
  51. time.sleep(1)
  52. ports_dict = device_control.scan_serial_port()
  53. temp_ports_dict = ports_dict
  54. if not ports_dict:
  55. # 全部清空 移除所有串口
  56. if p_list:
  57. _p = p_list.pop()
  58. device_control.remove_port(_p)
  59. # continue
  60. if ports_dict:
  61. # print(plist)
  62. for index, _i in enumerate(p_list):
  63. if _i not in ports_dict:
  64. _p = p_list.pop(index)
  65. device_control.remove_port(_p)
  66. for _port_name, _port_value in ports_dict.items():
  67. if _port_name not in p_list:
  68. try:
  69. p_list.append(_port_name)
  70. device_control.add_port_by_linkage(_port_name)
  71. except BaseException as e:
  72. print(
  73. e.__traceback__.tb_frame.f_globals["__file__"]
  74. ) # 发生异常所在的文件
  75. print(e.__traceback__.tb_lineno) # 发生异常所在的行数
  76. print("串口不存在{} {}".format(_port_name, e))
  77. # threading.Thread(target=self.add_port, args=(_port_name, _port_value)).start()
  78. # self.add_port(_p)
  79. @app.api_route(
  80. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  81. )
  82. async def forwardRequest(request: HlmForwardRequest):
  83. """
  84. 转发HTTP请求到目标URL
  85. :param request: FastAPI Request对象
  86. :return: 目标接口的响应
  87. """
  88. try:
  89. if request.method == "GET":
  90. params = request.query_params
  91. elif request.method == "POST":
  92. params = json.dump(request.query_params)
  93. else:
  94. raise UnicornException("仅支持GET和POST方法")
  95. target_url = request.target_url
  96. method = request.method.upper()
  97. headers = request.headers
  98. if not target_url:
  99. raise UnicornException("目标url地址不能为空")
  100. # 调用 hlm_http_request 中的 forward_request 函数
  101. response = forward_request(
  102. target_url, params=params, method=method, headers=headers
  103. )
  104. return response
  105. except requests.RequestException as e:
  106. raise UnicornException(e)
  107. except Exception as e:
  108. raise UnicornException(e)
  109. def fromExcelHandler(params: HandlerDetail):
  110. excel_path = params.excel_path
  111. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  112. handler_result = []
  113. handler_result_folder = ""
  114. if "文件夹名称" not in excel_df.columns:
  115. raise UnicornException("缺失 [文件夹名称] 列")
  116. if "商品货号" not in excel_df.columns:
  117. raise UnicornException("缺失 [商品货号] 列")
  118. for index, row in excel_df.iterrows():
  119. goods_art_no_image_dir = str(row["文件夹名称"])
  120. goods_art_no = str(row["商品货号"])
  121. try:
  122. if not goods_art_no:
  123. raise UnicornException("货号不能为空")
  124. token = "Bearer " + params.token
  125. session = SqlQuery()
  126. pr = CRUD(PhotoRecord)
  127. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  128. if not images:
  129. raise UnicornException("没有可用货号数据")
  130. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  131. check_path(image_dir)
  132. for itemImg in images:
  133. if not os.path.exists(
  134. image_dir + "/" + os.path.basename(itemImg.image_path)
  135. ):
  136. shutil.copy(itemImg.image_path, image_dir)
  137. dealImage = DealImage(image_dir)
  138. resFlag, path = dealImage.dealMoveImage(
  139. image_dir=image_dir,
  140. callback_func=None,
  141. goods_art_no=goods_art_no_image_dir,
  142. )
  143. if not resFlag:
  144. raise UnicornException(path)
  145. temp_class = {}
  146. temp_name_list = []
  147. for tempItem in params.temp_list:
  148. temp_class[tempItem.template_id] = tempItem.template_local_classes
  149. temp_name_list.append(tempItem.template_id)
  150. # if goods_art_no_image_dir not in path:
  151. # path = path + "/" + goods_art_no_image_dir
  152. config_data = {
  153. "image_dir": path,
  154. "image_order": params.template_image_order,
  155. "goods_art_no": goods_art_no,
  156. "is_check_number": False,
  157. "resize_image_view": "后跟",
  158. "cutout_mode": settings.CUTOUT_MODE,
  159. "logo_path": params.logo_path,
  160. "special_goods_art_no_folder_line": "",
  161. "is_use_excel": (
  162. False if params.excel_path == "" else True
  163. ), # 是否使用excel
  164. "excel_path": params.excel_path, # excel路径
  165. "is_check_color_is_all": False,
  166. "cutout_is_pass": True,
  167. "assigned_page_dict": {},
  168. "detail_is_pass": True,
  169. "upload_is_pass": False,
  170. "upload_is_enable": False,
  171. "is_filter": False,
  172. "temp_class": temp_class,
  173. "temp_name": params.temp_name,
  174. "temp_name_list": temp_name_list,
  175. "target_error_folder": f"{path}/软件-生成详情错误",
  176. }
  177. # 动态导入类
  178. temp_class_dict = {}
  179. for key, class_path in config_data["temp_class"].items():
  180. module_path, class_name = class_path.rsplit(".", 1)
  181. module = importlib.import_module(module_path)
  182. cls = getattr(module, class_name)
  183. temp_class_dict[key] = cls
  184. config_data["temp_class"] = temp_class_dict
  185. obj = None
  186. run_main = RunMain(obj, token)
  187. return_data = run_main.check_before_cutout(config_data)
  188. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  189. check_for_detail_first_res = None
  190. if cutout_res == True:
  191. return_data_check_before_detail = run_main.check_before_detail(
  192. config_data
  193. )
  194. print(
  195. "return_data_check_before_detail======> 测试 ==>",
  196. return_data_check_before_detail,
  197. )
  198. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  199. return_data_check_before_detail
  200. )
  201. if isinstance(check_for_detail_first_res, partial):
  202. result = check_for_detail_first_res()
  203. try:
  204. config_data = result["config_data"]
  205. except:
  206. config_data = result
  207. if config_data["sign_text"] == "已结束详情处理":
  208. # at_pic = AutoDealPics()
  209. print("config_data", config_data)
  210. if config_data["upload_is_enable"]:
  211. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  212. check_path(to_deal_dir)
  213. print("to_deal_dir", to_deal_dir)
  214. if os.path.exists(to_deal_dir):
  215. upload_pic = UploadPic(
  216. windows=None,
  217. to_deal_dir=to_deal_dir,
  218. config_data=config_data,
  219. token=token,
  220. )
  221. upload_pic.run()
  222. out_put_dir = config_data["out_put_dir"]
  223. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  224. "\\", "/"
  225. )
  226. handler_result_folder = os.path.dirname(out_put_dir_path)
  227. handler_result.append(
  228. {"goods_art_no": goods_art_no, "success": True, "info": "处理成功"}
  229. )
  230. else:
  231. handler_result.append(
  232. {"goods_art_no": goods_art_no, "success": False, "info": "处理失败"}
  233. )
  234. except Exception as e:
  235. handler_result.append(
  236. {"goods_art_no": goods_art_no, "success": False, "info": str(e)}
  237. )
  238. handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  239. return {
  240. "code": 0,
  241. "msg": "",
  242. "data": {"output_folder": handler_result_folder, "list": handler_result},
  243. }
  244. @app.post("/handle_detail")
  245. async def handle_detail(request: Request, params: HandlerDetail):
  246. goods_art_no_array = params.goods_art_no
  247. handler_result = []
  248. handler_result_folder = ""
  249. if params.excel_path != "" or params.excel_path != None:
  250. return fromExcelHandler(params)
  251. for goods_art_no in goods_art_no_array:
  252. try:
  253. if not goods_art_no:
  254. raise UnicornException("货号不能为空")
  255. token = "Bearer " + params.token
  256. session = SqlQuery()
  257. pr = CRUD(PhotoRecord)
  258. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  259. if not images:
  260. raise UnicornException("没有可用货号数据")
  261. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  262. check_path(image_dir)
  263. for itemImg in images:
  264. if not os.path.exists(
  265. image_dir + "/" + os.path.basename(itemImg.image_path)
  266. ):
  267. shutil.copy(itemImg.image_path, image_dir)
  268. dealImage = DealImage(image_dir)
  269. resFlag, path = dealImage.dealMoveImage(
  270. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  271. )
  272. if not resFlag:
  273. raise UnicornException(path)
  274. temp_class = {}
  275. temp_name_list = []
  276. for tempItem in params.temp_list:
  277. temp_class[tempItem.template_id] = tempItem.template_local_classes
  278. temp_name_list.append(tempItem.template_id)
  279. config_data = {
  280. "image_dir": path,
  281. "image_order": params.template_image_order,
  282. "goods_art_no": goods_art_no,
  283. "is_check_number": False,
  284. "resize_image_view": "后跟",
  285. "cutout_mode": settings.CUTOUT_MODE,
  286. "logo_path": params.logo_path,
  287. "special_goods_art_no_folder_line": "",
  288. "is_use_excel": False if params.excel_path == "" else True, # 是否使用excel
  289. "excel_path": params.excel_path, # excel路径
  290. "is_check_color_is_all": False,
  291. "cutout_is_pass": True,
  292. "assigned_page_dict": {},
  293. "detail_is_pass": True,
  294. "upload_is_pass": False,
  295. "upload_is_enable": False,
  296. "is_filter": False,
  297. "temp_class": temp_class,
  298. "temp_name": params.temp_name,
  299. "temp_name_list": temp_name_list,
  300. "target_error_folder": f"{path}/软件-生成详情错误",
  301. }
  302. # 动态导入类
  303. temp_class_dict = {}
  304. for key, class_path in config_data["temp_class"].items():
  305. module_path, class_name = class_path.rsplit(".", 1)
  306. module = importlib.import_module(module_path)
  307. cls = getattr(module, class_name)
  308. temp_class_dict[key] = cls
  309. config_data["temp_class"] = temp_class_dict
  310. obj = None
  311. run_main = RunMain(obj,token)
  312. return_data = run_main.check_before_cutout(config_data)
  313. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  314. check_for_detail_first_res = None
  315. if cutout_res == True:
  316. return_data_check_before_detail = run_main.check_before_detail(config_data)
  317. print(
  318. "return_data_check_before_detail======> 测试 ==>", return_data_check_before_detail
  319. )
  320. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  321. return_data_check_before_detail
  322. )
  323. if isinstance(check_for_detail_first_res, partial):
  324. result = check_for_detail_first_res()
  325. try:
  326. config_data = result["config_data"]
  327. except:
  328. config_data = result
  329. if config_data["sign_text"] == "已结束详情处理":
  330. # at_pic = AutoDealPics()
  331. print("config_data", config_data)
  332. if config_data["upload_is_enable"]:
  333. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  334. check_path(to_deal_dir)
  335. print("to_deal_dir", to_deal_dir)
  336. if os.path.exists(to_deal_dir):
  337. upload_pic = UploadPic(
  338. windows=None,
  339. to_deal_dir=to_deal_dir,
  340. config_data=config_data,
  341. token=token,
  342. )
  343. upload_pic.run()
  344. out_put_dir = config_data["out_put_dir"]
  345. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace("\\", "/")
  346. handler_result_folder = os.path.dirname(out_put_dir_path)
  347. handler_result.append(
  348. {"goods_art_no": goods_art_no, "success": True, "info": "处理成功"}
  349. )
  350. else:
  351. handler_result.append(
  352. {"goods_art_no": goods_art_no, "success": False, "info": "处理失败"}
  353. )
  354. except Exception as e:
  355. handler_result.append(
  356. {"goods_art_no": goods_art_no, "success": False, "info": str(e)}
  357. )
  358. return {
  359. "code": 0,
  360. "msg": "",
  361. "data": {"output_folder": handler_result_folder, "list": handler_result},
  362. }
  363. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  364. def get_device_configs(params: ModelGetDeviceConfig):
  365. mode_type = params.mode_type
  366. session = SqlQuery()
  367. configModel = CRUD(DeviceConfig)
  368. configList = configModel.read_all(
  369. session,
  370. conditions={"mode_type": mode_type},
  371. order_by="action_index",
  372. ascending=True,
  373. )
  374. return {
  375. "code": 0,
  376. "msg": "",
  377. "data": {"list": configList},
  378. }
  379. @app.post("/device_config_detail", description="获取可执行程序详情")
  380. def get_device_configs(params: ModelGetDeviceConfigDetail):
  381. action_id = params.id
  382. session = SqlQuery()
  383. configModel = CRUD(DeviceConfig)
  384. model = configModel.read(session, conditions={"id": action_id})
  385. if model == None:
  386. return {"code": 1, "msg": "数据不存在", "data": None}
  387. return {"code": 0, "msg": "", "data": model}
  388. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  389. def get_device_configs(params: ModelGetDeviceConfigDetailQuery):
  390. mode_type = params.mode_type
  391. action_name = params.action_name
  392. session = SqlQuery()
  393. configModel = CRUD(DeviceConfig)
  394. model = configModel.read(
  395. session, conditions={"mode_type": mode_type, "action_name": action_name}
  396. )
  397. if model == None:
  398. return {"code": 1, "msg": "数据不存在", "data": None}
  399. return {"code": 0, "msg": "", "data": model}
  400. @app.post("/remove_config", description="删除一条可执行命令")
  401. def get_device_configs(params: ModelGetDeviceConfigDetail):
  402. action_id = params.id
  403. session = SqlQuery()
  404. configModel = CRUD(DeviceConfig)
  405. model = configModel.read(session, conditions={"id": action_id})
  406. if model == None:
  407. return {"code": 1, "msg": "数据不存在", "data": None}
  408. configModel.delete(session, obj_id=action_id)
  409. return {"code": 0, "msg": "删除成功", "data": None}
  410. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  411. def save_device_config(params: SaveDeviceConfig):
  412. action_id = params.id
  413. session = SqlQuery()
  414. deviceConfig = CRUD(DeviceConfig)
  415. if action_id == None or action_id == 0:
  416. # 走新增逻辑
  417. params.id = None
  418. save_device_config = deviceConfig.create(session, obj_in=params)
  419. else:
  420. model = deviceConfig.read(session, conditions={"id": action_id})
  421. if model == None:
  422. return {"code": 1, "msg": "数据不存在", "data": None}
  423. # 走编辑逻辑
  424. kwargs = params.__dict__
  425. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  426. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  427. @app.post("/reset_config", description="创建或修改一条可执行命令")
  428. def reset_config(params: ModelGetDeviceConfig):
  429. mode_type = params.mode_type
  430. if mode_type == None or mode_type == "":
  431. return {"code": 1, "msg": "参数错误", "data": None}
  432. session = SqlQuery()
  433. deviceConfig = CRUD(DeviceConfig)
  434. res = deviceConfig.deleteConditions(session, conditions={"mode_type": mode_type})
  435. if res is False:
  436. return {"code": 1, "msg": "操作失败", "data": None}
  437. actions = json.load(open("action.json", encoding="utf-8"))
  438. act = []
  439. for item in actions:
  440. if item.get("mode_type") == mode_type:
  441. act.append(item)
  442. batch_insert_device_configs(session, act)
  443. return {"code": 0, "msg": "操作成功", "data": None}
  444. @app.get("/get_photo_records", description="获取拍照记录")
  445. def get_photo_records(page: int = 1, size: int = 5):
  446. session = SqlQuery()
  447. photos = CRUD(PhotoRecord)
  448. statement = (
  449. select(PhotoRecord)
  450. .offset((page - 1) * size)
  451. .limit(size)
  452. .order_by(desc("id"))
  453. .group_by("goods_art_no")
  454. )
  455. list = []
  456. result = session.exec(statement).all()
  457. for item in result:
  458. list_item = photos.read_all(
  459. session, conditions={"goods_art_no": item.goods_art_no}
  460. )
  461. list.append(
  462. {
  463. "goods_art_no": item.goods_art_no,
  464. "action_time": item.create_time,
  465. "items": list_item,
  466. }
  467. )
  468. session.close()
  469. return {
  470. "code": 0,
  471. "msg": "",
  472. "data": {"list": list, "page": page, "size": size},
  473. }
  474. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  475. def get_photo_records(goods_art_no: str = None):
  476. if goods_art_no == None:
  477. return {"code": 1, "msg": "参数错误", "data": None}
  478. session = SqlQuery()
  479. photos = CRUD(PhotoRecord)
  480. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  481. session.close()
  482. return {
  483. "code": 0,
  484. "msg": "",
  485. "data": {"list": items},
  486. }
  487. @app.post("/delect_goods_arts", description="通过货号删除记录")
  488. def delect_goods_arts(params: PhotoRecordDelete):
  489. session = SqlQuery()
  490. photos = CRUD(PhotoRecord)
  491. for item in params.goods_art_nos:
  492. photos.deleteConditions(session, conditions={"goods_art_no": item})
  493. session.close()
  494. return {
  495. "code": 0,
  496. "msg": "操作成功",
  497. "data": None,
  498. }
  499. @app.get("/get_sys_config", description="查询系统配置")
  500. def get_sys_config(key: str = None):
  501. if key == None:
  502. return {"code": 1, "msg": "参数错误", "data": None}
  503. session = SqlQuery()
  504. photos = CRUD(SysConfigs)
  505. item = photos.read(session, conditions={"key": key})
  506. session.close()
  507. return {
  508. "code": 0,
  509. "msg": "",
  510. "data": json.loads(item.value),
  511. }
  512. @app.post("/update_sys_configs", description="创建或修改系统配置")
  513. def save_sys_configs(params: SysConfigParams):
  514. session = SqlQuery()
  515. sysConfig = CRUD(SysConfigs)
  516. model = sysConfig.read(session, conditions={"key": params.key})
  517. if model == None:
  518. return {"code": 1, "msg": "配置不存在", "data": None}
  519. # 走编辑逻辑
  520. kwargs = params.__dict__
  521. save_device_config = sysConfig.updateConditions(
  522. session, conditions={"key": params.key}, **kwargs
  523. )
  524. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  525. @app.post("/create_main_image", description="创建主图测试")
  526. def create_main_image(params: MaineImageTest):
  527. file_path = params.file_path
  528. onePic = OnePicTest(pic_path=file_path)
  529. # session = SqlQuery()
  530. # sysConfig = CRUD(SysConfigs)
  531. # model = sysConfig.read(session, conditions={"key": params.key})
  532. # if model == None:
  533. # return {"code": 1, "msg": "配置不存在", "data": None}
  534. # # 走编辑逻辑
  535. # kwargs = params.__dict__
  536. # save_device_config = sysConfig.updateConditions(
  537. # session, conditions={"key": params.key}, **kwargs
  538. # )
  539. main_out_path = onePic.HandlerMainImage()
  540. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}