api.py 54 KB

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