api.py 74 KB

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