api.py 98 KB

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