api.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. from re import search
  2. from natsort.natsort import order_by_index
  3. from sqlalchemy import func
  4. from models import *
  5. import requests
  6. import json
  7. from logger import logger
  8. from serial.tools import list_ports
  9. from model import PhotoRecord
  10. import settings, datetime
  11. import pandas as pd
  12. from utils.hlm_http_request import forward_request
  13. from utils.utils_func import check_path
  14. from sockets.socket_client import socket_manager
  15. from mcu.DeviceControl import DeviceControl
  16. import time, shutil, os
  17. from sqlalchemy import and_, asc, desc
  18. from functools import partial
  19. from service.deal_image import DealImage
  20. from databases import DeviceConfig, SysConfigs, SqlQuery, CRUD, select, DeviceConfigTabs
  21. from service.run_main import RunMain
  22. import importlib
  23. from service.auto_deal_pics.upload_pic import UploadPic
  24. from service.OnePicTest import OnePicTest
  25. from service.base import check_move_goods_art_no_folder
  26. import hashlib
  27. import win32api, win32gui, win32con
  28. from win32gui import EnumWindows, GetWindowText
  29. from mcu.capture.smart_shooter_class import SmartShooter
  30. def calculate_md5(filepath):
  31. # 打开文件,以二进制只读模式打开
  32. with open(filepath, "rb") as f:
  33. # 创建MD5哈希对象
  34. md5hash = hashlib.md5()
  35. # 循环读取文件的内容并更新哈希对象
  36. for chunk in iter(lambda: f.read(4096), b""):
  37. md5hash.update(chunk)
  38. # 返回MD5哈希的十六进制表示
  39. return md5hash.hexdigest()
  40. @app.get("/")
  41. async def index():
  42. # await socket_manager.send_message(msg="测试")
  43. return {"message": "Hello World"}
  44. @app.get("/scan_serials", description="扫描可用的设备端口")
  45. async def scanSerials():
  46. """扫描串口"""
  47. ports = list_ports.comports()
  48. print("Scanning", ports)
  49. return {"message": "Hello World"}
  50. @app.api_route(
  51. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  52. )
  53. async def forwardRequest(request: HlmForwardRequest):
  54. """
  55. 转发HTTP请求到目标URL
  56. :param request: FastAPI Request对象
  57. :return: 目标接口的响应
  58. """
  59. try:
  60. if request.method == "GET":
  61. params = request.query_params
  62. elif request.method == "POST":
  63. params = json.dump(request.query_params)
  64. else:
  65. raise UnicornException("仅支持GET和POST方法")
  66. target_url = request.target_url
  67. method = request.method.upper()
  68. headers = request.headers
  69. if not target_url:
  70. raise UnicornException("目标url地址不能为空")
  71. # 调用 hlm_http_request 中的 forward_request 函数
  72. response = forward_request(
  73. target_url, params=params, method=method, headers=headers
  74. )
  75. return response
  76. except requests.RequestException as e:
  77. raise UnicornException(e)
  78. except Exception as e:
  79. raise UnicornException(e)
  80. async def fromExcelHandler(params: HandlerDetail):
  81. excel_path = params.excel_path
  82. token = "Bearer " + params.token
  83. uuid = params.uuid
  84. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  85. handler_result = []
  86. handler_result_folder = ""
  87. if "文件夹名称" not in excel_df.columns:
  88. raise UnicornException("缺失 [文件夹名称] 列")
  89. if "商品货号" not in excel_df.columns:
  90. raise UnicornException("缺失 [商品货号] 列")
  91. if "款号" not in excel_df.columns:
  92. raise UnicornException("缺失 [款号] 列")
  93. goods_art_dirs = excel_df.groupby(excel_df["款号"])
  94. obj = None
  95. run_main = RunMain(obj, token, uuid)
  96. temp_class = {}
  97. # 可用模板列表-需要导包
  98. temp_name_list = []
  99. for tempItem in params.temp_list:
  100. temp_class[tempItem.template_id] = tempItem.template_local_classes
  101. temp_name_list.append(tempItem.template_id)
  102. # 抠图时用到的货号列表,与生成详情图有所区别
  103. goods_art_no_arrays = []
  104. # # 详情图生成需要对同款商品进行分组,保证详情图可以生成多个色
  105. goods_art_no_group_arrays = []
  106. for _, goods_row in excel_df.iterrows():
  107. goods_art_no = str(goods_row["商品货号"])
  108. goods_art_no_arrays.append(goods_art_no)
  109. goods_no = str(goods_row["款号"])
  110. a001_df = goods_art_dirs.get_group(goods_no)
  111. goods_art_groups = a001_df["商品货号"].tolist()
  112. if goods_art_groups in goods_art_no_group_arrays:
  113. continue
  114. goods_art_no_group_arrays.append(goods_art_groups)
  115. limit_path = "output/{}".format(
  116. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  117. )
  118. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  119. move_folder_array = check_move_goods_art_no_folder(
  120. "output", goods_art_no_arrays, limit_path
  121. )
  122. for index, row in excel_df.iterrows():
  123. goods_art_no_image_dir = str(row["文件夹名称"])
  124. goods_art_no = str(row["商品货号"])
  125. print("货号数据", goods_art_no)
  126. if not goods_art_no:
  127. raise UnicornException("货号不能为空")
  128. session = SqlQuery()
  129. pr = CRUD(PhotoRecord)
  130. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  131. if not images:
  132. raise UnicornException("没有可用货号数据")
  133. # 货号目录不存在再去进行移动和创建操作
  134. if move_folder_array.get(goods_art_no) == None:
  135. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  136. check_path(image_dir)
  137. for idx, itemImg in enumerate(images):
  138. if itemImg.image_path == "" or itemImg.image_path == None:
  139. raise UnicornException(
  140. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  141. )
  142. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  143. if not os.path.exists(
  144. image_dir + "/" + os.path.basename(new_file_name)
  145. ):
  146. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  147. dealImage = DealImage(image_dir)
  148. resFlag, path = dealImage.dealMoveImage(
  149. image_dir=image_dir,
  150. callback_func=None,
  151. goods_art_no=goods_art_no_image_dir,
  152. )
  153. if not resFlag:
  154. raise UnicornException(path)
  155. shutil.rmtree(image_dir)
  156. # path = os.path.dirname(path)
  157. cutOutMode = (
  158. '0'
  159. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图") == "普通抠图"
  160. else '1'
  161. )
  162. config_data = {
  163. "image_dir": limit_path, # 这个目录作为本次生成的图片目录非常重要 例:./output/当前日期
  164. "image_order": params.template_image_order,
  165. "goods_art_no": goods_art_no,
  166. "goods_art_nos": goods_art_no_arrays,
  167. "is_check_number": False,
  168. "resize_image_view": "后跟",
  169. "cutout_mode": cutOutMode,
  170. "logo_path": params.logo_path,
  171. "special_goods_art_no_folder_line": "",
  172. "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  173. "excel_path": params.excel_path, # excel路径
  174. "is_check_color_is_all": False,
  175. "cutout_is_pass": True,
  176. "assigned_page_dict": {},
  177. "detail_is_pass": True,
  178. "upload_is_pass": False,
  179. "upload_is_enable": False,
  180. "is_filter": False,
  181. "temp_class": temp_class,
  182. "temp_name": params.temp_name,
  183. "temp_name_list": temp_name_list,
  184. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  185. "success_handler": [],
  186. }
  187. # 动态导入类
  188. temp_class_dict = {}
  189. for key, class_path in config_data["temp_class"].items():
  190. module_path, class_name = class_path.rsplit(".", 1)
  191. module = importlib.import_module(module_path)
  192. cls = getattr(module, class_name)
  193. temp_class_dict[key] = cls
  194. config_data["temp_class"] = temp_class_dict
  195. # 此处对抠图进行批量处理,保证所有的图片在生成详情图之前已经完成抠图,以保证详情图生成的效率
  196. return_data = run_main.check_before_cutout(config_data)
  197. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  198. check_for_detail_first_res = None
  199. try:
  200. if cutout_res:
  201. return_data_check_before_detail = run_main.check_before_detail(config_data)
  202. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  203. return_data_check_before_detail
  204. )
  205. if isinstance(check_for_detail_first_res, partial):
  206. result = check_for_detail_first_res()
  207. try:
  208. config_data = result["config_data"]
  209. except:
  210. config_data = result
  211. if config_data["sign_text"] == "已结束详情处理":
  212. print("config_data", config_data)
  213. if config_data["upload_is_enable"]:
  214. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  215. check_path(to_deal_dir)
  216. print("to_deal_dir", to_deal_dir)
  217. if os.path.exists(to_deal_dir):
  218. upload_pic = UploadPic(
  219. windows=None,
  220. to_deal_dir=to_deal_dir,
  221. config_data=config_data,
  222. token=token,
  223. )
  224. upload_pic.run()
  225. out_put_dir = config_data.get("out_put_dir")
  226. if out_put_dir == None:
  227. handler_result_folder = ""
  228. if len(config_data["success_handler"]) > 0:
  229. for good_art in config_data["success_handler"]:
  230. handler_result.append(good_art)
  231. else:
  232. for good_art in goods_art_no_arrays:
  233. handler_result.append(
  234. {
  235. "goods_art_no": good_art,
  236. "success": False,
  237. "info": "处理失败",
  238. }
  239. )
  240. else:
  241. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  242. "\\", "/"
  243. )
  244. handler_result_folder = os.path.dirname(out_put_dir_path)
  245. if len(config_data["success_handler"]) == 0:
  246. for good_art in goods_art_no_arrays:
  247. handler_result.append(
  248. {
  249. "goods_art_no": good_art,
  250. "success": False,
  251. "info": "处理失败",
  252. }
  253. )
  254. else:
  255. handler_result = config_data["success_handler"]
  256. else:
  257. for good_art in goods_art_no_arrays:
  258. handler_result.append(
  259. {"goods_art_no": good_art, "success": False, "info": "处理失败"}
  260. )
  261. except Exception as e:
  262. for good_art in goods_art_no_arrays:
  263. handler_result.append(
  264. {"goods_art_no": good_art, "success": False, "info": str(e)}
  265. )
  266. handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  267. return {
  268. "code": 0,
  269. "msg": "",
  270. "data": {"output_folder": handler_result_folder, "list": handler_result},
  271. }
  272. def group_by_style_number(data):
  273. result = {}
  274. for goods_id, info in data.items():
  275. style_number = info["款号"]
  276. if style_number not in result:
  277. result[style_number] = []
  278. result[style_number].append(goods_id)
  279. return result
  280. @app.post("/handle_detail")
  281. async def handle_detail(request: Request, params: HandlerDetail):
  282. obj = None
  283. token = "Bearer " + params.token
  284. uuid = params.uuid
  285. run_main = RunMain(obj, token, uuid)
  286. goods_art_no_arrays = params.goods_art_no
  287. is_only_cutout = params.is_only_cutout
  288. handler_result = []
  289. handler_result_folder = ""
  290. if is_only_cutout == 1:
  291. # 如果是仅抠图模式,避免进入到excel模式
  292. params.excel_path = ""
  293. if params.excel_path != "" and params.excel_path != None:
  294. return await fromExcelHandler(params)
  295. # goods_art_list = run_main.data_mode_generate_detail.get_goods_art_no_info(
  296. # goods_art_list=goods_art_no_arrays
  297. # )
  298. # goods_art_nos = []
  299. # goods_art_list_dict = group_by_style_number(goods_art_list)
  300. path = ""
  301. limit_path = "output/{}".format(
  302. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  303. )
  304. check_path(limit_path)
  305. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  306. move_folder_array = check_move_goods_art_no_folder(
  307. "output", goods_art_no_arrays, limit_path
  308. )
  309. for goods_art_no in goods_art_no_arrays:
  310. if not goods_art_no:
  311. raise UnicornException("货号不能为空")
  312. session = SqlQuery()
  313. pr = CRUD(PhotoRecord)
  314. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  315. if not images:
  316. raise UnicornException("没有可用货号数据")
  317. if is_only_cutout != 1:
  318. detail_counts = len(params.template_image_order.split(","))
  319. image_counts = len(images)
  320. if image_counts < detail_counts:
  321. raise UnicornException(
  322. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  323. )
  324. if move_folder_array.get(goods_art_no) == None:
  325. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  326. check_path(image_dir)
  327. for idx, itemImg in enumerate(images):
  328. if itemImg.image_path == "" or itemImg.image_path == None:
  329. raise UnicornException(
  330. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  331. )
  332. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  333. if not os.path.exists(
  334. image_dir + "/" + os.path.basename(new_file_name)
  335. ):
  336. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  337. dealImage = DealImage(image_dir)
  338. resFlag, path = dealImage.dealMoveImage(
  339. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  340. )
  341. if not resFlag:
  342. raise UnicornException(path)
  343. # try:
  344. temp_class = {}
  345. temp_name_list = []
  346. for tempItem in params.temp_list:
  347. temp_class[tempItem.template_id] = tempItem.template_local_classes
  348. temp_name_list.append(tempItem.template_id)
  349. cutOutMode = (
  350. '1'
  351. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  352. == "普通抠图"
  353. else '2'
  354. )
  355. config_data = {
  356. "image_dir": limit_path,
  357. "image_order": (
  358. "俯视,侧视,后跟,鞋底,内里"
  359. if params.template_image_order == None or params.template_image_order == ""
  360. else params.template_image_order
  361. ),
  362. "goods_art_no": "",
  363. "goods_art_nos": goods_art_no_arrays,
  364. "is_check_number": False,
  365. "resize_image_view": "后跟",
  366. "cutout_mode": cutOutMode,
  367. "logo_path": params.logo_path,
  368. "special_goods_art_no_folder_line": "",
  369. "is_use_excel": False, # 是否使用excel
  370. "excel_path": "", # excel路径
  371. "is_check_color_is_all": False,
  372. "cutout_is_pass": True,
  373. "assigned_page_dict": {},
  374. "detail_is_pass": True,
  375. "upload_is_pass": False,
  376. "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  377. "is_filter": False,
  378. "temp_class": temp_class,
  379. "temp_name": params.temp_name,
  380. "temp_name_list": temp_name_list,
  381. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  382. "success_handler": [],
  383. }
  384. print("image_dir=====>>>>>", config_data["image_dir"])
  385. # 动态导入类
  386. temp_class_dict = {}
  387. for key, class_path in config_data["temp_class"].items():
  388. module_path, class_name = class_path.rsplit(".", 1)
  389. module = importlib.import_module(module_path)
  390. cls = getattr(module, class_name)
  391. temp_class_dict[key] = cls
  392. config_data["temp_class"] = temp_class_dict
  393. return_data = run_main.check_before_cutout(config_data)
  394. cutout_res = await run_main.check_for_cutout_image_first_call_back(return_data)
  395. check_for_detail_first_res = None
  396. if cutout_res == True:
  397. sys_path = format(os.getcwd()).replace("\\", "/")
  398. handler_result_folder = f"{sys_path}/{limit_path}"
  399. for goods_art_item in goods_art_no_arrays:
  400. handler_result.append(
  401. {
  402. "goods_art_no": goods_art_item,
  403. "success": True,
  404. "info": "处理成功",
  405. }
  406. )
  407. if is_only_cutout == 1:
  408. return {
  409. "code": 0,
  410. "msg": "",
  411. "data": {"output_folder": handler_result_folder, "list": handler_result},
  412. }
  413. handler_result = []
  414. try:
  415. return_data_check_before_detail = run_main.check_before_detail(config_data)
  416. check_for_detail_first_res = await run_main.check_for_detail_first_call_back(
  417. return_data_check_before_detail
  418. )
  419. if isinstance(check_for_detail_first_res, partial):
  420. result = check_for_detail_first_res()
  421. try:
  422. config_data = result["config_data"]
  423. except:
  424. config_data = result
  425. if config_data["sign_text"] == "已结束详情处理":
  426. # at_pic = AutoDealPics()
  427. print("config_data", config_data)
  428. # if config_data["upload_is_enable"]:
  429. # to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  430. # check_path(to_deal_dir)
  431. # print("to_deal_dir", to_deal_dir)
  432. # if os.path.exists(to_deal_dir):
  433. # upload_pic = UploadPic(
  434. # windows=None,
  435. # to_deal_dir=to_deal_dir,
  436. # config_data=config_data,
  437. # token=token,
  438. # )
  439. # upload_pic.run()
  440. out_put_dir = config_data.get("out_put_dir")
  441. if out_put_dir == None:
  442. handler_result_folder = ""
  443. if len(config_data["success_handler"]) > 0:
  444. for good_art in config_data["success_handler"]:
  445. handler_result.append(good_art)
  446. else:
  447. for good_art in goods_art_no_arrays:
  448. handler_result.append(
  449. {
  450. "goods_art_no": good_art,
  451. "success": False,
  452. "info": "处理失败",
  453. }
  454. )
  455. else:
  456. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  457. "\\", "/"
  458. )
  459. handler_result_folder = os.path.dirname(out_put_dir_path)
  460. if len(config_data["success_handler"]) == 0:
  461. for good_art in goods_art_no_arrays:
  462. handler_result.append(
  463. {
  464. "goods_art_no": good_art,
  465. "success": False,
  466. "info": "处理失败",
  467. }
  468. )
  469. else:
  470. handler_result = config_data["success_handler"]
  471. else:
  472. handler_result.append(
  473. {"goods_art_no": "", "success": False, "info": "处理失败"}
  474. )
  475. except UnicornException as e:
  476. handler_result_folder = ""
  477. handler_result = e.msg
  478. except Exception as e:
  479. handler_result_folder = ""
  480. handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  481. return {
  482. "code": 0,
  483. "msg": "",
  484. "data": {"output_folder": handler_result_folder, "list": handler_result},
  485. }
  486. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  487. def get_device_tabs(type: int):
  488. session = SqlQuery()
  489. statement = (
  490. select(DeviceConfigTabs)
  491. .where(DeviceConfigTabs.mode_type == type)
  492. .order_by(asc("id"))
  493. )
  494. result = session.exec(statement).all()
  495. session.close()
  496. sys = CRUD(SysConfigs)
  497. action_configs = sys.read(session, conditions={"key": "action_configs"})
  498. session.close()
  499. return {
  500. "code": 0,
  501. "msg": "",
  502. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  503. }
  504. @app.post("/update_tab_name", description="更改tab名称")
  505. def update_tab_name(params: DeviceConfigTabsReq):
  506. if params.mode_name == "":
  507. return {"code": 1, "msg": "名称不能为空", "data": {}}
  508. session = SqlQuery()
  509. tabModel = CRUD(DeviceConfigTabs)
  510. kwargs = {"mode_name": params.mode_name}
  511. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  512. session.close()
  513. return {
  514. "code": 0,
  515. "msg": "",
  516. "data": None,
  517. }
  518. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  519. def get_device_configs(params: ModelGetDeviceConfig):
  520. tab_id = params.tab_id
  521. session = SqlQuery()
  522. configModel = CRUD(DeviceConfig)
  523. configList = configModel.read_all(
  524. session,
  525. conditions={"tab_id": tab_id},
  526. order_by="action_index",
  527. ascending=True,
  528. )
  529. return {
  530. "code": 0,
  531. "msg": "",
  532. "data": {"list": configList},
  533. }
  534. @app.post("/device_config_detail", description="获取可执行程序详情")
  535. def device_config_detail(params: ModelGetDeviceConfigDetail):
  536. action_id = params.id
  537. session = SqlQuery()
  538. configModel = CRUD(DeviceConfig)
  539. model = configModel.read(session, conditions={"id": action_id})
  540. if model == None:
  541. return {"code": 1, "msg": "数据不存在", "data": None}
  542. return {"code": 0, "msg": "", "data": model}
  543. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  544. def device_config_detail_query():
  545. # tab_id = params.tab_id
  546. # action_name = params.action_name
  547. session = SqlQuery()
  548. sys = CRUD(SysConfigs)
  549. action_configs = sys.read(session, conditions={"key": "action_configs"})
  550. action_configs_value = json.loads(action_configs.value)
  551. left_config = action_configs_value.get("left")
  552. configModel = CRUD(DeviceConfig)
  553. model = configModel.read(
  554. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  555. )
  556. if model == None:
  557. model = configModel.read(session, conditions={"tab_id": left_config})
  558. return {"code": 0, "msg": "", "data": model}
  559. @app.post("/remove_config", description="删除一条可执行命令")
  560. def get_device_configs(params: ModelGetDeviceConfigDetail):
  561. action_id = params.id
  562. session = SqlQuery()
  563. configModel = CRUD(DeviceConfig)
  564. model = configModel.read(session, conditions={"id": action_id})
  565. if model == None:
  566. return {"code": 1, "msg": "数据不存在", "data": None}
  567. if model.is_system == True:
  568. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  569. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  570. if len(configArray) == 1:
  571. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  572. configModel.delete(session, obj_id=action_id)
  573. return {"code": 0, "msg": "删除成功", "data": None}
  574. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  575. def save_device_config(params: SaveDeviceConfig):
  576. action_id = params.id
  577. session = SqlQuery()
  578. deviceConfig = CRUD(DeviceConfig)
  579. if action_id == None or action_id == 0:
  580. # 走新增逻辑
  581. params.id = None
  582. save_device_config = deviceConfig.create(session, obj_in=params)
  583. else:
  584. model = deviceConfig.read(session, conditions={"id": action_id})
  585. if model == None:
  586. return {"code": 1, "msg": "数据不存在", "data": None}
  587. # 走编辑逻辑
  588. kwargs = params.__dict__
  589. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  590. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  591. @app.post("/reset_config", description="创建或修改一条可执行命令")
  592. def reset_config(params: ModelGetDeviceConfig):
  593. tab_id = params.tab_id
  594. if tab_id == None or tab_id == "":
  595. return {"code": 1, "msg": "参数错误", "data": None}
  596. session = SqlQuery()
  597. deviceConfig = CRUD(DeviceConfig)
  598. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  599. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  600. if res is False:
  601. return {"code": 1, "msg": "操作失败", "data": None}
  602. actions = json.load(open("action.json", encoding="utf-8"))
  603. for data in actions:
  604. data["tab_id"] = tab_id
  605. data["is_system"] = first_config.is_system
  606. device_config = DeviceConfig(**data)
  607. session.add(device_config)
  608. session.commit()
  609. # session.close()
  610. return {"code": 0, "msg": "操作成功", "data": None}
  611. @app.get("/get_photo_records", description="获取拍照记录")
  612. def get_photo_records(page: int = 1, size: int = 5):
  613. session = SqlQuery()
  614. # photos = CRUD(PhotoRecord)
  615. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  616. statement = (
  617. select(PhotoRecord)
  618. .offset((page - 1) * size)
  619. .limit(size)
  620. .order_by(desc("id"))
  621. .group_by("goods_art_no")
  622. )
  623. list = []
  624. result = session.exec(statement).all()
  625. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  626. join_conditions = [
  627. {
  628. "model": DeviceConfig,
  629. "on": PhotoRecord.action_id == DeviceConfig.id,
  630. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  631. }
  632. ]
  633. for item in result:
  634. query = (
  635. select(PhotoRecord, DeviceConfig.action_name)
  636. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  637. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  638. )
  639. list_item = session.exec(query).mappings().all()
  640. list.append(
  641. {
  642. "goods_art_no": item.goods_art_no,
  643. "action_time": item.create_time,
  644. "items": list_item,
  645. }
  646. )
  647. # session.close()
  648. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  649. return {
  650. "code": 0,
  651. "msg": "",
  652. "data": {"list": list, "page": page, "size": size},
  653. }
  654. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  655. def get_last_photo_record():
  656. session = SqlQuery()
  657. statement = (
  658. select(PhotoRecord)
  659. .where(PhotoRecord.image_path != None)
  660. .order_by(desc("photo_create_time"))
  661. )
  662. result = session.exec(statement).first()
  663. # session.close()
  664. return {
  665. "code": 0,
  666. "msg": "",
  667. "data": result,
  668. }
  669. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  670. def get_photo_record_detail(goods_art_no: str = None):
  671. if goods_art_no == None:
  672. return {"code": 1, "msg": "参数错误", "data": None}
  673. session = SqlQuery()
  674. photos = CRUD(PhotoRecord)
  675. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  676. # session.close()
  677. return {
  678. "code": 0,
  679. "msg": "",
  680. "data": {"list": items},
  681. }
  682. @app.post("/delect_goods_arts", description="通过货号删除记录")
  683. def delect_goods_arts(params: PhotoRecordDelete):
  684. session = SqlQuery()
  685. photos = CRUD(PhotoRecord)
  686. for item in params.goods_art_nos:
  687. photos.deleteConditions(session, conditions={"goods_art_no": item})
  688. # session.close()
  689. return {
  690. "code": 0,
  691. "msg": "操作成功",
  692. "data": None,
  693. }
  694. def query_config_by_key(key_name):
  695. """
  696. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  697. Args:
  698. key_name (str): 要查询的key名称
  699. Returns:
  700. dict or None: 匹配的对象或None(如果没有找到)
  701. """
  702. try:
  703. # 获取所有配置数据
  704. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  705. # 遍历配置数据查找匹配的key
  706. for config in configs:
  707. if config.get("key") == key_name:
  708. return config
  709. return None
  710. except Exception as e:
  711. print(f"查询配置时出错: {e}")
  712. return None
  713. @app.get("/get_sys_config", description="查询系统配置")
  714. def get_sys_config(key: str = None):
  715. if key == None:
  716. return {"code": 1, "msg": "参数错误", "data": None}
  717. session = SqlQuery()
  718. photos = CRUD(SysConfigs)
  719. item = photos.read(session, conditions={"key": key})
  720. search_data = None if item == None else json.loads(item.value)
  721. if search_data == None:
  722. sys_config_json = query_config_by_key(key)
  723. if sys_config_json != None:
  724. config = SysConfigs(**sys_config_json)
  725. session.add(config)
  726. session.commit() # 合并事务提交
  727. search_data = json.loads(sys_config_json.get("value"))
  728. return {
  729. "code": 0,
  730. "msg": "",
  731. "data": search_data,
  732. }
  733. @app.post("/update_left_right_config", description="更新左右脚配置")
  734. def update_left_right_config(params: LeftRightParams):
  735. session = SqlQuery()
  736. sysConfig = CRUD(SysConfigs)
  737. model = sysConfig.read(session, conditions={"key": "action_configs"})
  738. if model == None:
  739. return {"code": 1, "msg": "配置不存在", "data": None}
  740. config_value = json.loads(model.value)
  741. config_value[params.type] = params.id
  742. update_value = json.dumps(config_value)
  743. # 走编辑逻辑
  744. kwargs = {"key": "action_configs", "value": update_value}
  745. save_device_config = sysConfig.updateConditions(
  746. session, conditions={"key": "action_configs"}, **kwargs
  747. )
  748. return {"code": 0, "msg": "操作成功", "data": None}
  749. @app.post("/update_record", description="更新拍照记录")
  750. def update_record(params: RecordUpdate):
  751. session = SqlQuery()
  752. photoRecord = CRUD(PhotoRecord)
  753. model = photoRecord.read(session, conditions={"id": params.id})
  754. if model == None:
  755. return {"code": 1, "msg": "记录不存在", "data": None}
  756. kwargs = params.__dict__
  757. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  758. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  759. @app.post("/update_sys_configs", description="创建或修改系统配置")
  760. def save_sys_configs(params: SysConfigParams):
  761. session = SqlQuery()
  762. sysConfig = CRUD(SysConfigs)
  763. model = sysConfig.read(session, conditions={"key": params.key})
  764. if model == None:
  765. return {"code": 1, "msg": "配置不存在", "data": None}
  766. # 走编辑逻辑
  767. kwargs = params.__dict__
  768. save_device_config = sysConfig.updateConditions(
  769. session, conditions={"key": params.key}, **kwargs
  770. )
  771. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  772. @app.post("/create_main_image", description="创建主图测试")
  773. def create_main_image(params: MaineImageTest):
  774. file_path = params.file_path
  775. onePic = OnePicTest(pic_path=file_path)
  776. main_out_path = onePic.HandlerMainImage()
  777. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  778. def insertEmptyLogoList(session):
  779. """插入空logo列表"""
  780. data = {"key": "logo_configs", "value": "[]"}
  781. config = SysConfigs(**data)
  782. session.add(config)
  783. session.commit()
  784. session.close()
  785. item = SysConfigs()
  786. item.key = "logo_configs"
  787. item.value = "[]"
  788. return item
  789. @app.get("/logo_list", description="logo列表")
  790. def logo_list():
  791. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  792. check_path(logo_dir)
  793. logo_files = os.listdir(logo_dir)
  794. logo_list = []
  795. for logoItem in logo_files:
  796. logo_list.append(f"{logo_dir}{logoItem}")
  797. return {"code": 0, "msg": "操作成功", "data": logo_list}
  798. @app.post("/add_logo", description="添加logo")
  799. def add_logo(params: LogoParams):
  800. logo_path = params.logo_path.replace("\\", "/")
  801. session = SqlQuery()
  802. sysConfig = CRUD(SysConfigs)
  803. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  804. if item == None:
  805. item = insertEmptyLogoList(session)
  806. if os.path.isfile(logo_path) == False:
  807. return {"code": 1, "msg": "logo文件不存在", "data": None}
  808. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  809. check_path(logo_dir)
  810. fpath, fname = os.path.split(logo_path)
  811. logo_path_info = logo_dir + fname
  812. shutil.copy(logo_path, logo_path_info) # 复制文件
  813. logo_files = os.listdir(logo_dir)
  814. logo_list = []
  815. for logoItem in logo_files:
  816. logo_list.append(f"{logo_dir}{logoItem}")
  817. return {
  818. "code": 0,
  819. "msg": "",
  820. "data": {"logo": logo_path_info},
  821. }
  822. @app.post("/delete_logo", description="删除logo")
  823. def delete_logo(params: LogoParamsupdate):
  824. logo_path = params.path
  825. if os.path.isfile(logo_path) == False:
  826. return {"code": 1, "msg": "logo文件不存在", "data": None}
  827. os.remove(logo_path)
  828. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  829. check_path(logo_dir)
  830. logo_files = os.listdir(logo_dir)
  831. logo_list = []
  832. for logoItem in logo_files:
  833. logo_list.append(f"{logo_dir}{logoItem}")
  834. return {"code": 0, "msg": "操作成功", "data": logo_list}
  835. @app.post("/close_other_window", description="关闭窗口")
  836. def close_other_window():
  837. hwnd_list = []
  838. def callback(hwnd, _):
  839. title = GetWindowText(hwnd)
  840. if title == "digiCamControl by Duka Istvan":
  841. hwnd_list.append(hwnd)
  842. EnumWindows(callback, None)
  843. if hwnd_list:
  844. hwnd = hwnd_list[0]
  845. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  846. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  847. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}