api.py 60 KB

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