api.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. path = ""
  296. limit_path = "output/{}".format(
  297. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  298. )
  299. check_path(limit_path)
  300. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  301. move_folder_array = check_move_goods_art_no_folder(
  302. "output", goods_art_no_arrays, limit_path
  303. )
  304. for goods_art_no in goods_art_no_arrays:
  305. if not goods_art_no:
  306. raise UnicornException("货号不能为空")
  307. session = SqlQuery()
  308. pr = CRUD(PhotoRecord)
  309. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  310. if not images:
  311. raise UnicornException("没有可用货号数据")
  312. if is_only_cutout != 1:
  313. detail_counts = len(params.template_image_order.split(","))
  314. image_counts = len(images)
  315. if image_counts < detail_counts:
  316. raise UnicornException(
  317. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  318. )
  319. if move_folder_array.get(goods_art_no) == None:
  320. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  321. check_path(image_dir)
  322. for idx, itemImg in enumerate(images):
  323. if itemImg.image_path == "" or itemImg.image_path == None:
  324. raise UnicornException(
  325. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  326. )
  327. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  328. if not os.path.exists(
  329. image_dir + "/" + os.path.basename(new_file_name)
  330. ):
  331. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  332. dealImage = DealImage(image_dir)
  333. resFlag, path = dealImage.dealMoveImage(
  334. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  335. )
  336. if not resFlag:
  337. raise UnicornException(path)
  338. # try:
  339. temp_class = {}
  340. temp_name_list = []
  341. for tempItem in params.temp_list:
  342. temp_class[tempItem.template_id] = tempItem.template_local_classes
  343. temp_name_list.append(tempItem.template_id)
  344. cutOutMode = (
  345. '1'
  346. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  347. == "普通抠图"
  348. else '2'
  349. )
  350. config_data = {
  351. "image_dir": limit_path,
  352. "image_order": (
  353. "俯视,侧视,后跟,鞋底,内里"
  354. if params.template_image_order == None or params.template_image_order == ""
  355. else params.template_image_order
  356. ),
  357. "goods_art_no": "",
  358. "goods_art_nos": goods_art_no_arrays,
  359. "is_check_number": False,
  360. "resize_image_view": "后跟",
  361. "cutout_mode": cutOutMode,
  362. "logo_path": params.logo_path,
  363. "special_goods_art_no_folder_line": "",
  364. "is_use_excel": False, # 是否使用excel
  365. "excel_path": "", # excel路径
  366. "is_check_color_is_all": False,
  367. "cutout_is_pass": True,
  368. "assigned_page_dict": {},
  369. "detail_is_pass": True,
  370. "upload_is_pass": False,
  371. "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  372. "is_filter": False,
  373. "temp_class": temp_class,
  374. "temp_name": params.temp_name,
  375. "temp_name_list": temp_name_list,
  376. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  377. "success_handler": [],
  378. }
  379. print("image_dir=====>>>>>", config_data["image_dir"])
  380. # 动态导入类
  381. temp_class_dict = {}
  382. for key, class_path in config_data["temp_class"].items():
  383. module_path, class_name = class_path.rsplit(".", 1)
  384. module = importlib.import_module(module_path)
  385. cls = getattr(module, class_name)
  386. temp_class_dict[key] = cls
  387. config_data["temp_class"] = temp_class_dict
  388. return_data = run_main.check_before_cutout(config_data)
  389. cutout_res = await run_main.check_for_cutout_image_first_call_back(return_data)
  390. check_for_detail_first_res = None
  391. if cutout_res == True:
  392. sys_path = format(os.getcwd()).replace("\\", "/")
  393. handler_result_folder = f"{sys_path}/{limit_path}"
  394. for goods_art_item in goods_art_no_arrays:
  395. handler_result.append(
  396. {
  397. "goods_art_no": goods_art_item,
  398. "success": True,
  399. "info": "处理成功",
  400. }
  401. )
  402. if is_only_cutout == 1:
  403. return {
  404. "code": 0,
  405. "msg": "",
  406. "data": {"output_folder": handler_result_folder, "list": handler_result},
  407. }
  408. handler_result = []
  409. try:
  410. return_data_check_before_detail = run_main.check_before_detail(config_data)
  411. check_for_detail_first_res = await run_main.check_for_detail_first_call_back(
  412. return_data_check_before_detail
  413. )
  414. if isinstance(check_for_detail_first_res, partial):
  415. result = check_for_detail_first_res()
  416. try:
  417. config_data = result["config_data"]
  418. except:
  419. config_data = result
  420. if config_data["sign_text"] == "已结束详情处理":
  421. # at_pic = AutoDealPics()
  422. print("config_data", config_data)
  423. # if config_data["upload_is_enable"]:
  424. # to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  425. # check_path(to_deal_dir)
  426. # print("to_deal_dir", to_deal_dir)
  427. # if os.path.exists(to_deal_dir):
  428. # upload_pic = UploadPic(
  429. # windows=None,
  430. # to_deal_dir=to_deal_dir,
  431. # config_data=config_data,
  432. # token=token,
  433. # )
  434. # upload_pic.run()
  435. out_put_dir = config_data.get("out_put_dir")
  436. if out_put_dir == None:
  437. handler_result_folder = ""
  438. if len(config_data["success_handler"]) > 0:
  439. for good_art in config_data["success_handler"]:
  440. handler_result.append(good_art)
  441. else:
  442. for good_art in goods_art_no_arrays:
  443. handler_result.append(
  444. {
  445. "goods_art_no": good_art,
  446. "success": False,
  447. "info": "处理失败",
  448. }
  449. )
  450. else:
  451. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  452. "\\", "/"
  453. )
  454. handler_result_folder = os.path.dirname(out_put_dir_path)
  455. if len(config_data["success_handler"]) == 0:
  456. for good_art in goods_art_no_arrays:
  457. handler_result.append(
  458. {
  459. "goods_art_no": good_art,
  460. "success": False,
  461. "info": "处理失败",
  462. }
  463. )
  464. else:
  465. handler_result = config_data["success_handler"]
  466. else:
  467. handler_result.append(
  468. {"goods_art_no": "", "success": False, "info": "处理失败"}
  469. )
  470. except UnicornException as e:
  471. handler_result_folder = ""
  472. handler_result = e.msg
  473. except Exception as e:
  474. handler_result_folder = ""
  475. handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  476. return {
  477. "code": 0,
  478. "msg": "",
  479. "data": {"output_folder": handler_result_folder, "list": handler_result},
  480. }
  481. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  482. def get_device_tabs(type: int):
  483. session = SqlQuery()
  484. statement = (
  485. select(DeviceConfigTabs)
  486. .where(DeviceConfigTabs.mode_type == type)
  487. .order_by(asc("id"))
  488. )
  489. result = session.exec(statement).all()
  490. session.close()
  491. sys = CRUD(SysConfigs)
  492. action_configs = sys.read(session, conditions={"key": "action_configs"})
  493. session.close()
  494. return {
  495. "code": 0,
  496. "msg": "",
  497. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  498. }
  499. @app.post("/update_tab_name", description="更改tab名称")
  500. def update_tab_name(params: DeviceConfigTabsReq):
  501. if params.mode_name == "":
  502. return {"code": 1, "msg": "名称不能为空", "data": {}}
  503. session = SqlQuery()
  504. tabModel = CRUD(DeviceConfigTabs)
  505. kwargs = {"mode_name": params.mode_name}
  506. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  507. session.close()
  508. return {
  509. "code": 0,
  510. "msg": "",
  511. "data": None,
  512. }
  513. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  514. def get_device_configs(params: ModelGetDeviceConfig):
  515. tab_id = params.tab_id
  516. session = SqlQuery()
  517. configModel = CRUD(DeviceConfig)
  518. configList = configModel.read_all(
  519. session,
  520. conditions={"tab_id": tab_id},
  521. order_by="action_index",
  522. ascending=True,
  523. )
  524. return {
  525. "code": 0,
  526. "msg": "",
  527. "data": {"list": configList},
  528. }
  529. @app.post("/device_config_detail", description="获取可执行程序详情")
  530. def device_config_detail(params: ModelGetDeviceConfigDetail):
  531. action_id = params.id
  532. session = SqlQuery()
  533. configModel = CRUD(DeviceConfig)
  534. model = configModel.read(session, conditions={"id": action_id})
  535. if model == None:
  536. return {"code": 1, "msg": "数据不存在", "data": None}
  537. return {"code": 0, "msg": "", "data": model}
  538. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  539. def device_config_detail_query():
  540. # tab_id = params.tab_id
  541. # action_name = params.action_name
  542. session = SqlQuery()
  543. sys = CRUD(SysConfigs)
  544. action_configs = sys.read(session, conditions={"key": "action_configs"})
  545. action_configs_value = json.loads(action_configs.value)
  546. left_config = action_configs_value.get("left")
  547. configModel = CRUD(DeviceConfig)
  548. model = configModel.read(
  549. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  550. )
  551. if model == None:
  552. model = configModel.read(session, conditions={"tab_id": left_config})
  553. return {"code": 0, "msg": "", "data": model}
  554. @app.post("/remove_config", description="删除一条可执行命令")
  555. def get_device_configs(params: ModelGetDeviceConfigDetail):
  556. action_id = params.id
  557. session = SqlQuery()
  558. configModel = CRUD(DeviceConfig)
  559. model = configModel.read(session, conditions={"id": action_id})
  560. if model == None:
  561. return {"code": 1, "msg": "数据不存在", "data": None}
  562. if model.is_system == True:
  563. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  564. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  565. if len(configArray) == 1:
  566. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  567. configModel.delete(session, obj_id=action_id)
  568. return {"code": 0, "msg": "删除成功", "data": None}
  569. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  570. def save_device_config(params: SaveDeviceConfig):
  571. action_id = params.id
  572. session = SqlQuery()
  573. deviceConfig = CRUD(DeviceConfig)
  574. if action_id == None or action_id == 0:
  575. # 走新增逻辑
  576. params.id = None
  577. save_device_config = deviceConfig.create(session, obj_in=params)
  578. else:
  579. model = deviceConfig.read(session, conditions={"id": action_id})
  580. if model == None:
  581. return {"code": 1, "msg": "数据不存在", "data": None}
  582. # 走编辑逻辑
  583. kwargs = params.__dict__
  584. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  585. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  586. @app.post("/reset_config", description="创建或修改一条可执行命令")
  587. def reset_config(params: ModelGetDeviceConfig):
  588. tab_id = params.tab_id
  589. if tab_id == None or tab_id == "":
  590. return {"code": 1, "msg": "参数错误", "data": None}
  591. session = SqlQuery()
  592. deviceConfig = CRUD(DeviceConfig)
  593. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  594. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  595. if res is False:
  596. return {"code": 1, "msg": "操作失败", "data": None}
  597. actions = json.load(open("action.json", encoding="utf-8"))
  598. for data in actions:
  599. data["tab_id"] = tab_id
  600. data["is_system"] = first_config.is_system
  601. device_config = DeviceConfig(**data)
  602. session.add(device_config)
  603. session.commit()
  604. # session.close()
  605. return {"code": 0, "msg": "操作成功", "data": None}
  606. @app.get("/get_photo_records", description="获取拍照记录")
  607. def get_photo_records(page: int = 1, size: int = 5):
  608. session = SqlQuery()
  609. # photos = CRUD(PhotoRecord)
  610. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  611. statement = (
  612. select(PhotoRecord)
  613. .offset((page - 1) * size)
  614. .limit(size)
  615. .order_by(desc("id"))
  616. .group_by("goods_art_no")
  617. )
  618. list = []
  619. result = session.exec(statement).all()
  620. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  621. join_conditions = [
  622. {
  623. "model": DeviceConfig,
  624. "on": PhotoRecord.action_id == DeviceConfig.id,
  625. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  626. }
  627. ]
  628. for item in result:
  629. query = (
  630. select(PhotoRecord, DeviceConfig.action_name)
  631. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  632. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  633. )
  634. list_item = session.exec(query).mappings().all()
  635. list.append(
  636. {
  637. "goods_art_no": item.goods_art_no,
  638. "action_time": item.create_time,
  639. "items": list_item,
  640. }
  641. )
  642. # session.close()
  643. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  644. return {
  645. "code": 0,
  646. "msg": "",
  647. "data": {"list": list, "page": page, "size": size},
  648. }
  649. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  650. def get_last_photo_record():
  651. session = SqlQuery()
  652. statement = (
  653. select(PhotoRecord)
  654. .where(PhotoRecord.image_path != None)
  655. .order_by(desc("photo_create_time"))
  656. )
  657. result = session.exec(statement).first()
  658. # session.close()
  659. return {
  660. "code": 0,
  661. "msg": "",
  662. "data": result,
  663. }
  664. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  665. def get_photo_record_detail(goods_art_no: str = None):
  666. if goods_art_no == None:
  667. return {"code": 1, "msg": "参数错误", "data": None}
  668. session = SqlQuery()
  669. photos = CRUD(PhotoRecord)
  670. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  671. # session.close()
  672. return {
  673. "code": 0,
  674. "msg": "",
  675. "data": {"list": items},
  676. }
  677. @app.post("/delect_goods_arts", description="通过货号删除记录")
  678. def delect_goods_arts(params: PhotoRecordDelete):
  679. session = SqlQuery()
  680. photos = CRUD(PhotoRecord)
  681. for item in params.goods_art_nos:
  682. photos.deleteConditions(session, conditions={"goods_art_no": item})
  683. # session.close()
  684. return {
  685. "code": 0,
  686. "msg": "操作成功",
  687. "data": None,
  688. }
  689. def query_config_by_key(key_name):
  690. """
  691. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  692. Args:
  693. key_name (str): 要查询的key名称
  694. Returns:
  695. dict or None: 匹配的对象或None(如果没有找到)
  696. """
  697. try:
  698. # 获取所有配置数据
  699. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  700. # 遍历配置数据查找匹配的key
  701. for config in configs:
  702. if config.get("key") == key_name:
  703. return config
  704. return None
  705. except Exception as e:
  706. print(f"查询配置时出错: {e}")
  707. return None
  708. @app.get("/get_sys_config", description="查询系统配置")
  709. def get_sys_config(key: str = None):
  710. if key == None:
  711. return {"code": 1, "msg": "参数错误", "data": None}
  712. session = SqlQuery()
  713. photos = CRUD(SysConfigs)
  714. item = photos.read(session, conditions={"key": key})
  715. search_data = None if item == None else json.loads(item.value)
  716. if search_data == None:
  717. sys_config_json = query_config_by_key(key)
  718. if sys_config_json != None:
  719. config = SysConfigs(**sys_config_json)
  720. session.add(config)
  721. session.commit() # 合并事务提交
  722. search_data = json.loads(sys_config_json.get("value"))
  723. return {
  724. "code": 0,
  725. "msg": "",
  726. "data": search_data,
  727. }
  728. @app.post("/update_left_right_config", description="更新左右脚配置")
  729. def update_left_right_config(params: LeftRightParams):
  730. session = SqlQuery()
  731. sysConfig = CRUD(SysConfigs)
  732. model = sysConfig.read(session, conditions={"key": "action_configs"})
  733. if model == None:
  734. return {"code": 1, "msg": "配置不存在", "data": None}
  735. config_value = json.loads(model.value)
  736. config_value[params.type] = params.id
  737. update_value = json.dumps(config_value)
  738. # 走编辑逻辑
  739. kwargs = {"key": "action_configs", "value": update_value}
  740. save_device_config = sysConfig.updateConditions(
  741. session, conditions={"key": "action_configs"}, **kwargs
  742. )
  743. return {"code": 0, "msg": "操作成功", "data": None}
  744. @app.post("/update_record", description="更新拍照记录")
  745. def update_record(params: RecordUpdate):
  746. session = SqlQuery()
  747. photoRecord = CRUD(PhotoRecord)
  748. model = photoRecord.read(session, conditions={"id": params.id})
  749. if model == None:
  750. return {"code": 1, "msg": "记录不存在", "data": None}
  751. kwargs = params.__dict__
  752. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  753. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  754. @app.post("/update_sys_configs", description="创建或修改系统配置")
  755. def save_sys_configs(params: SysConfigParams):
  756. session = SqlQuery()
  757. sysConfig = CRUD(SysConfigs)
  758. model = sysConfig.read(session, conditions={"key": params.key})
  759. if model == None:
  760. return {"code": 1, "msg": "配置不存在", "data": None}
  761. # 走编辑逻辑
  762. kwargs = params.__dict__
  763. save_device_config = sysConfig.updateConditions(
  764. session, conditions={"key": params.key}, **kwargs
  765. )
  766. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  767. @app.post("/create_main_image", description="创建主图测试")
  768. def create_main_image(params: MaineImageTest):
  769. file_path = params.file_path
  770. onePic = OnePicTest(pic_path=file_path)
  771. main_out_path = onePic.HandlerMainImage()
  772. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  773. def insertEmptyLogoList(session):
  774. """插入空logo列表"""
  775. data = {"key": "logo_configs", "value": "[]"}
  776. config = SysConfigs(**data)
  777. session.add(config)
  778. session.commit()
  779. session.close()
  780. item = SysConfigs()
  781. item.key = "logo_configs"
  782. item.value = "[]"
  783. return item
  784. @app.get("/logo_list", description="logo列表")
  785. def logo_list():
  786. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  787. check_path(logo_dir)
  788. logo_files = os.listdir(logo_dir)
  789. logo_list = []
  790. for logoItem in logo_files:
  791. logo_list.append(f"{logo_dir}{logoItem}")
  792. return {"code": 0, "msg": "操作成功", "data": logo_list}
  793. @app.post("/add_logo", description="添加logo")
  794. def add_logo(params: LogoParams):
  795. logo_path = params.logo_path.replace("\\", "/")
  796. session = SqlQuery()
  797. sysConfig = CRUD(SysConfigs)
  798. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  799. if item == None:
  800. item = insertEmptyLogoList(session)
  801. if os.path.isfile(logo_path) == False:
  802. return {"code": 1, "msg": "logo文件不存在", "data": None}
  803. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  804. check_path(logo_dir)
  805. fpath, fname = os.path.split(logo_path)
  806. logo_path_info = logo_dir + fname
  807. shutil.copy(logo_path, logo_path_info) # 复制文件
  808. logo_files = os.listdir(logo_dir)
  809. logo_list = []
  810. for logoItem in logo_files:
  811. logo_list.append(f"{logo_dir}{logoItem}")
  812. return {
  813. "code": 0,
  814. "msg": "",
  815. "data": {"logo": logo_path_info},
  816. }
  817. @app.post("/delete_logo", description="删除logo")
  818. def delete_logo(params: LogoParamsupdate):
  819. logo_path = params.path
  820. if os.path.isfile(logo_path) == False:
  821. return {"code": 1, "msg": "logo文件不存在", "data": None}
  822. os.remove(logo_path)
  823. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  824. check_path(logo_dir)
  825. logo_files = os.listdir(logo_dir)
  826. logo_list = []
  827. for logoItem in logo_files:
  828. logo_list.append(f"{logo_dir}{logoItem}")
  829. return {"code": 0, "msg": "操作成功", "data": logo_list}
  830. @app.post("/close_other_window", description="关闭窗口")
  831. def close_other_window():
  832. hwnd_list = []
  833. def callback(hwnd, _):
  834. title = GetWindowText(hwnd)
  835. if title == "digiCamControl by Duka Istvan":
  836. hwnd_list.append(hwnd)
  837. EnumWindows(callback, None)
  838. if hwnd_list:
  839. hwnd = hwnd_list[0]
  840. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  841. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  842. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}