api.py 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405
  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. def __createExcelGoodsArray(excel_path):
  126. '''创建通过excel形式得货号组数据'''
  127. excel_df = pd.read_excel(excel_path, sheet_name=0, header=0)
  128. if "文件夹名称" not in excel_df.columns:
  129. raise UnicornException("缺失 [文件夹名称] 列")
  130. if "商品货号" not in excel_df.columns:
  131. raise UnicornException("缺失 [商品货号] 列")
  132. if "款号" not in excel_df.columns:
  133. raise UnicornException("缺失 [款号] 列")
  134. goods_art_dirs = excel_df.groupby(excel_df["款号"])
  135. # 抠图时用到的货号列表,与生成详情图有所区别
  136. goods_art_no_arrays = []
  137. # # 详情图生成需要对同款商品进行分组,保证详情图可以生成多个色
  138. goods_art_no_group_arrays = []
  139. for _, goods_row in excel_df.iterrows():
  140. goods_art_no = str(goods_row["商品货号"])
  141. goods_art_no_arrays.append(goods_art_no)
  142. goods_no = str(goods_row["款号"])
  143. a001_df = goods_art_dirs.get_group(goods_no)
  144. goods_art_groups = a001_df["商品货号"].tolist()
  145. if goods_art_groups in goods_art_no_group_arrays:
  146. continue
  147. goods_art_no_group_arrays.append(goods_art_groups)
  148. return goods_art_no_arrays,excel_df,goods_art_no_group_arrays
  149. # async def fromExcelHandler(params: HandlerDetail):
  150. # obj = None
  151. # excel_path = params.excel_path
  152. # token = "Bearer " + params.token
  153. # uuid = params.uuid
  154. # aigc_clazz = AIGCDataRequest(token)
  155. # run_main = RunMain(obj, token, uuid)
  156. # onlineData = OnlineDataRequest(token)
  157. # online_stores = params.online_stores # 上传第三方的店铺名称数组
  158. # is_product_scene = params.is_product_scene # 上传第三方的店铺名称数组
  159. # is_upper_footer = params.is_upper_footer # 上传第三方的店铺名称数组
  160. # upper_footer_params = params.upper_footer_params # 上传第三方的店铺名称数组
  161. # product_scene_prompt = params.product_scene_prompt # 上传第三方的店铺名称数组
  162. # handler_result = []
  163. # handler_result_folder = ""
  164. # goods_art_no_arrays,excel_df,_ = __createExcelGoodsArray(excel_path)
  165. # limit_path = "output/{}".format(
  166. # time.strftime("%Y-%m-%d", time.localtime(time.time()))
  167. # )
  168. # # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  169. # move_folder_array = check_move_goods_art_no_folder(
  170. # "output", goods_art_no_arrays, limit_path
  171. # )
  172. # try:
  173. # for index, row in excel_df.iterrows():
  174. # goods_art_no_image_dir = str(row["文件夹名称"])
  175. # goods_art_no = str(row["商品货号"])
  176. # print("货号数据", goods_art_no)
  177. # if not goods_art_no:
  178. # raise UnicornException("货号不能为空")
  179. # session = SqlQuery()
  180. # pr = CRUD(PhotoRecord)
  181. # images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  182. # if not images:
  183. # raise UnicornException(
  184. # f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确"
  185. # )
  186. # # 货号目录不存在再去进行移动和创建操作
  187. # if move_folder_array.get(goods_art_no) == None:
  188. # image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  189. # check_path(image_dir)
  190. # for idx, itemImg in enumerate(images):
  191. # if itemImg.image_path == "" or itemImg.image_path == None:
  192. # raise UnicornException(
  193. # f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  194. # )
  195. # new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  196. # if not os.path.exists(
  197. # image_dir + "/" + os.path.basename(new_file_name)
  198. # ):
  199. # shutil.copy(itemImg.image_path, image_dir + new_file_name)
  200. # dealImage = DealImage(image_dir)
  201. # resFlag, path = dealImage.dealMoveImage(
  202. # image_dir=image_dir,
  203. # callback_func=None,
  204. # goods_art_no=goods_art_no_image_dir,
  205. # )
  206. # if not resFlag:
  207. # raise UnicornException(path)
  208. # shutil.rmtree(image_dir)
  209. # # path = os.path.dirname(path)
  210. # except UnicornException as e:
  211. # handler_result_folder = ""
  212. # handler_result.append(
  213. # {"goods_art_no": "", "success": False, "info": str(e.msg)}
  214. # )
  215. # print(f"UnicornException 生成错误信息:{e}")
  216. # await sendAsyncMessage(
  217. # msg="处理结束",
  218. # data={"output_folder": handler_result_folder, "list": handler_result},
  219. # status="处理结束",
  220. # msg_type="detail_result_progress",
  221. # )
  222. # return True
  223. # except Exception as e:
  224. # print(f"详情图生成错误信息:{e}")
  225. # handler_result_folder = ""
  226. # handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  227. # await sendAsyncMessage(
  228. # msg="处理结束",
  229. # data={"output_folder": handler_result_folder, "list": handler_result},
  230. # status="处理结束",
  231. # msg_type="detail_result_progress",
  232. # )
  233. # return True
  234. # temp_class = {}
  235. # # 可用模板列表-需要导包
  236. # temp_name_list = []
  237. # for tempItem in params.temp_list:
  238. # temp_class[tempItem.template_id] = tempItem.template_local_classes
  239. # temp_name_list.append(tempItem.template_id)
  240. # cutOutMode = (
  241. # "0"
  242. # if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  243. # == "普通抠图"
  244. # else "1"
  245. # )
  246. # config_data = {
  247. # "image_dir": limit_path, # 这个目录作为本次生成的图片目录非常重要 例:./output/当前日期
  248. # "image_order": (
  249. # "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  250. # if params.template_image_order == None or params.template_image_order == ""
  251. # else params.template_image_order
  252. # ),
  253. # "goods_art_no": goods_art_no,
  254. # "goods_art_nos": goods_art_no_arrays,
  255. # "is_check_number": False,
  256. # "resize_image_view": "后跟",
  257. # "cutout_mode": cutOutMode,
  258. # "logo_path": params.logo_path,
  259. # "special_goods_art_no_folder_line": "",
  260. # "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  261. # "excel_path": params.excel_path, # excel路径
  262. # "is_check_color_is_all": False,
  263. # "cutout_is_pass": True,
  264. # "assigned_page_dict": {},
  265. # "detail_is_pass": True,
  266. # "upload_is_pass": False,
  267. # "upload_is_enable": False,
  268. # "is_filter": False,
  269. # "temp_class": temp_class,
  270. # "temp_name": params.temp_name,
  271. # "temp_name_list": temp_name_list,
  272. # "target_error_folder": f"{limit_path}/软件-生成详情错误",
  273. # "success_handler": [],
  274. # }
  275. # # 动态导入类
  276. # temp_class_dict = {}
  277. # for key, class_path in config_data["temp_class"].items():
  278. # module_path, class_name = class_path.rsplit(".", 1)
  279. # module = importlib.import_module(module_path)
  280. # cls = getattr(module, class_name)
  281. # temp_class_dict[key] = cls
  282. # config_data["temp_class"] = temp_class_dict
  283. # # executor = ThreadPoolExecutor(max_workers=4)
  284. # # 此处对抠图进行批量处理,保证所有的图片在生成详情图之前已经完成抠图,以保证详情图生成的效率
  285. # return_data = run_main.check_before_cutout(config_data)
  286. # cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  287. # check_for_detail_first_res = None
  288. # if cutout_res == True:
  289. # sys_path = format(os.getcwd()).replace("\\", "/")
  290. # handler_result_folder = f"{sys_path}/{limit_path}"
  291. # for goods_art_item in goods_art_no_arrays:
  292. # handler_result.append(
  293. # {
  294. # "goods_art_no": goods_art_item,
  295. # "success": True,
  296. # "info": "处理成功",
  297. # }
  298. # )
  299. # if len(move_folder_array.keys()) == len(goods_art_no_arrays):
  300. # progress = {"status":"处理完成",
  301. # "current":len(goods_art_no_arrays),
  302. # "total":len(goods_art_no_arrays),
  303. # "error":0
  304. # }
  305. # await sendAsyncMessage(
  306. # msg="抠图完成",
  307. # data={"output_folder": handler_result_folder, "list": handler_result},
  308. # status="抠图完成",
  309. # msg_type="segment_progress",
  310. # progress=progress
  311. # )
  312. # try:
  313. # if is_product_scene == 1:
  314. # if product_scene_prompt == "" or product_scene_prompt == None:
  315. # raise UnicornException("请填写场景描述")
  316. # if is_upper_footer == 1:
  317. # if upper_footer_params == {} or upper_footer_params == None:
  318. # raise UnicornException("请选择模特")
  319. # man_id = upper_footer_params.get("man_id")
  320. # if not man_id:
  321. # raise UnicornException("请选择男模特")
  322. # women_id = upper_footer_params.get("women_id")
  323. # if not women_id:
  324. # raise UnicornException("请选择女模特")
  325. # return_data_check_before_detail = run_main.check_before_detail(config_data)
  326. # print("报错前返回的结果数据", return_data_check_before_detail)
  327. # success_handler = return_data_check_before_detail.get("data").get("config_data").get("success_handler",[])
  328. # failed_items = [item for item in success_handler if item.get('success') == False]
  329. # print("failed_items",failed_items)
  330. # if len(failed_items) > 0:
  331. # await sendAsyncMessage(
  332. # msg="处理结束",
  333. # data={"output_folder": handler_result_folder, "list": failed_items},
  334. # status="处理结束",
  335. # msg_type="detail_result_progress",
  336. # )
  337. # if len(failed_items)!=0 and len(failed_items) == len(success_handler):
  338. # # 如果全部错误 直接终止
  339. # return True
  340. # else:
  341. # if is_product_scene == 1:
  342. # goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  343. # new_goods_dict = {}
  344. # product_scene_total_progress = len(goods_dict.keys())
  345. # product_scene_finish_progress = 0
  346. # product_scene_error_progress = 0
  347. # product_scene_progress = {"status":"正在处理", "current":product_scene_finish_progress, "total":product_scene_total_progress, "error":product_scene_error_progress}
  348. # print("product_scene_progress",goods_dict,product_scene_progress)
  349. # await sendAsyncMessage(
  350. # msg="开始处理场景图",
  351. # goods_arts=[goods_art_no for goods_art_no in goods_dict.keys()],
  352. # status="开始处理",
  353. # msg_type="scene_progress",
  354. # progress=product_scene_progress
  355. # )
  356. # for goods_art_no in goods_dict.keys():
  357. # print("处理场景图", goods_art_no)
  358. # product_scene_finish_progress+=1
  359. # 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}
  360. # await sendAsyncMessage(
  361. # msg="正在处理场景图",
  362. # goods_arts=[goods_art_no],
  363. # status="正在处理场景图",
  364. # msg_type="scene_progress",
  365. # progress=product_scene_progress
  366. # )
  367. # goods_art_dict_info = goods_dict[goods_art_no]
  368. # first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  369. # first_pics = first_goods_art_no_info.get("pics")
  370. # ceshi_image_path = first_pics.get("侧视-抠图")
  371. # save_root_path = ceshi_image_path.split("阴影图处理")[0]
  372. # save_image_path = f"{save_root_path}场景图.jpg"
  373. # if os.path.isfile(save_image_path):
  374. # goods_art_dict_info["场景图"] = save_image_path
  375. # new_goods_dict[goods_art_no] = goods_art_dict_info
  376. # continue
  377. # aigc_clazz.center_paste_image(ceshi_image_path, save_image_path)
  378. # try:
  379. # image_path = aigc_clazz.generateProductScene(
  380. # save_image_path, product_scene_prompt, save_image_path
  381. # )
  382. # # image_path = aigc_clazz.generateProductSceneQW(
  383. # # save_image_path, product_scene_prompt, save_image_path
  384. # # )
  385. # goods_art_dict_info["场景图"] = image_path
  386. # new_goods_dict[goods_art_no] = goods_art_dict_info
  387. # handler_result.append(
  388. # {
  389. # "goods_art_no": goods_art_no,
  390. # "success": True,
  391. # "info": "场景图处理成功",
  392. # }
  393. # )
  394. # product_scene_progress = {
  395. # "status":"处理成功",
  396. # "current":product_scene_finish_progress,
  397. # "total":product_scene_total_progress,
  398. # "error":product_scene_error_progress,
  399. # "goods_art_no":goods_art_no,
  400. # }
  401. # await sendAsyncMessage(
  402. # msg="场景图处理完成",
  403. # goods_arts=[goods_art_no],
  404. # status="场景图处理完成",
  405. # msg_type="scene_progress",
  406. # progress=product_scene_progress
  407. # )
  408. # except Exception as e:
  409. # os.remove(save_image_path)
  410. # handler_result.append(
  411. # {
  412. # "goods_art_no": goods_art_no,
  413. # "success": False,
  414. # "info": f"场景图处理失败:{e}",
  415. # }
  416. # )
  417. # product_scene_finish_progress -=1
  418. # product_scene_error_progress +=1
  419. # 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}
  420. # await sendAsyncMessage(
  421. # msg="场景图处理失败",
  422. # goods_arts=[goods_art_no],
  423. # status="场景图处理失败",
  424. # msg_type="scene_progress",
  425. # progress=product_scene_progress
  426. # )
  427. # product_scene_progress = {"status":"处理完成", "current":product_scene_finish_progress, "total":product_scene_total_progress, "error":product_scene_error_progress}
  428. # await sendAsyncMessage(
  429. # msg="场景图处理结束",
  430. # goods_arts=[],
  431. # status="场景图处理结束",
  432. # msg_type="scene_progress",
  433. # progress=product_scene_progress
  434. # )
  435. # if new_goods_dict is not None or new_goods_dict != {}:
  436. # return_data_check_before_detail["data"][
  437. # "goods_no_dict"
  438. # ] = new_goods_dict
  439. # if is_upper_footer == 1:
  440. # goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  441. # new_goods_dict = {}
  442. # upper_footer_total_progress = len(goods_dict.keys())
  443. # upper_footer_finish_progress = 0
  444. # upper_footer_error_progress = 0
  445. # upper_footer_progress = {"status":"正在处理", "current":upper_footer_finish_progress, "total":upper_footer_total_progress, "error":upper_footer_error_progress}
  446. # await sendAsyncMessage(
  447. # msg="开始处理模特图",
  448. # goods_arts=list(goods_dict.keys()),
  449. # status="开始处理模特图",
  450. # msg_type="upper_footer_progress",
  451. # progress=upper_footer_progress
  452. # )
  453. # for goods_art_no in goods_dict.keys():
  454. # upper_footer_finish_progress+=1
  455. # 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}
  456. # await sendAsyncMessage(
  457. # msg="正在处理模特图",
  458. # goods_arts=[goods_art_no],
  459. # status="正在处理模特图",
  460. # msg_type="upper_footer_progress",
  461. # progress=upper_footer_progress
  462. # )
  463. # goods_art_dict_info = goods_dict[goods_art_no]
  464. # first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  465. # first_pics = first_goods_art_no_info.get("pics")
  466. # gender = goods_art_dict_info.get("性别")
  467. # model_id = man_id if "男" in gender else women_id
  468. # ceshi_image_path = first_pics.get("侧视-抠图")
  469. # save_root_path = ceshi_image_path.split("阴影图处理")[0]
  470. # save_image_path = f"{save_root_path}模特图.jpg"
  471. # if os.path.isfile(save_image_path):
  472. # goods_art_dict_info["模特图"] = save_image_path
  473. # new_goods_dict[goods_art_no] = goods_art_dict_info
  474. # continue
  475. # shutil.copy(ceshi_image_path, save_image_path)
  476. # try:
  477. # image_path = aigc_clazz.generateUpperShoes(
  478. # save_image_path, model_id, save_image_path
  479. # )
  480. # # image_path = aigc_clazz.generateModelShoesQW(
  481. # # save_image_path, model_id, save_image_path
  482. # # )
  483. # goods_art_dict_info["模特图"] = image_path
  484. # new_goods_dict[goods_art_no] = goods_art_dict_info
  485. # handler_result.append(
  486. # {
  487. # "goods_art_no": goods_art_no,
  488. # "success": True,
  489. # "info": "模特图处理成功",
  490. # }
  491. # )
  492. # 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}
  493. # await sendAsyncMessage(
  494. # msg="模特图处理成功",
  495. # goods_arts=[goods_art_no],
  496. # status="模特图处理成功",
  497. # msg_type="upper_footer_progress",
  498. # progress=upper_footer_progress
  499. # )
  500. # except Exception as e:
  501. # os.remove(save_image_path)
  502. # handler_result.append(
  503. # {
  504. # "goods_art_no": goods_art_no,
  505. # "success": False,
  506. # "info": f"模特图处理失败:{e}",
  507. # }
  508. # )
  509. # upper_footer_error_progress+=1
  510. # 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}
  511. # await sendAsyncMessage(
  512. # msg="模特图处理失败",
  513. # goods_arts=[goods_art_no],
  514. # status="模特图处理失败",
  515. # msg_type="upper_footer_progress",
  516. # progress=upper_footer_progress
  517. # )
  518. # upper_footer_progress = {"status":"处理完成", "current":upper_footer_finish_progress, "total":upper_footer_total_progress, "error":upper_footer_error_progress}
  519. # await sendAsyncMessage(
  520. # msg="模特图处理结束",
  521. # goods_arts=[],
  522. # status="模特图处理结束",
  523. # msg_type="upper_footer_progress",
  524. # progress=upper_footer_progress
  525. # )
  526. # if new_goods_dict is not None or new_goods_dict != {}:
  527. # return_data_check_before_detail["data"][
  528. # "goods_no_dict"
  529. # ] = new_goods_dict
  530. # check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  531. # return_data_check_before_detail
  532. # )
  533. # if isinstance(check_for_detail_first_res, partial):
  534. # result = check_for_detail_first_res()
  535. # try:
  536. # config_data = result["config_data"]
  537. # except:
  538. # config_data = result
  539. # if config_data["sign_text"] == "已结束详情处理":
  540. # await sendAsyncMessage(
  541. # msg="详情页处理结束",
  542. # goods_arts=[],
  543. # status="详情页处理结束",
  544. # msg_type="detail_progress",
  545. # )
  546. # print("config_data", config_data)
  547. # out_put_dir = config_data.get("out_put_dir")
  548. # if out_put_dir == None:
  549. # handler_result_folder = ""
  550. # if len(config_data["success_handler"]) > 0:
  551. # for good_art in config_data["success_handler"]:
  552. # handler_result.append(good_art)
  553. # else:
  554. # for good_art in goods_art_no_arrays:
  555. # handler_result.append(
  556. # {
  557. # "goods_art_no": good_art,
  558. # "success": False,
  559. # "info": "处理失败",
  560. # }
  561. # )
  562. # else:
  563. # out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  564. # "\\", "/"
  565. # )
  566. # handler_result_folder = os.path.dirname(out_put_dir_path)
  567. # if len(config_data["success_handler"]) == 0:
  568. # for good_art in goods_art_no_arrays:
  569. # handler_result.append(
  570. # {
  571. # "goods_art_no": good_art,
  572. # "success": False,
  573. # "info": "处理失败",
  574. # }
  575. # )
  576. # else:
  577. # if len(online_stores) > 0:
  578. # result_goods_no_dict = return_data_check_before_detail["data"][
  579. # "goods_no_dict"
  580. # ]
  581. # for goods_idx, goods_no_dict in enumerate(
  582. # result_goods_no_dict.keys()
  583. # ):
  584. # all_detail_path_list = config_data["all_detail_path_list"]
  585. # for detail_path in all_detail_path_list:
  586. # if goods_no_dict in detail_path:
  587. # detail_path_replace = detail_path.replace("\\", "/")
  588. # result_goods_no_dict[goods_no_dict][
  589. # "detail_path"
  590. # ] = f"{detail_path_replace}/详情页.jpg"
  591. # await sendAsyncMessage(
  592. # msg="开始上传商品数据",
  593. # goods_arts=[],
  594. # status="开始上传商品数据",
  595. # msg_type="upload_goods_progress",
  596. # )
  597. # try:
  598. # onlineData.uploadGoods2ThirdParty(
  599. # result_goods_no_dict, online_stores=online_stores
  600. # )
  601. # except Exception as e:
  602. # print(f"上传任务出现错误:{e}")
  603. # await sendAsyncMessage(
  604. # msg="商品上传第三方成功",
  605. # goods_arts=[],
  606. # status="商品上传第三方成功",
  607. # msg_type="upload_goods_progress",
  608. # )
  609. # handler_result = config_data["success_handler"]
  610. # else:
  611. # for good_art in goods_art_no_arrays:
  612. # handler_result.append(
  613. # {"goods_art_no": good_art, "success": False, "info": "处理失败"}
  614. # )
  615. # except UnicornException as e:
  616. # handler_result_folder = ""
  617. # handler_result.append(
  618. # {"goods_art_no": "", "success": False, "info": str(e.msg)}
  619. # )
  620. # print(f"UnicornException 生成错误信息:{e}")
  621. # except Exception as e:
  622. # for good_art in goods_art_no_arrays:
  623. # handler_result.append(
  624. # {"goods_art_no": good_art, "success": False, "info": str(e)}
  625. # )
  626. # handler_result_folder = "/".join(handler_result_folder.split("/")[:-1])
  627. # await sendAsyncMessage(
  628. # msg="处理结束",
  629. # data={"output_folder": handler_result_folder, "list": handler_result},
  630. # status="处理结束",
  631. # msg_type="detail_result_progress",
  632. # )
  633. # return True
  634. def group_by_style_number(data):
  635. result = {}
  636. for goods_id, info in data.items():
  637. style_number = info["款号"]
  638. if style_number not in result:
  639. result[style_number] = []
  640. result[style_number].append(goods_id)
  641. return result
  642. @app.post("/handle_detail")
  643. async def handle_detail_background(
  644. request: Request, params: HandlerDetail, background_tasks: BackgroundTasks
  645. ):
  646. goods_art_no_arrays = params.goods_art_no
  647. is_check = params.is_check
  648. obj = None
  649. token = "Bearer " + params.token
  650. uuid = params.uuid
  651. run_main = RunMain(obj, token, uuid)
  652. online_stores = params.online_stores # 上传第三方的店铺名称数组
  653. is_detail = params.is_detail # 上传第三方的店铺名称数组
  654. is_product_scene = params.is_product_scene # 上传第三方的店铺名称数组
  655. is_upper_footer = params.is_upper_footer # 上传第三方的店铺名称数组
  656. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  657. try:
  658. excel_path = params.excel_path.strip()
  659. print("excel信息打印输出:",excel_path)
  660. if excel_path:
  661. goods_art_no_arrays,excel_df,_ = __createExcelGoodsArray(excel_path)
  662. await _process_excel_mode(
  663. goods_art_no_arrays, excel_df
  664. )
  665. else:
  666. await _process_non_excel_mode(
  667. params, goods_art_no_arrays
  668. )
  669. remote_data = run_main.data_mode_generate_detail.get_goods_art_no_info(goods_art_list=goods_art_no_arrays)
  670. if remote_data == {}:
  671. raise UnicornException("所有货号在商品档案资料中不存在,请检查货号是否正确")
  672. error_goods_art_no = []
  673. for goods_art_no_check in goods_art_no_arrays:
  674. check_item = remote_data.get(goods_art_no_check,None)
  675. if not check_item:
  676. error_goods_art_no.append(goods_art_no_check)
  677. if len(error_goods_art_no) > 0:
  678. raise UnicornException("以下货号在商品档案资料中不存在,请检查货号是否正确:{}".format(error_goods_art_no))
  679. except Exception as e:
  680. raise UnicornException(str(e))
  681. progress = [{"msg_type":"segment_progress","name":"抠图","status":"等待处理","current":0,"total":0,"error":0}]
  682. if is_product_scene == 1:
  683. progress.append({"msg_type":"scene_progress","name":"场景图","status":"等待处理","current":0,"total":0,"error":0})
  684. if is_upper_footer == 1:
  685. progress.append({"msg_type":"upper_footer_progress","name":"模特图","status":"等待处理","current":0,"total":0,"error":0})
  686. if is_detail==1 or (params.excel_path != "" and params.excel_path != None):
  687. progress.append({"msg_type":"detail_progress","name":"详情页","status":"等待处理","current":0,"total":0,"error":0})
  688. if len(online_stores) > 0:
  689. progress.append({"msg_type":"upload_goods_progress","name":"上传第三方商品","status":"等待处理","current":0,"total":0,"error":0})
  690. if is_check == 1:
  691. return {
  692. "code": 0,
  693. "msg": "检测通过",
  694. "data": {"progress":progress},
  695. }
  696. asyncio.create_task(process_handle_detail(request, params))
  697. return {"code": 0, "msg": "任务已提交后台处理", "data": {"status": "processing"}}
  698. # 重构后的简化版本
  699. async def process_handle_detail(request: Request, params: HandlerDetail):
  700. """处理商品详情图生成的主要函数"""
  701. try:
  702. # 初始化基础变量
  703. handler_result = []
  704. handler_result_folder = ""
  705. # 处理参数
  706. obj, token, uuid = None, "Bearer " + params.token, params.uuid
  707. aigc_clazz = AIGCDataRequest(token)
  708. run_main = RunMain(obj, token, uuid)
  709. onlineData = OnlineDataRequest(token)
  710. # 提取参数
  711. goods_art_no_arrays = params.goods_art_no
  712. online_stores = params.online_stores
  713. is_detail = params.is_detail
  714. is_product_scene = params.is_product_scene
  715. is_upper_footer = params.is_upper_footer
  716. upper_footer_params = params.upper_footer_params
  717. product_scene_prompt = params.product_scene_prompt
  718. if params.excel_path and params.excel_path.strip():
  719. # 处理Excel模式
  720. is_detail = 1#强制处理详情页
  721. goods_art_no_arrays,excel_df,_ = __createExcelGoodsArray(params.excel_path)
  722. move_folder_array = await _process_excel_mode(
  723. goods_art_no_arrays, excel_df
  724. )
  725. else:
  726. # 处理非Excel模式
  727. move_folder_array = await _process_non_excel_mode(
  728. params, goods_art_no_arrays
  729. )
  730. # 构建配置数据
  731. config_data = await _build_config_data(params, goods_art_no_arrays)
  732. # 执行抠图处理
  733. handler_result_folder, handler_result = await _process_cutout(
  734. run_main, config_data, goods_art_no_arrays, move_folder_array
  735. )
  736. # 处理场景图和模特图
  737. return_data_check_before_detail = run_main.check_before_detail(config_data)
  738. # 检查处理结果
  739. success_handler = return_data_check_before_detail.get("data", {}).get("config_data", {}).get("success_handler", [])
  740. failed_items = [item for item in success_handler if item.get('success') == False]
  741. if failed_items:
  742. await sendAsyncMessage(
  743. msg="处理结束",
  744. data={"output_folder": handler_result_folder, "list": failed_items},
  745. status="处理结束",
  746. msg_type="detail_result_progress",
  747. )
  748. # 如果全部失败,直接终止
  749. if failed_items and len(failed_items) == len(success_handler):
  750. check_progress = {
  751. "status": "处理失败",
  752. "current": 0,
  753. "total": len(success_handler),
  754. "error": len(failed_items)
  755. }
  756. await sendAsyncMessage(
  757. msg="检查失败",
  758. goods_arts=[],
  759. status="检查失败",
  760. msg_type="segment_progress",
  761. progress=check_progress
  762. )
  763. return True
  764. # 处理场景图
  765. if is_product_scene == 1:
  766. return_data_check_before_detail = await _process_scene_images(
  767. aigc_clazz, run_main, return_data_check_before_detail, product_scene_prompt
  768. )
  769. # 处理模特图
  770. if is_upper_footer == 1:
  771. return_data_check_before_detail = await _process_model_images(
  772. aigc_clazz, run_main, return_data_check_before_detail, upper_footer_params
  773. )
  774. # 处理详情页
  775. if is_detail == 1:
  776. handler_result_folder, handler_result= await _process_detail_pages(
  777. run_main, return_data_check_before_detail, onlineData,
  778. online_stores, goods_art_no_arrays, handler_result_folder
  779. )
  780. # 如果需要上传到第三方平台
  781. if online_stores:
  782. await _upload_to_third_party(
  783. onlineData, return_data_check_before_detail,
  784. config_data, online_stores
  785. )
  786. await sendAsyncMessage(
  787. msg="处理结束",
  788. data={"output_folder": handler_result_folder, "list": handler_result},
  789. status="处理结束",
  790. msg_type="detail_result_progress",
  791. )
  792. else:
  793. await sendAsyncMessage(
  794. msg="处理结束",
  795. data={"output_folder": handler_result_folder, "list": handler_result},
  796. status="处理结束",
  797. msg_type="detail_result_progress",
  798. )
  799. except UnicornException as e:
  800. await _handle_exception(e.msg, handler_result_folder)
  801. # except Exception as e:
  802. # await _handle_exception(str(e), handler_result_folder)
  803. return True
  804. async def _process_non_excel_mode(params, goods_art_no_arrays):
  805. """处理非Excel模式的准备工作"""
  806. limit_path = "output/{}".format(time.strftime("%Y-%m-%d", time.localtime(time.time())))
  807. check_path(limit_path)
  808. move_folder_array = check_move_goods_art_no_folder("output", goods_art_no_arrays, limit_path)
  809. for goods_art_no in goods_art_no_arrays:
  810. if not goods_art_no:
  811. raise UnicornException("货号不能为空")
  812. session = SqlQuery()
  813. pr = CRUD(PhotoRecord)
  814. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  815. if not images:
  816. raise UnicornException(
  817. f"商品货号【{goods_art_no}】未查询到拍摄记录,请检查货号是否正确"
  818. )
  819. detail_counts = len(params.template_image_order.split(","))
  820. image_counts = len(images)
  821. if image_counts < detail_counts:
  822. raise UnicornException(
  823. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  824. )
  825. if move_folder_array.get(goods_art_no) is None:
  826. await _process_image_copy_and_move(goods_art_no, images,False)
  827. return move_folder_array
  828. async def _process_excel_mode(goods_art_no_arrays,excel_df):
  829. """处理非Excel模式的准备工作"""
  830. limit_path = "output/{}".format(time.strftime("%Y-%m-%d", time.localtime(time.time())))
  831. check_path(limit_path)
  832. move_folder_array = check_move_goods_art_no_folder("output", goods_art_no_arrays, limit_path)
  833. for index, row in excel_df.iterrows():
  834. goods_art_no_image_dir = str(row["文件夹名称"])
  835. goods_art_no = str(row["商品货号"])
  836. print("货号数据", goods_art_no)
  837. if not goods_art_no:
  838. raise UnicornException("货号不能为空")
  839. session = SqlQuery()
  840. pr = CRUD(PhotoRecord)
  841. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  842. if not images:
  843. raise UnicornException(
  844. f"商品货号【{goods_art_no}】未查询到拍摄记录,请检查表格中的货号数据列"
  845. )
  846. # 货号目录不存在再去进行移动和创建操作
  847. if move_folder_array.get(goods_art_no) is None:
  848. await _process_image_copy_and_move(goods_art_no_image_dir, images,True)
  849. return move_folder_array
  850. async def _process_image_copy_and_move(goods_art_no, images,is_excel):
  851. """处理图片复制和移动"""
  852. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  853. check_path(image_dir)
  854. for idx, itemImg in enumerate(images):
  855. if not itemImg.image_path:
  856. raise UnicornException(
  857. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  858. )
  859. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  860. if not os.path.exists(image_dir + "/" + os.path.basename(new_file_name)):
  861. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  862. dealImage = DealImage(image_dir)
  863. resFlag, path = dealImage.dealMoveImage(
  864. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  865. )
  866. if not resFlag:
  867. raise UnicornException(path)
  868. if is_excel:
  869. shutil.rmtree(image_dir)
  870. async def _build_config_data(params, goods_art_no_arrays):
  871. """构建配置数据"""
  872. temp_class = {}
  873. temp_name_list = []
  874. for tempItem in params.temp_list:
  875. temp_class[tempItem.template_id] = tempItem.template_local_classes
  876. temp_name_list.append(tempItem.template_id)
  877. cutOutMode = (
  878. "1"
  879. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图") == "普通抠图"
  880. else "2"
  881. )
  882. limit_path = "output/{}".format(time.strftime("%Y-%m-%d", time.localtime(time.time())))
  883. config_data = {
  884. "image_dir": limit_path,
  885. "image_order": (
  886. "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  887. if not params.template_image_order
  888. else params.template_image_order
  889. ),
  890. "goods_art_no": "",
  891. "goods_art_nos": goods_art_no_arrays,
  892. "is_check_number": False,
  893. "resize_image_view": "后跟",
  894. "cutout_mode": cutOutMode,
  895. "logo_path": params.logo_path,
  896. "special_goods_art_no_folder_line": "",
  897. "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  898. "excel_path": params.excel_path, # excel路径
  899. "is_check_color_is_all": False,
  900. "cutout_is_pass": True,
  901. "assigned_page_dict": {},
  902. "detail_is_pass": True,
  903. "upload_is_pass": False,
  904. "upload_is_enable": False,
  905. "is_filter": False,
  906. "temp_class": temp_class,
  907. "temp_name": params.temp_name,
  908. "temp_name_list": temp_name_list,
  909. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  910. "success_handler": [],
  911. }
  912. # 动态导入类
  913. try:
  914. temp_class_dict = {}
  915. for key, class_path in config_data["temp_class"].items():
  916. module_path, class_name = class_path.rsplit(".", 1)
  917. module = importlib.import_module(module_path)
  918. cls = getattr(module, class_name)
  919. temp_class_dict[key] = cls
  920. except:
  921. raise UnicornException("详情页模板不存在或未下载完成,请重启软件后重试")
  922. config_data["temp_class"] = temp_class_dict
  923. return config_data
  924. async def _process_cutout(run_main, config_data, goods_art_no_arrays, move_folder_array):
  925. """处理抠图"""
  926. handler_result = []
  927. handler_result_folder = ""
  928. return_data = run_main.check_before_cutout(config_data)
  929. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  930. if cutout_res:
  931. sys_path = format(os.getcwd()).replace("\\", "/")
  932. handler_result_folder = f"{sys_path}/{config_data['image_dir']}"
  933. for goods_art_item in goods_art_no_arrays:
  934. handler_result.append({
  935. "goods_art_no": goods_art_item,
  936. "success": True,
  937. "info": "处理成功",
  938. })
  939. if len(move_folder_array.keys()) == len(goods_art_no_arrays):
  940. progress = {
  941. "status": "处理完成",
  942. "current": len(goods_art_no_arrays),
  943. "total": len(goods_art_no_arrays),
  944. "error": 0
  945. }
  946. await sendAsyncMessage(
  947. msg="抠图完成",
  948. data={"output_folder": handler_result_folder, "list": handler_result},
  949. status="抠图完成",
  950. msg_type="segment_progress",
  951. progress=progress
  952. )
  953. return handler_result_folder, handler_result
  954. async def _process_scene_images(aigc_clazz, run_main, return_data_check_before_detail, product_scene_prompt):
  955. """处理场景图生成"""
  956. # 参数验证
  957. if not product_scene_prompt:
  958. raise UnicornException("请填写场景描述")
  959. goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  960. new_goods_dict = {}
  961. product_scene_total_progress = len(goods_dict.keys())
  962. product_scene_finish_progress = 0
  963. product_scene_error_progress = 0
  964. product_scene_progress = {
  965. "status": "正在处理",
  966. "current": product_scene_finish_progress,
  967. "total": product_scene_total_progress,
  968. "error": product_scene_error_progress
  969. }
  970. await sendAsyncMessage(
  971. msg="开始处理场景图",
  972. goods_arts=[goods_art_no for goods_art_no in goods_dict.keys()],
  973. status="开始处理",
  974. msg_type="scene_progress",
  975. progress=product_scene_progress
  976. )
  977. for goods_art_no in goods_dict.keys():
  978. product_scene_finish_progress += 1
  979. product_scene_progress = {
  980. "status": "正在处理",
  981. "goods_art_no": goods_art_no,
  982. "current": product_scene_finish_progress,
  983. "total": product_scene_total_progress,
  984. "error": product_scene_error_progress
  985. }
  986. await sendAsyncMessage(
  987. msg="正在处理场景图",
  988. goods_arts=[goods_art_no],
  989. status="正在处理场景图",
  990. msg_type="scene_progress",
  991. progress=product_scene_progress
  992. )
  993. goods_art_dict_info = goods_dict[goods_art_no]
  994. first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  995. first_pics = first_goods_art_no_info.get("pics")
  996. ceshi_image_path = first_pics.get("侧视-抠图")
  997. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  998. save_image_path = f"{save_root_path}场景图.jpg"
  999. if os.path.isfile(save_image_path):
  1000. goods_art_dict_info["场景图"] = save_image_path
  1001. new_goods_dict[goods_art_no] = goods_art_dict_info
  1002. continue
  1003. aigc_clazz.center_paste_image(ceshi_image_path, save_image_path)
  1004. try:
  1005. image_path = aigc_clazz.generateProductScene(
  1006. save_image_path, product_scene_prompt, save_image_path
  1007. )
  1008. goods_art_dict_info["场景图"] = image_path
  1009. new_goods_dict[goods_art_no] = goods_art_dict_info
  1010. product_scene_progress = {
  1011. "status": "正在处理",
  1012. "current": product_scene_finish_progress,
  1013. "total": product_scene_total_progress,
  1014. "error": product_scene_error_progress,
  1015. "goods_art_no": goods_art_no,
  1016. }
  1017. await sendAsyncMessage(
  1018. msg="场景图处理完成",
  1019. goods_arts=[goods_art_no],
  1020. status="场景图处理完成",
  1021. msg_type="scene_progress",
  1022. progress=product_scene_progress
  1023. )
  1024. except Exception as e:
  1025. os.remove(save_image_path)
  1026. product_scene_finish_progress -= 1
  1027. product_scene_error_progress += 1
  1028. product_scene_progress = {
  1029. "status": "处理失败",
  1030. "goods_art_no": goods_art_no,
  1031. "current": product_scene_finish_progress,
  1032. "total": product_scene_total_progress,
  1033. "error": product_scene_error_progress
  1034. }
  1035. await sendAsyncMessage(
  1036. msg="场景图处理失败",
  1037. goods_arts=[goods_art_no],
  1038. status="场景图处理失败",
  1039. msg_type="scene_progress",
  1040. progress=product_scene_progress
  1041. )
  1042. status_text = "处理完成" if product_scene_finish_progress > 0 else "处理失败"
  1043. product_scene_progress = {
  1044. "status": status_text,
  1045. "current": product_scene_finish_progress,
  1046. "total": product_scene_total_progress,
  1047. "error": product_scene_error_progress
  1048. }
  1049. await sendAsyncMessage(
  1050. msg="场景图处理结束",
  1051. goods_arts=[],
  1052. status="场景图处理结束",
  1053. msg_type="scene_progress",
  1054. progress=product_scene_progress
  1055. )
  1056. if new_goods_dict:
  1057. return_data_check_before_detail["data"]["goods_no_dict"] = new_goods_dict
  1058. return return_data_check_before_detail
  1059. async def _process_model_images(aigc_clazz, run_main, return_data_check_before_detail, upper_footer_params):
  1060. """处理模特图生成"""
  1061. # 参数验证
  1062. if not upper_footer_params:
  1063. raise UnicornException("请选择模特")
  1064. man_id = upper_footer_params.get("man_id")
  1065. women_id = upper_footer_params.get("women_id")
  1066. if not man_id:
  1067. raise UnicornException("请选择男模特")
  1068. if not women_id:
  1069. raise UnicornException("请选择女模特")
  1070. goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  1071. new_goods_dict = {}
  1072. upper_footer_total_progress = len(goods_dict.keys())
  1073. upper_footer_finish_progress = 0
  1074. upper_footer_error_progress = 0
  1075. upper_footer_progress = {
  1076. "status": "正在处理",
  1077. "current": upper_footer_finish_progress,
  1078. "total": upper_footer_total_progress,
  1079. "error": upper_footer_error_progress
  1080. }
  1081. await sendAsyncMessage(
  1082. msg="开始处理模特图",
  1083. goods_arts=list(goods_dict.keys()),
  1084. status="开始处理模特图",
  1085. msg_type="upper_footer_progress",
  1086. progress=upper_footer_progress
  1087. )
  1088. for goods_art_no in goods_dict.keys():
  1089. upper_footer_finish_progress += 1
  1090. upper_footer_progress = {
  1091. "status": "正在处理",
  1092. "goods_art_no": goods_art_no,
  1093. "current": upper_footer_finish_progress,
  1094. "total": upper_footer_total_progress,
  1095. "error": upper_footer_error_progress
  1096. }
  1097. await sendAsyncMessage(
  1098. msg="正在处理模特图",
  1099. goods_arts=[goods_art_no],
  1100. status="正在处理模特图",
  1101. msg_type="upper_footer_progress",
  1102. progress=upper_footer_progress
  1103. )
  1104. goods_art_dict_info = goods_dict[goods_art_no]
  1105. first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  1106. first_pics = first_goods_art_no_info.get("pics")
  1107. gender = goods_art_dict_info.get("性别","女")
  1108. model_id = man_id if "男" in gender else women_id
  1109. ceshi_image_path = first_pics.get("侧视-抠图")
  1110. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  1111. save_image_path = f"{save_root_path}模特图.jpg"
  1112. if os.path.isfile(save_image_path):
  1113. goods_art_dict_info["模特图"] = save_image_path
  1114. new_goods_dict[goods_art_no] = goods_art_dict_info
  1115. continue
  1116. shutil.copy(ceshi_image_path, save_image_path)
  1117. try:
  1118. image_path = aigc_clazz.generateUpperShoes(
  1119. save_image_path, model_id, save_image_path
  1120. )
  1121. goods_art_dict_info["模特图"] = image_path
  1122. new_goods_dict[goods_art_no] = goods_art_dict_info
  1123. upper_footer_progress = {
  1124. "status": "正在处理",
  1125. "goods_art_no": goods_art_no,
  1126. "current": upper_footer_finish_progress,
  1127. "total": upper_footer_total_progress,
  1128. "error": upper_footer_error_progress
  1129. }
  1130. await sendAsyncMessage(
  1131. msg="模特图处理成功",
  1132. goods_arts=[goods_art_no],
  1133. status="模特图处理成功",
  1134. msg_type="upper_footer_progress",
  1135. progress=upper_footer_progress
  1136. )
  1137. except Exception as e:
  1138. os.remove(save_image_path)
  1139. upper_footer_error_progress += 1
  1140. upper_footer_progress = {
  1141. "status": "处理失败",
  1142. "goods_art_no": goods_art_no,
  1143. "current": upper_footer_finish_progress,
  1144. "total": upper_footer_total_progress,
  1145. "error": upper_footer_error_progress
  1146. }
  1147. await sendAsyncMessage(
  1148. msg="模特图处理失败",
  1149. goods_arts=[goods_art_no],
  1150. status="模特图处理失败",
  1151. msg_type="upper_footer_progress",
  1152. progress=upper_footer_progress
  1153. )
  1154. status_text = "处理完成" if upper_footer_finish_progress > 0 else "处理失败"
  1155. upper_footer_progress = {
  1156. "status": status_text,
  1157. "current": upper_footer_finish_progress,
  1158. "total": upper_footer_total_progress,
  1159. "error": upper_footer_error_progress
  1160. }
  1161. await sendAsyncMessage(
  1162. msg="模特图处理结束",
  1163. goods_arts=[],
  1164. status="模特图处理结束",
  1165. msg_type="upper_footer_progress",
  1166. progress=upper_footer_progress
  1167. )
  1168. if new_goods_dict:
  1169. return_data_check_before_detail["data"]["goods_no_dict"] = new_goods_dict
  1170. return return_data_check_before_detail
  1171. async def _process_detail_pages(run_main, return_data_check_before_detail, onlineData,
  1172. online_stores, goods_art_no_arrays, handler_result_folder):
  1173. """处理详情页生成和上传"""
  1174. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  1175. return_data_check_before_detail
  1176. )
  1177. print("<======>check_for_detail_first_res<======>",check_for_detail_first_res)
  1178. if isinstance(check_for_detail_first_res, partial):
  1179. result = check_for_detail_first_res()
  1180. try:
  1181. config_data = result["config_data"]
  1182. except:
  1183. config_data = result
  1184. else:
  1185. config_data = check_for_detail_first_res
  1186. out_put_dir = config_data.get("out_put_dir")
  1187. success_handler = config_data.get("success_handler")
  1188. if not out_put_dir:
  1189. handler_result_folder = ""
  1190. # 处理失败情况
  1191. else:
  1192. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace("\\", "/")
  1193. handler_result_folder = os.path.dirname(out_put_dir_path)
  1194. if handler_result_folder:
  1195. handler_result_folder = os.path.dirname(handler_result_folder)
  1196. return handler_result_folder,success_handler
  1197. async def _upload_to_third_party(onlineData, return_data_check_before_detail,
  1198. config_data, online_stores):
  1199. """上传到第三方平台"""
  1200. result_goods_no_dict = return_data_check_before_detail["data"]["goods_no_dict"]
  1201. for goods_idx, goods_no_dict in enumerate(result_goods_no_dict.keys()):
  1202. all_detail_path_list = config_data["all_detail_path_list"]
  1203. for detail_path in all_detail_path_list:
  1204. if goods_no_dict in detail_path:
  1205. detail_path_replace = detail_path.replace("\\", "/")
  1206. result_goods_no_dict[goods_no_dict]["detail_path"] = f"{detail_path_replace}/详情页.jpg"
  1207. upload_total_progress = len(result_goods_no_dict.keys())
  1208. upload_finish_progress = 0
  1209. upload_error_progress = 0
  1210. upload_progress = {
  1211. "status": "开始处理",
  1212. "current": upload_finish_progress,
  1213. "total": upload_total_progress,
  1214. "error": upload_error_progress
  1215. }
  1216. await sendAsyncMessage(
  1217. msg="开始上传商品数据",
  1218. goods_arts=[],
  1219. status="开始上传商品数据",
  1220. msg_type="upload_goods_progress",
  1221. progress=upload_progress
  1222. )
  1223. try:
  1224. onlineData.uploadGoods2ThirdParty(
  1225. result_goods_no_dict, online_stores=online_stores
  1226. )
  1227. except Exception as e:
  1228. upload_error_progress = upload_total_progress
  1229. print(f"上传任务出现错误:{e}")
  1230. upload_finish_progress = upload_total_progress
  1231. if upload_error_progress > 0:
  1232. upload_finish_progress = 0
  1233. upload_progress = {
  1234. "status": "处理完成",
  1235. "current": upload_finish_progress,
  1236. "total": upload_total_progress,
  1237. "error": upload_error_progress
  1238. }
  1239. await sendAsyncMessage(
  1240. msg="商品上传第三方成功",
  1241. goods_arts=[],
  1242. status="商品上传第三方成功",
  1243. msg_type="upload_goods_progress",
  1244. progress=upload_progress
  1245. )
  1246. async def _handle_exception(error_msg, handler_result_folder):
  1247. """处理异常情况"""
  1248. handler_result = [{"goods_art_no": "", "success": False, "info": error_msg}]
  1249. await sendAsyncMessage(
  1250. msg="处理结束",
  1251. data={"output_folder": handler_result_folder, "list": handler_result},
  1252. status="处理结束",
  1253. msg_type="detail_result_progress",
  1254. )
  1255. # async def process_handle_detail(request: Request, params: HandlerDetail):
  1256. # obj = None
  1257. # token = "Bearer " + params.token
  1258. # uuid = params.uuid
  1259. # aigc_clazz = AIGCDataRequest(token)
  1260. # run_main = RunMain(obj, token, uuid)
  1261. # onlineData = OnlineDataRequest(token)
  1262. # goods_art_no_arrays = params.goods_art_no
  1263. # is_only_cutout = params.is_only_cutout # 是否仅抠图
  1264. # online_stores = params.online_stores # 上传第三方的店铺名称数组
  1265. # is_detail = params.is_detail # 上传第三方的店铺名称数组
  1266. # is_product_scene = params.is_product_scene # 上传第三方的店铺名称数组
  1267. # is_upper_footer = params.is_upper_footer # 上传第三方的店铺名称数组
  1268. # upper_footer_params = params.upper_footer_params # 上传第三方的店铺名称数组
  1269. # product_scene_prompt = params.product_scene_prompt # 上传第三方的店铺名称数组
  1270. # handler_result = []
  1271. # handler_result_folder = ""
  1272. # if is_only_cutout == 1:
  1273. # # 如果是仅抠图模式,避免进入到excel模式
  1274. # params.excel_path = ""
  1275. # if params.excel_path != "" and params.excel_path != None:
  1276. # return await fromExcelHandler(params)
  1277. # else:
  1278. # path = ""
  1279. # limit_path = "output/{}".format(
  1280. # time.strftime("%Y-%m-%d", time.localtime(time.time()))
  1281. # )
  1282. # check_path(limit_path)
  1283. # # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  1284. # move_folder_array = check_move_goods_art_no_folder(
  1285. # "output", goods_art_no_arrays, limit_path
  1286. # )
  1287. # try:
  1288. # for goods_art_no in goods_art_no_arrays:
  1289. # if not goods_art_no:
  1290. # raise UnicornException("货号不能为空")
  1291. # session = SqlQuery()
  1292. # pr = CRUD(PhotoRecord)
  1293. # images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  1294. # if not images:
  1295. # raise UnicornException(
  1296. # f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确"
  1297. # )
  1298. # if is_only_cutout != 1:
  1299. # detail_counts = len(params.template_image_order.split(","))
  1300. # image_counts = len(images)
  1301. # if image_counts < detail_counts:
  1302. # raise UnicornException(
  1303. # f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  1304. # )
  1305. # if move_folder_array.get(goods_art_no) == None:
  1306. # image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  1307. # check_path(image_dir)
  1308. # for idx, itemImg in enumerate(images):
  1309. # if itemImg.image_path == "" or itemImg.image_path == None:
  1310. # raise UnicornException(
  1311. # f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  1312. # )
  1313. # new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  1314. # if not os.path.exists(
  1315. # image_dir + "/" + os.path.basename(new_file_name)
  1316. # ):
  1317. # shutil.copy(itemImg.image_path, image_dir + new_file_name)
  1318. # dealImage = DealImage(image_dir)
  1319. # resFlag, path = dealImage.dealMoveImage(
  1320. # image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  1321. # )
  1322. # if not resFlag:
  1323. # raise UnicornException(path)
  1324. # except UnicornException as e:
  1325. # handler_result_folder = ""
  1326. # handler_result.append(
  1327. # {"goods_art_no": "", "success": False, "info": str(e.msg)}
  1328. # )
  1329. # print(f"UnicornException 生成错误信息:{e}")
  1330. # await sendAsyncMessage(
  1331. # msg="处理结束",
  1332. # data={"output_folder": handler_result_folder, "list": handler_result},
  1333. # status="处理结束",
  1334. # msg_type="detail_result_progress",
  1335. # )
  1336. # return True
  1337. # except Exception as e:
  1338. # print(f"详情图生成错误信息:{e}")
  1339. # handler_result_folder = ""
  1340. # handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  1341. # await sendAsyncMessage(
  1342. # msg="处理结束",
  1343. # data={"output_folder": handler_result_folder, "list": handler_result},
  1344. # status="处理结束",
  1345. # msg_type="detail_result_progress",
  1346. # )
  1347. # return True
  1348. # # try:
  1349. # temp_class = {}
  1350. # temp_name_list = []
  1351. # for tempItem in params.temp_list:
  1352. # temp_class[tempItem.template_id] = tempItem.template_local_classes
  1353. # temp_name_list.append(tempItem.template_id)
  1354. # cutOutMode = (
  1355. # "1"
  1356. # if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  1357. # == "普通抠图"
  1358. # else "2"
  1359. # )
  1360. # config_data = {
  1361. # "image_dir": limit_path,
  1362. # "image_order": (
  1363. # "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  1364. # if params.template_image_order == None or params.template_image_order == ""
  1365. # else params.template_image_order
  1366. # ),
  1367. # "goods_art_no": "",
  1368. # "goods_art_nos": goods_art_no_arrays,
  1369. # "is_check_number": False,
  1370. # "resize_image_view": "后跟",
  1371. # "cutout_mode": cutOutMode,
  1372. # "logo_path": params.logo_path,
  1373. # "special_goods_art_no_folder_line": "",
  1374. # "is_use_excel": False, # 是否使用excel
  1375. # "excel_path": "", # excel路径
  1376. # "is_check_color_is_all": False,
  1377. # "cutout_is_pass": True,
  1378. # "assigned_page_dict": {},
  1379. # "detail_is_pass": True,
  1380. # "upload_is_pass": False,
  1381. # "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  1382. # "is_filter": False,
  1383. # "temp_class": temp_class,
  1384. # "temp_name": params.temp_name,
  1385. # "temp_name_list": temp_name_list,
  1386. # "target_error_folder": f"{limit_path}/软件-生成详情错误",
  1387. # "success_handler": [],
  1388. # }
  1389. # print("image_dir=====>>>>>", config_data["image_dir"])
  1390. # # 动态导入类
  1391. # temp_class_dict = {}
  1392. # for key, class_path in config_data["temp_class"].items():
  1393. # module_path, class_name = class_path.rsplit(".", 1)
  1394. # module = importlib.import_module(module_path)
  1395. # cls = getattr(module, class_name)
  1396. # temp_class_dict[key] = cls
  1397. # config_data["temp_class"] = temp_class_dict
  1398. # return_data = run_main.check_before_cutout(config_data)
  1399. # cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  1400. # check_for_detail_first_res = None
  1401. # if cutout_res == True:
  1402. # sys_path = format(os.getcwd()).replace("\\", "/")
  1403. # handler_result_folder = f"{sys_path}/{limit_path}"
  1404. # for goods_art_item in goods_art_no_arrays:
  1405. # handler_result.append(
  1406. # {
  1407. # "goods_art_no": goods_art_item,
  1408. # "success": True,
  1409. # "info": "处理成功",
  1410. # }
  1411. # )
  1412. # if len(move_folder_array.keys()) == len(goods_art_no_arrays):
  1413. # progress = {"status":"处理完成",
  1414. # "current":len(goods_art_no_arrays),
  1415. # "total":len(goods_art_no_arrays),
  1416. # "error":0
  1417. # }
  1418. # await sendAsyncMessage(
  1419. # msg="抠图完成",
  1420. # data={"output_folder": handler_result_folder, "list": handler_result},
  1421. # status="抠图完成",
  1422. # msg_type="segment_progress",
  1423. # progress=progress
  1424. # )
  1425. # try:
  1426. # if is_product_scene == 1:
  1427. # if product_scene_prompt == "" or product_scene_prompt == None:
  1428. # raise UnicornException("请填写场景描述")
  1429. # if is_upper_footer == 1:
  1430. # if upper_footer_params == {} or upper_footer_params == None:
  1431. # raise UnicornException("请选择模特")
  1432. # man_id = upper_footer_params.get("man_id")
  1433. # if not man_id:
  1434. # raise UnicornException("请选择男模特")
  1435. # women_id = upper_footer_params.get("women_id")
  1436. # if not women_id:
  1437. # raise UnicornException("请选择女模特")
  1438. # return_data_check_before_detail = run_main.check_before_detail(config_data)
  1439. # success_handler = return_data_check_before_detail.get("data").get("config_data").get("success_handler",[])
  1440. # failed_items = [item for item in success_handler if item.get('success') == False]
  1441. # print("failed_items",failed_items)
  1442. # if len(failed_items) > 0:
  1443. # await sendAsyncMessage(
  1444. # msg="处理结束",
  1445. # data={"output_folder": handler_result_folder, "list": failed_items},
  1446. # status="处理结束",
  1447. # msg_type="detail_result_progress",
  1448. # )
  1449. # if len(failed_items)!=0 and len(failed_items) == len(success_handler):
  1450. # # 如果全部错误 直接终止
  1451. # return True
  1452. # else:
  1453. # if is_product_scene == 1:
  1454. # goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  1455. # new_goods_dict = {}
  1456. # product_scene_total_progress = len(goods_dict.keys())
  1457. # product_scene_finish_progress = 0
  1458. # product_scene_error_progress = 0
  1459. # product_scene_progress = {"status":"正在处理", "current":product_scene_finish_progress, "total":product_scene_total_progress, "error":product_scene_error_progress}
  1460. # print("product_scene_progress",goods_dict,product_scene_progress)
  1461. # await sendAsyncMessage(
  1462. # msg="开始处理场景图",
  1463. # goods_arts=[goods_art_no for goods_art_no in goods_dict.keys()],
  1464. # status="开始处理",
  1465. # msg_type="scene_progress",
  1466. # progress=product_scene_progress
  1467. # )
  1468. # for goods_art_no in goods_dict.keys():
  1469. # print("处理场景图", goods_art_no)
  1470. # product_scene_finish_progress+=1
  1471. # 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}
  1472. # await sendAsyncMessage(
  1473. # msg="正在处理场景图",
  1474. # goods_arts=[goods_art_no],
  1475. # status="正在处理场景图",
  1476. # msg_type="scene_progress",
  1477. # progress=product_scene_progress
  1478. # )
  1479. # goods_art_dict_info = goods_dict[goods_art_no]
  1480. # first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  1481. # first_pics = first_goods_art_no_info.get("pics")
  1482. # ceshi_image_path = first_pics.get("侧视-抠图")
  1483. # save_root_path = ceshi_image_path.split("阴影图处理")[0]
  1484. # save_image_path = f"{save_root_path}场景图.jpg"
  1485. # if os.path.isfile(save_image_path):
  1486. # goods_art_dict_info["场景图"] = save_image_path
  1487. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1488. # continue
  1489. # aigc_clazz.center_paste_image(ceshi_image_path, save_image_path)
  1490. # try:
  1491. # image_path = aigc_clazz.generateProductScene(
  1492. # save_image_path, product_scene_prompt, save_image_path
  1493. # )
  1494. # # image_path = aigc_clazz.generateProductSceneQW(
  1495. # # save_image_path, product_scene_prompt, save_image_path
  1496. # # )
  1497. # goods_art_dict_info["场景图"] = image_path
  1498. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1499. # handler_result.append(
  1500. # {
  1501. # "goods_art_no": goods_art_no,
  1502. # "success": True,
  1503. # "info": "场景图处理成功",
  1504. # }
  1505. # )
  1506. # product_scene_progress = {
  1507. # "status":"处理成功",
  1508. # "current":product_scene_finish_progress,
  1509. # "total":product_scene_total_progress,
  1510. # "error":product_scene_error_progress,
  1511. # "goods_art_no":goods_art_no,
  1512. # }
  1513. # await sendAsyncMessage(
  1514. # msg="场景图处理完成",
  1515. # goods_arts=[goods_art_no],
  1516. # status="场景图处理完成",
  1517. # msg_type="scene_progress",
  1518. # progress=product_scene_progress
  1519. # )
  1520. # except Exception as e:
  1521. # os.remove(save_image_path)
  1522. # handler_result.append(
  1523. # {
  1524. # "goods_art_no": goods_art_no,
  1525. # "success": False,
  1526. # "info": f"场景图处理失败:{e}",
  1527. # }
  1528. # )
  1529. # product_scene_finish_progress -=1
  1530. # product_scene_error_progress +=1
  1531. # 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}
  1532. # await sendAsyncMessage(
  1533. # msg="场景图处理失败",
  1534. # goods_arts=[goods_art_no],
  1535. # status="场景图处理失败",
  1536. # msg_type="scene_progress",
  1537. # progress=product_scene_progress
  1538. # )
  1539. # product_scene_progress = {"status":"处理完成", "current":product_scene_finish_progress, "total":product_scene_total_progress, "error":product_scene_error_progress}
  1540. # await sendAsyncMessage(
  1541. # msg="场景图处理结束",
  1542. # goods_arts=[],
  1543. # status="场景图处理结束",
  1544. # msg_type="scene_progress",
  1545. # progress=product_scene_progress
  1546. # )
  1547. # if new_goods_dict is not None or new_goods_dict != {}:
  1548. # return_data_check_before_detail["data"][
  1549. # "goods_no_dict"
  1550. # ] = new_goods_dict
  1551. # if is_upper_footer == 1:
  1552. # goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  1553. # new_goods_dict = {}
  1554. # upper_footer_total_progress = len(goods_dict.keys())
  1555. # upper_footer_finish_progress = 0
  1556. # upper_footer_error_progress = 0
  1557. # upper_footer_progress = {"status":"正在处理", "current":upper_footer_finish_progress, "total":upper_footer_total_progress, "error":upper_footer_error_progress}
  1558. # await sendAsyncMessage(
  1559. # msg="开始处理模特图",
  1560. # goods_arts=list(goods_dict.keys()),
  1561. # status="开始处理模特图",
  1562. # msg_type="upper_footer_progress",
  1563. # progress=upper_footer_progress
  1564. # )
  1565. # for goods_art_no in goods_dict.keys():
  1566. # upper_footer_finish_progress+=1
  1567. # 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}
  1568. # await sendAsyncMessage(
  1569. # msg="正在处理模特图",
  1570. # goods_arts=[goods_art_no],
  1571. # status="正在处理模特图",
  1572. # msg_type="upper_footer_progress",
  1573. # progress=upper_footer_progress
  1574. # )
  1575. # goods_art_dict_info = goods_dict[goods_art_no]
  1576. # first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  1577. # first_pics = first_goods_art_no_info.get("pics")
  1578. # gender = goods_art_dict_info.get("性别")
  1579. # model_id = man_id if "男" in gender else women_id
  1580. # ceshi_image_path = first_pics.get("侧视-抠图")
  1581. # save_root_path = ceshi_image_path.split("阴影图处理")[0]
  1582. # save_image_path = f"{save_root_path}模特图.jpg"
  1583. # if os.path.isfile(save_image_path):
  1584. # goods_art_dict_info["模特图"] = save_image_path
  1585. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1586. # continue
  1587. # shutil.copy(ceshi_image_path, save_image_path)
  1588. # try:
  1589. # image_path = aigc_clazz.generateUpperShoes(
  1590. # save_image_path, model_id, save_image_path
  1591. # )
  1592. # # image_path = aigc_clazz.generateModelShoesQW(
  1593. # # save_image_path, model_id, save_image_path
  1594. # # )
  1595. # goods_art_dict_info["模特图"] = image_path
  1596. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1597. # handler_result.append(
  1598. # {
  1599. # "goods_art_no": goods_art_no,
  1600. # "success": True,
  1601. # "info": "模特图处理成功",
  1602. # }
  1603. # )
  1604. # 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}
  1605. # await sendAsyncMessage(
  1606. # msg="模特图处理成功",
  1607. # goods_arts=[goods_art_no],
  1608. # status="模特图处理成功",
  1609. # msg_type="upper_footer_progress",
  1610. # progress=upper_footer_progress
  1611. # )
  1612. # except Exception as e:
  1613. # os.remove(save_image_path)
  1614. # handler_result.append(
  1615. # {
  1616. # "goods_art_no": goods_art_no,
  1617. # "success": False,
  1618. # "info": f"模特图处理失败:{e}",
  1619. # }
  1620. # )
  1621. # upper_footer_error_progress+=1
  1622. # 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}
  1623. # await sendAsyncMessage(
  1624. # msg="模特图处理失败",
  1625. # goods_arts=[goods_art_no],
  1626. # status="模特图处理失败",
  1627. # msg_type="upper_footer_progress",
  1628. # progress=upper_footer_progress
  1629. # )
  1630. # upper_footer_progress = {"status":"处理完成", "current":upper_footer_finish_progress, "total":upper_footer_total_progress, "error":upper_footer_error_progress}
  1631. # await sendAsyncMessage(
  1632. # msg="模特图处理结束",
  1633. # goods_arts=[],
  1634. # status="模特图处理结束",
  1635. # msg_type="upper_footer_progress",
  1636. # progress=upper_footer_progress
  1637. # )
  1638. # if new_goods_dict is not None or new_goods_dict != {}:
  1639. # return_data_check_before_detail["data"][
  1640. # "goods_no_dict"
  1641. # ] = new_goods_dict
  1642. # if is_detail == 0:
  1643. # await sendAsyncMessage(
  1644. # msg="处理结束",
  1645. # data={"output_folder": handler_result_folder, "list": handler_result},
  1646. # status="处理结束",
  1647. # msg_type="detail_result_progress",
  1648. # )
  1649. # return True
  1650. # check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  1651. # return_data_check_before_detail
  1652. # )
  1653. # if isinstance(check_for_detail_first_res, partial):
  1654. # result = check_for_detail_first_res()
  1655. # try:
  1656. # config_data = result["config_data"]
  1657. # except:
  1658. # config_data = result
  1659. # if config_data["sign_text"] == "已结束详情处理":
  1660. # print("config_data", config_data)
  1661. # out_put_dir = config_data.get("out_put_dir")
  1662. # if out_put_dir == None:
  1663. # handler_result_folder = ""
  1664. # if len(config_data["success_handler"]) > 0:
  1665. # for good_art in config_data["success_handler"]:
  1666. # handler_result.append(good_art)
  1667. # else:
  1668. # for good_art in goods_art_no_arrays:
  1669. # handler_result.append(
  1670. # {
  1671. # "goods_art_no": good_art,
  1672. # "success": False,
  1673. # "info": "处理失败",
  1674. # }
  1675. # )
  1676. # else:
  1677. # out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  1678. # "\\", "/"
  1679. # )
  1680. # handler_result_folder = os.path.dirname(out_put_dir_path)
  1681. # if len(config_data["success_handler"]) == 0:
  1682. # for good_art in goods_art_no_arrays:
  1683. # handler_result.append(
  1684. # {
  1685. # "goods_art_no": good_art,
  1686. # "success": False,
  1687. # "info": "处理失败",
  1688. # }
  1689. # )
  1690. # else:
  1691. # if len(online_stores) > 0:
  1692. # result_goods_no_dict = return_data_check_before_detail["data"][
  1693. # "goods_no_dict"
  1694. # ]
  1695. # for goods_idx, goods_no_dict in enumerate(
  1696. # result_goods_no_dict.keys()
  1697. # ):
  1698. # all_detail_path_list = config_data["all_detail_path_list"]
  1699. # for detail_path in all_detail_path_list:
  1700. # if goods_no_dict in detail_path:
  1701. # detail_path_replace = detail_path.replace("\\", "/")
  1702. # result_goods_no_dict[goods_no_dict][
  1703. # "detail_path"
  1704. # ] = f"{detail_path_replace}/详情页.jpg"
  1705. # upload_total_progress = len(result_goods_no_dict.keys())
  1706. # upload_finish_progress = 0
  1707. # upload_error_progress = 0
  1708. # upload_progress = {"status":"开始处理", "current":upload_finish_progress, "total":upload_total_progress, "error":upload_error_progress}
  1709. # await sendAsyncMessage(
  1710. # msg="开始上传商品数据",
  1711. # goods_arts=[],
  1712. # status="开始上传商品数据",
  1713. # msg_type="upload_goods_progress",
  1714. # progress=upload_progress
  1715. # )
  1716. # try:
  1717. # onlineData.uploadGoods2ThirdParty(
  1718. # result_goods_no_dict, online_stores=online_stores
  1719. # )
  1720. # except Exception as e:
  1721. # upload_error_progress = upload_total_progress
  1722. # print(f"上传任务出现错误:{e}")
  1723. # upload_finish_progress = upload_total_progress
  1724. # if upload_error_progress > 0:
  1725. # upload_finish_progress = 0
  1726. # upload_progress = {"status":"处理完成", "current":upload_finish_progress, "total":upload_total_progress, "error":upload_error_progress}
  1727. # await sendAsyncMessage(
  1728. # msg="商品上传第三方成功",
  1729. # goods_arts=[],
  1730. # status="商品上传第三方成功",
  1731. # msg_type="upload_goods_progress",
  1732. # progress=upload_progress
  1733. # )
  1734. # handler_result = config_data["success_handler"]
  1735. # else:
  1736. # handler_result.append(
  1737. # {"goods_art_no": "", "success": False, "info": "处理失败"}
  1738. # )
  1739. # except UnicornException as e:
  1740. # handler_result_folder = ""
  1741. # handler_result.append(
  1742. # {"goods_art_no": "", "success": False, "info": str(e.msg)}
  1743. # )
  1744. # print(f"UnicornException 生成错误信息:{e}")
  1745. # except Exception as e:
  1746. # print(f"详情图生成错误信息:{e}")
  1747. # handler_result_folder = ""
  1748. # handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  1749. # await sendAsyncMessage(
  1750. # msg="处理结束",
  1751. # data={"output_folder": handler_result_folder, "list": handler_result},
  1752. # status="处理结束",
  1753. # msg_type="detail_result_progress",
  1754. # )
  1755. # return True
  1756. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  1757. def get_device_tabs(type: int):
  1758. session = SqlQuery()
  1759. statement = (
  1760. select(DeviceConfigTabs)
  1761. .where(DeviceConfigTabs.mode_type == type)
  1762. .order_by(asc("id"))
  1763. )
  1764. result = session.exec(statement).all()
  1765. session.close()
  1766. sys = CRUD(SysConfigs)
  1767. action_configs = sys.read(session, conditions={"key": "action_configs"})
  1768. session.close()
  1769. return {
  1770. "code": 0,
  1771. "msg": "",
  1772. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  1773. }
  1774. @app.post("/update_tab_name", description="更改tab名称")
  1775. def update_tab_name(params: DeviceConfigTabsReq):
  1776. if params.mode_name == "":
  1777. return {"code": 1, "msg": "名称不能为空", "data": {}}
  1778. session = SqlQuery()
  1779. tabModel = CRUD(DeviceConfigTabs)
  1780. kwargs = {"mode_name": params.mode_name}
  1781. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  1782. session.close()
  1783. return {
  1784. "code": 0,
  1785. "msg": "",
  1786. "data": None,
  1787. }
  1788. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  1789. def get_device_configs(params: ModelGetDeviceConfig):
  1790. tab_id = params.tab_id
  1791. session = SqlQuery()
  1792. configModel = CRUD(DeviceConfig)
  1793. configList = configModel.read_all(
  1794. session,
  1795. conditions={"tab_id": tab_id},
  1796. order_by="action_index",
  1797. ascending=True,
  1798. )
  1799. return {
  1800. "code": 0,
  1801. "msg": "",
  1802. "data": {"list": configList},
  1803. }
  1804. @app.post("/device_config_detail", description="获取可执行程序详情")
  1805. def device_config_detail(params: ModelGetDeviceConfigDetail):
  1806. action_id = params.id
  1807. session = SqlQuery()
  1808. configModel = CRUD(DeviceConfig)
  1809. model = configModel.read(session, conditions={"id": action_id})
  1810. if model == None:
  1811. return {"code": 1, "msg": "数据不存在", "data": None}
  1812. return {"code": 0, "msg": "", "data": model}
  1813. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  1814. def device_config_detail_query():
  1815. # tab_id = params.tab_id
  1816. # action_name = params.action_name
  1817. session = SqlQuery()
  1818. sys = CRUD(SysConfigs)
  1819. action_configs = sys.read(session, conditions={"key": "action_configs"})
  1820. action_configs_value = json.loads(action_configs.value)
  1821. left_config = action_configs_value.get("left")
  1822. configModel = CRUD(DeviceConfig)
  1823. model = configModel.read(
  1824. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  1825. )
  1826. if model == None:
  1827. model = configModel.read(session, conditions={"tab_id": left_config})
  1828. return {"code": 0, "msg": "", "data": model}
  1829. @app.post("/remove_config", description="删除一条可执行命令")
  1830. def get_device_configs(params: ModelGetDeviceConfigDetail):
  1831. action_id = params.id
  1832. session = SqlQuery()
  1833. configModel = CRUD(DeviceConfig)
  1834. model = configModel.read(session, conditions={"id": action_id})
  1835. if model == None:
  1836. return {"code": 1, "msg": "数据不存在", "data": None}
  1837. if model.is_system == True:
  1838. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  1839. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  1840. if len(configArray) == 1:
  1841. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  1842. configModel.delete(session, obj_id=action_id)
  1843. return {"code": 0, "msg": "删除成功", "data": None}
  1844. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  1845. def save_device_config(params: SaveDeviceConfig):
  1846. action_id = params.id
  1847. session = SqlQuery()
  1848. deviceConfig = CRUD(DeviceConfig)
  1849. if action_id == None or action_id == 0:
  1850. # 走新增逻辑
  1851. params.id = None
  1852. save_device_config = deviceConfig.create(session, obj_in=params)
  1853. else:
  1854. model = deviceConfig.read(session, conditions={"id": action_id})
  1855. if model == None:
  1856. return {"code": 1, "msg": "数据不存在", "data": None}
  1857. # 走编辑逻辑
  1858. kwargs = params.__dict__
  1859. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  1860. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  1861. @app.post("/reset_config", description="创建或修改一条可执行命令")
  1862. def reset_config(params: ModelGetDeviceConfig):
  1863. tab_id = params.tab_id
  1864. if tab_id == None or tab_id == "":
  1865. return {"code": 1, "msg": "参数错误", "data": None}
  1866. session = SqlQuery()
  1867. deviceConfig = CRUD(DeviceConfig)
  1868. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  1869. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  1870. if res is False:
  1871. return {"code": 1, "msg": "操作失败", "data": None}
  1872. actions = json.load(open("action.json", encoding="utf-8"))
  1873. for data in actions:
  1874. data["tab_id"] = tab_id
  1875. data["is_system"] = first_config.is_system
  1876. device_config = DeviceConfig(**data)
  1877. session.add(device_config)
  1878. session.commit()
  1879. # session.close()
  1880. return {"code": 0, "msg": "操作成功", "data": None}
  1881. @app.get("/get_photo_records", description="获取拍照记录")
  1882. def get_photo_records(page: int = 1, size: int = 5):
  1883. session = SqlQuery()
  1884. # photos = CRUD(PhotoRecord)
  1885. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1886. statement = (
  1887. select(PhotoRecord)
  1888. .offset((page - 1) * size)
  1889. .limit(size)
  1890. .order_by(desc("id"))
  1891. .group_by("goods_art_no")
  1892. )
  1893. list = []
  1894. result = session.exec(statement).all()
  1895. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1896. join_conditions = [
  1897. {
  1898. "model": DeviceConfig,
  1899. "on": PhotoRecord.action_id == DeviceConfig.id,
  1900. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  1901. }
  1902. ]
  1903. for item in result:
  1904. query = (
  1905. select(PhotoRecord, DeviceConfig.action_name)
  1906. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  1907. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  1908. )
  1909. list_item = session.exec(query).mappings().all()
  1910. list.append(
  1911. {
  1912. "goods_art_no": item.goods_art_no,
  1913. "action_time": item.create_time,
  1914. "items": list_item,
  1915. }
  1916. )
  1917. # session.close()
  1918. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1919. return {
  1920. "code": 0,
  1921. "msg": "",
  1922. "data": {"list": list, "page": page, "size": size},
  1923. }
  1924. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  1925. def get_last_photo_record():
  1926. session = SqlQuery()
  1927. statement = (
  1928. select(PhotoRecord)
  1929. .where(PhotoRecord.image_path != None)
  1930. .order_by(desc("photo_create_time"))
  1931. )
  1932. result = session.exec(statement).first()
  1933. # session.close()
  1934. return {
  1935. "code": 0,
  1936. "msg": "",
  1937. "data": result,
  1938. }
  1939. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  1940. def get_photo_record_detail(goods_art_no: str = None):
  1941. if goods_art_no == None:
  1942. return {"code": 1, "msg": "参数错误", "data": None}
  1943. session = SqlQuery()
  1944. photos = CRUD(PhotoRecord)
  1945. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  1946. # session.close()
  1947. return {
  1948. "code": 0,
  1949. "msg": "",
  1950. "data": {"list": items},
  1951. }
  1952. @app.post("/delect_goods_arts", description="通过货号删除记录")
  1953. def delect_goods_arts(params: PhotoRecordDelete):
  1954. session = SqlQuery()
  1955. photos = CRUD(PhotoRecord)
  1956. for item in params.goods_art_nos:
  1957. photos.deleteConditions(session, conditions={"goods_art_no": item})
  1958. # session.close()
  1959. return {
  1960. "code": 0,
  1961. "msg": "操作成功",
  1962. "data": None,
  1963. }
  1964. def query_config_by_key(key_name):
  1965. """
  1966. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  1967. Args:
  1968. key_name (str): 要查询的key名称
  1969. Returns:
  1970. dict or None: 匹配的对象或None(如果没有找到)
  1971. """
  1972. try:
  1973. # 获取所有配置数据
  1974. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  1975. # 遍历配置数据查找匹配的key
  1976. for config in configs:
  1977. if config.get("key") == key_name:
  1978. return config
  1979. return None
  1980. except Exception as e:
  1981. print(f"查询配置时出错: {e}")
  1982. return None
  1983. @app.get("/get_sys_config", description="查询系统配置")
  1984. def get_sys_config(key: str = None):
  1985. if key == None:
  1986. return {"code": 1, "msg": "参数错误", "data": None}
  1987. session = SqlQuery()
  1988. photos = CRUD(SysConfigs)
  1989. item = photos.read(session, conditions={"key": key})
  1990. search_data = None if item == None else json.loads(item.value)
  1991. if search_data == None:
  1992. sys_config_json = query_config_by_key(key)
  1993. if sys_config_json != None:
  1994. config = SysConfigs(**sys_config_json)
  1995. session.add(config)
  1996. session.commit() # 合并事务提交
  1997. search_data = json.loads(sys_config_json.get("value"))
  1998. return {
  1999. "code": 0,
  2000. "msg": "",
  2001. "data": search_data,
  2002. }
  2003. @app.post("/update_left_right_config", description="更新左右脚配置")
  2004. def update_left_right_config(params: LeftRightParams):
  2005. session = SqlQuery()
  2006. sysConfig = CRUD(SysConfigs)
  2007. model = sysConfig.read(session, conditions={"key": "action_configs"})
  2008. if model == None:
  2009. return {"code": 1, "msg": "配置不存在", "data": None}
  2010. config_value = json.loads(model.value)
  2011. config_value[params.type] = params.id
  2012. update_value = json.dumps(config_value)
  2013. # 走编辑逻辑
  2014. kwargs = {"key": "action_configs", "value": update_value}
  2015. save_device_config = sysConfig.updateConditions(
  2016. session, conditions={"key": "action_configs"}, **kwargs
  2017. )
  2018. return {"code": 0, "msg": "操作成功", "data": None}
  2019. @app.post("/update_record", description="更新拍照记录")
  2020. def update_record(params: RecordUpdate):
  2021. session = SqlQuery()
  2022. photoRecord = CRUD(PhotoRecord)
  2023. model = photoRecord.read(session, conditions={"id": params.id})
  2024. if model == None:
  2025. return {"code": 1, "msg": "记录不存在", "data": None}
  2026. kwargs = params.__dict__
  2027. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  2028. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  2029. @app.post("/update_sys_configs", description="创建或修改系统配置")
  2030. def save_sys_configs(params: SysConfigParams):
  2031. session = SqlQuery()
  2032. sysConfig = CRUD(SysConfigs)
  2033. model = sysConfig.read(session, conditions={"key": params.key})
  2034. if model == None:
  2035. return {"code": 1, "msg": "配置不存在", "data": None}
  2036. # 走编辑逻辑
  2037. kwargs = params.__dict__
  2038. save_device_config = sysConfig.updateConditions(
  2039. session, conditions={"key": params.key}, **kwargs
  2040. )
  2041. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  2042. @app.post("/create_main_image", description="创建主图测试")
  2043. def create_main_image(params: MaineImageTest):
  2044. file_path = params.file_path
  2045. onePic = OnePicTest(pic_path=file_path)
  2046. main_out_path = onePic.HandlerMainImage()
  2047. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  2048. def insertEmptyLogoList(session):
  2049. """插入空logo列表"""
  2050. data = {"key": "logo_configs", "value": "[]"}
  2051. config = SysConfigs(**data)
  2052. session.add(config)
  2053. session.commit()
  2054. session.close()
  2055. item = SysConfigs()
  2056. item.key = "logo_configs"
  2057. item.value = "[]"
  2058. return item
  2059. @app.get("/logo_list", description="logo列表")
  2060. def logo_list():
  2061. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  2062. check_path(logo_dir)
  2063. logo_files = os.listdir(logo_dir)
  2064. logo_list = []
  2065. for logoItem in logo_files:
  2066. logo_list.append(f"{logo_dir}{logoItem}")
  2067. return {"code": 0, "msg": "操作成功", "data": logo_list}
  2068. @app.post("/add_logo", description="添加logo")
  2069. def add_logo(params: LogoParams):
  2070. logo_path = params.logo_path.replace("\\", "/")
  2071. session = SqlQuery()
  2072. sysConfig = CRUD(SysConfigs)
  2073. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  2074. if item == None:
  2075. item = insertEmptyLogoList(session)
  2076. if os.path.isfile(logo_path) == False:
  2077. return {"code": 1, "msg": "logo文件不存在", "data": None}
  2078. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  2079. check_path(logo_dir)
  2080. fpath, fname = os.path.split(logo_path)
  2081. logo_path_info = logo_dir + fname
  2082. shutil.copy(logo_path, logo_path_info) # 复制文件
  2083. logo_files = os.listdir(logo_dir)
  2084. logo_list = []
  2085. for logoItem in logo_files:
  2086. logo_list.append(f"{logo_dir}{logoItem}")
  2087. return {
  2088. "code": 0,
  2089. "msg": "",
  2090. "data": {"logo": logo_path_info},
  2091. }
  2092. @app.post("/delete_logo", description="删除logo")
  2093. def delete_logo(params: LogoParamsupdate):
  2094. logo_path = params.path
  2095. if os.path.isfile(logo_path) == False:
  2096. return {"code": 1, "msg": "logo文件不存在", "data": None}
  2097. os.remove(logo_path)
  2098. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  2099. check_path(logo_dir)
  2100. logo_files = os.listdir(logo_dir)
  2101. logo_list = []
  2102. for logoItem in logo_files:
  2103. logo_list.append(f"{logo_dir}{logoItem}")
  2104. return {"code": 0, "msg": "操作成功", "data": logo_list}
  2105. @app.post("/close_other_window", description="关闭窗口")
  2106. def close_other_window():
  2107. hwnd_list = []
  2108. def callback(hwnd, _):
  2109. title = GetWindowText(hwnd)
  2110. if title == "digiCamControl by Duka Istvan":
  2111. hwnd_list.append(hwnd)
  2112. EnumWindows(callback, None)
  2113. if hwnd_list:
  2114. hwnd = hwnd_list[0]
  2115. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  2116. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  2117. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}
  2118. def syncUserJsonConfigs(token):
  2119. hlm_token = token
  2120. headers = {
  2121. "Authorization": f"Bearer {hlm_token}",
  2122. "content-type": "application/json",
  2123. }
  2124. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_configs"
  2125. result = requests.get(url=url, headers=headers)
  2126. sys_configs = result.json().get("data", {}).get("configs")
  2127. session = SqlQuery()
  2128. sysConfigs = CRUD(SysConfigs)
  2129. if sys_configs:
  2130. sysConfigs.deleteConditions(session, {})
  2131. configList = []
  2132. for config_keys in sys_configs.keys():
  2133. sys_configs[config_keys]
  2134. configList.append(
  2135. {
  2136. "key": config_keys,
  2137. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  2138. }
  2139. )
  2140. batch_insert_sys_configs(session, configList)
  2141. @app.post("/sync_sys_configs", description="同步线上配置到本地")
  2142. def sync_sys_configs(params: SyncLocalConfigs):
  2143. hlm_token = params.token
  2144. headers = {
  2145. "Authorization": f"Bearer {hlm_token}",
  2146. "content-type": "application/json",
  2147. }
  2148. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_configs"
  2149. result = requests.get(url=url, headers=headers)
  2150. sys_configs = result.json().get("data", {}).get("configs")
  2151. session = SqlQuery()
  2152. sysConfigs = CRUD(SysConfigs)
  2153. if sys_configs:
  2154. sysConfigs.deleteConditions(session, {})
  2155. configList = []
  2156. for config_keys in sys_configs.keys():
  2157. sys_configs[config_keys]
  2158. configList.append(
  2159. {
  2160. "key": config_keys,
  2161. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  2162. }
  2163. )
  2164. batch_insert_sys_configs(session, configList)
  2165. else:
  2166. all_configs = sysConfigs.read_all(session)
  2167. localConfigData = {}
  2168. for local_config in all_configs:
  2169. localConfigData[local_config.key] = json.loads(local_config.value)
  2170. data_json = json.dumps({"configs": localConfigData}, ensure_ascii=False)
  2171. # 同步本地到线上
  2172. url = settings.DOMAIN + "/api/ai_image/camera_machine/update_all_user_configs"
  2173. requests.post(url=url, headers=headers, data=data_json)
  2174. return {"code": 0, "msg": "操作成功", "data": None}
  2175. @app.post("/sync_actions", description="同步左右脚配置到本地")
  2176. def sync_action_configs(params: SyncLocalConfigs):
  2177. hlm_token = params.token
  2178. headers = {
  2179. "Authorization": f"Bearer {hlm_token}",
  2180. "content-type": "application/json",
  2181. }
  2182. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_tabs"
  2183. result = requests.get(url=url, headers=headers)
  2184. session = SqlQuery()
  2185. deviceConfigs = CRUD(DeviceConfig)
  2186. deviceConfigTabs = CRUD(DeviceConfigTabs)
  2187. tabs = result.json().get("data", {}).get("tabs")
  2188. actions = result.json().get("data", {}).get("actions")
  2189. if tabs:
  2190. # 先删除再创建
  2191. deviceConfigTabs.deleteConditions(session, {})
  2192. deviceConfigs.deleteConditions(session, {})
  2193. batch_insert_device_configsNew(session, tabs, actions)
  2194. else:
  2195. all_actions = deviceConfigs.read_all(session)
  2196. all_tabs = deviceConfigTabs.read_all(session)
  2197. all_tabs_json = [item.model_dump(mode='json') for item in all_tabs]
  2198. all_actions_json = [item.model_dump(mode="json") for item in all_actions]
  2199. data_json = json.dumps(
  2200. {"tabs": all_tabs_json, "actions": all_actions_json}, ensure_ascii=False
  2201. )
  2202. sync_url = settings.DOMAIN + "/api/ai_image/camera_machine/sync_actions"
  2203. result = requests.post(url=sync_url, headers=headers, data=data_json)
  2204. tabs = result.json().get("data", {}).get("tabs")
  2205. actions = result.json().get("data", {}).get("actions")
  2206. insert_action_ids = result.json().get("data", {}).get("insert_action_ids")
  2207. if tabs:
  2208. deviceConfigTabs.deleteConditions(session, {})
  2209. deviceConfigs.deleteConditions(session, {})
  2210. batch_insert_device_configsNew(session, tabs, actions)
  2211. if insert_action_ids:
  2212. for action_item in insert_action_ids:
  2213. photos = CRUD(PhotoRecord)
  2214. old_id = action_item.get("old_id")
  2215. new_id = action_item.get("new_id")
  2216. kwargs = {"action_id": new_id}
  2217. photos.updateConditionsAll(
  2218. session, conditions={"action_id": old_id}, **kwargs
  2219. )
  2220. # 因为左右脚线上id可能会发生变化 所以需要重新同步一下本地得配置信息
  2221. # syncUserJsonConfigs(hlm_token)
  2222. return {"code": 0, "msg": "操作成功", "data": None}