api.py 98 KB

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