api.py 74 KB

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