detail_generate_base.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. import asyncio
  2. import settings
  3. import os
  4. try:
  5. is_test_plugins = settings.is_test_plugins
  6. except:
  7. is_test_plugins = False
  8. if is_test_plugins:
  9. from custom_plugins.plugins_mode.pic_deal import PictureProcessing
  10. else:
  11. from plugins_mode.pic_deal import PictureProcessing
  12. from PIL import Image
  13. import shutil
  14. from service.base import get_images, check_path, get_image_mask
  15. from natsort import ns, natsorted
  16. import threading
  17. from concurrent.futures import ThreadPoolExecutor
  18. from concurrent.futures import TimeoutError as THTimeoutError
  19. from middleware import UnicornException
  20. # import math
  21. from PIL import ImageFont
  22. import settings
  23. from settings import sendSocketMessage
  24. # 全局线程池
  25. _executor = ThreadPoolExecutor(max_workers=4)
  26. # 全局事件循环和线程
  27. _message_loop = None
  28. _message_thread = None
  29. def _start_message_loop():
  30. """在单独线程中启动事件循环"""
  31. global _message_loop
  32. _message_loop = asyncio.new_event_loop()
  33. asyncio.set_event_loop(_message_loop)
  34. _message_loop.run_forever()
  35. def _init_message_thread():
  36. """初始化消息线程"""
  37. global _message_thread
  38. if _message_thread is None or not _message_thread.is_alive():
  39. _message_thread = threading.Thread(target=_start_message_loop, daemon=True)
  40. _message_thread.start()
  41. # 初始化消息线程
  42. _init_message_thread()
  43. # def sendMessageAsync(code=0, msg="开始处理详情", data=None, msg_type="detail_progress",progress=None):
  44. # """异步发送消息"""
  45. # if progress is None:
  46. # data["progress"] = progress
  47. # def _send_in_thread():
  48. # # 在消息线程中调度任务
  49. # future = asyncio.run_coroutine_threadsafe(
  50. # sendSocketMessage(
  51. # code=code,
  52. # msg=msg,
  53. # data=data,
  54. # msg_type=msg_type,
  55. # ),
  56. # _message_loop,
  57. # )
  58. # # 可选:等待结果或设置超时
  59. # try:
  60. # result = future.result(timeout=5.0)
  61. # except THTimeoutError:
  62. # print("消息发送超时")
  63. # # 在线程中执行异步任务的调度
  64. # _send_in_thread()
  65. class DetailBase(object):
  66. def __init__(
  67. self,
  68. goods_no,
  69. goods_no_value: dict,
  70. out_put_dir,
  71. windows=None,
  72. excel_data=None,
  73. assigned_page_list=None,
  74. output_queue=None,
  75. ):
  76. self.goods_no = goods_no
  77. self.output_queue = output_queue
  78. self.out_put_dir = out_put_dir
  79. self.deal_pic_func_list = []
  80. self.goods_no_value = goods_no_value
  81. self.goods_art_nos = [
  82. item.get("货号", "") for item in self.goods_no_value.get("货号资料", [])
  83. ]
  84. self.root = ""
  85. self.windows = windows
  86. self.template_name = None
  87. print(goods_no_value)
  88. # 重新解析为新的数据结构
  89. self.data = {}
  90. self.detailed_images = []
  91. self.assigned_page_list = assigned_page_list
  92. self.overlay_pic_dict = {}
  93. self.init()
  94. # for goods_art_no_dict in self.goods_no_value["货号资料"]:
  95. # print(goods_art_no_dict)
  96. #
  97. # raise 1
  98. if excel_data:
  99. ig_keys = ["模板名称"]
  100. for k, v in excel_data.items():
  101. if k not in ig_keys:
  102. self.goods_no_value[k] = v
  103. def check_shoe_is_right_by_pixel(self, im=None, image_path=None):
  104. if im is None:
  105. im = Image.open(image_path)
  106. # 注意,只支持透明图
  107. # 打开图像文件
  108. im = im.crop(im.getbbox())
  109. # image.show()
  110. # 获取图像第一行的像素数据
  111. pixel_data = im.load()
  112. pix_list = []
  113. h = int(im.height / 20)
  114. for i in range(im.width):
  115. _r, _g, _b, _a = pixel_data[i, h]
  116. if _a > 10:
  117. pix_list.append(i)
  118. left_f_num = 0
  119. middle_w = int(im.width / 2)
  120. for i in pix_list:
  121. if i < middle_w:
  122. left_f_num += 1
  123. else:
  124. left_f_num -= 1
  125. if left_f_num > 0:
  126. return True
  127. else:
  128. return False
  129. def del_detail_folder(self):
  130. out_path = "{out_put_dir}/{goods_no}".format(
  131. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  132. )
  133. if not os.path.exists(out_path):
  134. return
  135. try:
  136. shutil.rmtree(out_path)
  137. except BaseException as e:
  138. print("删除文件夹失败", e)
  139. def run_all(self):
  140. if self.template_name:
  141. self.out_put_dir = "{}/详情模板{}".format(
  142. self.out_put_dir, self.template_name
  143. )
  144. print("===================detailed_images=================")
  145. # 如果没有指定页面,则删除指定目录下的对应的详情文件夹
  146. if not self.assigned_page_list:
  147. self.del_detail_folder()
  148. detailed_images = self.deal_details()
  149. self.create_folder(self.out_put_dir)
  150. detail_path = "{out_put_dir}/{goods_no}/详情页切片".format(
  151. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  152. )
  153. self.create_folder(detail_path)
  154. self.save_to_png(detailed_images=detailed_images, detail_path=detail_path)
  155. # 生成拼接图
  156. self.generate_spliced_picture()
  157. # ------------移动其他图片---------------------
  158. # 获取主图模板列表
  159. main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)[
  160. "main_pic_path_list"
  161. ]
  162. if not main_pic_path_list:
  163. self.move_other_pic(move_main_pic=True)
  164. else:
  165. self.move_other_pic(move_main_pic=True)
  166. if not self.assigned_page_list:
  167. self.deal_all_main_pic()
  168. else:
  169. if "主图" in self.assigned_page_list:
  170. self.deal_all_main_pic()
  171. # ----------如果是红蜻蜓则创建同颜色下的其他货号颜色文件夹---------------
  172. if settings.PROJECT == "红蜻蜓":
  173. if "data_all_goods_art_info" in self.goods_no_value:
  174. # 数据格式:[{'number': '14250232', 'goods_art_no': 'AC52001173', 'color': '杏色'}, ]
  175. for pic_data in self.goods_no_value["货号资料"]:
  176. if "颜色名称" not in pic_data:
  177. continue
  178. color_name = pic_data["颜色名称"]
  179. color_file_path = "{out_put_dir}/{goods_no}/{goods_number}".format(
  180. out_put_dir=self.out_put_dir,
  181. goods_no=self.goods_no,
  182. goods_number=pic_data["编号"],
  183. )
  184. for i in self.goods_no_value["data_all_goods_art_info"]:
  185. if color_name in i["color"]:
  186. new_path = "{out_put_dir}/{goods_no}/{goods_number}".format(
  187. out_put_dir=self.out_put_dir,
  188. goods_no=self.goods_no,
  189. goods_number="NUM{}".format(i["number"]),
  190. )
  191. if not os.path.exists(new_path):
  192. # 创建文件夹
  193. os.makedirs(new_path)
  194. self.move_one_pic(
  195. color_file_path,
  196. new_path,
  197. "NUM{}".format(i["number"]),
  198. )
  199. scp_path = "{out_put_dir}/{goods_no}".format(
  200. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  201. )
  202. if self.get_text_value("模特图"):
  203. model_pic = self.get_text_value("模特图")
  204. self.copyImage(model_pic, f"{scp_path}/模特图.jpg")
  205. if self.get_text_value("场景图"):
  206. scene_pic = self.get_text_value("场景图")
  207. self.copyImage(scene_pic, f"{scp_path}/场景图.jpg")
  208. return True
  209. def copyImage(self,src_path,limit_path):
  210. try:
  211. shutil.copy(src_path, limit_path)
  212. except Exception as e:
  213. print(f'An exception occurred:{e}')
  214. def concatAigcImage(self,image_path,resize=1600,bg_color=(255,255,255)):
  215. """拼接模特图场景图"""
  216. try:
  217. mote_img = PictureProcessing(image_path)
  218. mote_img = mote_img.resize(value=resize)
  219. bg_img = PictureProcessing(
  220. "RGB", (mote_img.width, mote_img.height), bg_color
  221. )
  222. bg_img = bg_img.paste_img(top_img=mote_img, base="nc", value=(0, 0))
  223. return bg_img
  224. except:
  225. print('An exception occurred')
  226. return
  227. # 移动一张图片到新的文件夹
  228. def move_one_pic(self, old_path, new_path, new_name):
  229. image_file = os.listdir(old_path)[0]
  230. old_image_path = "{}/{}".format(old_path, image_file)
  231. image_e = os.path.splitext(image_file)[1]
  232. new_image_path = "{}/{}{}".format(new_path, new_name, image_e)
  233. shutil.copy(old_image_path, new_image_path)
  234. # 生成各个详情图切片
  235. def deal_details(self):
  236. try:
  237. detailed_images = []
  238. for index, func in enumerate(self.deal_pic_func_list):
  239. image_pp = func()
  240. if not self.assigned_page_list:
  241. self.image_list_append(detailed_images, image_pp)
  242. else:
  243. index = "{}".format(index + 1)
  244. if index in self.assigned_page_list:
  245. self.image_list_append(detailed_images, image_pp)
  246. else:
  247. self.image_list_append(detailed_images, {"mes": "不生成"})
  248. return [x for x in detailed_images if x]
  249. except KeyError as e:
  250. raise UnicornException(f"缺少详情页资料:[{e}],请检查系统商品信息或excel是否缺少该字段")
  251. except Exception as e:
  252. raise UnicornException(str(e))
  253. # 生成拼接的图片
  254. def generate_spliced_picture(self):
  255. # sendMessageAsync(
  256. # code=0,
  257. # msg="正在生成详情拼接图",
  258. # msg_type="detail_progress",
  259. # data={
  260. # "goods_no": self.goods_no,
  261. # "temp_name": self.template_name,
  262. # "status": "进行中",
  263. # "goods_art_nos": self.goods_art_nos,
  264. # },
  265. # )
  266. detail_path = "{out_put_dir}/{goods_no}/详情页切片".format(
  267. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  268. )
  269. if not os.path.exists(detail_path):
  270. return
  271. detailed_images = []
  272. for image_data in get_images(detail_path):
  273. detailed_images.append(PictureProcessing(image_data["file_path"]))
  274. # 生成拼接图
  275. img = self.add_pic(detailed_images)
  276. join_path = "{out_put_dir}/{goods_no}/详情页".format(
  277. out_put_dir=self.out_put_dir, goods_no=self.goods_no
  278. )
  279. # self.create_folder(join_path)
  280. img.save("{}.jpg".format(join_path), format="JPEG")
  281. def image_list_append(self, image_list: list, data):
  282. self.check_state_end()
  283. if isinstance(data, list):
  284. image_list.extend(data)
  285. else:
  286. image_list.append(data)
  287. def save_to_png(self, detailed_images, detail_path):
  288. self.check_state_end()
  289. for index, pp in enumerate(detailed_images):
  290. if isinstance(pp, dict):
  291. continue
  292. pp.im.save(
  293. "{}/{}({}).png".format(
  294. detail_path, self.goods_no, str(index + 11).zfill(2)
  295. )
  296. )
  297. def check_state_end(self):
  298. if self.windows is not None:
  299. if self.windows.state == 99:
  300. raise "用户主动取消"
  301. @classmethod
  302. def get_temp_pic_info(cls, root):
  303. """
  304. 获取详情页模板中的信息
  305. """
  306. main_pic_list = []
  307. mask_pic_list = []
  308. if os.path.exists(r"{}\main_image".format(root)):
  309. for _name in os.listdir(r"{}\main_image".format(root)):
  310. _path = r"{}\main_image\{}".format(root, _name)
  311. if os.path.isdir(_path):
  312. main_pic_list.append([x["file_path"] for x in get_images(_path)])
  313. mask_pic_list.append(
  314. [x["file_path"] for x in get_image_mask(_path)]
  315. )
  316. _l = get_images(r"{}\show".format(root))
  317. temp_pic_path = _l[0]["file_path"] if _l else None
  318. other_pic_list = [x["file_path"] for x in get_images(r"{}".format(root))]
  319. return {
  320. "main_pic_path_list": main_pic_list,
  321. "temp_pic_path": temp_pic_path,
  322. "mask_pic_list": mask_pic_list,
  323. "other_pic_path_list": other_pic_list,
  324. }
  325. def init(self):
  326. for goods_art_no_value in self.goods_no_value["货号资料"]:
  327. self.data[goods_art_no_value["货号"]] = {
  328. "pics": goods_art_no_value["pics"],
  329. "pic_is_deal": {},
  330. }
  331. def get_text_value(self, key, subsection_len=0):
  332. try:
  333. text = ""
  334. if key in self.goods_no_value:
  335. if self.goods_no_value[key]:
  336. text = str(self.goods_no_value[key])
  337. text = text.replace(r"\n", "\n")
  338. # if key in ["跟高", "鞋宽", "帮高", "脚掌围", "鞋长"]:
  339. # if text:
  340. # text = text.split(".")[0]
  341. if subsection_len != 0:
  342. text = text.split("\n")
  343. text = [x for x in text if x]
  344. if len(text) == 2:
  345. text_1 = text[0]
  346. text_2 = text[1]
  347. return text_1, text_2
  348. else:
  349. if text:
  350. text_1 = text[0]
  351. else:
  352. text_1 = ""
  353. text_2 = ""
  354. return text_1, text_2
  355. return text
  356. except:
  357. raise UnicornException(f"缺少货号资料:[{key}],请检查系统商品信息或excel是否缺少该字段")
  358. def create_folder(self, path):
  359. if not os.path.exists(path):
  360. os.makedirs(path)
  361. def get_all_process_pics(self):
  362. """
  363. 获取所有颜色的过程图片
  364. data = [
  365. {"货号": "",
  366. "素材": [{
  367. "名称": "俯视",
  368. "抠图": "路径1",
  369. "阴影": "路径2"
  370. }, ]},
  371. ]
  372. """
  373. return_data = []
  374. for goods_art_no in self.data:
  375. goods_art_no_dict = {
  376. "货号": goods_art_no,
  377. "素材": [],
  378. }
  379. # 图片数据重新排序
  380. pic_data = []
  381. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  382. root_path, file_name = os.path.split(pic_path)
  383. pic_data.append(file_name)
  384. pic_data = natsorted(pic_data, alg=ns.PATH)
  385. for file_name in pic_data:
  386. if "阴影" in file_name:
  387. _, action_name, _ = file_name.split("_")
  388. pic_path = self.data[goods_art_no]["pics"][
  389. "{}-阴影".format(action_name)
  390. ]
  391. pic_cutout_path = self.data[goods_art_no]["pics"][
  392. "{}-抠图".format(action_name)
  393. ]
  394. if os.path.exists(pic_path) and os.path.exists(pic_cutout_path):
  395. goods_art_no_dict["素材"].append(
  396. {
  397. "名称": action_name,
  398. "抠图": pic_cutout_path,
  399. "阴影": pic_path,
  400. }
  401. )
  402. return_data.append(goods_art_no_dict)
  403. return return_data
  404. def get_overlay_pic_from_dict(
  405. self, goods_art_no, color_name, bg_color
  406. ) -> PictureProcessing:
  407. self.check_state_end()
  408. # 增加逻辑,获取任意货号下的组合图
  409. if "组合" in color_name:
  410. goods_art_no, color_name = self.get_all_scene_list(goods_art_no, color_name)
  411. key = "{}-{}-{}".format(goods_art_no, color_name, bg_color)
  412. if key in self.overlay_pic_dict:
  413. return self.overlay_pic_dict[key]
  414. if goods_art_no in self.data:
  415. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  416. if "阴影" in pic_name:
  417. action_name = pic_name.replace("-阴影", "")
  418. if action_name == color_name:
  419. pp1 = PictureProcessing(pic_path)
  420. pp2 = PictureProcessing(
  421. self.data[goods_art_no]["pics"][
  422. "{}-抠图".format(action_name)
  423. ]
  424. )
  425. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(
  426. mode="pixel", base="width", value=1600
  427. )
  428. self.overlay_pic_dict[key] = pp1
  429. if key in self.overlay_pic_dict:
  430. return self.overlay_pic_dict[key]
  431. def image_init(self, bg_color=(246, 246, 246)):
  432. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  433. for goods_art_no in self.data:
  434. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  435. if "阴影" in pic_name:
  436. action_name = pic_name.replace("-阴影", "")
  437. pp1 = PictureProcessing(pic_path)
  438. pp2 = PictureProcessing(
  439. self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)]
  440. )
  441. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(
  442. mode="pixel", base="width", value=1600
  443. )
  444. self.data[goods_art_no]["pic_is_deal"][action_name] = pp1
  445. # 获取任意货号的场景图,优先取指定货号;
  446. # 调整,按顺序从货号列表中提取所有组合图
  447. def get_all_scene_info(self, goods_art_no):
  448. data = []
  449. # 收集所有组合图
  450. # 找任意一个有组合图的货号
  451. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  452. _goods_art_no = goods_art_no_dict["货号"]
  453. _view_name_list = set([x.split("-")[0] for x in goods_art_no_dict["pics"]])
  454. for _view_name in _view_name_list:
  455. if "组合" not in _view_name:
  456. continue
  457. return _goods_art_no
  458. return goods_art_no
  459. def get_all_scene_list(self, goods_art_no, view_name: str):
  460. if "组合" == view_name:
  461. view_name = "组合1"
  462. try:
  463. view_index = int(view_name.replace("组合", "")) - 1
  464. except:
  465. return goods_art_no, "无法匹配"
  466. data = []
  467. # 收集所有组合图
  468. # 找任意一个有组合图的货号
  469. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  470. _goods_art_no = goods_art_no_dict["货号"]
  471. if _goods_art_no != goods_art_no:
  472. continue
  473. _view_name_list = set([x.split("-")[0] for x in goods_art_no_dict["pics"]])
  474. for _view_name in _view_name_list:
  475. if "组合" not in _view_name:
  476. continue
  477. data.append(
  478. {
  479. "goods_art_no": _goods_art_no,
  480. "view_name": _view_name,
  481. "real_view_name": (
  482. "组合1" if _view_name == "组合" else _view_name
  483. ),
  484. }
  485. )
  486. if len(data) <= view_index:
  487. return goods_art_no, "无法匹配"
  488. else:
  489. data.sort(key=lambda x: x["real_view_name"], reverse=False)
  490. return data[view_index]["goods_art_no"], data[view_index]["view_name"]
  491. def image_one_pic(self, goods_art_no, name, bg_color=None, return_orign=None):
  492. # 增加逻辑,获取任意货号下的组合图
  493. if "组合" in name:
  494. print("324==== goods_art_no, name", goods_art_no, name)
  495. goods_art_no, name = self.get_all_scene_list(goods_art_no, name)
  496. print("324 goods_art_no, name", goods_art_no, name)
  497. # 制作一批素材图,添加背景色,并保留阴影,以及处理成最小尺寸
  498. for pic_name, pic_path in self.data[goods_art_no]["pics"].items():
  499. if "阴影" in pic_name:
  500. action_name = pic_name.replace("-阴影", "")
  501. if name != action_name:
  502. continue
  503. pp1 = PictureProcessing(pic_path)
  504. pp2 = PictureProcessing(
  505. self.data[goods_art_no]["pics"]["{}-抠图".format(action_name)]
  506. )
  507. if not return_orign:
  508. pp1 = pp1.get_overlay_pic(top_img=pp2, color=bg_color).resize(
  509. mode="pixel", base="width", value=1600
  510. )
  511. return pp1
  512. else:
  513. return pp1, pp2
  514. if not return_orign:
  515. return None
  516. else:
  517. return None, None
  518. def move_other_pic(self, move_main_pic=True):
  519. # ------------------------------移动其他图片------------------------------
  520. goods_no_main_pic_number = 0
  521. for goods_art_no_dict in self.goods_no_value["货号资料"]:
  522. if "800x800" not in goods_art_no_dict:
  523. continue
  524. if not goods_art_no_dict["800x800"]:
  525. continue
  526. goods_art_no = ""
  527. if "编号" in goods_art_no_dict:
  528. if goods_art_no_dict["编号"]:
  529. goods_art_no = goods_art_no_dict["编号"]
  530. if not goods_art_no:
  531. goods_art_no = goods_art_no_dict["货号"]
  532. # print("goods_art_no:", goods_art_no)
  533. # 移动颜色图=====================
  534. goods_art_no_f = "{}/{}".format(self.out_put_dir, self.goods_no)
  535. self.create_folder(goods_art_no_f)
  536. # 放入一张主图
  537. old_pic_path_1 = goods_art_no_dict["800x800"][0]
  538. shutil.copy(
  539. old_pic_path_1,
  540. "{}/颜色图{}{}".format(
  541. goods_art_no_f, goods_art_no, os.path.splitext(old_pic_path_1)[1]
  542. ),
  543. )
  544. # 把其他主图放入作为款号图=====================
  545. if move_main_pic:
  546. for pic_path in goods_art_no_dict["800x800"]:
  547. goods_no_main_pic_number += 1
  548. e = os.path.splitext(pic_path)[1]
  549. shutil.copy(
  550. pic_path,
  551. "{out_put_dir}/{goods_no}/主图{goods_no}({goods_no_main_pic_number}){e}".format(
  552. out_put_dir=self.out_put_dir,
  553. goods_no=self.goods_no,
  554. goods_no_main_pic_number=str(
  555. goods_no_main_pic_number + 10
  556. ).zfill(2),
  557. e=e,
  558. ),
  559. )
  560. def deal_all_main_pic(self):
  561. """
  562. 处理主图模板,如存在出图模板则进行对应处理
  563. """
  564. # 获取主图模板列表
  565. all_main_pic_path_list = DetailBase.get_temp_pic_info(root=self.root)[
  566. "main_pic_path_list"
  567. ]
  568. if not all_main_pic_path_list:
  569. return
  570. mask_pic_list = DetailBase.get_temp_pic_info(root=self.root)["mask_pic_list"]
  571. data = self.get_all_process_pics()
  572. print("========deal_all_main_pic=========主图相关素材:")
  573. view_list = [
  574. "组合",
  575. "组合2",
  576. "组合3",
  577. "组合4",
  578. "组合5",
  579. "组合6",
  580. "俯视",
  581. "侧视",
  582. "后跟",
  583. "鞋底",
  584. "内里",
  585. ]
  586. for _index, main_pic_path_list in enumerate(all_main_pic_path_list):
  587. self.check_state_end()
  588. out_path_root = "{out_put_dir}/{goods_no}/main_image_{_index}".format(
  589. out_put_dir=self.out_put_dir, goods_no=self.goods_no, _index=_index
  590. )
  591. check_path(out_path_root)
  592. if mask_pic_list[_index]:
  593. mask_pic = mask_pic_list[_index][0]
  594. else:
  595. mask_pic = None
  596. goods_no_main_pic_number = 10
  597. # g_index 为第几个颜色货号
  598. for g_index, goods_art_no_dict in enumerate(data):
  599. goods_art_no = goods_art_no_dict["货号"]
  600. # =====================重新指定=================================
  601. _material_sort_dict = {}
  602. for index, material_dict in enumerate(goods_art_no_dict["素材"]):
  603. name = material_dict["名称"]
  604. _material_sort_dict[name] = material_dict
  605. # ======================================================
  606. file_name_index = -1
  607. for view_name in view_list:
  608. # 组合图比较特殊,为全局获取
  609. if g_index != 0:
  610. if "组合" in view_name:
  611. continue
  612. if view_name not in _material_sort_dict:
  613. continue
  614. self.check_state_end()
  615. pp_jpg, pp_png = self.image_one_pic(
  616. goods_art_no, view_name, bg_color=None, return_orign=True
  617. )
  618. if not pp_jpg:
  619. continue
  620. file_name_index += 1
  621. # 获取对应主图模板
  622. if len(main_pic_path_list) < file_name_index + 1:
  623. main_pic_path = main_pic_path_list[-1]
  624. else:
  625. main_pic_path = main_pic_path_list[file_name_index]
  626. pp_bg = PictureProcessing(main_pic_path)
  627. original_width = pp_bg.width
  628. if original_width != 1600:
  629. pp_bg = pp_bg.resize(value=1600)
  630. if mask_pic:
  631. mask_bg = PictureProcessing(mask_pic)
  632. mask_bg = mask_bg.resize(value=1600)
  633. mask_box_im = mask_bg.get_im()
  634. box_size = mask_box_im.getbbox()
  635. result_image = mask_box_im.crop(box_size)
  636. mask_width, mask_height = result_image.size
  637. mask_x, mask_y = box_size[0], box_size[1]
  638. else:
  639. mask_width, mask_height = pp_bg.size
  640. mask_width, mask_height = int(mask_width * 12 / 16), int(
  641. mask_height * 12 / 16
  642. )
  643. mask_x, mask_y = int((pp_bg.size[0] - mask_width) / 2), int(
  644. (pp_bg.size[1] - mask_height) / 2
  645. )
  646. if view_name != "后跟":
  647. pp_jpg = pp_jpg.resize(base_by_box=(mask_width, mask_height))
  648. pp_png = pp_png.resize(base_by_box=(mask_width, mask_height))
  649. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  650. p_x = mask_x + int((mask_width - pp_jpg.width) / 2)
  651. p_y = mask_y + int((mask_height - pp_jpg.height) / 2)
  652. pp_bg = pp_bg.to_overlay_pic_advance(
  653. mode="pixel",
  654. top_img=pp_jpg,
  655. base="nw",
  656. value=(p_x, p_y),
  657. top_png_img=pp_png,
  658. )
  659. else:
  660. new_mask_width, new_mask_height = int(mask_width / 1.6), int(
  661. mask_height / 1.6
  662. )
  663. pp_jpg = pp_jpg.resize(
  664. base_by_box=(new_mask_width, new_mask_height)
  665. )
  666. pp_png = pp_png.resize(
  667. base_by_box=(new_mask_width, new_mask_height)
  668. )
  669. new_mask_x = int((mask_width - new_mask_width) / 2 + mask_x)
  670. new_mask_y = int((mask_height - new_mask_height) / 2 + mask_y)
  671. # 计算粘贴的位置 mask的位置+图片在mask中的位置
  672. p_x = new_mask_x + int((new_mask_width - pp_jpg.width) / 2)
  673. p_y = new_mask_y + int((new_mask_height - pp_jpg.height) / 2)
  674. pp_bg = pp_bg.to_overlay_pic_advance(
  675. mode="pixel",
  676. top_img=pp_jpg,
  677. base="nw",
  678. value=(p_x, p_y),
  679. top_png_img=pp_png,
  680. )
  681. out_pci_mode = "." + settings.getSysConfigs(
  682. "basic_configs", "image_out_format", "png"
  683. )
  684. goods_no_main_pic_number += 1
  685. out_pic_path = "{out_path_root}/{goods_no}({goods_no_main_pic_number}){pic_mode}".format(
  686. out_path_root=out_path_root,
  687. goods_no=self.goods_no,
  688. goods_no_main_pic_number=goods_no_main_pic_number,
  689. pic_mode=out_pci_mode,
  690. )
  691. out_pci_factor = float(
  692. 1
  693. if settings.getSysConfigs(
  694. "basic_configs", "image_sharpening", "1"
  695. )
  696. == ""
  697. else settings.getSysConfigs(
  698. "basic_configs", "image_sharpening", "1"
  699. )
  700. )
  701. if out_pci_factor > 1.0:
  702. print("图片锐化处理")
  703. pp_bg = pp_bg.sharpen_image(factor=out_pci_factor)
  704. if original_width < 1600:
  705. pp_bg = pp_bg.resize(value=original_width)
  706. print("392 out_pic_path", out_pic_path)
  707. if out_pci_mode == ".jpg":
  708. pp_bg.save_as_rgb(out_pic_path)
  709. elif out_pci_mode == ".png":
  710. pp_bg.save_as_png(out_pic_path)
  711. else:
  712. pp_bg.save_as_other(out_pic_path, out_pci_mode.split(".")[-1])
  713. def add_pic(self, detailed_images):
  714. self.check_state_end()
  715. todo_detailed_images = []
  716. detailed_images = [x for x in detailed_images if x]
  717. if not detailed_images:
  718. return
  719. for i in detailed_images:
  720. if isinstance(i, list):
  721. for n in i:
  722. todo_detailed_images.append(n)
  723. else:
  724. todo_detailed_images.append(i)
  725. page_len = 0
  726. for index, pp in enumerate(todo_detailed_images):
  727. page_len += pp.height
  728. bg_im = Image.new("RGB", (pp.width, page_len), (255, 255, 255))
  729. n = 0
  730. for index, pp in enumerate(todo_detailed_images):
  731. bg_im.paste(pp.im, (0, n))
  732. n += pp.height
  733. return bg_im
  734. # 通用方法,用于写文字
  735. def add_text_list(self, text_list, spacing=5, base="wn", base_width=1600):
  736. text_list = [x for x in text_list if x["text"]]
  737. # print(text_list)
  738. # spacing 行间距
  739. text_image_list = []
  740. max_w = 0
  741. total_h = 0
  742. for text_data in text_list:
  743. _pp = PictureProcessing("RGBA", (base_width, 1200), (255, 255, 255, 0))
  744. if base == "wn" or base == "nw":
  745. align = "left"
  746. anchor = None
  747. value = (0, 250)
  748. if base == "cn" or base == "nc":
  749. align = "center"
  750. anchor = "mm"
  751. value = (int(base_width / 2), 250)
  752. if base == "en" or base == "ne":
  753. align = "right"
  754. anchor = "rs"
  755. value = (base_width - 10, 250)
  756. _pp = _pp.get_text_image_advanced(
  757. value=value,
  758. font=text_data["font"],
  759. text=text_data["text"],
  760. align=align,
  761. anchor=anchor,
  762. spacing=5,
  763. fill=text_data["fill"],
  764. return_mode="min_image",
  765. margins=(0, 0, 0, 0),
  766. )
  767. text_image_list.append(_pp)
  768. if _pp.width > max_w:
  769. max_w = _pp.width
  770. total_h += _pp.height
  771. if "spacing" in text_data:
  772. total_h += text_data["spacing"]
  773. if not text_image_list:
  774. return None
  775. #
  776. bg = PictureProcessing("RGBA", (max_w, total_h * 3), (0, 0, 0, 0))
  777. y = 0
  778. for text_image, text_data in zip(text_image_list, text_list):
  779. bg = bg.paste_img(top_img=text_image, value=(0, y), base=base)
  780. y += spacing + text_image.height
  781. if "spacing" in text_data:
  782. y += text_data["spacing"]
  783. bg = bg.crop(mode="min")
  784. # _ = bg.paste_img_invert(top_img=PictureProcessing("RGB", (bg.width,bg.height), (255, 255, 255)))
  785. # _.show()
  786. return bg
  787. def generate_font_list_to_pic(self):
  788. font_path_list = [
  789. r"resources\ttf\puhui\Bold.ttf",
  790. r"resources\ttf\puhui\Medium.ttf",
  791. r"resources\ttf\puhui\Heavy.ttf",
  792. r"resources\ttf\puhui\Light.ttf",
  793. r"resources\ttf\puhui\Regular.ttf",
  794. ]
  795. text_v_list = [
  796. "这是一段话Bold",
  797. "这是一段话Medium",
  798. "这是一段话Heavy",
  799. "这是一段话Light",
  800. "这是一段话Regular",
  801. ]
  802. detailed_images = []
  803. for font_path, text in zip(font_path_list, text_v_list):
  804. text_list = []
  805. for size in range(26, 80, 2):
  806. font = ImageFont.truetype(font_path, size)
  807. text_list.append(
  808. {
  809. "text": "{}-字号{}".format(text, size),
  810. "font": font,
  811. "fill": (110, 110, 110),
  812. }
  813. )
  814. text_image = self.add_text_list(text_list, spacing=15, base="nw")
  815. text_image = text_image.crop(mode="min")
  816. text_image = text_image.paste_img_invert(
  817. top_img=PictureProcessing("RGB", text_image.size, (255, 255, 255))
  818. )
  819. detailed_images.append(text_image)
  820. return PictureProcessing(im=self.add_pic(detailed_images))
  821. # 图片分段,每段至少大于N长度
  822. def pp_pic_subsection(self, pp: PictureProcessing, one_height=3200):
  823. total_height = pp.height
  824. now_height = 0
  825. detailed_images = []
  826. while 1:
  827. if now_height + one_height < total_height:
  828. h1 = now_height
  829. h2 = now_height + one_height
  830. bbox = (0, h1, pp.width, h2)
  831. # print("bbox1", bbox)
  832. detailed_images.append(pp.crop(bbox=bbox))
  833. now_height = now_height + one_height
  834. continue
  835. if now_height + one_height >= total_height:
  836. h1 = now_height
  837. h2 = total_height
  838. bbox = (0, h1, pp.width, h2)
  839. # print("bbox2", bbox)
  840. detailed_images.append(pp.crop(bbox=bbox))
  841. break
  842. return detailed_images