api.py 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390
  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. goods_art_no_arrays,excel_df,_ = __createExcelGoodsArray(params.excel_path)
  721. move_folder_array = await _process_excel_mode(
  722. goods_art_no_arrays, excel_df
  723. )
  724. else:
  725. # 处理非Excel模式
  726. move_folder_array = await _process_non_excel_mode(
  727. params, goods_art_no_arrays
  728. )
  729. # 构建配置数据
  730. config_data = await _build_config_data(params, goods_art_no_arrays)
  731. # 执行抠图处理
  732. handler_result_folder, handler_result = await _process_cutout(
  733. run_main, config_data, goods_art_no_arrays, move_folder_array
  734. )
  735. # 处理场景图和模特图
  736. return_data_check_before_detail = run_main.check_before_detail(config_data)
  737. # 检查处理结果
  738. success_handler = return_data_check_before_detail.get("data", {}).get("config_data", {}).get("success_handler", [])
  739. failed_items = [item for item in success_handler if item.get('success') == False]
  740. if failed_items:
  741. await sendAsyncMessage(
  742. msg="处理结束",
  743. data={"output_folder": handler_result_folder, "list": failed_items},
  744. status="处理结束",
  745. msg_type="detail_result_progress",
  746. )
  747. # 如果全部失败,直接终止
  748. if failed_items and len(failed_items) == len(success_handler):
  749. return True
  750. # 处理场景图
  751. if is_product_scene == 1:
  752. return_data_check_before_detail = await _process_scene_images(
  753. aigc_clazz, run_main, return_data_check_before_detail, product_scene_prompt
  754. )
  755. # 处理模特图
  756. if is_upper_footer == 1:
  757. return_data_check_before_detail = await _process_model_images(
  758. aigc_clazz, run_main, return_data_check_before_detail, upper_footer_params
  759. )
  760. # 处理详情页
  761. if is_detail == 1:
  762. handler_result_folder, handler_result= await _process_detail_pages(
  763. run_main, return_data_check_before_detail, onlineData,
  764. online_stores, goods_art_no_arrays, handler_result_folder
  765. )
  766. # 如果需要上传到第三方平台
  767. if online_stores:
  768. await _upload_to_third_party(
  769. onlineData, return_data_check_before_detail,
  770. config_data, online_stores
  771. )
  772. await sendAsyncMessage(
  773. msg="处理结束",
  774. data={"output_folder": handler_result_folder, "list": handler_result},
  775. status="处理结束",
  776. msg_type="detail_result_progress",
  777. )
  778. else:
  779. await sendAsyncMessage(
  780. msg="处理结束",
  781. data={"output_folder": handler_result_folder, "list": handler_result},
  782. status="处理结束",
  783. msg_type="detail_result_progress",
  784. )
  785. except UnicornException as e:
  786. await _handle_exception(e.msg, handler_result_folder)
  787. # except Exception as e:
  788. # await _handle_exception(str(e), handler_result_folder)
  789. return True
  790. async def _process_non_excel_mode(params, goods_art_no_arrays):
  791. """处理非Excel模式的准备工作"""
  792. limit_path = "output/{}".format(time.strftime("%Y-%m-%d", time.localtime(time.time())))
  793. check_path(limit_path)
  794. move_folder_array = check_move_goods_art_no_folder("output", goods_art_no_arrays, limit_path)
  795. for goods_art_no in goods_art_no_arrays:
  796. if not goods_art_no:
  797. raise UnicornException("货号不能为空")
  798. session = SqlQuery()
  799. pr = CRUD(PhotoRecord)
  800. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  801. if not images:
  802. raise UnicornException(
  803. f"商品货号【{goods_art_no}】未查询到拍摄记录,请检查货号是否正确"
  804. )
  805. detail_counts = len(params.template_image_order.split(","))
  806. image_counts = len(images)
  807. if image_counts < detail_counts:
  808. raise UnicornException(
  809. f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  810. )
  811. if move_folder_array.get(goods_art_no) is None:
  812. await _process_image_copy_and_move(goods_art_no, images,False)
  813. return move_folder_array
  814. async def _process_excel_mode(goods_art_no_arrays,excel_df):
  815. """处理非Excel模式的准备工作"""
  816. limit_path = "output/{}".format(time.strftime("%Y-%m-%d", time.localtime(time.time())))
  817. check_path(limit_path)
  818. move_folder_array = check_move_goods_art_no_folder("output", goods_art_no_arrays, limit_path)
  819. for index, row in excel_df.iterrows():
  820. goods_art_no_image_dir = str(row["文件夹名称"])
  821. goods_art_no = str(row["商品货号"])
  822. print("货号数据", goods_art_no)
  823. if not goods_art_no:
  824. raise UnicornException("货号不能为空")
  825. session = SqlQuery()
  826. pr = CRUD(PhotoRecord)
  827. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  828. if not images:
  829. raise UnicornException(
  830. f"商品货号【{goods_art_no}】未查询到拍摄记录,请检查表格中的货号数据列"
  831. )
  832. # 货号目录不存在再去进行移动和创建操作
  833. if move_folder_array.get(goods_art_no) is None:
  834. await _process_image_copy_and_move(goods_art_no_image_dir, images,True)
  835. return move_folder_array
  836. async def _process_image_copy_and_move(goods_art_no, images,is_excel):
  837. """处理图片复制和移动"""
  838. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  839. check_path(image_dir)
  840. for idx, itemImg in enumerate(images):
  841. if not itemImg.image_path:
  842. raise UnicornException(
  843. f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  844. )
  845. new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  846. if not os.path.exists(image_dir + "/" + os.path.basename(new_file_name)):
  847. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  848. dealImage = DealImage(image_dir)
  849. resFlag, path = dealImage.dealMoveImage(
  850. image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  851. )
  852. if not resFlag:
  853. raise UnicornException(path)
  854. if is_excel:
  855. shutil.rmtree(image_dir)
  856. async def _build_config_data(params, goods_art_no_arrays):
  857. """构建配置数据"""
  858. temp_class = {}
  859. temp_name_list = []
  860. for tempItem in params.temp_list:
  861. temp_class[tempItem.template_id] = tempItem.template_local_classes
  862. temp_name_list.append(tempItem.template_id)
  863. cutOutMode = (
  864. "1"
  865. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图") == "普通抠图"
  866. else "2"
  867. )
  868. limit_path = "output/{}".format(time.strftime("%Y-%m-%d", time.localtime(time.time())))
  869. config_data = {
  870. "image_dir": limit_path,
  871. "image_order": (
  872. "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  873. if not params.template_image_order
  874. else params.template_image_order
  875. ),
  876. "goods_art_no": "",
  877. "goods_art_nos": goods_art_no_arrays,
  878. "is_check_number": False,
  879. "resize_image_view": "后跟",
  880. "cutout_mode": cutOutMode,
  881. "logo_path": params.logo_path,
  882. "special_goods_art_no_folder_line": "",
  883. "is_use_excel": (False if params.excel_path == "" else True), # 是否使用excel
  884. "excel_path": params.excel_path, # excel路径
  885. "is_check_color_is_all": False,
  886. "cutout_is_pass": True,
  887. "assigned_page_dict": {},
  888. "detail_is_pass": True,
  889. "upload_is_pass": False,
  890. "upload_is_enable": False,
  891. "is_filter": False,
  892. "temp_class": temp_class,
  893. "temp_name": params.temp_name,
  894. "temp_name_list": temp_name_list,
  895. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  896. "success_handler": [],
  897. }
  898. # 动态导入类
  899. try:
  900. temp_class_dict = {}
  901. for key, class_path in config_data["temp_class"].items():
  902. module_path, class_name = class_path.rsplit(".", 1)
  903. module = importlib.import_module(module_path)
  904. cls = getattr(module, class_name)
  905. temp_class_dict[key] = cls
  906. except:
  907. raise UnicornException("详情页模板不存在或未下载完成,请重启软件后重试")
  908. config_data["temp_class"] = temp_class_dict
  909. return config_data
  910. async def _process_cutout(run_main, config_data, goods_art_no_arrays, move_folder_array):
  911. """处理抠图"""
  912. handler_result = []
  913. handler_result_folder = ""
  914. return_data = run_main.check_before_cutout(config_data)
  915. cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  916. if cutout_res:
  917. sys_path = format(os.getcwd()).replace("\\", "/")
  918. handler_result_folder = f"{sys_path}/{config_data['image_dir']}"
  919. for goods_art_item in goods_art_no_arrays:
  920. handler_result.append({
  921. "goods_art_no": goods_art_item,
  922. "success": True,
  923. "info": "处理成功",
  924. })
  925. if len(move_folder_array.keys()) == len(goods_art_no_arrays):
  926. progress = {
  927. "status": "处理完成",
  928. "current": len(goods_art_no_arrays),
  929. "total": len(goods_art_no_arrays),
  930. "error": 0
  931. }
  932. await sendAsyncMessage(
  933. msg="抠图完成",
  934. data={"output_folder": handler_result_folder, "list": handler_result},
  935. status="抠图完成",
  936. msg_type="segment_progress",
  937. progress=progress
  938. )
  939. return handler_result_folder, handler_result
  940. async def _process_scene_images(aigc_clazz, run_main, return_data_check_before_detail, product_scene_prompt):
  941. """处理场景图生成"""
  942. # 参数验证
  943. if not product_scene_prompt:
  944. raise UnicornException("请填写场景描述")
  945. goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  946. new_goods_dict = {}
  947. product_scene_total_progress = len(goods_dict.keys())
  948. product_scene_finish_progress = 0
  949. product_scene_error_progress = 0
  950. product_scene_progress = {
  951. "status": "正在处理",
  952. "current": product_scene_finish_progress,
  953. "total": product_scene_total_progress,
  954. "error": product_scene_error_progress
  955. }
  956. await sendAsyncMessage(
  957. msg="开始处理场景图",
  958. goods_arts=[goods_art_no for goods_art_no in goods_dict.keys()],
  959. status="开始处理",
  960. msg_type="scene_progress",
  961. progress=product_scene_progress
  962. )
  963. for goods_art_no in goods_dict.keys():
  964. product_scene_finish_progress += 1
  965. product_scene_progress = {
  966. "status": "正在处理",
  967. "goods_art_no": goods_art_no,
  968. "current": product_scene_finish_progress,
  969. "total": product_scene_total_progress,
  970. "error": product_scene_error_progress
  971. }
  972. await sendAsyncMessage(
  973. msg="正在处理场景图",
  974. goods_arts=[goods_art_no],
  975. status="正在处理场景图",
  976. msg_type="scene_progress",
  977. progress=product_scene_progress
  978. )
  979. goods_art_dict_info = goods_dict[goods_art_no]
  980. first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  981. first_pics = first_goods_art_no_info.get("pics")
  982. ceshi_image_path = first_pics.get("侧视-抠图")
  983. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  984. save_image_path = f"{save_root_path}场景图.jpg"
  985. if os.path.isfile(save_image_path):
  986. goods_art_dict_info["场景图"] = save_image_path
  987. new_goods_dict[goods_art_no] = goods_art_dict_info
  988. continue
  989. aigc_clazz.center_paste_image(ceshi_image_path, save_image_path)
  990. try:
  991. image_path = aigc_clazz.generateProductScene(
  992. save_image_path, product_scene_prompt, save_image_path
  993. )
  994. goods_art_dict_info["场景图"] = image_path
  995. new_goods_dict[goods_art_no] = goods_art_dict_info
  996. product_scene_progress = {
  997. "status": "处理成功",
  998. "current": product_scene_finish_progress,
  999. "total": product_scene_total_progress,
  1000. "error": product_scene_error_progress,
  1001. "goods_art_no": goods_art_no,
  1002. }
  1003. await sendAsyncMessage(
  1004. msg="场景图处理完成",
  1005. goods_arts=[goods_art_no],
  1006. status="场景图处理完成",
  1007. msg_type="scene_progress",
  1008. progress=product_scene_progress
  1009. )
  1010. except Exception as e:
  1011. os.remove(save_image_path)
  1012. product_scene_finish_progress -= 1
  1013. product_scene_error_progress += 1
  1014. product_scene_progress = {
  1015. "status": "处理失败",
  1016. "goods_art_no": goods_art_no,
  1017. "current": product_scene_finish_progress,
  1018. "total": product_scene_total_progress,
  1019. "error": product_scene_error_progress
  1020. }
  1021. await sendAsyncMessage(
  1022. msg="场景图处理失败",
  1023. goods_arts=[goods_art_no],
  1024. status="场景图处理失败",
  1025. msg_type="scene_progress",
  1026. progress=product_scene_progress
  1027. )
  1028. product_scene_progress = {
  1029. "status": "处理完成",
  1030. "current": product_scene_finish_progress,
  1031. "total": product_scene_total_progress,
  1032. "error": product_scene_error_progress
  1033. }
  1034. await sendAsyncMessage(
  1035. msg="场景图处理结束",
  1036. goods_arts=[],
  1037. status="场景图处理结束",
  1038. msg_type="scene_progress",
  1039. progress=product_scene_progress
  1040. )
  1041. if new_goods_dict:
  1042. return_data_check_before_detail["data"]["goods_no_dict"] = new_goods_dict
  1043. return return_data_check_before_detail
  1044. async def _process_model_images(aigc_clazz, run_main, return_data_check_before_detail, upper_footer_params):
  1045. """处理模特图生成"""
  1046. # 参数验证
  1047. if not upper_footer_params:
  1048. raise UnicornException("请选择模特")
  1049. man_id = upper_footer_params.get("man_id")
  1050. women_id = upper_footer_params.get("women_id")
  1051. if not man_id:
  1052. raise UnicornException("请选择男模特")
  1053. if not women_id:
  1054. raise UnicornException("请选择女模特")
  1055. goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  1056. new_goods_dict = {}
  1057. upper_footer_total_progress = len(goods_dict.keys())
  1058. upper_footer_finish_progress = 0
  1059. upper_footer_error_progress = 0
  1060. upper_footer_progress = {
  1061. "status": "正在处理",
  1062. "current": upper_footer_finish_progress,
  1063. "total": upper_footer_total_progress,
  1064. "error": upper_footer_error_progress
  1065. }
  1066. await sendAsyncMessage(
  1067. msg="开始处理模特图",
  1068. goods_arts=list(goods_dict.keys()),
  1069. status="开始处理模特图",
  1070. msg_type="upper_footer_progress",
  1071. progress=upper_footer_progress
  1072. )
  1073. for goods_art_no in goods_dict.keys():
  1074. upper_footer_finish_progress += 1
  1075. upper_footer_progress = {
  1076. "status": "正在处理",
  1077. "goods_art_no": goods_art_no,
  1078. "current": upper_footer_finish_progress,
  1079. "total": upper_footer_total_progress,
  1080. "error": upper_footer_error_progress
  1081. }
  1082. await sendAsyncMessage(
  1083. msg="正在处理模特图",
  1084. goods_arts=[goods_art_no],
  1085. status="正在处理模特图",
  1086. msg_type="upper_footer_progress",
  1087. progress=upper_footer_progress
  1088. )
  1089. goods_art_dict_info = goods_dict[goods_art_no]
  1090. first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  1091. first_pics = first_goods_art_no_info.get("pics")
  1092. gender = goods_art_dict_info.get("性别")
  1093. model_id = man_id if "男" in gender else women_id
  1094. ceshi_image_path = first_pics.get("侧视-抠图")
  1095. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  1096. save_image_path = f"{save_root_path}模特图.jpg"
  1097. if os.path.isfile(save_image_path):
  1098. goods_art_dict_info["模特图"] = save_image_path
  1099. new_goods_dict[goods_art_no] = goods_art_dict_info
  1100. continue
  1101. shutil.copy(ceshi_image_path, save_image_path)
  1102. try:
  1103. image_path = aigc_clazz.generateUpperShoes(
  1104. save_image_path, model_id, save_image_path
  1105. )
  1106. goods_art_dict_info["模特图"] = image_path
  1107. new_goods_dict[goods_art_no] = goods_art_dict_info
  1108. upper_footer_progress = {
  1109. "status": "处理完成",
  1110. "goods_art_no": goods_art_no,
  1111. "current": upper_footer_finish_progress,
  1112. "total": upper_footer_total_progress,
  1113. "error": upper_footer_error_progress
  1114. }
  1115. await sendAsyncMessage(
  1116. msg="模特图处理成功",
  1117. goods_arts=[goods_art_no],
  1118. status="模特图处理成功",
  1119. msg_type="upper_footer_progress",
  1120. progress=upper_footer_progress
  1121. )
  1122. except Exception as e:
  1123. os.remove(save_image_path)
  1124. upper_footer_error_progress += 1
  1125. upper_footer_progress = {
  1126. "status": "处理失败",
  1127. "goods_art_no": goods_art_no,
  1128. "current": upper_footer_finish_progress,
  1129. "total": upper_footer_total_progress,
  1130. "error": upper_footer_error_progress
  1131. }
  1132. await sendAsyncMessage(
  1133. msg="模特图处理失败",
  1134. goods_arts=[goods_art_no],
  1135. status="模特图处理失败",
  1136. msg_type="upper_footer_progress",
  1137. progress=upper_footer_progress
  1138. )
  1139. upper_footer_progress = {
  1140. "status": "处理完成",
  1141. "current": upper_footer_finish_progress,
  1142. "total": upper_footer_total_progress,
  1143. "error": upper_footer_error_progress
  1144. }
  1145. await sendAsyncMessage(
  1146. msg="模特图处理结束",
  1147. goods_arts=[],
  1148. status="模特图处理结束",
  1149. msg_type="upper_footer_progress",
  1150. progress=upper_footer_progress
  1151. )
  1152. if new_goods_dict:
  1153. return_data_check_before_detail["data"]["goods_no_dict"] = new_goods_dict
  1154. return return_data_check_before_detail
  1155. async def _process_detail_pages(run_main, return_data_check_before_detail, onlineData,
  1156. online_stores, goods_art_no_arrays, handler_result_folder):
  1157. """处理详情页生成和上传"""
  1158. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  1159. return_data_check_before_detail
  1160. )
  1161. print("<======>check_for_detail_first_res<======>",check_for_detail_first_res)
  1162. if isinstance(check_for_detail_first_res, partial):
  1163. result = check_for_detail_first_res()
  1164. try:
  1165. config_data = result["config_data"]
  1166. except:
  1167. config_data = result
  1168. else:
  1169. config_data = check_for_detail_first_res
  1170. out_put_dir = config_data.get("out_put_dir")
  1171. success_handler = config_data.get("success_handler")
  1172. if not out_put_dir:
  1173. handler_result_folder = ""
  1174. # 处理失败情况
  1175. else:
  1176. out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace("\\", "/")
  1177. handler_result_folder = os.path.dirname(out_put_dir_path)
  1178. if handler_result_folder:
  1179. handler_result_folder = os.path.dirname(handler_result_folder)
  1180. return handler_result_folder,success_handler
  1181. async def _upload_to_third_party(onlineData, return_data_check_before_detail,
  1182. config_data, online_stores):
  1183. """上传到第三方平台"""
  1184. result_goods_no_dict = return_data_check_before_detail["data"]["goods_no_dict"]
  1185. for goods_idx, goods_no_dict in enumerate(result_goods_no_dict.keys()):
  1186. all_detail_path_list = config_data["all_detail_path_list"]
  1187. for detail_path in all_detail_path_list:
  1188. if goods_no_dict in detail_path:
  1189. detail_path_replace = detail_path.replace("\\", "/")
  1190. result_goods_no_dict[goods_no_dict]["detail_path"] = f"{detail_path_replace}/详情页.jpg"
  1191. upload_total_progress = len(result_goods_no_dict.keys())
  1192. upload_finish_progress = 0
  1193. upload_error_progress = 0
  1194. upload_progress = {
  1195. "status": "开始处理",
  1196. "current": upload_finish_progress,
  1197. "total": upload_total_progress,
  1198. "error": upload_error_progress
  1199. }
  1200. await sendAsyncMessage(
  1201. msg="开始上传商品数据",
  1202. goods_arts=[],
  1203. status="开始上传商品数据",
  1204. msg_type="upload_goods_progress",
  1205. progress=upload_progress
  1206. )
  1207. try:
  1208. onlineData.uploadGoods2ThirdParty(
  1209. result_goods_no_dict, online_stores=online_stores
  1210. )
  1211. except Exception as e:
  1212. upload_error_progress = upload_total_progress
  1213. print(f"上传任务出现错误:{e}")
  1214. upload_finish_progress = upload_total_progress
  1215. if upload_error_progress > 0:
  1216. upload_finish_progress = 0
  1217. upload_progress = {
  1218. "status": "处理完成",
  1219. "current": upload_finish_progress,
  1220. "total": upload_total_progress,
  1221. "error": upload_error_progress
  1222. }
  1223. await sendAsyncMessage(
  1224. msg="商品上传第三方成功",
  1225. goods_arts=[],
  1226. status="商品上传第三方成功",
  1227. msg_type="upload_goods_progress",
  1228. progress=upload_progress
  1229. )
  1230. async def _handle_exception(error_msg, handler_result_folder):
  1231. """处理异常情况"""
  1232. handler_result = [{"goods_art_no": "", "success": False, "info": error_msg}]
  1233. await sendAsyncMessage(
  1234. msg="处理结束",
  1235. data={"output_folder": handler_result_folder, "list": handler_result},
  1236. status="处理结束",
  1237. msg_type="detail_result_progress",
  1238. )
  1239. # async def process_handle_detail(request: Request, params: HandlerDetail):
  1240. # obj = None
  1241. # token = "Bearer " + params.token
  1242. # uuid = params.uuid
  1243. # aigc_clazz = AIGCDataRequest(token)
  1244. # run_main = RunMain(obj, token, uuid)
  1245. # onlineData = OnlineDataRequest(token)
  1246. # goods_art_no_arrays = params.goods_art_no
  1247. # is_only_cutout = params.is_only_cutout # 是否仅抠图
  1248. # online_stores = params.online_stores # 上传第三方的店铺名称数组
  1249. # is_detail = params.is_detail # 上传第三方的店铺名称数组
  1250. # is_product_scene = params.is_product_scene # 上传第三方的店铺名称数组
  1251. # is_upper_footer = params.is_upper_footer # 上传第三方的店铺名称数组
  1252. # upper_footer_params = params.upper_footer_params # 上传第三方的店铺名称数组
  1253. # product_scene_prompt = params.product_scene_prompt # 上传第三方的店铺名称数组
  1254. # handler_result = []
  1255. # handler_result_folder = ""
  1256. # if is_only_cutout == 1:
  1257. # # 如果是仅抠图模式,避免进入到excel模式
  1258. # params.excel_path = ""
  1259. # if params.excel_path != "" and params.excel_path != None:
  1260. # return await fromExcelHandler(params)
  1261. # else:
  1262. # path = ""
  1263. # limit_path = "output/{}".format(
  1264. # time.strftime("%Y-%m-%d", time.localtime(time.time()))
  1265. # )
  1266. # check_path(limit_path)
  1267. # # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  1268. # move_folder_array = check_move_goods_art_no_folder(
  1269. # "output", goods_art_no_arrays, limit_path
  1270. # )
  1271. # try:
  1272. # for goods_art_no in goods_art_no_arrays:
  1273. # if not goods_art_no:
  1274. # raise UnicornException("货号不能为空")
  1275. # session = SqlQuery()
  1276. # pr = CRUD(PhotoRecord)
  1277. # images = pr.read_all(session, conditions={"goods_art_no": goods_art_no})
  1278. # if not images:
  1279. # raise UnicornException(
  1280. # f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确"
  1281. # )
  1282. # if is_only_cutout != 1:
  1283. # detail_counts = len(params.template_image_order.split(","))
  1284. # image_counts = len(images)
  1285. # if image_counts < detail_counts:
  1286. # raise UnicornException(
  1287. # f"货号:[{goods_art_no}],实际照片数量:{image_counts}张,小于详情图要求数量:{detail_counts}张"
  1288. # )
  1289. # if move_folder_array.get(goods_art_no) == None:
  1290. # image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  1291. # check_path(image_dir)
  1292. # for idx, itemImg in enumerate(images):
  1293. # if itemImg.image_path == "" or itemImg.image_path == None:
  1294. # raise UnicornException(
  1295. # f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
  1296. # )
  1297. # new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  1298. # if not os.path.exists(
  1299. # image_dir + "/" + os.path.basename(new_file_name)
  1300. # ):
  1301. # shutil.copy(itemImg.image_path, image_dir + new_file_name)
  1302. # dealImage = DealImage(image_dir)
  1303. # resFlag, path = dealImage.dealMoveImage(
  1304. # image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
  1305. # )
  1306. # if not resFlag:
  1307. # raise UnicornException(path)
  1308. # except UnicornException as e:
  1309. # handler_result_folder = ""
  1310. # handler_result.append(
  1311. # {"goods_art_no": "", "success": False, "info": str(e.msg)}
  1312. # )
  1313. # print(f"UnicornException 生成错误信息:{e}")
  1314. # await sendAsyncMessage(
  1315. # msg="处理结束",
  1316. # data={"output_folder": handler_result_folder, "list": handler_result},
  1317. # status="处理结束",
  1318. # msg_type="detail_result_progress",
  1319. # )
  1320. # return True
  1321. # except Exception as e:
  1322. # print(f"详情图生成错误信息:{e}")
  1323. # handler_result_folder = ""
  1324. # handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  1325. # await sendAsyncMessage(
  1326. # msg="处理结束",
  1327. # data={"output_folder": handler_result_folder, "list": handler_result},
  1328. # status="处理结束",
  1329. # msg_type="detail_result_progress",
  1330. # )
  1331. # return True
  1332. # # try:
  1333. # temp_class = {}
  1334. # temp_name_list = []
  1335. # for tempItem in params.temp_list:
  1336. # temp_class[tempItem.template_id] = tempItem.template_local_classes
  1337. # temp_name_list.append(tempItem.template_id)
  1338. # cutOutMode = (
  1339. # "1"
  1340. # if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  1341. # == "普通抠图"
  1342. # else "2"
  1343. # )
  1344. # config_data = {
  1345. # "image_dir": limit_path,
  1346. # "image_order": (
  1347. # "俯视,侧视,后跟,鞋底,内里,组合,组合2,组合3,组合4,组合5"
  1348. # if params.template_image_order == None or params.template_image_order == ""
  1349. # else params.template_image_order
  1350. # ),
  1351. # "goods_art_no": "",
  1352. # "goods_art_nos": goods_art_no_arrays,
  1353. # "is_check_number": False,
  1354. # "resize_image_view": "后跟",
  1355. # "cutout_mode": cutOutMode,
  1356. # "logo_path": params.logo_path,
  1357. # "special_goods_art_no_folder_line": "",
  1358. # "is_use_excel": False, # 是否使用excel
  1359. # "excel_path": "", # excel路径
  1360. # "is_check_color_is_all": False,
  1361. # "cutout_is_pass": True,
  1362. # "assigned_page_dict": {},
  1363. # "detail_is_pass": True,
  1364. # "upload_is_pass": False,
  1365. # "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  1366. # "is_filter": False,
  1367. # "temp_class": temp_class,
  1368. # "temp_name": params.temp_name,
  1369. # "temp_name_list": temp_name_list,
  1370. # "target_error_folder": f"{limit_path}/软件-生成详情错误",
  1371. # "success_handler": [],
  1372. # }
  1373. # print("image_dir=====>>>>>", config_data["image_dir"])
  1374. # # 动态导入类
  1375. # temp_class_dict = {}
  1376. # for key, class_path in config_data["temp_class"].items():
  1377. # module_path, class_name = class_path.rsplit(".", 1)
  1378. # module = importlib.import_module(module_path)
  1379. # cls = getattr(module, class_name)
  1380. # temp_class_dict[key] = cls
  1381. # config_data["temp_class"] = temp_class_dict
  1382. # return_data = run_main.check_before_cutout(config_data)
  1383. # cutout_res = run_main.check_for_cutout_image_first_call_back(return_data)
  1384. # check_for_detail_first_res = None
  1385. # if cutout_res == True:
  1386. # sys_path = format(os.getcwd()).replace("\\", "/")
  1387. # handler_result_folder = f"{sys_path}/{limit_path}"
  1388. # for goods_art_item in goods_art_no_arrays:
  1389. # handler_result.append(
  1390. # {
  1391. # "goods_art_no": goods_art_item,
  1392. # "success": True,
  1393. # "info": "处理成功",
  1394. # }
  1395. # )
  1396. # if len(move_folder_array.keys()) == len(goods_art_no_arrays):
  1397. # progress = {"status":"处理完成",
  1398. # "current":len(goods_art_no_arrays),
  1399. # "total":len(goods_art_no_arrays),
  1400. # "error":0
  1401. # }
  1402. # await sendAsyncMessage(
  1403. # msg="抠图完成",
  1404. # data={"output_folder": handler_result_folder, "list": handler_result},
  1405. # status="抠图完成",
  1406. # msg_type="segment_progress",
  1407. # progress=progress
  1408. # )
  1409. # try:
  1410. # if is_product_scene == 1:
  1411. # if product_scene_prompt == "" or product_scene_prompt == None:
  1412. # raise UnicornException("请填写场景描述")
  1413. # if is_upper_footer == 1:
  1414. # if upper_footer_params == {} or upper_footer_params == None:
  1415. # raise UnicornException("请选择模特")
  1416. # man_id = upper_footer_params.get("man_id")
  1417. # if not man_id:
  1418. # raise UnicornException("请选择男模特")
  1419. # women_id = upper_footer_params.get("women_id")
  1420. # if not women_id:
  1421. # raise UnicornException("请选择女模特")
  1422. # return_data_check_before_detail = run_main.check_before_detail(config_data)
  1423. # success_handler = return_data_check_before_detail.get("data").get("config_data").get("success_handler",[])
  1424. # failed_items = [item for item in success_handler if item.get('success') == False]
  1425. # print("failed_items",failed_items)
  1426. # if len(failed_items) > 0:
  1427. # await sendAsyncMessage(
  1428. # msg="处理结束",
  1429. # data={"output_folder": handler_result_folder, "list": failed_items},
  1430. # status="处理结束",
  1431. # msg_type="detail_result_progress",
  1432. # )
  1433. # if len(failed_items)!=0 and len(failed_items) == len(success_handler):
  1434. # # 如果全部错误 直接终止
  1435. # return True
  1436. # else:
  1437. # if is_product_scene == 1:
  1438. # goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  1439. # new_goods_dict = {}
  1440. # product_scene_total_progress = len(goods_dict.keys())
  1441. # product_scene_finish_progress = 0
  1442. # product_scene_error_progress = 0
  1443. # product_scene_progress = {"status":"正在处理", "current":product_scene_finish_progress, "total":product_scene_total_progress, "error":product_scene_error_progress}
  1444. # print("product_scene_progress",goods_dict,product_scene_progress)
  1445. # await sendAsyncMessage(
  1446. # msg="开始处理场景图",
  1447. # goods_arts=[goods_art_no for goods_art_no in goods_dict.keys()],
  1448. # status="开始处理",
  1449. # msg_type="scene_progress",
  1450. # progress=product_scene_progress
  1451. # )
  1452. # for goods_art_no in goods_dict.keys():
  1453. # print("处理场景图", goods_art_no)
  1454. # product_scene_finish_progress+=1
  1455. # 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}
  1456. # await sendAsyncMessage(
  1457. # msg="正在处理场景图",
  1458. # goods_arts=[goods_art_no],
  1459. # status="正在处理场景图",
  1460. # msg_type="scene_progress",
  1461. # progress=product_scene_progress
  1462. # )
  1463. # goods_art_dict_info = goods_dict[goods_art_no]
  1464. # first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  1465. # first_pics = first_goods_art_no_info.get("pics")
  1466. # ceshi_image_path = first_pics.get("侧视-抠图")
  1467. # save_root_path = ceshi_image_path.split("阴影图处理")[0]
  1468. # save_image_path = f"{save_root_path}场景图.jpg"
  1469. # if os.path.isfile(save_image_path):
  1470. # goods_art_dict_info["场景图"] = save_image_path
  1471. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1472. # continue
  1473. # aigc_clazz.center_paste_image(ceshi_image_path, save_image_path)
  1474. # try:
  1475. # image_path = aigc_clazz.generateProductScene(
  1476. # save_image_path, product_scene_prompt, save_image_path
  1477. # )
  1478. # # image_path = aigc_clazz.generateProductSceneQW(
  1479. # # save_image_path, product_scene_prompt, save_image_path
  1480. # # )
  1481. # goods_art_dict_info["场景图"] = image_path
  1482. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1483. # handler_result.append(
  1484. # {
  1485. # "goods_art_no": goods_art_no,
  1486. # "success": True,
  1487. # "info": "场景图处理成功",
  1488. # }
  1489. # )
  1490. # product_scene_progress = {
  1491. # "status":"处理成功",
  1492. # "current":product_scene_finish_progress,
  1493. # "total":product_scene_total_progress,
  1494. # "error":product_scene_error_progress,
  1495. # "goods_art_no":goods_art_no,
  1496. # }
  1497. # await sendAsyncMessage(
  1498. # msg="场景图处理完成",
  1499. # goods_arts=[goods_art_no],
  1500. # status="场景图处理完成",
  1501. # msg_type="scene_progress",
  1502. # progress=product_scene_progress
  1503. # )
  1504. # except Exception as e:
  1505. # os.remove(save_image_path)
  1506. # handler_result.append(
  1507. # {
  1508. # "goods_art_no": goods_art_no,
  1509. # "success": False,
  1510. # "info": f"场景图处理失败:{e}",
  1511. # }
  1512. # )
  1513. # product_scene_finish_progress -=1
  1514. # product_scene_error_progress +=1
  1515. # 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}
  1516. # await sendAsyncMessage(
  1517. # msg="场景图处理失败",
  1518. # goods_arts=[goods_art_no],
  1519. # status="场景图处理失败",
  1520. # msg_type="scene_progress",
  1521. # progress=product_scene_progress
  1522. # )
  1523. # product_scene_progress = {"status":"处理完成", "current":product_scene_finish_progress, "total":product_scene_total_progress, "error":product_scene_error_progress}
  1524. # await sendAsyncMessage(
  1525. # msg="场景图处理结束",
  1526. # goods_arts=[],
  1527. # status="场景图处理结束",
  1528. # msg_type="scene_progress",
  1529. # progress=product_scene_progress
  1530. # )
  1531. # if new_goods_dict is not None or new_goods_dict != {}:
  1532. # return_data_check_before_detail["data"][
  1533. # "goods_no_dict"
  1534. # ] = new_goods_dict
  1535. # if is_upper_footer == 1:
  1536. # goods_dict = parserGoodsDict2Aigc(return_data_check_before_detail)
  1537. # new_goods_dict = {}
  1538. # upper_footer_total_progress = len(goods_dict.keys())
  1539. # upper_footer_finish_progress = 0
  1540. # upper_footer_error_progress = 0
  1541. # upper_footer_progress = {"status":"正在处理", "current":upper_footer_finish_progress, "total":upper_footer_total_progress, "error":upper_footer_error_progress}
  1542. # await sendAsyncMessage(
  1543. # msg="开始处理模特图",
  1544. # goods_arts=list(goods_dict.keys()),
  1545. # status="开始处理模特图",
  1546. # msg_type="upper_footer_progress",
  1547. # progress=upper_footer_progress
  1548. # )
  1549. # for goods_art_no in goods_dict.keys():
  1550. # upper_footer_finish_progress+=1
  1551. # 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}
  1552. # await sendAsyncMessage(
  1553. # msg="正在处理模特图",
  1554. # goods_arts=[goods_art_no],
  1555. # status="正在处理模特图",
  1556. # msg_type="upper_footer_progress",
  1557. # progress=upper_footer_progress
  1558. # )
  1559. # goods_art_dict_info = goods_dict[goods_art_no]
  1560. # first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
  1561. # first_pics = first_goods_art_no_info.get("pics")
  1562. # gender = goods_art_dict_info.get("性别")
  1563. # model_id = man_id if "男" in gender else women_id
  1564. # ceshi_image_path = first_pics.get("侧视-抠图")
  1565. # save_root_path = ceshi_image_path.split("阴影图处理")[0]
  1566. # save_image_path = f"{save_root_path}模特图.jpg"
  1567. # if os.path.isfile(save_image_path):
  1568. # goods_art_dict_info["模特图"] = save_image_path
  1569. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1570. # continue
  1571. # shutil.copy(ceshi_image_path, save_image_path)
  1572. # try:
  1573. # image_path = aigc_clazz.generateUpperShoes(
  1574. # save_image_path, model_id, save_image_path
  1575. # )
  1576. # # image_path = aigc_clazz.generateModelShoesQW(
  1577. # # save_image_path, model_id, save_image_path
  1578. # # )
  1579. # goods_art_dict_info["模特图"] = image_path
  1580. # new_goods_dict[goods_art_no] = goods_art_dict_info
  1581. # handler_result.append(
  1582. # {
  1583. # "goods_art_no": goods_art_no,
  1584. # "success": True,
  1585. # "info": "模特图处理成功",
  1586. # }
  1587. # )
  1588. # 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}
  1589. # await sendAsyncMessage(
  1590. # msg="模特图处理成功",
  1591. # goods_arts=[goods_art_no],
  1592. # status="模特图处理成功",
  1593. # msg_type="upper_footer_progress",
  1594. # progress=upper_footer_progress
  1595. # )
  1596. # except Exception as e:
  1597. # os.remove(save_image_path)
  1598. # handler_result.append(
  1599. # {
  1600. # "goods_art_no": goods_art_no,
  1601. # "success": False,
  1602. # "info": f"模特图处理失败:{e}",
  1603. # }
  1604. # )
  1605. # upper_footer_error_progress+=1
  1606. # 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}
  1607. # await sendAsyncMessage(
  1608. # msg="模特图处理失败",
  1609. # goods_arts=[goods_art_no],
  1610. # status="模特图处理失败",
  1611. # msg_type="upper_footer_progress",
  1612. # progress=upper_footer_progress
  1613. # )
  1614. # upper_footer_progress = {"status":"处理完成", "current":upper_footer_finish_progress, "total":upper_footer_total_progress, "error":upper_footer_error_progress}
  1615. # await sendAsyncMessage(
  1616. # msg="模特图处理结束",
  1617. # goods_arts=[],
  1618. # status="模特图处理结束",
  1619. # msg_type="upper_footer_progress",
  1620. # progress=upper_footer_progress
  1621. # )
  1622. # if new_goods_dict is not None or new_goods_dict != {}:
  1623. # return_data_check_before_detail["data"][
  1624. # "goods_no_dict"
  1625. # ] = new_goods_dict
  1626. # if is_detail == 0:
  1627. # await sendAsyncMessage(
  1628. # msg="处理结束",
  1629. # data={"output_folder": handler_result_folder, "list": handler_result},
  1630. # status="处理结束",
  1631. # msg_type="detail_result_progress",
  1632. # )
  1633. # return True
  1634. # check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  1635. # return_data_check_before_detail
  1636. # )
  1637. # if isinstance(check_for_detail_first_res, partial):
  1638. # result = check_for_detail_first_res()
  1639. # try:
  1640. # config_data = result["config_data"]
  1641. # except:
  1642. # config_data = result
  1643. # if config_data["sign_text"] == "已结束详情处理":
  1644. # print("config_data", config_data)
  1645. # out_put_dir = config_data.get("out_put_dir")
  1646. # if out_put_dir == None:
  1647. # handler_result_folder = ""
  1648. # if len(config_data["success_handler"]) > 0:
  1649. # for good_art in config_data["success_handler"]:
  1650. # handler_result.append(good_art)
  1651. # else:
  1652. # for good_art in goods_art_no_arrays:
  1653. # handler_result.append(
  1654. # {
  1655. # "goods_art_no": good_art,
  1656. # "success": False,
  1657. # "info": "处理失败",
  1658. # }
  1659. # )
  1660. # else:
  1661. # out_put_dir_path = "{}/{}".format(os.getcwd(), out_put_dir).replace(
  1662. # "\\", "/"
  1663. # )
  1664. # handler_result_folder = os.path.dirname(out_put_dir_path)
  1665. # if len(config_data["success_handler"]) == 0:
  1666. # for good_art in goods_art_no_arrays:
  1667. # handler_result.append(
  1668. # {
  1669. # "goods_art_no": good_art,
  1670. # "success": False,
  1671. # "info": "处理失败",
  1672. # }
  1673. # )
  1674. # else:
  1675. # if len(online_stores) > 0:
  1676. # result_goods_no_dict = return_data_check_before_detail["data"][
  1677. # "goods_no_dict"
  1678. # ]
  1679. # for goods_idx, goods_no_dict in enumerate(
  1680. # result_goods_no_dict.keys()
  1681. # ):
  1682. # all_detail_path_list = config_data["all_detail_path_list"]
  1683. # for detail_path in all_detail_path_list:
  1684. # if goods_no_dict in detail_path:
  1685. # detail_path_replace = detail_path.replace("\\", "/")
  1686. # result_goods_no_dict[goods_no_dict][
  1687. # "detail_path"
  1688. # ] = f"{detail_path_replace}/详情页.jpg"
  1689. # upload_total_progress = len(result_goods_no_dict.keys())
  1690. # upload_finish_progress = 0
  1691. # upload_error_progress = 0
  1692. # upload_progress = {"status":"开始处理", "current":upload_finish_progress, "total":upload_total_progress, "error":upload_error_progress}
  1693. # await sendAsyncMessage(
  1694. # msg="开始上传商品数据",
  1695. # goods_arts=[],
  1696. # status="开始上传商品数据",
  1697. # msg_type="upload_goods_progress",
  1698. # progress=upload_progress
  1699. # )
  1700. # try:
  1701. # onlineData.uploadGoods2ThirdParty(
  1702. # result_goods_no_dict, online_stores=online_stores
  1703. # )
  1704. # except Exception as e:
  1705. # upload_error_progress = upload_total_progress
  1706. # print(f"上传任务出现错误:{e}")
  1707. # upload_finish_progress = upload_total_progress
  1708. # if upload_error_progress > 0:
  1709. # upload_finish_progress = 0
  1710. # upload_progress = {"status":"处理完成", "current":upload_finish_progress, "total":upload_total_progress, "error":upload_error_progress}
  1711. # await sendAsyncMessage(
  1712. # msg="商品上传第三方成功",
  1713. # goods_arts=[],
  1714. # status="商品上传第三方成功",
  1715. # msg_type="upload_goods_progress",
  1716. # progress=upload_progress
  1717. # )
  1718. # handler_result = config_data["success_handler"]
  1719. # else:
  1720. # handler_result.append(
  1721. # {"goods_art_no": "", "success": False, "info": "处理失败"}
  1722. # )
  1723. # except UnicornException as e:
  1724. # handler_result_folder = ""
  1725. # handler_result.append(
  1726. # {"goods_art_no": "", "success": False, "info": str(e.msg)}
  1727. # )
  1728. # print(f"UnicornException 生成错误信息:{e}")
  1729. # except Exception as e:
  1730. # print(f"详情图生成错误信息:{e}")
  1731. # handler_result_folder = ""
  1732. # handler_result.append({"goods_art_no": "", "success": False, "info": str(e)})
  1733. # await sendAsyncMessage(
  1734. # msg="处理结束",
  1735. # data={"output_folder": handler_result_folder, "list": handler_result},
  1736. # status="处理结束",
  1737. # msg_type="detail_result_progress",
  1738. # )
  1739. # return True
  1740. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  1741. def get_device_tabs(type: int):
  1742. session = SqlQuery()
  1743. statement = (
  1744. select(DeviceConfigTabs)
  1745. .where(DeviceConfigTabs.mode_type == type)
  1746. .order_by(asc("id"))
  1747. )
  1748. result = session.exec(statement).all()
  1749. session.close()
  1750. sys = CRUD(SysConfigs)
  1751. action_configs = sys.read(session, conditions={"key": "action_configs"})
  1752. session.close()
  1753. return {
  1754. "code": 0,
  1755. "msg": "",
  1756. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  1757. }
  1758. @app.post("/update_tab_name", description="更改tab名称")
  1759. def update_tab_name(params: DeviceConfigTabsReq):
  1760. if params.mode_name == "":
  1761. return {"code": 1, "msg": "名称不能为空", "data": {}}
  1762. session = SqlQuery()
  1763. tabModel = CRUD(DeviceConfigTabs)
  1764. kwargs = {"mode_name": params.mode_name}
  1765. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  1766. session.close()
  1767. return {
  1768. "code": 0,
  1769. "msg": "",
  1770. "data": None,
  1771. }
  1772. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  1773. def get_device_configs(params: ModelGetDeviceConfig):
  1774. tab_id = params.tab_id
  1775. session = SqlQuery()
  1776. configModel = CRUD(DeviceConfig)
  1777. configList = configModel.read_all(
  1778. session,
  1779. conditions={"tab_id": tab_id},
  1780. order_by="action_index",
  1781. ascending=True,
  1782. )
  1783. return {
  1784. "code": 0,
  1785. "msg": "",
  1786. "data": {"list": configList},
  1787. }
  1788. @app.post("/device_config_detail", description="获取可执行程序详情")
  1789. def device_config_detail(params: ModelGetDeviceConfigDetail):
  1790. action_id = params.id
  1791. session = SqlQuery()
  1792. configModel = CRUD(DeviceConfig)
  1793. model = configModel.read(session, conditions={"id": action_id})
  1794. if model == None:
  1795. return {"code": 1, "msg": "数据不存在", "data": None}
  1796. return {"code": 0, "msg": "", "data": model}
  1797. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  1798. def device_config_detail_query():
  1799. # tab_id = params.tab_id
  1800. # action_name = params.action_name
  1801. session = SqlQuery()
  1802. sys = CRUD(SysConfigs)
  1803. action_configs = sys.read(session, conditions={"key": "action_configs"})
  1804. action_configs_value = json.loads(action_configs.value)
  1805. left_config = action_configs_value.get("left")
  1806. configModel = CRUD(DeviceConfig)
  1807. model = configModel.read(
  1808. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  1809. )
  1810. if model == None:
  1811. model = configModel.read(session, conditions={"tab_id": left_config})
  1812. return {"code": 0, "msg": "", "data": model}
  1813. @app.post("/remove_config", description="删除一条可执行命令")
  1814. def get_device_configs(params: ModelGetDeviceConfigDetail):
  1815. action_id = params.id
  1816. session = SqlQuery()
  1817. configModel = CRUD(DeviceConfig)
  1818. model = configModel.read(session, conditions={"id": action_id})
  1819. if model == None:
  1820. return {"code": 1, "msg": "数据不存在", "data": None}
  1821. if model.is_system == True:
  1822. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  1823. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  1824. if len(configArray) == 1:
  1825. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  1826. configModel.delete(session, obj_id=action_id)
  1827. return {"code": 0, "msg": "删除成功", "data": None}
  1828. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  1829. def save_device_config(params: SaveDeviceConfig):
  1830. action_id = params.id
  1831. session = SqlQuery()
  1832. deviceConfig = CRUD(DeviceConfig)
  1833. if action_id == None or action_id == 0:
  1834. # 走新增逻辑
  1835. params.id = None
  1836. save_device_config = deviceConfig.create(session, obj_in=params)
  1837. else:
  1838. model = deviceConfig.read(session, conditions={"id": action_id})
  1839. if model == None:
  1840. return {"code": 1, "msg": "数据不存在", "data": None}
  1841. # 走编辑逻辑
  1842. kwargs = params.__dict__
  1843. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  1844. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  1845. @app.post("/reset_config", description="创建或修改一条可执行命令")
  1846. def reset_config(params: ModelGetDeviceConfig):
  1847. tab_id = params.tab_id
  1848. if tab_id == None or tab_id == "":
  1849. return {"code": 1, "msg": "参数错误", "data": None}
  1850. session = SqlQuery()
  1851. deviceConfig = CRUD(DeviceConfig)
  1852. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  1853. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  1854. if res is False:
  1855. return {"code": 1, "msg": "操作失败", "data": None}
  1856. actions = json.load(open("action.json", encoding="utf-8"))
  1857. for data in actions:
  1858. data["tab_id"] = tab_id
  1859. data["is_system"] = first_config.is_system
  1860. device_config = DeviceConfig(**data)
  1861. session.add(device_config)
  1862. session.commit()
  1863. # session.close()
  1864. return {"code": 0, "msg": "操作成功", "data": None}
  1865. @app.get("/get_photo_records", description="获取拍照记录")
  1866. def get_photo_records(page: int = 1, size: int = 5):
  1867. session = SqlQuery()
  1868. # photos = CRUD(PhotoRecord)
  1869. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1870. statement = (
  1871. select(PhotoRecord)
  1872. .offset((page - 1) * size)
  1873. .limit(size)
  1874. .order_by(desc("id"))
  1875. .group_by("goods_art_no")
  1876. )
  1877. list = []
  1878. result = session.exec(statement).all()
  1879. print("group 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1880. join_conditions = [
  1881. {
  1882. "model": DeviceConfig,
  1883. "on": PhotoRecord.action_id == DeviceConfig.id,
  1884. "is_outer": False, # 可选,默认False,设为True则为LEFT JOIN
  1885. }
  1886. ]
  1887. for item in result:
  1888. query = (
  1889. select(PhotoRecord, DeviceConfig.action_name)
  1890. .where(PhotoRecord.goods_art_no == item.goods_art_no)
  1891. .join(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  1892. )
  1893. list_item = session.exec(query).mappings().all()
  1894. list.append(
  1895. {
  1896. "goods_art_no": item.goods_art_no,
  1897. "action_time": item.create_time,
  1898. "items": list_item,
  1899. }
  1900. )
  1901. # session.close()
  1902. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1903. return {
  1904. "code": 0,
  1905. "msg": "",
  1906. "data": {"list": list, "page": page, "size": size},
  1907. }
  1908. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  1909. def get_last_photo_record():
  1910. session = SqlQuery()
  1911. statement = (
  1912. select(PhotoRecord)
  1913. .where(PhotoRecord.image_path != None)
  1914. .order_by(desc("photo_create_time"))
  1915. )
  1916. result = session.exec(statement).first()
  1917. # session.close()
  1918. return {
  1919. "code": 0,
  1920. "msg": "",
  1921. "data": result,
  1922. }
  1923. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  1924. def get_photo_record_detail(goods_art_no: str = None):
  1925. if goods_art_no == None:
  1926. return {"code": 1, "msg": "参数错误", "data": None}
  1927. session = SqlQuery()
  1928. photos = CRUD(PhotoRecord)
  1929. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no})
  1930. # session.close()
  1931. return {
  1932. "code": 0,
  1933. "msg": "",
  1934. "data": {"list": items},
  1935. }
  1936. @app.post("/delect_goods_arts", description="通过货号删除记录")
  1937. def delect_goods_arts(params: PhotoRecordDelete):
  1938. session = SqlQuery()
  1939. photos = CRUD(PhotoRecord)
  1940. for item in params.goods_art_nos:
  1941. photos.deleteConditions(session, conditions={"goods_art_no": item})
  1942. # session.close()
  1943. return {
  1944. "code": 0,
  1945. "msg": "操作成功",
  1946. "data": None,
  1947. }
  1948. def query_config_by_key(key_name):
  1949. """
  1950. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  1951. Args:
  1952. key_name (str): 要查询的key名称
  1953. Returns:
  1954. dict or None: 匹配的对象或None(如果没有找到)
  1955. """
  1956. try:
  1957. # 获取所有配置数据
  1958. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  1959. # 遍历配置数据查找匹配的key
  1960. for config in configs:
  1961. if config.get("key") == key_name:
  1962. return config
  1963. return None
  1964. except Exception as e:
  1965. print(f"查询配置时出错: {e}")
  1966. return None
  1967. @app.get("/get_sys_config", description="查询系统配置")
  1968. def get_sys_config(key: str = None):
  1969. if key == None:
  1970. return {"code": 1, "msg": "参数错误", "data": None}
  1971. session = SqlQuery()
  1972. photos = CRUD(SysConfigs)
  1973. item = photos.read(session, conditions={"key": key})
  1974. search_data = None if item == None else json.loads(item.value)
  1975. if search_data == None:
  1976. sys_config_json = query_config_by_key(key)
  1977. if sys_config_json != None:
  1978. config = SysConfigs(**sys_config_json)
  1979. session.add(config)
  1980. session.commit() # 合并事务提交
  1981. search_data = json.loads(sys_config_json.get("value"))
  1982. return {
  1983. "code": 0,
  1984. "msg": "",
  1985. "data": search_data,
  1986. }
  1987. @app.post("/update_left_right_config", description="更新左右脚配置")
  1988. def update_left_right_config(params: LeftRightParams):
  1989. session = SqlQuery()
  1990. sysConfig = CRUD(SysConfigs)
  1991. model = sysConfig.read(session, conditions={"key": "action_configs"})
  1992. if model == None:
  1993. return {"code": 1, "msg": "配置不存在", "data": None}
  1994. config_value = json.loads(model.value)
  1995. config_value[params.type] = params.id
  1996. update_value = json.dumps(config_value)
  1997. # 走编辑逻辑
  1998. kwargs = {"key": "action_configs", "value": update_value}
  1999. save_device_config = sysConfig.updateConditions(
  2000. session, conditions={"key": "action_configs"}, **kwargs
  2001. )
  2002. return {"code": 0, "msg": "操作成功", "data": None}
  2003. @app.post("/update_record", description="更新拍照记录")
  2004. def update_record(params: RecordUpdate):
  2005. session = SqlQuery()
  2006. photoRecord = CRUD(PhotoRecord)
  2007. model = photoRecord.read(session, conditions={"id": params.id})
  2008. if model == None:
  2009. return {"code": 1, "msg": "记录不存在", "data": None}
  2010. kwargs = params.__dict__
  2011. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  2012. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  2013. @app.post("/update_sys_configs", description="创建或修改系统配置")
  2014. def save_sys_configs(params: SysConfigParams):
  2015. session = SqlQuery()
  2016. sysConfig = CRUD(SysConfigs)
  2017. model = sysConfig.read(session, conditions={"key": params.key})
  2018. if model == None:
  2019. return {"code": 1, "msg": "配置不存在", "data": None}
  2020. # 走编辑逻辑
  2021. kwargs = params.__dict__
  2022. save_device_config = sysConfig.updateConditions(
  2023. session, conditions={"key": params.key}, **kwargs
  2024. )
  2025. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  2026. @app.post("/create_main_image", description="创建主图测试")
  2027. def create_main_image(params: MaineImageTest):
  2028. file_path = params.file_path
  2029. onePic = OnePicTest(pic_path=file_path)
  2030. main_out_path = onePic.HandlerMainImage()
  2031. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  2032. def insertEmptyLogoList(session):
  2033. """插入空logo列表"""
  2034. data = {"key": "logo_configs", "value": "[]"}
  2035. config = SysConfigs(**data)
  2036. session.add(config)
  2037. session.commit()
  2038. session.close()
  2039. item = SysConfigs()
  2040. item.key = "logo_configs"
  2041. item.value = "[]"
  2042. return item
  2043. @app.get("/logo_list", description="logo列表")
  2044. def logo_list():
  2045. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  2046. check_path(logo_dir)
  2047. logo_files = os.listdir(logo_dir)
  2048. logo_list = []
  2049. for logoItem in logo_files:
  2050. logo_list.append(f"{logo_dir}{logoItem}")
  2051. return {"code": 0, "msg": "操作成功", "data": logo_list}
  2052. @app.post("/add_logo", description="添加logo")
  2053. def add_logo(params: LogoParams):
  2054. logo_path = params.logo_path.replace("\\", "/")
  2055. session = SqlQuery()
  2056. sysConfig = CRUD(SysConfigs)
  2057. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  2058. if item == None:
  2059. item = insertEmptyLogoList(session)
  2060. if os.path.isfile(logo_path) == False:
  2061. return {"code": 1, "msg": "logo文件不存在", "data": None}
  2062. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  2063. check_path(logo_dir)
  2064. fpath, fname = os.path.split(logo_path)
  2065. logo_path_info = logo_dir + fname
  2066. shutil.copy(logo_path, logo_path_info) # 复制文件
  2067. logo_files = os.listdir(logo_dir)
  2068. logo_list = []
  2069. for logoItem in logo_files:
  2070. logo_list.append(f"{logo_dir}{logoItem}")
  2071. return {
  2072. "code": 0,
  2073. "msg": "",
  2074. "data": {"logo": logo_path_info},
  2075. }
  2076. @app.post("/delete_logo", description="删除logo")
  2077. def delete_logo(params: LogoParamsupdate):
  2078. logo_path = params.path
  2079. if os.path.isfile(logo_path) == False:
  2080. return {"code": 1, "msg": "logo文件不存在", "data": None}
  2081. os.remove(logo_path)
  2082. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  2083. check_path(logo_dir)
  2084. logo_files = os.listdir(logo_dir)
  2085. logo_list = []
  2086. for logoItem in logo_files:
  2087. logo_list.append(f"{logo_dir}{logoItem}")
  2088. return {"code": 0, "msg": "操作成功", "data": logo_list}
  2089. @app.post("/close_other_window", description="关闭窗口")
  2090. def close_other_window():
  2091. hwnd_list = []
  2092. def callback(hwnd, _):
  2093. title = GetWindowText(hwnd)
  2094. if title == "digiCamControl by Duka Istvan":
  2095. hwnd_list.append(hwnd)
  2096. EnumWindows(callback, None)
  2097. if hwnd_list:
  2098. hwnd = hwnd_list[0]
  2099. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  2100. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  2101. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}
  2102. def syncUserJsonConfigs(token):
  2103. hlm_token = token
  2104. headers = {
  2105. "Authorization": f"Bearer {hlm_token}",
  2106. "content-type": "application/json",
  2107. }
  2108. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_configs"
  2109. result = requests.get(url=url, headers=headers)
  2110. sys_configs = result.json().get("data", {}).get("configs")
  2111. session = SqlQuery()
  2112. sysConfigs = CRUD(SysConfigs)
  2113. if sys_configs:
  2114. sysConfigs.deleteConditions(session, {})
  2115. configList = []
  2116. for config_keys in sys_configs.keys():
  2117. sys_configs[config_keys]
  2118. configList.append(
  2119. {
  2120. "key": config_keys,
  2121. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  2122. }
  2123. )
  2124. batch_insert_sys_configs(session, configList)
  2125. @app.post("/sync_sys_configs", description="同步线上配置到本地")
  2126. def sync_sys_configs(params: SyncLocalConfigs):
  2127. hlm_token = params.token
  2128. headers = {
  2129. "Authorization": f"Bearer {hlm_token}",
  2130. "content-type": "application/json",
  2131. }
  2132. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_configs"
  2133. result = requests.get(url=url, headers=headers)
  2134. sys_configs = result.json().get("data", {}).get("configs")
  2135. session = SqlQuery()
  2136. sysConfigs = CRUD(SysConfigs)
  2137. if sys_configs:
  2138. sysConfigs.deleteConditions(session, {})
  2139. configList = []
  2140. for config_keys in sys_configs.keys():
  2141. sys_configs[config_keys]
  2142. configList.append(
  2143. {
  2144. "key": config_keys,
  2145. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  2146. }
  2147. )
  2148. batch_insert_sys_configs(session, configList)
  2149. else:
  2150. all_configs = sysConfigs.read_all(session)
  2151. localConfigData = {}
  2152. for local_config in all_configs:
  2153. localConfigData[local_config.key] = json.loads(local_config.value)
  2154. data_json = json.dumps({"configs": localConfigData}, ensure_ascii=False)
  2155. # 同步本地到线上
  2156. url = settings.DOMAIN + "/api/ai_image/camera_machine/update_all_user_configs"
  2157. requests.post(url=url, headers=headers, data=data_json)
  2158. return {"code": 0, "msg": "操作成功", "data": None}
  2159. @app.post("/sync_actions", description="同步左右脚配置到本地")
  2160. def sync_action_configs(params: SyncLocalConfigs):
  2161. hlm_token = params.token
  2162. headers = {
  2163. "Authorization": f"Bearer {hlm_token}",
  2164. "content-type": "application/json",
  2165. }
  2166. url = settings.DOMAIN + "/api/ai_image/camera_machine/get_all_user_tabs"
  2167. result = requests.get(url=url, headers=headers)
  2168. session = SqlQuery()
  2169. deviceConfigs = CRUD(DeviceConfig)
  2170. deviceConfigTabs = CRUD(DeviceConfigTabs)
  2171. tabs = result.json().get("data", {}).get("tabs")
  2172. actions = result.json().get("data", {}).get("actions")
  2173. if tabs:
  2174. # 先删除再创建
  2175. deviceConfigTabs.deleteConditions(session, {})
  2176. deviceConfigs.deleteConditions(session, {})
  2177. batch_insert_device_configsNew(session, tabs, actions)
  2178. else:
  2179. all_actions = deviceConfigs.read_all(session)
  2180. all_tabs = deviceConfigTabs.read_all(session)
  2181. all_tabs_json = [item.model_dump(mode='json') for item in all_tabs]
  2182. all_actions_json = [item.model_dump(mode="json") for item in all_actions]
  2183. data_json = json.dumps(
  2184. {"tabs": all_tabs_json, "actions": all_actions_json}, ensure_ascii=False
  2185. )
  2186. sync_url = settings.DOMAIN + "/api/ai_image/camera_machine/sync_actions"
  2187. result = requests.post(url=sync_url, headers=headers, data=data_json)
  2188. tabs = result.json().get("data", {}).get("tabs")
  2189. actions = result.json().get("data", {}).get("actions")
  2190. insert_action_ids = result.json().get("data", {}).get("insert_action_ids")
  2191. if tabs:
  2192. deviceConfigTabs.deleteConditions(session, {})
  2193. deviceConfigs.deleteConditions(session, {})
  2194. batch_insert_device_configsNew(session, tabs, actions)
  2195. if insert_action_ids:
  2196. for action_item in insert_action_ids:
  2197. photos = CRUD(PhotoRecord)
  2198. old_id = action_item.get("old_id")
  2199. new_id = action_item.get("new_id")
  2200. kwargs = {"action_id": new_id}
  2201. photos.updateConditionsAll(
  2202. session, conditions={"action_id": old_id}, **kwargs
  2203. )
  2204. # 因为左右脚线上id可能会发生变化 所以需要重新同步一下本地得配置信息
  2205. # syncUserJsonConfigs(hlm_token)
  2206. return {"code": 0, "msg": "操作成功", "data": None}