api.py 74 KB

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