api.py 87 KB

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