Forráskód Böngészése

```
feat(api): 更新图片处理逻辑并优化商品图片管理

- 注释掉原有的文件复制逻辑,避免重复复制文件
- 将图片处理方法从 dealMoveImage 替换为新的 dealMoveImageV2 方法
- 在查询条件中添加 delete_time 限制,只获取未删除的记录
- 新增 get_goods_art_no_files 方法用于获取商品图片文件列表
- 新增 copy_images 方法用于复制和重命名图片文件
- 实现新的图片移动逻辑,支持按商品编号分组处理图片
- 优化错误处理和异常捕获机制
```

rambo 3 hete
szülő
commit
0d7e3311c2
3 módosított fájl, 111 hozzáadás és 28 törlés
  1. 13 17
      python/api.py
  2. 90 1
      python/service/deal_image.py
  3. 8 10
      python/sockets/message_handler.py

+ 13 - 17
python/api.py

@@ -446,15 +446,14 @@ async def _process_image_copy_and_move(goods_art_no, images,is_excel):
                 f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试"
             )
             
-        new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
-        if not os.path.exists(image_dir + "/" + os.path.basename(new_file_name)):
-            shutil.copy(itemImg.image_path, image_dir + new_file_name)
+        # new_file_name = str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
+        # if not os.path.exists(image_dir + "/" + os.path.basename(new_file_name)):
+        #     shutil.copy(itemImg.image_path, image_dir + new_file_name)
             
     dealImage = DealImage(image_dir)
-    resFlag, path = dealImage.dealMoveImage(
-        image_dir=image_dir, callback_func=None, goods_art_no=goods_art_no
+    resFlag, path = dealImage.dealMoveImageV2(
+        goods_art_no=goods_art_no
     )
-    
     if not resFlag:
         raise UnicornException(path)
     if is_excel:
@@ -462,7 +461,6 @@ async def _process_image_copy_and_move(goods_art_no, images,is_excel):
             shutil.rmtree(image_dir,onerror=settings.handle_remove_readonly)
         except Exception as e:
             logger.info(f"删除图片失败:{str(e)}")
-
 async def _build_config_data(params, goods_art_no_arrays):
     """构建配置数据"""
     temp_class = {}
@@ -1672,17 +1670,15 @@ async def remove_background(params:PhotoRecordRemoveBackground):
             for idx, itemImg in enumerate(images):
                 if itemImg.image_path == "" or itemImg.image_path == None:
                     raise UnicornException(f"货号【{goods_art_no}】存在没有拍摄完成的图片,请重拍或删除后重试")
-                new_file_name = (
-                    str(idx)+"_"+str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
-                )
-                if not os.path.exists(
-                    image_dir + "/" + os.path.basename(new_file_name)
-                ):
-                    shutil.copy(itemImg.image_path, image_dir + new_file_name)
+                # new_file_name = (
+                #     str(idx)+"_"+str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
+                # )
+                # if not os.path.exists(
+                #     image_dir + "/" + os.path.basename(new_file_name)
+                # ):
+                #     shutil.copy(itemImg.image_path, image_dir + new_file_name)
             dealImage = DealImage(image_dir)
-            resFlag, path = dealImage.dealMoveImage(
-                image_dir=image_dir,
-                callback_func=None,
+            resFlag, path = dealImage.dealMoveImageV2(
                 goods_art_no=goods_art_no,
             )
             if not resFlag:

+ 90 - 1
python/service/deal_image.py

@@ -52,7 +52,7 @@ class DealImage(BaseDealImage):
         configModel = CRUD(PhotoRecord)
         result = configModel.read(
             session,
-            conditions={"goods_art_no": goods_art_no},
+            conditions={"goods_art_no": goods_art_no,"delete_time": None},
             order_by="id",
             ascending=True,
         )
@@ -61,7 +61,25 @@ class DealImage(BaseDealImage):
             return result.goods_art_no, result.image_index, result.image_deal_mode
         else:
             return None
+    def get_goods_art_no_files(self, goods_art_no):
+        # time_array = time.strptime(date_time_original, "%Y:%m:%d %H:%M:%S")
 
+        # time_array = time.mktime(time_array)
+        # datetime_obj = datetime.datetime.fromtimestamp(time_array)
+
+        session = SqlQuery()
+        configModel = CRUD(PhotoRecord)
+        result = configModel.read_all(
+            session,
+            conditions={"goods_art_no": goods_art_no,"delete_time": None},
+            order_by="id",
+            ascending=True,
+        )
+        session.close()
+        if result:
+            return [{"image_path":item.image_path,"id":item.id,"image_index":item.image_index} for item in result]
+        else:
+            return []
     def get_data_from_hqt_with_goods_art_no(self, goods_art_no_list):
         _goods_art_no_list = copy.deepcopy(goods_art_no_list)
         _list = []
@@ -176,7 +194,34 @@ class DealImage(BaseDealImage):
             shutil.move(old_image_path, original_image_path)
         except Exception as e:
             print(f"文件操作异常:{e}")
+    def copy_images(self, goods_art_no, goods_art_no_path, old_image_path):
+        """
+        步骤:
+        1、移动到原始图
+        Args:
+            goods_art_no:
+            goods_art_no_path:
+            old_image_path:
+
+        Returns:
 
+        """
+        # 移动到原始图
+        file = os.path.split(old_image_path)[1]
+        # 扩展名
+        e = os.path.splitext(file)[1]
+        print("self.goods_images_count_dict", self.goods_images_count_dict)
+        # 获取图片序列
+        self.goods_images_count_dict[goods_art_no] += 1
+        # A9999(1).jpg
+        new_file_name = "{}({})".format(goods_art_no, self.goods_images_count_dict[goods_art_no])
+        original_image_path = "{}/原始图/{}{}".format(goods_art_no_path, new_file_name, e)
+        try:
+            shutil.copy2(old_image_path, original_image_path)
+            return True,"移动成功"
+        except Exception as e:
+            print(f"文件操作异常:{e}")
+            return False,f"货号[{goods_art_no}]原始图{old_image_path}不存在或已被删除"
     def dealMoveImage(self, image_dir: str, callback_func=None,goods_art_no=None) -> dict:
         if not self.check_path(image_dir=image_dir + "/历史"):
             raise UnicornException("文件夹创建失败")
@@ -277,7 +322,51 @@ class DealImage(BaseDealImage):
         # 完成处理
         # self.set_state(state_value=2)
         return True, output_path
+    def dealMoveImageV2(self,goods_art_no=None) -> dict:
+        # 遍历目标文件夹,获取有拍摄信息的图片,并按拍摄时间排序
+        original_photo_list = []  # 原始图片列表
+        _data = self.get_goods_art_no_files(goods_art_no)
+        if _data:
+            for file_idx, dataItem in enumerate(_data):
+            # 能匹配上数据库
+                file_path = dataItem['image_path']
+                original_photo_list.append({"file_path": file_path,
+                                            "goods_art_no": goods_art_no,
+                                            "image_index": file_idx,
+                                            })
+        if not original_photo_list:
+            raise UnicornException("没有任何匹配的图片")
+        # 当天日期作为文件夹
+        seconds = time.time()
+        output_path = "{}/{f_name}".format(settings.OUTPUT_DIR,f_name=time.strftime("%Y-%m-%d", time.localtime(seconds)))
 
+        # 遍历每个匹配好的数据进行处理
+        print(f"original_photo_list:",original_photo_list)
+        n = 0
+        for photo_dict in original_photo_list:
+            n += 1
+            print("处理dict:",photo_dict)
+            # 进度条
+            goods_art_no = photo_dict["goods_art_no"]
+            original_image_path = photo_dict["file_path"]
+            goods_art_no_path = "{output_path}/{goods_art_no}".format(output_path=output_path,
+                                                                      goods_art_no=goods_art_no)
+            # 创建货号下的一系列文件夹
+            self.create_folder(goods_art_no_path)
+            # 重命名并进行移动
+            print("开始移动:{}  {} 命名为:{}".format(goods_art_no, original_image_path, goods_art_no_path))
+            result, message = self.copy_images(goods_art_no, goods_art_no_path, original_image_path)  # 货号、货号文件路径、原始图路径
+            if not result:
+                return result, message
+            time.sleep(0.1)
+            print("已完成移动处理")
+        if n != 0:
+            # 自动生成一个货号表
+            print("output_path", output_path)
+            self.deal(output_path)
+        # 完成处理
+        # self.set_state(state_value=2)
+        return True, output_path
     def deal(cls, dir_path):
 
         # print("dir_path", dir_path)

+ 8 - 10
python/sockets/message_handler.py

@@ -566,17 +566,15 @@ async def handlerSend(
                             )
                             await manager.send_personal_message(data, websocket)
                             return
-                        new_file_name = (
-                            str(idx)+"_"+str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
-                        )
-                        if not os.path.exists(
-                            image_dir + "/" + os.path.basename(new_file_name)
-                        ):
-                            shutil.copy(itemImg.image_path, image_dir + new_file_name)
+                        # new_file_name = (
+                        #     str(idx)+"_"+str(itemImg.goods_art_no) + "_" + str(idx) + ".jpg"
+                        # )
+                        # if not os.path.exists(
+                        #     image_dir + "/" + os.path.basename(new_file_name)
+                        # ):
+                        #     shutil.copy(itemImg.image_path, image_dir + new_file_name)
                     dealImage = DealImage(image_dir)
-                    resFlag, path = dealImage.dealMoveImage(
-                        image_dir=image_dir,
-                        callback_func=None,
+                    resFlag, path = dealImage.dealMoveImageV2(
                         goods_art_no=goods_art_no,
                     )
                     if not resFlag: