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