api.py 101 KB

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