api.py 54 KB

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