api.py 78 KB

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