api.py 60 KB

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