api.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  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. ceshi_image_path = first_pics.get("侧视-抠图")
  697. save_root_path = ceshi_image_path.split("阴影图处理")[0]
  698. save_image_path = f"{save_root_path}模特图.jpg"
  699. if os.path.isfile(save_image_path):
  700. goods_art_dict_info_item["模特图"] = save_image_path
  701. new_goods_dict[goods_art_no_info]["货号资料"][idx_key] = goods_art_dict_info_item
  702. upper_footer_progress["folder"] = save_image_path.replace("模特图.jpg", "")
  703. await sendAsyncMessage(
  704. msg="模特图处理成功",
  705. goods_arts=[goods_art_no],
  706. status="模特图处理成功",
  707. msg_type="upper_footer_progress",
  708. progress=upper_footer_progress
  709. )
  710. continue
  711. shutil.copy(ceshi_image_path, save_image_path)
  712. image_path = aigc_clazz.generateUpperShoes(save_image_path, model_id, save_image_path)
  713. goods_art_dict_info_item["模特图"] = image_path
  714. new_goods_dict[goods_art_no_info]["货号资料"][idx_key] = goods_art_dict_info_item
  715. upper_footer_progress["folder"] = save_image_path.replace("模特图.jpg", "")
  716. await sendAsyncMessage(
  717. msg="模特图处理成功",
  718. goods_arts=[goods_art_no],
  719. status="模特图处理成功",
  720. msg_type="upper_footer_progress",
  721. progress=upper_footer_progress
  722. )
  723. except (concurrent.futures.TimeoutError, Exception) as e:
  724. print("模特图处理异常信息",e)
  725. os.remove(save_image_path)
  726. # upper_footer_finish_progress-=1
  727. upper_footer_error_progress += 1
  728. goods_art_dict_info_item["模特图"] = ""
  729. new_goods_dict[goods_art_no_info]["货号资料"][idx_key] = goods_art_dict_info_item
  730. upper_footer_progress = {
  731. "status": "处理失败",
  732. "goods_art_no": goods_art_no,
  733. "current": upper_footer_finish_progress,
  734. "total": upper_footer_total_progress,
  735. "error": upper_footer_error_progress,
  736. "folder":""
  737. }
  738. await sendAsyncMessage(
  739. msg="模特图处理失败",
  740. goods_arts=[goods_art_no],
  741. status="模特图处理失败",
  742. msg_type="upper_footer_progress",
  743. progress=upper_footer_progress
  744. )
  745. status_text = "处理完成" if upper_footer_finish_progress > 0 else "处理失败"
  746. upper_footer_progress = {
  747. "status": status_text,
  748. "current": upper_footer_finish_progress,
  749. "total": upper_footer_total_progress,
  750. "error": upper_footer_error_progress
  751. }
  752. await sendAsyncMessage(
  753. msg="模特图处理结束",
  754. goods_arts=[],
  755. status="模特图处理结束",
  756. msg_type="upper_footer_progress",
  757. progress=upper_footer_progress
  758. )
  759. if new_goods_dict:
  760. return_data_check_before_detail["data"]["goods_no_dict"] = new_goods_dict
  761. return return_data_check_before_detail
  762. async def _process_detail_pages(run_main, return_data_check_before_detail, onlineData,
  763. online_stores, goods_art_no_arrays, handler_result_folder,request_params):
  764. """处理详情页生成和上传"""
  765. check_for_detail_first_res = run_main.check_for_detail_first_call_back(
  766. return_data_check_before_detail,request_params
  767. )
  768. print("<======>check_for_detail_first_res<======>",check_for_detail_first_res)
  769. if isinstance(check_for_detail_first_res, partial):
  770. try:
  771. result = check_for_detail_first_res()
  772. config_data = result["config_data"]
  773. except:
  774. config_data = result
  775. else:
  776. config_data = check_for_detail_first_res
  777. out_put_dir = config_data.get("out_put_dir")
  778. success_handler = config_data.get("success_handler")
  779. if not out_put_dir:
  780. handler_result_folder = ""
  781. # 处理失败情况
  782. else:
  783. out_put_dir_path = "{}".format(out_put_dir).replace("\\", "/")
  784. handler_result_folder = os.path.dirname(out_put_dir_path)
  785. if handler_result_folder:
  786. handler_result_folder = os.path.dirname(handler_result_folder)
  787. return handler_result_folder,success_handler
  788. async def _upload_to_third_party(onlineData, return_data_check_before_detail,
  789. config_data, online_stores,temp_name):
  790. """上传到第三方平台"""
  791. result_goods_no_dict = return_data_check_before_detail["data"]["goods_no_dict"]
  792. for goods_idx, goods_no_dict in enumerate(result_goods_no_dict.keys()):
  793. all_detail_path_list = config_data["all_detail_path_list"]
  794. for detail_path in all_detail_path_list:
  795. if goods_no_dict in detail_path:
  796. detail_path_replace = detail_path.replace("\\", "/")
  797. result_goods_no_dict[goods_no_dict]["detail_path"] = f"{detail_path_replace}/详情页-{temp_name}.jpg"
  798. upload_total_progress = len(result_goods_no_dict.keys())
  799. upload_finish_progress = 0
  800. upload_error_progress = 0
  801. upload_progress = {
  802. "status": "开始处理",
  803. "current": upload_finish_progress,
  804. "total": upload_total_progress,
  805. "error": upload_error_progress
  806. }
  807. await sendAsyncMessage(
  808. msg="开始上传商品数据",
  809. goods_arts=[],
  810. status="开始上传商品数据",
  811. msg_type="upload_goods_progress",
  812. progress=upload_progress
  813. )
  814. try:
  815. onlineData.uploadGoods2ThirdParty(
  816. result_goods_no_dict, online_stores=online_stores
  817. )
  818. except Exception as e:
  819. upload_error_progress = upload_total_progress
  820. print(f"上传任务出现错误:{e}")
  821. upload_finish_progress = upload_total_progress
  822. if upload_error_progress > 0:
  823. upload_finish_progress = 0
  824. upload_progress = {
  825. "status": "处理完成",
  826. "current": upload_finish_progress,
  827. "total": upload_total_progress,
  828. "error": upload_error_progress
  829. }
  830. await sendAsyncMessage(
  831. msg="商品上传第三方成功",
  832. goods_arts=[],
  833. status="商品上传第三方成功",
  834. msg_type="upload_goods_progress",
  835. progress=upload_progress
  836. )
  837. async def _handle_exception(error_msg, handler_result_folder):
  838. """处理异常情况"""
  839. handler_result = [{"goods_art_no": "", "success": False, "info": error_msg}]
  840. await sendAsyncMessage(
  841. msg="处理结束",
  842. data={"output_folder": handler_result_folder, "list": handler_result},
  843. status="处理结束",
  844. msg_type="detail_result_progress",
  845. )
  846. @app.get("/get_device_tabs", description="获取可执行程序命令列表")
  847. def get_device_tabs(type: int):
  848. session = SqlQuery()
  849. statement = (
  850. select(DeviceConfigTabs)
  851. .where(DeviceConfigTabs.mode_type == type)
  852. .order_by(asc("id"))
  853. )
  854. result = session.exec(statement).all()
  855. sys = CRUD(SysConfigs)
  856. action_configs = sys.read(session, conditions={"key": "action_configs"})
  857. session.close()
  858. return {
  859. "code": 0,
  860. "msg": "",
  861. "data": {"tabs": result, "select_configs": json.loads(action_configs.value)},
  862. }
  863. @app.post("/update_tab_name", description="更改tab名称")
  864. def update_tab_name(params: DeviceConfigTabsReq):
  865. if params.mode_name == "":
  866. return {"code": 1, "msg": "名称不能为空", "data": {}}
  867. session = SqlQuery()
  868. tabModel = CRUD(DeviceConfigTabs)
  869. kwargs = {"mode_name": params.mode_name}
  870. tabModel.updateConditions(session, conditions={"id": params.id}, **kwargs)
  871. session.close()
  872. return {
  873. "code": 0,
  874. "msg": "",
  875. "data": None,
  876. }
  877. @app.post("/get_device_configs", description="获取可执行程序命令列表")
  878. def get_device_configs(params: ModelGetDeviceConfig):
  879. tab_id = params.tab_id
  880. session = SqlQuery()
  881. configModel = CRUD(DeviceConfig)
  882. configList = configModel.read_all(
  883. session,
  884. conditions={"tab_id": tab_id},
  885. order_by="action_index",
  886. ascending=True,
  887. )
  888. session.close()
  889. return {
  890. "code": 0,
  891. "msg": "",
  892. "data": {"list": configList},
  893. }
  894. @app.post("/device_config_detail", description="获取可执行程序详情")
  895. def device_config_detail(params: ModelGetDeviceConfigDetail):
  896. action_id = params.id
  897. session = SqlQuery()
  898. configModel = CRUD(DeviceConfig)
  899. model = configModel.read(session, conditions={"id": action_id})
  900. session.close()
  901. if model == None:
  902. return {"code": 1, "msg": "相关配置不存在,请删除当前货号后重新拍摄", "data": None}
  903. return {"code": 0, "msg": "", "data": model}
  904. @app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
  905. def device_config_detail_query():
  906. # tab_id = params.tab_id
  907. # action_name = params.action_name
  908. session = SqlQuery()
  909. sys = CRUD(SysConfigs)
  910. action_configs = sys.read(session, conditions={"key": "action_configs"})
  911. action_configs_value = json.loads(action_configs.value)
  912. left_config = action_configs_value.get("left")
  913. configModel = CRUD(DeviceConfig)
  914. model = configModel.read(
  915. session, conditions={"tab_id": left_config, "action_name": "侧视"}
  916. )
  917. if model == None:
  918. model = configModel.read(session, conditions={"tab_id": left_config})
  919. session.close()
  920. return {"code": 0, "msg": "", "data": model}
  921. @app.post("/remove_config", description="删除一条可执行命令")
  922. def get_device_configs(params: ModelGetDeviceConfigDetail):
  923. action_id = params.id
  924. session = SqlQuery()
  925. configModel = CRUD(DeviceConfig)
  926. model = configModel.read(session, conditions={"id": action_id})
  927. if model == None:
  928. return {"code": 1, "msg": "数据不存在", "data": None}
  929. if model.is_system == True:
  930. return {"code": 1, "msg": "系统配置不允许删除", "data": None}
  931. configArray = configModel.read_all(session, conditions={"tab_id": model.tab_id})
  932. if len(configArray) == 1:
  933. return {"code": 1, "msg": "请至少保留一个配置", "data": None}
  934. configModel.delete(session, obj_id=action_id)
  935. session.close()
  936. return {"code": 0, "msg": "删除成功", "data": None}
  937. @app.post("/save_device_config", description="创建或修改一条可执行命令")
  938. def save_device_config(params: SaveDeviceConfig):
  939. action_id = params.id
  940. session = SqlQuery()
  941. deviceConfig = CRUD(DeviceConfig)
  942. if action_id == None or action_id == 0:
  943. # 走新增逻辑
  944. params.id = None
  945. save_device_config = deviceConfig.create(session, obj_in=params)
  946. else:
  947. model = deviceConfig.read(session, conditions={"id": action_id})
  948. if model == None:
  949. return {"code": 1, "msg": "数据不存在", "data": None}
  950. # 走编辑逻辑
  951. kwargs = params.__dict__
  952. save_device_config = deviceConfig.update(session, obj_id=action_id, **kwargs)
  953. session.close()
  954. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  955. @app.post("/reset_config", description="创建或修改一条可执行命令")
  956. def reset_config(params: ModelGetDeviceConfig):
  957. tab_id = params.tab_id
  958. if tab_id == None or tab_id == "":
  959. return {"code": 1, "msg": "参数错误", "data": None}
  960. session = SqlQuery()
  961. deviceConfig = CRUD(DeviceConfig)
  962. first_config = deviceConfig.read(session, conditions={"tab_id": tab_id})
  963. res = deviceConfig.deleteConditions(session, conditions={"tab_id": tab_id})
  964. if res is False:
  965. return {"code": 1, "msg": "操作失败", "data": None}
  966. actions = json.load(open("action.json", encoding="utf-8"))
  967. for data in actions:
  968. data["tab_id"] = tab_id
  969. data["is_system"] = first_config.is_system
  970. device_config = DeviceConfig(**data)
  971. session.add(device_config)
  972. session.commit()
  973. session.close()
  974. return {"code": 0, "msg": "操作成功", "data": None}
  975. @app.get("/get_photo_records", description="获取拍照记录")
  976. def get_photo_records(page: int = 1, size: int = 5):
  977. session = SqlQuery()
  978. current_page = page
  979. # photos = CRUD(PhotoRecord)
  980. print("准备查询拍摄记录", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  981. # 首先统计总数
  982. count_statement = (
  983. select(func.count(PhotoRecord.goods_art_no.distinct()))
  984. .where(PhotoRecord.delete_time == None)
  985. )
  986. total_count = session.exec(count_statement).one()
  987. # 查询所有不重复的货号及对应的最大时间,进行分页
  988. base_statement = (
  989. select(PhotoRecord.goods_art_no, func.max(PhotoRecord.id).label('max_id'))
  990. .where(PhotoRecord.delete_time == None)
  991. .group_by(PhotoRecord.goods_art_no)
  992. .order_by(desc('max_id'))
  993. .offset((page - 1) * size)
  994. .limit(size)
  995. )
  996. paginated_results = session.exec(base_statement).all()
  997. # 获取这些货号的详细记录
  998. list_data = []
  999. if paginated_results:
  1000. # 获取当前页的货号列表
  1001. current_goods_art_nos = [item.goods_art_no for item in paginated_results]
  1002. # 查询这些货号的所有记录
  1003. query = (
  1004. select(PhotoRecord, DeviceConfig.action_name)
  1005. .outerjoin(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  1006. .where(PhotoRecord.goods_art_no.in_(current_goods_art_nos))
  1007. .where(PhotoRecord.delete_time == None)
  1008. .order_by(asc("image_index")) # 按货号分组并按ID倒序
  1009. )
  1010. all_items = session.exec(query).mappings().all()
  1011. # 按货号分组
  1012. items_by_goods = {}
  1013. for item in all_items:
  1014. goods_art_no = item.PhotoRecord.goods_art_no
  1015. if goods_art_no not in items_by_goods:
  1016. items_by_goods[goods_art_no] = []
  1017. items_by_goods[goods_art_no].append(item)
  1018. # 构建结果列表,保持分页的顺序
  1019. for item in paginated_results:
  1020. goods_art_no = item.goods_art_no
  1021. if goods_art_no in items_by_goods:
  1022. # 获取该货号下时间最新的记录作为action_time
  1023. latest_record = items_by_goods[goods_art_no][0].PhotoRecord
  1024. list_data.append(
  1025. {
  1026. "goods_art_no": goods_art_no,
  1027. "action_time": latest_record.create_time,
  1028. "items": items_by_goods[goods_art_no],
  1029. }
  1030. )
  1031. session.close()
  1032. print("循环查询 完成 ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  1033. # 计算分页信息
  1034. total_pages = (total_count + size - 1) // size # 向上取整
  1035. has_prev = page > 1
  1036. has_next = page < total_pages
  1037. return {
  1038. "code": 0,
  1039. "msg": "",
  1040. "data": {
  1041. "list": list_data,
  1042. "current_page": current_page,
  1043. "size": size,
  1044. "total_count": total_count,
  1045. "total_pages": total_pages,
  1046. "has_prev": has_prev,
  1047. "has_next": has_next
  1048. },
  1049. }
  1050. @app.get("/get_last_photo_record", description="获取最后一条拍照记录")
  1051. def get_last_photo_record():
  1052. session = SqlQuery()
  1053. statement = (
  1054. select(PhotoRecord)
  1055. .where(PhotoRecord.image_path != None)
  1056. .where(PhotoRecord.delete_time == None)
  1057. .order_by(desc("photo_create_time"))
  1058. )
  1059. result = session.exec(statement).first()
  1060. session.close()
  1061. return {
  1062. "code": 0,
  1063. "msg": "",
  1064. "data": result,
  1065. }
  1066. @app.get("/get_photo_record_detail", description="通过货号获取拍照记录详情")
  1067. def get_photo_record_detail(goods_art_no: str = None):
  1068. if goods_art_no == None:
  1069. return {"code": 1, "msg": "参数错误", "data": None}
  1070. session = SqlQuery()
  1071. photos = CRUD(PhotoRecord)
  1072. items = photos.read_all(session, conditions={"goods_art_no": goods_art_no,"delete_time": None})
  1073. session.close()
  1074. return {
  1075. "code": 0,
  1076. "msg": "",
  1077. "data": {"list": items},
  1078. }
  1079. @app.post("/delect_goods_arts", description="通过货号删除记录")
  1080. def delect_goods_arts(params: PhotoRecordDelete):
  1081. limit_path = "{}/{}".format(settings.OUTPUT_DIR,
  1082. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  1083. )
  1084. handlerFolderDelete(limit_path,params.goods_art_nos,False)
  1085. session = SqlQuery()
  1086. photos = CRUD(PhotoRecord)
  1087. for item in params.goods_art_nos:
  1088. settings.syncPhotoRecord({"goods_art_no": item},action_type=2)
  1089. photos.deleteConditions(session, conditions={"goods_art_no": item,"delete_time": None})
  1090. session.close()
  1091. return {
  1092. "code": 0,
  1093. "msg": "操作成功",
  1094. "data": None,
  1095. }
  1096. def query_config_by_key(key_name):
  1097. """
  1098. 在sys_configs.json格式的数据中查询指定的key,如果匹配则返回整个对象
  1099. Args:
  1100. key_name (str): 要查询的key名称
  1101. Returns:
  1102. dict or None: 匹配的对象或None(如果没有找到)
  1103. """
  1104. try:
  1105. # 获取所有配置数据
  1106. configs = json.load(open("sys_configs.json", encoding="utf-8"))
  1107. # 遍历配置数据查找匹配的key
  1108. for config in configs:
  1109. if config.get("key") == key_name:
  1110. return config
  1111. return None
  1112. except Exception as e:
  1113. print(f"查询配置时出错: {e}")
  1114. return None
  1115. @app.get("/get_sys_config", description="查询系统配置")
  1116. def get_sys_config(key: str = None):
  1117. if key == None:
  1118. return {"code": 1, "msg": "参数错误", "data": None}
  1119. session = SqlQuery()
  1120. photos = CRUD(SysConfigs)
  1121. item = photos.read(session, conditions={"key": key})
  1122. search_data = None if item == None else json.loads(item.value)
  1123. if search_data == None:
  1124. sys_config_json = query_config_by_key(key)
  1125. if sys_config_json != None:
  1126. config = SysConfigs(**sys_config_json)
  1127. session.add(config)
  1128. session.commit() # 合并事务提交
  1129. search_data = json.loads(sys_config_json.get("value"))
  1130. session.close()
  1131. return {
  1132. "code": 0,
  1133. "msg": "",
  1134. "data": search_data,
  1135. }
  1136. @app.post("/update_left_right_config", description="更新左右脚配置")
  1137. def update_left_right_config(params: LeftRightParams):
  1138. session = SqlQuery()
  1139. sysConfig = CRUD(SysConfigs)
  1140. model = sysConfig.read(session, conditions={"key": "action_configs"})
  1141. if model == None:
  1142. return {"code": 1, "msg": "配置不存在", "data": None}
  1143. config_value = json.loads(model.value)
  1144. config_value[params.type] = params.id
  1145. update_value = json.dumps(config_value)
  1146. # 走编辑逻辑
  1147. kwargs = {"key": "action_configs", "value": update_value}
  1148. save_device_config = sysConfig.updateConditions(
  1149. session, conditions={"key": "action_configs"}, **kwargs
  1150. )
  1151. session.close()
  1152. return {"code": 0, "msg": "操作成功", "data": None}
  1153. @app.post("/update_record", description="更新拍照记录")
  1154. def update_record(params: RecordUpdate):
  1155. session = SqlQuery()
  1156. photoRecord = CRUD(PhotoRecord)
  1157. model = photoRecord.read(session, conditions={"id": params.id,"delete_time": None})
  1158. if model == None:
  1159. return {"code": 1, "msg": "记录不存在", "data": None}
  1160. kwargs = params.__dict__
  1161. save_device_config = photoRecord.update(session, obj_id=params.id, **kwargs)
  1162. session.close()
  1163. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  1164. @app.post("/update_sys_configs", description="创建或修改系统配置")
  1165. def save_sys_configs(params: SysConfigParams):
  1166. session = SqlQuery()
  1167. sysConfig = CRUD(SysConfigs)
  1168. model = sysConfig.read(session, conditions={"key": params.key})
  1169. if model == None:
  1170. return {"code": 1, "msg": "配置不存在", "data": None}
  1171. # 走编辑逻辑
  1172. kwargs = params.__dict__
  1173. save_device_config = sysConfig.updateConditions(
  1174. session, conditions={"key": params.key}, **kwargs
  1175. )
  1176. session.close()
  1177. return {"code": 0, "msg": "操作成功", "data": save_device_config}
  1178. @app.post("/create_main_image", description="创建主图测试")
  1179. def create_main_image(params: MaineImageTest):
  1180. file_path = params.file_path
  1181. onePic = OnePicTest(pic_path=file_path)
  1182. main_out_path = onePic.HandlerMainImage()
  1183. return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}
  1184. def insertEmptyLogoList(session):
  1185. """插入空logo列表"""
  1186. data = {"key": "logo_configs", "value": "[]"}
  1187. config = SysConfigs(**data)
  1188. session.add(config)
  1189. session.commit()
  1190. item = SysConfigs()
  1191. item.key = "logo_configs"
  1192. item.value = "[]"
  1193. return item
  1194. @app.get("/logo_list", description="logo列表")
  1195. def logo_list():
  1196. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  1197. check_path(logo_dir)
  1198. logo_files = os.listdir(logo_dir)
  1199. logo_list = []
  1200. for logoItem in logo_files:
  1201. logo_list.append(f"{logo_dir}{logoItem}")
  1202. return {"code": 0, "msg": "操作成功", "data": logo_list}
  1203. @app.post("/add_logo", description="添加logo")
  1204. def add_logo(params: LogoParams):
  1205. logo_path = params.logo_path.replace("\\", "/")
  1206. session = SqlQuery()
  1207. sysConfig = CRUD(SysConfigs)
  1208. item = sysConfig.read(session, conditions={"key": "logo_configs"})
  1209. if item == None:
  1210. item = insertEmptyLogoList(session)
  1211. if os.path.isfile(logo_path) == False:
  1212. return {"code": 1, "msg": "logo文件不存在", "data": None}
  1213. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  1214. check_path(logo_dir)
  1215. session.close()
  1216. fpath, fname = os.path.split(logo_path)
  1217. logo_path_info = logo_dir + fname
  1218. shutil.copy(logo_path, logo_path_info) # 复制文件
  1219. logo_files = os.listdir(logo_dir)
  1220. logo_list = []
  1221. for logoItem in logo_files:
  1222. logo_list.append(f"{logo_dir}{logoItem}")
  1223. return {
  1224. "code": 0,
  1225. "msg": "",
  1226. "data": {"logo": logo_path_info},
  1227. }
  1228. @app.post("/delete_logo", description="删除logo")
  1229. def delete_logo(params: LogoParamsupdate):
  1230. logo_path = params.path
  1231. if os.path.isfile(logo_path) == False:
  1232. return {"code": 1, "msg": "logo文件不存在", "data": None}
  1233. os.remove(logo_path)
  1234. logo_dir = "{}/data/logo/".format(os.getcwd()).replace("\\", "/")
  1235. check_path(logo_dir)
  1236. logo_files = os.listdir(logo_dir)
  1237. logo_list = []
  1238. for logoItem in logo_files:
  1239. logo_list.append(f"{logo_dir}{logoItem}")
  1240. return {"code": 0, "msg": "操作成功", "data": logo_list}
  1241. @app.post("/close_other_window", description="关闭窗口")
  1242. def close_other_window():
  1243. hwnd_list = []
  1244. def callback(hwnd, _):
  1245. title = GetWindowText(hwnd)
  1246. if title == "digiCamControl by Duka Istvan":
  1247. hwnd_list.append(hwnd)
  1248. EnumWindows(callback, None)
  1249. if hwnd_list:
  1250. hwnd = hwnd_list[0]
  1251. win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
  1252. return {"code": 0, "msg": "关闭成功", "data": {"status": True}}
  1253. return {"code": 0, "msg": "关闭失败", "data": {"status": False}}
  1254. def syncUserJsonConfigs(token):
  1255. hlm_token = token
  1256. headers = {
  1257. "Authorization": f"Bearer {hlm_token}",
  1258. "content-type": "application/json",
  1259. }
  1260. # 追加配置参数 machine_type 拍照机设备类型;0鞋;1服装
  1261. url = settings.DOMAIN + f"/api/ai_image/camera_machine/get_all_user_configs?machine_type={MACHINE_TYPE}"
  1262. result = requests.get(url=url, headers=headers)
  1263. sys_configs = result.json().get("data", {}).get("configs")
  1264. session = SqlQuery()
  1265. sysConfigs = CRUD(SysConfigs)
  1266. if sys_configs:
  1267. sysConfigs.deleteConditions(session, {})
  1268. configList = []
  1269. for config_keys in sys_configs.keys():
  1270. sys_configs[config_keys]
  1271. configList.append(
  1272. {
  1273. "key": config_keys,
  1274. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  1275. }
  1276. )
  1277. batch_insert_sys_configs(session, configList)
  1278. session.close()
  1279. @app.post("/sync_sys_configs", description="同步线上配置到本地")
  1280. def sync_sys_configs(params: SyncLocalConfigs):
  1281. hlm_token = params.token
  1282. env = params.env
  1283. settings.USER_TOKEN = hlm_token
  1284. settings.USER_ENV = env
  1285. headers = {
  1286. "Authorization": f"Bearer {hlm_token}",
  1287. "content-type": "application/json",
  1288. }
  1289. # 追加配置参数 machine_type 拍照机设备类型;0鞋;1服装
  1290. url = settings.getDoman(env) + f"/api/ai_image/camera_machine/get_all_user_configs?machine_type={MACHINE_TYPE}"
  1291. result = requests.get(url=url, headers=headers)
  1292. sys_configs = result.json().get("data", {}).get("configs")
  1293. session = SqlQuery()
  1294. sysConfigs = CRUD(SysConfigs)
  1295. if sys_configs:
  1296. sysConfigs.deleteConditions(session, {})
  1297. configList = []
  1298. for config_keys in sys_configs.keys():
  1299. sys_configs[config_keys]
  1300. configList.append(
  1301. {
  1302. "key": config_keys,
  1303. "value": json.dumps(sys_configs[config_keys], ensure_ascii=False),
  1304. }
  1305. )
  1306. batch_insert_sys_configs(session, configList)
  1307. else:
  1308. all_configs = sysConfigs.read_all(session)
  1309. localConfigData = {}
  1310. for local_config in all_configs:
  1311. localConfigData[local_config.key] = json.loads(local_config.value)
  1312. data_json = json.dumps({"configs": localConfigData,"machine_type":MACHINE_TYPE}, ensure_ascii=False)
  1313. # 同步本地到线上
  1314. url = settings.DOMAIN + "/api/ai_image/camera_machine/update_all_user_configs"
  1315. requests.post(url=url, headers=headers, data=data_json)
  1316. session.close()
  1317. return {"code": 0, "msg": "操作成功", "data": None}
  1318. @app.post("/sync_actions", description="同步左右脚配置到本地")
  1319. def sync_action_configs(params: SyncLocalConfigs):
  1320. hlm_token = params.token
  1321. env = params.env
  1322. settings.USER_TOKEN = hlm_token
  1323. settings.USER_ENV = env
  1324. headers = {
  1325. "Authorization": f"Bearer {hlm_token}",
  1326. "content-type": "application/json",
  1327. }
  1328. url = settings.getDoman(env) + f"/api/ai_image/camera_machine/get_all_user_tabs?machine_type={MACHINE_TYPE}"
  1329. result = requests.get(url=url, headers=headers)
  1330. session = SqlQuery()
  1331. deviceConfigs = CRUD(DeviceConfig)
  1332. deviceConfigTabs = CRUD(DeviceConfigTabs)
  1333. tabs = result.json().get("data", {}).get("tabs")
  1334. actions = result.json().get("data", {}).get("actions")
  1335. if tabs:
  1336. # 先删除再创建
  1337. deviceConfigTabs.deleteConditions(session, {})
  1338. deviceConfigs.deleteConditions(session, {},False)
  1339. batch_insert_device_configsNew(session, tabs, actions)
  1340. else:
  1341. all_actions = deviceConfigs.read_all(session)
  1342. all_tabs = deviceConfigTabs.read_all(session)
  1343. all_tabs_json = [item.model_dump(mode='json') for item in all_tabs]
  1344. all_actions_json = [item.model_dump(mode="json") for item in all_actions]
  1345. data_json = json.dumps(
  1346. {"tabs": all_tabs_json, "actions": all_actions_json,"machine_type":MACHINE_TYPE}, ensure_ascii=False
  1347. )
  1348. sync_url = settings.DOMAIN + "/api/ai_image/camera_machine/sync_actions"
  1349. result = requests.post(url=sync_url, headers=headers, data=data_json)
  1350. tabs = result.json().get("data", {}).get("tabs")
  1351. actions = result.json().get("data", {}).get("actions")
  1352. insert_action_ids = result.json().get("data", {}).get("insert_action_ids")
  1353. if tabs:
  1354. deviceConfigTabs.deleteConditions(session, {})
  1355. deviceConfigs.deleteConditions(session, {})
  1356. batch_insert_device_configsNew(session, tabs, actions)
  1357. if insert_action_ids:
  1358. for action_item in insert_action_ids:
  1359. photos = CRUD(PhotoRecord)
  1360. old_id = action_item.get("old_id")
  1361. new_id = action_item.get("new_id")
  1362. kwargs = {"action_id": new_id}
  1363. photos.updateConditionsAll(
  1364. session, conditions={"action_id": old_id}, **kwargs
  1365. )
  1366. # 因为左右脚线上id可能会发生变化 所以需要重新同步一下本地得配置信息
  1367. # syncUserJsonConfigs(hlm_token)
  1368. session.close()
  1369. return {"code": 0, "msg": "操作成功", "data": None}
  1370. @app.get("/get_goods_image_json", description="关闭窗口")
  1371. def get_goods_image_json(goods_art_no: str,token:str):
  1372. remove_pic_ins = RemoveBgALi()
  1373. if goods_art_no == None or goods_art_no == "":
  1374. # 判断货号是否存在
  1375. raise UnicornException("货号不能为空")
  1376. session = SqlQuery()
  1377. photoRecord = CRUD(PhotoRecord)
  1378. goods_art_record = photoRecord.read_all(
  1379. session, conditions={"goods_art_no": goods_art_no,"delete_time": None}
  1380. )
  1381. if not goods_art_record:
  1382. raise UnicornException("该货号拍摄记录不存在")
  1383. action_id_array = [record.action_id for record in goods_art_record]
  1384. devices = CRUD(DeviceConfig)
  1385. devices_record = devices.read_all(session,conditions={"id": action_id_array})
  1386. # 提取 action_name 字段并拼接
  1387. action_names = [str(record.action_name) for record in devices_record]
  1388. action_names_str = ",".join(action_names)
  1389. image_arrays = []
  1390. for goods_art_record_item in goods_art_record:
  1391. image_path = goods_art_record_item.image_path
  1392. try:
  1393. image_url = uploadImage(remove_pic_ins=remove_pic_ins,token=token, local_path=image_path)
  1394. except Exception as e:
  1395. raise UnicornException("网络异常,请重试")
  1396. image_arrays.append(image_url)
  1397. session.close()
  1398. return {"code": 0, "msg": "关闭失败", "data": {"customer_template_images": image_arrays,"template_image_order":action_names_str}}
  1399. def uploadImage(remove_pic_ins,token:str, local_path: str) -> str:
  1400. im = remove_pic_ins.get_image_cut_new(file_path=local_path)
  1401. post_headers = {"Authorization": "Bearer " +token}
  1402. url = settings.DOMAIN + "/api/upload"
  1403. resultData = requests.post(
  1404. url, files={"file":im}, headers=post_headers
  1405. ).json()
  1406. return resultData["data"]["url"]
  1407. @app.post("/remove_background", description="图片抠图-http请求")
  1408. async def remove_background(params:PhotoRecordRemoveBackground):
  1409. # await socket_manager.send_message(msg="测试")
  1410. executor = ThreadPoolExecutor(max_workers=4)
  1411. obj = None
  1412. token = params.token
  1413. token = "Bearer " + token
  1414. uuid = mine_uuid.uuid4().hex
  1415. run_main = RunMain(obj, token, uuid)
  1416. goods_art_no_arrays = params.goods_art_nos
  1417. limit_path = "{}/{}".format(settings.OUTPUT_DIR,
  1418. time.strftime("%Y-%m-%d", time.localtime(time.time()))
  1419. )
  1420. try:
  1421. move_folder_array = handlerFolderDelete(limit_path,goods_art_no_arrays,True)
  1422. except UnicornException as e:
  1423. raise UnicornException(e.msg)
  1424. # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
  1425. session = SqlQuery()
  1426. for goods_art_no in goods_art_no_arrays:
  1427. pr = CRUD(PhotoRecord)
  1428. images = pr.read_all(session, conditions={"goods_art_no": goods_art_no,"delete_time": None})
  1429. if not images:
  1430. raise UnicornException(f"商品货号【{goods_art_no}】在商品档案资料中不存在,请检查货号是否正确")
  1431. if move_folder_array.get(goods_art_no) == None:
  1432. image_dir = "{}/data/".format(os.getcwd()).replace("\\", "/")
  1433. check_path(image_dir)
  1434. for idx, itemImg in enumerate(images):
  1435. if itemImg.image_path == "" or itemImg.image_path == None:
  1436. raise UnicornException(f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试")
  1437. new_file_name = (
  1438. str(idx)+"_"+str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
  1439. )
  1440. if not os.path.exists(
  1441. image_dir + "/" + os.path.basename(new_file_name)
  1442. ):
  1443. shutil.copy(itemImg.image_path, image_dir + new_file_name)
  1444. dealImage = DealImage(image_dir)
  1445. resFlag, path = dealImage.dealMoveImage(
  1446. image_dir=image_dir,
  1447. callback_func=None,
  1448. goods_art_no=goods_art_no,
  1449. )
  1450. if not resFlag:
  1451. raise UnicornException(f"抠图操作异常,请检查目录是否存在,或者权限不足")
  1452. session.close()
  1453. # try:
  1454. cutOutMode = (
  1455. "1"
  1456. if settings.getSysConfigs("other_configs", "cutout_mode", "普通抠图")
  1457. == "普通抠图"
  1458. else "2"
  1459. )
  1460. config_data = {
  1461. "image_dir": limit_path,
  1462. "image_order": (
  1463. "俯视,侧视,后跟,鞋底,内里,组合,组合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"
  1464. ),
  1465. "goods_art_no": "",
  1466. "goods_art_nos": goods_art_no_arrays,
  1467. "is_check_number": False,
  1468. "resize_image_view": "后跟",
  1469. "cutout_mode": cutOutMode,
  1470. "logo_path": "",
  1471. "special_goods_art_no_folder_line": "",
  1472. "is_use_excel": False, # 是否使用excel
  1473. "excel_path": "", # excel路径
  1474. "is_check_color_is_all": False,
  1475. "cutout_is_pass": True,
  1476. "assigned_page_dict": {},
  1477. "detail_is_pass": True,
  1478. "upload_is_pass": False,
  1479. "upload_is_enable": settings.IS_UPLOAD_HLM, # 是否上传到惠利玛商品库,通过config.ini得is_upload开启
  1480. "is_filter": False,
  1481. "temp_class": {},
  1482. "temp_name": "",
  1483. "temp_name_list": [],
  1484. "target_error_folder": f"{limit_path}/软件-生成详情错误",
  1485. "success_handler": [],
  1486. }
  1487. try:
  1488. loop = asyncio.get_event_loop()
  1489. return_data = await loop.run_in_executor(
  1490. executor, partial(run_main.check_before_cutout, config_data)
  1491. )
  1492. cutout_res = await loop.run_in_executor(
  1493. executor,
  1494. partial(run_main.check_for_cutout_image_first_call_back, return_data),
  1495. )
  1496. handler_result = []
  1497. have_handler_keys = move_folder_array.keys()
  1498. if cutout_res:
  1499. handler_result_folder = f"{config_data['image_dir']}"
  1500. for goods_art_item in goods_art_no_arrays:
  1501. handler_result.append({
  1502. "goods_art_no": goods_art_item,
  1503. "success": True,
  1504. "info": "处理成功",
  1505. })
  1506. else:
  1507. return {"code": 1, "message": "抠图失败", "data": None}
  1508. if len(have_handler_keys) == len(goods_art_no_arrays) or (len(have_handler_keys) == 0 and cutout_res):
  1509. handler_result_folder = handler_result_folder.replace("\\", "/")
  1510. success_items = [item for item in handler_result if item.get('success') == True]
  1511. cutout_folder = handler_result_folder+"/"+success_items[0].get("goods_art_no")+"/800x800" if len(success_items) > 0 else ""
  1512. progress = {
  1513. "status": "处理完成",
  1514. "current": len(goods_art_no_arrays),
  1515. "total": len(goods_art_no_arrays),
  1516. "error": 0,
  1517. "folder":cutout_folder,
  1518. }
  1519. return {"code": 0, "message": "抠图完成", "data": {"output_folder": handler_result_folder, "list": handler_result,"progress":progress}}
  1520. except UnicornException as e:
  1521. raise UnicornException(e.msg)
  1522. except Exception as e:
  1523. print("error",e)
  1524. raise UnicornException(f"抠图异常,请稍后重试:{e}")
  1525. @app.post("/syncPhotoRecord", description="同步本地拍照记录-和output目录")
  1526. async def syncPhotoRecord(params:SyncPhotoRecord):
  1527. # 查询所有不重复的货号及对应的最大时间,进行分页
  1528. settings.USER_TOKEN = params.token
  1529. settings.USER_ENV = params.env
  1530. syncStatus = settings.checkRecordSyncStatus()
  1531. if syncStatus == True:
  1532. # 同步过就无需再同步
  1533. return {"code": 0, "message": "同步完成", "data": None}
  1534. session = SqlQuery()
  1535. base_statement = (
  1536. select(PhotoRecord)
  1537. .where(PhotoRecord.delete_time == None)
  1538. )
  1539. paginated_results = session.exec(base_statement).all()
  1540. def model_to_dict(model):
  1541. """将SQLAlchemy模型对象转换为字典,排除_sa_instance_state"""
  1542. result = {}
  1543. for column in model.__table__.columns:
  1544. result[column.name] = getattr(model, column.name)
  1545. return result
  1546. json_results = []
  1547. for result in paginated_results:
  1548. # 使用自定义函数将SQLAlchemy对象转换为字典
  1549. json_results.append(model_to_dict(result))
  1550. # 最终转换为JSON字符串
  1551. settings.syncPhotoRecord(json_results,action_type=0)
  1552. session.close()
  1553. return {"code": 0, "message": "同步完成", "data": None}
  1554. def copy_directory_walk(src, dst):
  1555. """
  1556. 使用 os.walk() 遍历并复制目录
  1557. """
  1558. for root, dirs, files in os.walk(src):
  1559. # 计算相对路径
  1560. rel_path = os.path.relpath(root, src)
  1561. dst_dir = os.path.join(dst, rel_path) if rel_path != '.' else dst
  1562. # 创建目标目录
  1563. if not os.path.exists(dst_dir):
  1564. os.makedirs(dst_dir)
  1565. # 复制文件
  1566. for file in files:
  1567. src_file = os.path.join(root, file)
  1568. dst_file = os.path.join(dst_dir, file)
  1569. shutil.copy2(src_file, dst_file)
  1570. def rename_file_safe(src, dst, overwrite=True):
  1571. """
  1572. 安全地重命名文件
  1573. Args:
  1574. src: 源文件路径
  1575. dst: 新文件路径
  1576. overwrite: 是否覆盖已存在的文件
  1577. """
  1578. try:
  1579. # 检查源文件是否存在
  1580. if not os.path.exists(src):
  1581. return False, f"源文件 {src} 不存在"
  1582. # 检查目标文件是否存在
  1583. if os.path.exists(dst) and not overwrite:
  1584. return False, f"目标文件 {dst} 已存在,设置 overwrite=True 以覆盖"
  1585. # 执行重命名
  1586. os.rename(src, dst)
  1587. return True, f"文件已成功从 {src} 重命名为 {dst}"
  1588. except OSError as e:
  1589. return False, f"重命名失败: {str(e)}"
  1590. @app.post("/rename_shadow_folder", description="同步本地拍照记录-和output目录")
  1591. async def rename_shadow_folder(params:RenameShadow):
  1592. # 货号数组
  1593. goods_art_nos = params.goods_art_nos
  1594. # for goods_art_no in goods_art_nos:
  1595. # 查询这些货号的所有记录
  1596. goods_art_dict = {}
  1597. for goods in goods_art_nos:
  1598. query = (
  1599. select(PhotoRecord, DeviceConfig.action_name)
  1600. .outerjoin(DeviceConfig, PhotoRecord.action_id == DeviceConfig.id)
  1601. .where(PhotoRecord.goods_art_no.in_(goods_art_nos))
  1602. .where(PhotoRecord.delete_time == None)
  1603. .order_by(PhotoRecord.goods_art_no, asc("id")) # 按货号分组并按ID倒序
  1604. )
  1605. all_items = session.exec(query).mappings().all()
  1606. if len(all_items) == 0: # 如果没有记录则返回
  1607. # raise UnicornException("暂无可用货号")
  1608. continue
  1609. goods_art_rename_list = []
  1610. for item in all_items:
  1611. if item["action_name"] == None:
  1612. continue
  1613. data = {"goods_art_no": item.PhotoRecord.goods_art_no, "action_name": item["action_name"],"image_index":item.PhotoRecord.image_index}
  1614. goods_art_rename_list.append(data)
  1615. goods_art_dict[goods] = goods_art_rename_list
  1616. outputDir = settings.OUTPUT_DIR
  1617. if not os.path.exists(outputDir):
  1618. raise UnicornException(f"生成目录[{outputDir}]暂无文件,请拍摄或抠图后处理")
  1619. outputList = os.listdir(outputDir)
  1620. success_result = []
  1621. for firstDir in outputList:
  1622. secondPath = f"{outputDir}\\{firstDir}"
  1623. for goodsArt in goods_art_dict:
  1624. goods_art_no_obj = goods_art_dict[goodsArt]
  1625. goodsArtPath = f"{secondPath}\\{goodsArt}"
  1626. if not os.path.exists(goodsArtPath):
  1627. continue
  1628. renameSrcPath = f"{goodsArtPath}\\阴影图处理"
  1629. renameDstPath = f"{goodsArtPath}\\阴影图处理-重命名"
  1630. if not os.path.exists(renameSrcPath):
  1631. print("阴影图目录不存在...","不处理")
  1632. continue
  1633. if len(os.listdir(renameSrcPath)) == 0:
  1634. print("阴影图处理目录无内容...","不处理")
  1635. continue
  1636. if not os.path.exists(renameDstPath):
  1637. try:
  1638. copy_directory_walk(renameSrcPath,renameDstPath)
  1639. except Exception as e:
  1640. print("重命名失败",e)
  1641. continue
  1642. dstPath = os.listdir(renameDstPath)
  1643. for dts_files in dstPath:
  1644. for goods_obj in goods_art_no_obj:
  1645. goods_art_no_name = goods_obj["goods_art_no"]
  1646. image_index = goods_obj["image_index"]
  1647. action_name = goods_obj["action_name"]
  1648. image_index+=1
  1649. basic_name = f"{goods_art_no_name}({image_index})"
  1650. if basic_name in dts_files:
  1651. if "抠图" in dts_files:
  1652. is_ok,msg = rename_file_safe(f"{renameDstPath}\\{dts_files}",f"{renameDstPath}\\{basic_name}_{action_name}_抠图.png")
  1653. print(is_ok,msg)
  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. print("goods_obj",goods_obj)
  1658. success_result.append({"goods_art_no":goodsArt,"path":renameDstPath})
  1659. return {"code": 0, "message": "重命名完成", "data": {"result": success_result}}