api.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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 win32api, win32gui, win32con
  27. from win32gui import EnumWindows, GetWindowText
  28. from service.online_request.module_online_data import OnlineDataRequest
  29. from concurrent.futures import ThreadPoolExecutor
  30. from functools import partial
  31. from service.online_request.module_online_data import AIGCDataRequest
  32. import asyncio
  33. from fastapi import BackgroundTasks
  34. import functools
  35. import traceback
  36. def log_exception_with_context(context_message=""):
  37. """装饰器:为函数添加异常日志上下文"""
  38. def decorator(func):
  39. @functools.wraps(func)
  40. def wrapper(*args, **kwargs):
  41. try:
  42. return func(*args, **kwargs)
  43. except Exception as e:
  44. logger.error(f"=== 异常发生在函数: {func.__name__} ===")
  45. if context_message:
  46. logger.error(f"上下文信息: {context_message}")
  47. logger.error(f"函数参数: args={args}, kwargs={kwargs}")
  48. logger.error(f"异常类型: {type(e).__name__}")
  49. logger.error(f"异常信息: {str(e)}")
  50. logger.error("完整堆栈跟踪:")
  51. logger.error(traceback.format_exc())
  52. raise # 重新抛出异常
  53. return wrapper
  54. return decorator
  55. def parserGoodsDict2Aigc(return_data_check_before_detail):
  56. """获取商品组装数据"""
  57. goods_no_dict = return_data_check_before_detail.get("data", {}).get(
  58. "goods_no_dict", {}
  59. )
  60. return goods_no_dict
  61. async def sendAsyncMessage(msg="", goods_arts=[], status="", msg_type="", data=None):
  62. """异步发送消息"""
  63. data = {
  64. "code": 0,
  65. "msg": msg,
  66. "status": 2,
  67. "data": (
  68. data
  69. if data is not None
  70. else {
  71. "status": status,
  72. "goods_art_nos": goods_arts,
  73. }
  74. ),
  75. "msg_type": msg_type,
  76. }
  77. await message_queue.put(data)
  78. @app.get("/")
  79. async def index():
  80. # await socket_manager.send_message(msg="测试")
  81. return {"message": "Hello World"}
  82. @app.get("/scan_serials", description="扫描可用的设备端口")
  83. async def scanSerials():
  84. """扫描串口"""
  85. ports = list_ports.comports()
  86. print("Scanning", ports)
  87. return {"message": "Hello World"}
  88. @app.api_route(
  89. "/forward_request", methods=["GET", "POST"], description="代理转发hlm项目得请求"
  90. )
  91. async def forwardRequest(request: HlmForwardRequest):
  92. """
  93. 转发HTTP请求到目标URL
  94. :param request: FastAPI Request对象
  95. :return: 目标接口的响应
  96. """
  97. try:
  98. if request.method == "GET":
  99. params = request.query_params
  100. elif request.method == "POST":
  101. params = json.dump(request.query_params)
  102. else:
  103. raise UnicornException("仅支持GET和POST方法")
  104. target_url = request.target_url
  105. method = request.method.upper()
  106. headers = request.headers
  107. if not target_url:
  108. raise UnicornException("目标url地址不能为空")
  109. # 调用 hlm_http_request 中的 forward_request 函数
  110. response = forward_request(
  111. target_url, params=params, method=method, headers=headers
  112. )
  113. return response
  114. except requests.RequestException as e:
  115. raise UnicornException(e)
  116. except Exception as e:
  117. raise UnicornException(e)
  118. async def fromExcelHandler(params: HandlerDetail):
  119. excel_path = params.excel_path
  120. token = "Bearer " + params.token
  121. uuid = params.uuid
  122. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  123. handler_result = []
  124. handler_result_folder = ""
  125. if "文件夹名称" not in excel_df.columns:
  126. raise UnicornException("缺失 [文件夹名称] 列")
  127. if "商品货号" not in excel_df.columns:
  128. raise UnicornException("缺失 [商品货号] 列")
  129. if "款号" not in excel_df.columns:
  130. raise UnicornException("缺失 [款号] 列")
  131. goods_art_dirs = excel_df.groupby(excel_df["款号"])
  132. obj = None
  133. run_main = RunMain(obj, token, uuid)
  134. temp_class = {}
  135. # 可用模板列表-需要导包
  136. temp_name_list = []
  137. for tempItem in params.temp_list:
  138. temp_class[tempItem.template_id] = tempItem.template_local_classes
  139. temp_name_list.append(tempItem.template_id)
  140. # 抠图时用到的货号列表,与生成详情图有所区别
  141. goods_art_no_arrays = []
  142. # # 详情图生成需要对同款商品进行分组,保证详情图可以生成多个色
  143. goods_art_no_group_arrays = []
  144. for _, goods_row in excel_df.iterrows():
  145. goods_art_no = str(goods_row["商品货号"])
  146. goods_art_no_arrays.append(goods_art_no)
  147. goods_no = str(goods_row["款号"])
  148. a001_df = goods_art_dirs.get_group(goods_no)
  149. goods_art_groups = a001_df["商品货号"].tolist()
  150. if goods_art_groups in goods_art_no_group_arrays:
  151. continue
  152. goods_art_no_group_arrays.append(goods_art_groups)
  153. limit_path = "output/{}".format(
  154. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  155. )
  156. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  157. move_folder_array = check_move_goods_art_no_folder(
  158. "output", goods_art_no_arrays, limit_path
  159. )
  160. for index, row in excel_df.iterrows():
  161. goods_art_no_image_dir = str(row["文件夹名称"])
  162. goods_art_no = str(row["商品货号"])
  163. print("货号数据", goods_art_no)
  164. if not goods_art_no:
  165. raise UnicornException("货号不能为空")
  166. session = SqlQuery()
  167. pr = CRUD(PhotoRecord)
  168. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  169. if not images:
  170. raise UnicornException(
  171. f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确"
  172. )
  173. # 货号目录不存在再去进行移动和创建操作
  174. if move_folder_array.get(goods_art_no) == None:
  175. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  176. check_path(image_dir)
  177. for idx, itemImg in enumerate(images):
  178. if itemImg.image_path == "" or itemImg.image_path == None:
  179. raise UnicornException(
  180. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  181. )
  182. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  183. if not os.path.exists(
  184. image_dir + "/" + os.path.basename(new_file_name)
  185. ):
  186. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  187. dealImage = DealImage(image_dir)
  188. resFlag, path = dealImage.dealMoveImage(
  189. image_dir=image_dir,
  190. callback_func=None,
  191. goods_art_no=goods_art_no_image_dir,
  192. )
  193. if not resFlag:
  194. raise UnicornException(path)
  195. shutil.rmtree(image_dir)
  196. # path = os.path.dirname(path)
  197. cutOutMode = (
  198. "0"
  199. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  200. == "普通抠图"
  201. else "1"
  202. )
  203. config_data = {
  204. "image_dir": limit_path, # 这个目录作为本次生成的图片目录非常重要 例:./output/当前日期
  205. "image_order": (
  206. "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  207. if params.template_image_order == None or params.template_image_order == ""
  208. else params.template_image_order
  209. ),
  210. "goods_art_no": goods_art_no,
  211. "goods_art_nos": goods_art_no_arrays,
  212. "is_check_number": False,
  213. "resize_image_view": "后跟",
  214. "cutout_mode": cutOutMode,
  215. "logo_path": params.logo_path,
  216. "special_goods_art_no_folder_line": "",
  217. "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  218. "excel_path": params.excel_path, # excel路径
  219. "is_check_color_is_all": False,
  220. "cutout_is_pass": True,
  221. "assigned_page_dict": {},
  222. "detail_is_pass": True,
  223. "upload_is_pass": False,
  224. "upload_is_enable": False,
  225. "is_filter": False,
  226. "temp_class": temp_class,
  227. "temp_name": params.temp_name,
  228. "temp_name_list": temp_name_list,
  229. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  230. "success_handler": [],
  231. }
  232. # 动态导入类
  233. temp_class_dict = {}
  234. for key, class_path in config_data["temp_class"].items():
  235. module_path, class_name = class_path.rsplit(".", 1)
  236. module = importlib.import_module(module_path)
  237. cls = getattr(module, class_name)
  238. temp_class_dict[key] = cls
  239. config_data["temp_class"] = temp_class_dict
  240. # executor = ThreadPoolExecutor(max_workers=4)
  241. # 此处对抠图进行批量处理,保证所有的图片在生成详情图之前已经完成抠图,以保证详情图生成的效率
  242. return_data = run_main.check_before_cutout(config_data)
  243. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  244. check_for_detail_first_res = None
  245. try:
  246. if cutout_res:
  247. return_data_check_before_detail = run_main.check_before_detail(config_data)
  248. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  249. return_data_check_before_detail
  250. )
  251. if isinstance(check_for_detail_first_res, partial):
  252. result = check_for_detail_first_res()
  253. try:
  254. config_data = result["config_data"]
  255. except:
  256. config_data = result
  257. if config_data["sign_text"] == "已结束详情处理":
  258. print("config_data", config_data)
  259. if config_data["upload_is_enable"]:
  260. to_deal_dir = "{}/软件-详情图生成".format(config_data["image_dir"])
  261. check_path(to_deal_dir)
  262. print("to_deal_dir", to_deal_dir)
  263. if os.path.exists(to_deal_dir):
  264. upload_pic = UploadPic(
  265. windows=None,
  266. to_deal_dir=to_deal_dir,
  267. config_data=config_data,
  268. token=token,
  269. )
  270. upload_pic.run()
  271. out_put_dir = config_data.get("out_put_dir")
  272. if out_put_dir == None:
  273. handler_result_folder = ""
  274. if len(config_data["success_handler"]) > 0:
  275. for good_art in config_data["success_handler"]:
  276. handler_result.append(good_art)
  277. else:
  278. for good_art in goods_art_no_arrays:
  279. handler_result.append(
  280. {
  281. "goods_art_no": good_art,
  282. "success": False,
  283. "info": "处理失败",
  284. }
  285. )
  286. else:
  287. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  288. "\\", "/"
  289. )
  290. handler_result_folder = os.path.dirname(out_put_dir_path)
  291. if len(config_data["success_handler"]) == 0:
  292. for good_art in goods_art_no_arrays:
  293. handler_result.append(
  294. {
  295. "goods_art_no": good_art,
  296. "success": False,
  297. "info": "处理失败",
  298. }
  299. )
  300. else:
  301. handler_result = config_data["success_handler"]
  302. else:
  303. for good_art in goods_art_no_arrays:
  304. handler_result.append(
  305. {"goods_art_no": good_art, "success": False, "info": "处理失败"}
  306. )
  307. except Exception as e:
  308. for good_art in goods_art_no_arrays:
  309. handler_result.append(
  310. {"goods_art_no": good_art, "success": False, "info": str(e)}
  311. )
  312. handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  313. await sendAsyncMessage(
  314. msg="处理结束",
  315. data={"output_folder": handler_result_folder, "list": handler_result},
  316. status="处理结束",
  317. msg_type="detail_result_progress",
  318. )
  319. return True
  320. def group_by_style_number(data):
  321. result = {}
  322. for goods_id, info in data.items():
  323. style_number = info["款号"]
  324. if style_number not in result:
  325. result[style_number] = []
  326. result[style_number].append(goods_id)
  327. return result
  328. @app.post("/handle_detail")
  329. async def handle_detail_background(
  330. request: Request, params: HandlerDetail, background_tasks: BackgroundTasks
  331. ):
  332. goods_art_no_arrays = params.goods_art_no
  333. is_check = params.is_check
  334. is_only_cutout = params.is_only_cutout # 是否仅抠图
  335. if is_only_cutout == 1:
  336. # 如果是仅抠图模式,避免进入到excel模式
  337. params.excel_path = ""
  338. if params.excel_path != "" and params.excel_path != None:
  339. return await fromExcelHandler(params)
  340. path = ""
  341. limit_path = "output/{}".format(
  342. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  343. )
  344. check_path(limit_path)
  345. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  346. move_folder_array = check_move_goods_art_no_folder(
  347. "output", goods_art_no_arrays, limit_path
  348. )
  349. try:
  350. for goods_art_no in goods_art_no_arrays:
  351. if not goods_art_no:
  352. raise UnicornException("货号不能为空")
  353. session = SqlQuery()
  354. pr = CRUD(PhotoRecord)
  355. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  356. if not images:
  357. raise UnicornException(
  358. f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确"
  359. )
  360. if is_only_cutout != 1:
  361. detail_counts = len(params.template_image_order.split(","))
  362. image_counts = len(images)
  363. if image_counts < detail_counts:
  364. raise UnicornException(
  365. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  366. )
  367. if move_folder_array.get(goods_art_no) == None:
  368. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  369. check_path(image_dir)
  370. for idx, itemImg in enumerate(images):
  371. if itemImg.image_path == "" or itemImg.image_path == None:
  372. raise UnicornException(
  373. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  374. )
  375. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  376. if not os.path.exists(
  377. image_dir + "/" + os.path.basename(new_file_name)
  378. ):
  379. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  380. dealImage = DealImage(image_dir)
  381. resFlag, path = dealImage.dealMoveImage(
  382. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  383. )
  384. if not resFlag:
  385. raise UnicornException(path)
  386. except Exception as e:
  387. raise UnicornException(str(e))
  388. if is_check == 1:
  389. return {
  390. "code": 0,
  391. "msg": "检测通过",
  392. "data": None,
  393. }
  394. asyncio.create_task(process_handle_detail(request, params))
  395. return {"code": 0, "msg": "任务已提交后台处理", "data": {"status": "processing"}}
  396. async def process_handle_detail(request: Request, params: HandlerDetail):
  397. obj = None
  398. token = "Bearer " + params.token
  399. uuid = params.uuid
  400. aigc_clazz = AIGCDataRequest(token)
  401. run_main = RunMain(obj, token, uuid)
  402. onlineData = OnlineDataRequest(token)
  403. goods_art_no_arrays = params.goods_art_no
  404. is_only_cutout = params.is_only_cutout # 是否仅抠图
  405. online_stores = params.online_stores # 上传第三方的店铺名称数组
  406. is_detail = params.is_detail # 上传第三方的店铺名称数组
  407. is_product_scene = params.is_product_scene # 上传第三方的店铺名称数组
  408. is_upper_footer = params.is_upper_footer # 上传第三方的店铺名称数组
  409. upper_footer_params = params.upper_footer_params # 上传第三方的店铺名称数组
  410. product_scene_prompt = params.product_scene_prompt # 上传第三方的店铺名称数组
  411. handler_result = []
  412. handler_result_folder = ""
  413. if is_only_cutout == 1:
  414. # 如果是仅抠图模式,避免进入到excel模式
  415. params.excel_path = ""
  416. if params.excel_path != "" and params.excel_path != None:
  417. return await fromExcelHandler(params)
  418. path = ""
  419. limit_path = "output/{}".format(
  420. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  421. )
  422. check_path(limit_path)
  423. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  424. move_folder_array = check_move_goods_art_no_folder(
  425. "output", goods_art_no_arrays, limit_path
  426. )
  427. try:
  428. for goods_art_no in goods_art_no_arrays:
  429. if not goods_art_no:
  430. raise UnicornException("货号不能为空")
  431. session = SqlQuery()
  432. pr = CRUD(PhotoRecord)
  433. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  434. if not images:
  435. raise UnicornException(
  436. f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确"
  437. )
  438. if is_only_cutout != 1:
  439. detail_counts = len(params.template_image_order.split(","))
  440. image_counts = len(images)
  441. if image_counts < detail_counts:
  442. raise UnicornException(
  443. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  444. )
  445. if move_folder_array.get(goods_art_no) == None:
  446. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  447. check_path(image_dir)
  448. for idx, itemImg in enumerate(images):
  449. if itemImg.image_path == "" or itemImg.image_path == None:
  450. raise UnicornException(
  451. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  452. )
  453. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  454. if not os.path.exists(
  455. image_dir + "/" + os.path.basename(new_file_name)
  456. ):
  457. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  458. dealImage = DealImage(image_dir)
  459. resFlag, path = dealImage.dealMoveImage(
  460. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  461. )
  462. if not resFlag:
  463. raise UnicornException(path)
  464. except UnicornException as e:
  465. handler_result_folder = ""
  466. handler_result.append(
  467. {"goods_art_no": "", "success": False, "info": str(e.msg)}
  468. )
  469. print(f"UnicornException 生成错误信息:{e}")
  470. await sendAsyncMessage(
  471. msg="处理结束",
  472. data={"output_folder": handler_result_folder, "list": handler_result},
  473. status="处理结束",
  474. msg_type="detail_result_progress",
  475. )
  476. return True
  477. except Exception as e:
  478. print(f"详情图生成错误信息:{e}")
  479. handler_result_folder = ""
  480. handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  481. await sendAsyncMessage(
  482. msg="处理结束",
  483. data={"output_folder": handler_result_folder, "list": handler_result},
  484. status="处理结束",
  485. msg_type="detail_result_progress",
  486. )
  487. return True
  488. # try:
  489. temp_class = {}
  490. temp_name_list = []
  491. for tempItem in params.temp_list:
  492. temp_class[tempItem.template_id] = tempItem.template_local_classes
  493. temp_name_list.append(tempItem.template_id)
  494. cutOutMode = (
  495. "1"
  496. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  497. == "普通抠图"
  498. else "2"
  499. )
  500. config_data = {
  501. "image_dir": limit_path,
  502. "image_order": (
  503. "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  504. if params.template_image_order == None or params.template_image_order == ""
  505. else params.template_image_order
  506. ),
  507. "goods_art_no": "",
  508. "goods_art_nos": goods_art_no_arrays,
  509. "is_check_number": False,
  510. "resize_image_view": "后跟",
  511. "cutout_mode": cutOutMode,
  512. "logo_path": params.logo_path,
  513. "special_goods_art_no_folder_line": "",
  514. "is_use_excel": False, # 是否使用excel
  515. "excel_path": "", # excel路径
  516. "is_check_color_is_all": False,
  517. "cutout_is_pass": True,
  518. "assigned_page_dict": {},
  519. "detail_is_pass": True,
  520. "upload_is_pass": False,
  521. "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  522. "is_filter": False,
  523. "temp_class": temp_class,
  524. "temp_name": params.temp_name,
  525. "temp_name_list": temp_name_list,
  526. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  527. "success_handler": [],
  528. }
  529. print("image_dir=====>>>>>", config_data["image_dir"])
  530. # 动态导入类
  531. temp_class_dict = {}
  532. for key, class_path in config_data["temp_class"].items():
  533. module_path, class_name = class_path.rsplit(".", 1)
  534. module = importlib.import_module(module_path)
  535. cls = getattr(module, class_name)
  536. temp_class_dict[key] = cls
  537. config_data["temp_class"] = temp_class_dict
  538. return_data = run_main.check_before_cutout(config_data)
  539. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  540. check_for_detail_first_res = None
  541. if cutout_res == True:
  542. sys_path = format(os.getcwd()).replace("\\", "/")
  543. handler_result_folder = f"{sys_path}/{limit_path}"
  544. for goods_art_item in goods_art_no_arrays:
  545. handler_result.append(
  546. {
  547. "goods_art_no": goods_art_item,
  548. "success": True,
  549. "info": "处理成功",
  550. }
  551. )
  552. if is_only_cutout == 1:
  553. # return {
  554. # "code": 0,
  555. # "msg": "",
  556. # "data": {"output_folder": handler_result_folder, "list": handler_result},
  557. # }
  558. await sendAsyncMessage(
  559. msg="处理结束",
  560. data={"output_folder": handler_result_folder, "list": handler_result},
  561. status="处理结束",
  562. msg_type="detail_result_progress",
  563. )
  564. return True
  565. try:
  566. if is_product_scene == 1:
  567. if product_scene_prompt == "" or product_scene_prompt == None:
  568. raise UnicornException("请填写场景描述")
  569. if is_upper_footer == 1:
  570. if upper_footer_params == {} or upper_footer_params == None:
  571. raise UnicornException("请选择模特")
  572. man_id = upper_footer_params.get("man_id")
  573. if not man_id:
  574. raise UnicornException("请选择男模特")
  575. women_id = upper_footer_params.get("women_id")
  576. if not women_id:
  577. raise UnicornException("请选择女模特")
  578. return_data_check_before_detail = run_main.check_before_detail(config_data)
  579. print("报错前返回的结果数据", return_data_check_before_detail)
  580. if is_product_scene == 1:
  581. goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  582. new_goods_dict = {}
  583. await sendAsyncMessage(
  584. msg="开始处理场景图",
  585. goods_arts=[goods_art_no for goods_art_no in goods_dict.keys()],
  586. status="开始处理",
  587. msg_type="scene_progress",
  588. )
  589. for goods_art_no in goods_dict.keys():
  590. print("处理场景图", goods_art_no)
  591. goods_art_dict_info = goods_dict[goods_art_no]
  592. first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  593. first_pics = first_goods_art_no_info.get("pics")
  594. ceshi_image_path = first_pics.get("侧视-抠图")
  595. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  596. save_image_path = f"{save_root_path}场景图.jpg"
  597. if os.path.isfile(save_image_path):
  598. goods_art_dict_info["场景图"] = save_image_path
  599. new_goods_dict[goods_art_no] = goods_art_dict_info
  600. continue
  601. aigc_clazz.center_paste_image(ceshi_image_path, save_image_path)
  602. try:
  603. # image_path = aigc_clazz.generateProductScene(
  604. # save_image_path, product_scene_prompt, save_image_path
  605. # )
  606. image_path = aigc_clazz.generateProductSceneQW(
  607. save_image_path, product_scene_prompt, save_image_path
  608. )
  609. goods_art_dict_info["场景图"] = image_path
  610. new_goods_dict[goods_art_no] = goods_art_dict_info
  611. handler_result.append(
  612. {
  613. "goods_art_no": goods_art_no,
  614. "success": True,
  615. "info": "场景图处理成功",
  616. }
  617. )
  618. await sendAsyncMessage(
  619. msg="场景图处理完成",
  620. goods_arts=[goods_art_no],
  621. status="场景图处理完成",
  622. msg_type="scene_progress",
  623. )
  624. except Exception as e:
  625. os.remove(save_image_path)
  626. handler_result.append(
  627. {
  628. "goods_art_no": goods_art_no,
  629. "success": False,
  630. "info": f"场景图处理失败:{e}",
  631. }
  632. )
  633. await sendAsyncMessage(
  634. msg="场景图处理失败",
  635. goods_arts=[goods_art_no],
  636. status="场景图处理失败",
  637. msg_type="scene_progress",
  638. )
  639. if new_goods_dict is not None or new_goods_dict != {}:
  640. return_data_check_before_detail["data"][
  641. "goods_no_dict"
  642. ] = new_goods_dict
  643. if is_upper_footer == 1:
  644. goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  645. new_goods_dict = {}
  646. await sendAsyncMessage(
  647. msg="开始处理模特图",
  648. goods_arts=list(goods_dict.keys()),
  649. status="开始处理模特图",
  650. msg_type="upper_footer_progress",
  651. )
  652. for goods_art_no in goods_dict.keys():
  653. goods_art_dict_info = goods_dict[goods_art_no]
  654. first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  655. first_pics = first_goods_art_no_info.get("pics")
  656. gender = goods_art_dict_info.get("性别")
  657. model_id = man_id if "男" in gender else women_id
  658. ceshi_image_path = first_pics.get("侧视-抠图")
  659. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  660. save_image_path = f"{save_root_path}模特图.jpg"
  661. if os.path.isfile(save_image_path):
  662. goods_art_dict_info["模特图"] = save_image_path
  663. new_goods_dict[goods_art_no] = goods_art_dict_info
  664. continue
  665. shutil.copy(ceshi_image_path, save_image_path)
  666. try:
  667. # image_path = aigc_clazz.generateUpperShoes(
  668. # save_image_path, model_id, save_image_path
  669. # )
  670. image_path = aigc_clazz.generateModelShoesQW(
  671. save_image_path, model_id, save_image_path
  672. )
  673. goods_art_dict_info["模特图"] = image_path
  674. new_goods_dict[goods_art_no] = goods_art_dict_info
  675. handler_result.append(
  676. {
  677. "goods_art_no": goods_art_no,
  678. "success": True,
  679. "info": "模特图处理成功",
  680. }
  681. )
  682. await sendAsyncMessage(
  683. msg="模特图处理成功",
  684. goods_arts=[goods_art_no],
  685. status="模特图处理成功",
  686. msg_type="upper_footer_progress",
  687. )
  688. except Exception as e:
  689. os.remove(save_image_path)
  690. handler_result.append(
  691. {
  692. "goods_art_no": goods_art_no,
  693. "success": False,
  694. "info": f"模特图处理失败:{e}",
  695. }
  696. )
  697. await sendAsyncMessage(
  698. msg="模特图处理失败",
  699. goods_arts=[goods_art_no],
  700. status="模特图处理失败",
  701. msg_type="upper_footer_progress",
  702. )
  703. if new_goods_dict is not None or new_goods_dict != {}:
  704. return_data_check_before_detail["data"][
  705. "goods_no_dict"
  706. ] = new_goods_dict
  707. if is_detail == 0:
  708. # return {
  709. # "code": 0,
  710. # "msg": "",
  711. # "data": {
  712. # "output_folder": handler_result_folder,
  713. # "list": handler_result,
  714. # },
  715. # }
  716. await sendAsyncMessage(
  717. msg="处理结束",
  718. data={"output_folder": handler_result_folder, "list": handler_result},
  719. status="处理结束",
  720. msg_type="detail_result_progress",
  721. )
  722. return True
  723. await sendAsyncMessage(
  724. msg="开始处理详情页",
  725. goods_arts=[],
  726. status="开始处理详情页",
  727. msg_type="detail_progress",
  728. )
  729. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  730. return_data_check_before_detail
  731. )
  732. if isinstance(check_for_detail_first_res, partial):
  733. result = check_for_detail_first_res()
  734. try:
  735. config_data = result["config_data"]
  736. except:
  737. config_data = result
  738. if config_data["sign_text"] == "已结束详情处理":
  739. await sendAsyncMessage(
  740. msg="详情页处理结束",
  741. goods_arts=[],
  742. status="详情页处理结束",
  743. msg_type="detail_progress",
  744. )
  745. print("config_data", config_data)
  746. out_put_dir = config_data.get("out_put_dir")
  747. if out_put_dir == None:
  748. handler_result_folder = ""
  749. if len(config_data["success_handler"]) > 0:
  750. for good_art in config_data["success_handler"]:
  751. handler_result.append(good_art)
  752. else:
  753. for good_art in goods_art_no_arrays:
  754. handler_result.append(
  755. {
  756. "goods_art_no": good_art,
  757. "success": False,
  758. "info": "处理失败",
  759. }
  760. )
  761. else:
  762. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  763. "\\", "/"
  764. )
  765. handler_result_folder = os.path.dirname(out_put_dir_path)
  766. if len(config_data["success_handler"]) == 0:
  767. for good_art in goods_art_no_arrays:
  768. handler_result.append(
  769. {
  770. "goods_art_no": good_art,
  771. "success": False,
  772. "info": "处理失败",
  773. }
  774. )
  775. else:
  776. if len(online_stores) > 0:
  777. result_goods_no_dict = return_data_check_before_detail["data"][
  778. "goods_no_dict"
  779. ]
  780. for goods_idx, goods_no_dict in enumerate(
  781. result_goods_no_dict.keys()
  782. ):
  783. all_detail_path_list = config_data["all_detail_path_list"]
  784. for detail_path in all_detail_path_list:
  785. if goods_no_dict in detail_path:
  786. detail_path_replace = detail_path.replace("\\", "/")
  787. result_goods_no_dict[goods_no_dict][
  788. "detail_path"
  789. ] = f"{detail_path_replace}/详情页.jpg"
  790. await sendAsyncMessage(
  791. msg="开始上传商品数据",
  792. goods_arts=[],
  793. status="开始上传商品数据",
  794. msg_type="upload_goods_progress",
  795. )
  796. try:
  797. onlineData.uploadGoods2ThirdParty(
  798. result_goods_no_dict, online_stores=online_stores
  799. )
  800. except Exception as e:
  801. print(f"上传任务出现错误:{e}")
  802. await sendAsyncMessage(
  803. msg="商品上传第三方成功",
  804. goods_arts=[],
  805. status="商品上传第三方成功",
  806. msg_type="upload_goods_progress",
  807. )
  808. handler_result = config_data["success_handler"]
  809. else:
  810. handler_result.append(
  811. {"goods_art_no": "", "success": False, "info": "处理失败"}
  812. )
  813. except UnicornException as e:
  814. handler_result_folder = ""
  815. handler_result.append(
  816. {"goods_art_no": "", "success": False, "info": str(e.msg)}
  817. )
  818. print(f"UnicornException 生成错误信息:{e}")
  819. except Exception as e:
  820. print(f"详情图生成错误信息:{e}")
  821. handler_result_folder = ""
  822. handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  823. await sendAsyncMessage(
  824. msg="处理结束",
  825. data={"output_folder": handler_result_folder, "list": handler_result},
  826. status="处理结束",
  827. msg_type="detail_result_progress",
  828. )
  829. return True
  830. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  831. def get_device_tabs(type: int):
  832. session = SqlQuery()
  833. statement = (
  834. select(DeviceConfigTabs)
  835. .where(DeviceConfigTabs.mode_type == type)
  836. .order_by(asc("id"))
  837. )
  838. result = session.exec(statement).all()
  839. session.close()
  840. sys = CRUD(SysConfigs)
  841. action_configs = sys.read(session, conditions={"key": "action_configs"})
  842. session.close()
  843. return {
  844. "code": 0,
  845. "msg": "",
  846. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  847. }
  848. @app.post("/update_tab_name", description="更改tab名称")
  849. def update_tab_name(params: DeviceConfigTabsReq):
  850. if params.mode_name == "":
  851. return {"code": 1, "msg": "名称不能为空", "data": {}}
  852. session = SqlQuery()
  853. tabModel = CRUD(DeviceConfigTabs)
  854. kwargs = {"mode_name": params.mode_name}
  855. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  856. session.close()
  857. return {
  858. "code": 0,
  859. "msg": "",
  860. "data": None,
  861. }
  862. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  863. def get_device_configs(params: ModelGetDeviceConfig):
  864. tab_id = params.tab_id
  865. session = SqlQuery()
  866. configModel = CRUD(DeviceConfig)
  867. configList = configModel.read_all(
  868. session,
  869. conditions={"tab_id": tab_id},
  870. order_by="action_index",
  871. ascending=True,
  872. )
  873. return {
  874. "code": 0,
  875. "msg": "",
  876. "data": {"list": configList},
  877. }
  878. @app.post("/device_config_detail", description="获取可执行程序详情")
  879. def device_config_detail(params: ModelGetDeviceConfigDetail):
  880. action_id = params.id
  881. session = SqlQuery()
  882. configModel = CRUD(DeviceConfig)
  883. model = configModel.read(session, conditions={"id": action_id})
  884. if model == None:
  885. return {"code": 1, "msg": "数据不存在", "data": None}
  886. return {"code": 0, "msg": "", "data": model}
  887. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  888. def device_config_detail_query():
  889. # tab_id = params.tab_id
  890. # action_name = params.action_name
  891. session = SqlQuery()
  892. sys = CRUD(SysConfigs)
  893. action_configs = sys.read(session, conditions={"key": "action_configs"})
  894. action_configs_value = json.loads(action_configs.value)
  895. left_config = action_configs_value.get("left")
  896. configModel = CRUD(DeviceConfig)
  897. model = configModel.read(
  898. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  899. )
  900. if model == None:
  901. model = configModel.read(session, conditions={"tab_id": left_config})
  902. return {"code": 0, "msg": "", "data": model}
  903. @app.post("/remove_config", description="删除一条可执行命令")
  904. def get_device_configs(params: ModelGetDeviceConfigDetail):
  905. action_id = params.id
  906. session = SqlQuery()
  907. configModel = CRUD(DeviceConfig)
  908. model = configModel.read(session, conditions={"id": action_id})
  909. if model == None:
  910. return {"code": 1, "msg": "数据不存在", "data": None}
  911. if model.is_system == True:
  912. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  913. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  914. if len(configArray) == 1:
  915. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  916. configModel.delete(session, obj_id=action_id)
  917. return {"code": 0, "msg": "删除成功", "data": None}
  918. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  919. def save_device_config(params: SaveDeviceConfig):
  920. action_id = params.id
  921. session = SqlQuery()
  922. deviceConfig = CRUD(DeviceConfig)
  923. if action_id == None or action_id == 0:
  924. # 走新增逻辑
  925. params.id = None
  926. save_device_config = deviceConfig.create(session, obj_in=params)
  927. else:
  928. model = deviceConfig.read(session, conditions={"id": action_id})
  929. if model == None:
  930. return {"code": 1, "msg": "数据不存在", "data": None}
  931. # 走编辑逻辑
  932. kwargs = params.__dict__
  933. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  934. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  935. @app.post("/reset_config", description="创建或修改一条可执行命令")
  936. def reset_config(params: ModelGetDeviceConfig):
  937. tab_id = params.tab_id
  938. if tab_id == None or tab_id == "":
  939. return {"code": 1, "msg": "参数错误", "data": None}
  940. session = SqlQuery()
  941. deviceConfig = CRUD(DeviceConfig)
  942. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  943. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  944. if res is False:
  945. return {"code": 1, "msg": "操作失败", "data": None}
  946. actions = json.load(open("action.json", encoding="utf-8"))
  947. for data in actions:
  948. data["tab_id"] = tab_id
  949. data["is_system"] = first_config.is_system
  950. device_config = DeviceConfig(**data)
  951. session.add(device_config)
  952. session.commit()
  953. # session.close()
  954. return {"code": 0, "msg": "操作成功", "data": None}
  955. @app.get("/get_photo_records", description="获取拍照记录")
  956. def get_photo_records(page: int = 1, size: int = 5):
  957. session = SqlQuery()
  958. # photos = CRUD(PhotoRecord)
  959. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  960. statement = (
  961. select(PhotoRecord)
  962. .offset((page - 1) * size)
  963. .limit(size)
  964. .order_by(desc("id"))
  965. .group_by("goods_art_no")
  966. )
  967. list = []
  968. result = session.exec(statement).all()
  969. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  970. join_conditions = [
  971. {
  972. "model": DeviceConfig,
  973. "on": PhotoRecord.action_id == DeviceConfig.id,
  974. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  975. }
  976. ]
  977. for item in result:
  978. query = (
  979. select(PhotoRecord, DeviceConfig.action_name)
  980. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  981. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  982. )
  983. list_item = session.exec(query).mappings().all()
  984. list.append(
  985. {
  986. "goods_art_no": item.goods_art_no,
  987. "action_time": item.create_time,
  988. "items": list_item,
  989. }
  990. )
  991. # session.close()
  992. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  993. return {
  994. "code": 0,
  995. "msg": "",
  996. "data": {"list": list, "page": page, "size": size},
  997. }
  998. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  999. def get_last_photo_record():
  1000. session = SqlQuery()
  1001. statement = (
  1002. select(PhotoRecord)
  1003. .where(PhotoRecord.image_path != None)
  1004. .order_by(desc("photo_create_time"))
  1005. )
  1006. result = session.exec(statement).first()
  1007. # session.close()
  1008. return {
  1009. "code": 0,
  1010. "msg": "",
  1011. "data": result,
  1012. }
  1013. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  1014. def get_photo_record_detail(goods_art_no: str = None):
  1015. if goods_art_no == None:
  1016. return {"code": 1, "msg": "参数错误", "data": None}
  1017. session = SqlQuery()
  1018. photos = CRUD(PhotoRecord)
  1019. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  1020. # session.close()
  1021. return {
  1022. "code": 0,
  1023. "msg": "",
  1024. "data": {"list": items},
  1025. }
  1026. @app.post("/delect_goods_arts", description="通过货号删除记录")
  1027. def delect_goods_arts(params: PhotoRecordDelete):
  1028. session = SqlQuery()
  1029. photos = CRUD(PhotoRecord)
  1030. for item in params.goods_art_nos:
  1031. photos.deleteConditions(session, conditions={"goods_art_no": item})
  1032. # session.close()
  1033. return {
  1034. "code": 0,
  1035. "msg": "操作成功",
  1036. "data": None,
  1037. }
  1038. def query_config_by_key(key_name):
  1039. """
  1040. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  1041. Args:
  1042. key_name (str): 要查询的key名称
  1043. Returns:
  1044. dict or None: 匹配的对象或None(如果没有找到)
  1045. """
  1046. try:
  1047. # 获取所有配置数据
  1048. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  1049. # 遍历配置数据查找匹配的key
  1050. for config in configs:
  1051. if config.get("key") == key_name:
  1052. return config
  1053. return None
  1054. except Exception as e:
  1055. print(f"查询配置时出错: {e}")
  1056. return None
  1057. @app.get("/get_sys_config", description="查询系统配置")
  1058. def get_sys_config(key: str = None):
  1059. if key == None:
  1060. return {"code": 1, "msg": "参数错误", "data": None}
  1061. session = SqlQuery()
  1062. photos = CRUD(SysConfigs)
  1063. item = photos.read(session, conditions={"key": key})
  1064. search_data = None if item == None else json.loads(item.value)
  1065. if search_data == None:
  1066. sys_config_json = query_config_by_key(key)
  1067. if sys_config_json != None:
  1068. config = SysConfigs(**sys_config_json)
  1069. session.add(config)
  1070. session.commit() # 合并事务提交
  1071. search_data = json.loads(sys_config_json.get("value"))
  1072. return {
  1073. "code": 0,
  1074. "msg": "",
  1075. "data": search_data,
  1076. }
  1077. @app.post("/update_left_right_config", description="更新左右脚配置")
  1078. def update_left_right_config(params: LeftRightParams):
  1079. session = SqlQuery()
  1080. sysConfig = CRUD(SysConfigs)
  1081. model = sysConfig.read(session, conditions={"key": "action_configs"})
  1082. if model == None:
  1083. return {"code": 1, "msg": "配置不存在", "data": None}
  1084. config_value = json.loads(model.value)
  1085. config_value[params.type] = params.id
  1086. update_value = json.dumps(config_value)
  1087. # 走编辑逻辑
  1088. kwargs = {"key": "action_configs", "value": update_value}
  1089. save_device_config = sysConfig.updateConditions(
  1090. session, conditions={"key": "action_configs"}, **kwargs
  1091. )
  1092. return {"code": 0, "msg": "操作成功", "data": None}
  1093. @app.post("/update_record", description="更新拍照记录")
  1094. def update_record(params: RecordUpdate):
  1095. session = SqlQuery()
  1096. photoRecord = CRUD(PhotoRecord)
  1097. model = photoRecord.read(session, conditions={"id": params.id})
  1098. if model == None:
  1099. return {"code": 1, "msg": "记录不存在", "data": None}
  1100. kwargs = params.__dict__
  1101. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  1102. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  1103. @app.post("/update_sys_configs", description="创建或修改系统配置")
  1104. def save_sys_configs(params: SysConfigParams):
  1105. session = SqlQuery()
  1106. sysConfig = CRUD(SysConfigs)
  1107. model = sysConfig.read(session, conditions={"key": params.key})
  1108. if model == None:
  1109. return {"code": 1, "msg": "配置不存在", "data": None}
  1110. # 走编辑逻辑
  1111. kwargs = params.__dict__
  1112. save_device_config = sysConfig.updateConditions(
  1113. session, conditions={"key": params.key}, **kwargs
  1114. )
  1115. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  1116. @app.post("/create_main_image", description="创建主图测试")
  1117. def create_main_image(params: MaineImageTest):
  1118. file_path = params.file_path
  1119. onePic = OnePicTest(pic_path=file_path)
  1120. main_out_path = onePic.HandlerMainImage()
  1121. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  1122. def insertEmptyLogoList(session):
  1123. """插入空logo列表"""
  1124. data = {"key": "logo_configs", "value": "[]"}
  1125. config = SysConfigs(**data)
  1126. session.add(config)
  1127. session.commit()
  1128. session.close()
  1129. item = SysConfigs()
  1130. item.key = "logo_configs"
  1131. item.value = "[]"
  1132. return item
  1133. @app.get("/logo_list", description="logo列表")
  1134. def logo_list():
  1135. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  1136. check_path(logo_dir)
  1137. logo_files = os.listdir(logo_dir)
  1138. logo_list = []
  1139. for logoItem in logo_files:
  1140. logo_list.append(f"{logo_dir}{logoItem}")
  1141. return {"code": 0, "msg": "操作成功", "data": logo_list}
  1142. @app.post("/add_logo", description="添加logo")
  1143. def add_logo(params: LogoParams):
  1144. logo_path = params.logo_path.replace("\\", "/")
  1145. session = SqlQuery()
  1146. sysConfig = CRUD(SysConfigs)
  1147. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  1148. if item == None:
  1149. item = insertEmptyLogoList(session)
  1150. if os.path.isfile(logo_path) == False:
  1151. return {"code": 1, "msg": "logo文件不存在", "data": None}
  1152. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  1153. check_path(logo_dir)
  1154. fpath, fname = os.path.split(logo_path)
  1155. logo_path_info = logo_dir + fname
  1156. shutil.copy(logo_path, logo_path_info) # 复制文件
  1157. logo_files = os.listdir(logo_dir)
  1158. logo_list = []
  1159. for logoItem in logo_files:
  1160. logo_list.append(f"{logo_dir}{logoItem}")
  1161. return {
  1162. "code": 0,
  1163. "msg": "",
  1164. "data": {"logo": logo_path_info},
  1165. }
  1166. @app.post("/delete_logo", description="删除logo")
  1167. def delete_logo(params: LogoParamsupdate):
  1168. logo_path = params.path
  1169. if os.path.isfile(logo_path) == False:
  1170. return {"code": 1, "msg": "logo文件不存在", "data": None}
  1171. os.remove(logo_path)
  1172. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  1173. check_path(logo_dir)
  1174. logo_files = os.listdir(logo_dir)
  1175. logo_list = []
  1176. for logoItem in logo_files:
  1177. logo_list.append(f"{logo_dir}{logoItem}")
  1178. return {"code": 0, "msg": "操作成功", "data": logo_list}
  1179. @app.post("/close_other_window", description="关闭窗口")
  1180. def close_other_window():
  1181. hwnd_list = []
  1182. def callback(hwnd, _):
  1183. title = GetWindowText(hwnd)
  1184. if title == "digiCamControl by Duka Istvan":
  1185. hwnd_list.append(hwnd)
  1186. EnumWindows(callback, None)
  1187. if hwnd_list:
  1188. hwnd = hwnd_list[0]
  1189. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  1190. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  1191. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}
  1192. def syncUserJsonConfigs(token):
  1193. hlm_token = token
  1194. headers = {
  1195. "Authorization": f"Bearer {hlm_token}",
  1196. "content-type": "application/json",
  1197. }
  1198. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_configs"
  1199. result = requests.get(url=url, headers=headers)
  1200. sys_configs = result.json().get("data", {}).get("configs")
  1201. session = SqlQuery()
  1202. sysConfigs = CRUD(SysConfigs)
  1203. if sys_configs:
  1204. sysConfigs.deleteConditions(session, {})
  1205. configList = []
  1206. for config_keys in sys_configs.keys():
  1207. sys_configs[config_keys]
  1208. configList.append(
  1209. {
  1210. "key": config_keys,
  1211. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  1212. }
  1213. )
  1214. batch_insert_sys_configs(session, configList)
  1215. @app.post("/sync_sys_configs", description="同步线上配置到本地")
  1216. def sync_sys_configs(params: SyncLocalConfigs):
  1217. hlm_token = params.token
  1218. headers = {
  1219. "Authorization": f"Bearer {hlm_token}",
  1220. "content-type": "application/json",
  1221. }
  1222. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_configs"
  1223. result = requests.get(url=url, headers=headers)
  1224. sys_configs = result.json().get("data", {}).get("configs")
  1225. session = SqlQuery()
  1226. sysConfigs = CRUD(SysConfigs)
  1227. if sys_configs:
  1228. sysConfigs.deleteConditions(session, {})
  1229. configList = []
  1230. for config_keys in sys_configs.keys():
  1231. sys_configs[config_keys]
  1232. configList.append(
  1233. {
  1234. "key": config_keys,
  1235. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  1236. }
  1237. )
  1238. batch_insert_sys_configs(session, configList)
  1239. else:
  1240. all_configs = sysConfigs.read_all(session)
  1241. localConfigData = {}
  1242. for local_config in all_configs:
  1243. localConfigData[local_config.key] = json.loads(local_config.value)
  1244. data_json = json.dumps({"configs": localConfigData}, ensure_ascii=False)
  1245. # 同步本地到线上
  1246. url = settings.DOMAIN + "/api/ai_image/camera_machine/update_all_user_configs"
  1247. requests.post(url=url, headers=headers, data=data_json)
  1248. return {"code": 0, "msg": "操作成功", "data": None}
  1249. @app.post("/sync_actions", description="同步左右脚配置到本地")
  1250. def sync_action_configs(params: SyncLocalConfigs):
  1251. hlm_token = params.token
  1252. headers = {
  1253. "Authorization": f"Bearer {hlm_token}",
  1254. "content-type": "application/json",
  1255. }
  1256. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_tabs"
  1257. result = requests.get(url=url, headers=headers)
  1258. session = SqlQuery()
  1259. deviceConfigs = CRUD(DeviceConfig)
  1260. deviceConfigTabs = CRUD(DeviceConfigTabs)
  1261. tabs = result.json().get("data", {}).get("tabs")
  1262. actions = result.json().get("data", {}).get("actions")
  1263. if tabs:
  1264. # 先删除再创建
  1265. deviceConfigTabs.deleteConditions(session, {})
  1266. deviceConfigs.deleteConditions(session, {})
  1267. batch_insert_device_configsNew(session, tabs, actions)
  1268. else:
  1269. all_actions = deviceConfigs.read_all(session)
  1270. all_tabs = deviceConfigTabs.read_all(session)
  1271. all_tabs_json = [item.model_dump(mode='json') for item in all_tabs]
  1272. all_actions_json = [item.model_dump(mode="json") for item in all_actions]
  1273. data_json = json.dumps(
  1274. {"tabs": all_tabs_json, "actions": all_actions_json}, ensure_ascii=False
  1275. )
  1276. sync_url = settings.DOMAIN + "/api/ai_image/camera_machine/sync_actions"
  1277. result = requests.post(url=sync_url, headers=headers, data=data_json)
  1278. tabs = result.json().get("data", {}).get("tabs")
  1279. actions = result.json().get("data", {}).get("actions")
  1280. if tabs:
  1281. deviceConfigTabs.deleteConditions(session, {})
  1282. deviceConfigs.deleteConditions(session, {})
  1283. batch_insert_device_configsNew(session, tabs, actions)
  1284. #因为左右脚线上id可能会发生变化 所以需要重新同步一下本地得配置信息
  1285. syncUserJsonConfigs(hlm_token)
  1286. return {"code": 0, "msg": "操作成功", "data": None}