api.py 108 KB

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