rambo il y a 3 mois
Parent
commit
d31b46f874
3 fichiers modifiés avec 110 ajouts et 61 suppressions
  1. 47 38
      python/api.py
  2. 41 22
      python/service/online_request/module_online_data.py
  3. 22 1
      python/temp.py

+ 47 - 38
python/api.py

@@ -33,7 +33,7 @@ import asyncio
 from fastapi import BackgroundTasks
 import functools
 import traceback
-
+import concurrent.futures
 
 def log_exception_with_context(context_message=""):
     """装饰器:为函数添加异常日志上下文"""
@@ -679,6 +679,10 @@ async def handle_detail_background(
     is_product_scene = params.is_product_scene  # 上传第三方的店铺名称数组
     is_upper_footer = params.is_upper_footer  # 上传第三方的店铺名称数组
     # 该数组表示是否需要后面的移动文件夹操作,减少重复抠图,提升抠图时间和速度
+    if online_stores:
+            """如果上传第三方,则需要强制生成详情页"""
+            params.is_detail = 1
+            is_detail = 1
     try:
         excel_path = params.excel_path.strip()
         print("excel信息打印输出:",excel_path)
@@ -810,7 +814,6 @@ async def process_handle_detail(request: Request, params: HandlerDetail):
             return_data_check_before_detail = await _process_model_images(
                 aigc_clazz, run_main, return_data_check_before_detail, upper_footer_params
             )
-            
         # 处理详情页
         if is_detail == 1:
             handler_result_folder, handler_result= await _process_detail_pages(
@@ -1184,43 +1187,49 @@ async def _process_model_images(aigc_clazz, run_main, return_data_check_before_d
     )
     
     for goods_art_no in goods_dict.keys():
-        upper_footer_finish_progress += 1
-        upper_footer_progress = {
-            "status": "正在处理",
-            "goods_art_no": goods_art_no, 
-            "current": upper_footer_finish_progress, 
-            "total": upper_footer_total_progress, 
-            "error": upper_footer_error_progress
-        }
-        
-        await sendAsyncMessage(
-            msg="正在处理模特图",
-            goods_arts=[goods_art_no],
-            status="正在处理模特图",
-            msg_type="upper_footer_progress",
-            progress=upper_footer_progress
-        )
-        
-        goods_art_dict_info = goods_dict[goods_art_no]
-        first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
-        first_pics = first_goods_art_no_info.get("pics")
-        gender = goods_art_dict_info.get("性别","女")
-        model_id = man_id if "男" in gender else women_id
-        ceshi_image_path = first_pics.get("侧视-抠图")
-        save_root_path = ceshi_image_path.split("阴影图处理")[0]
-        save_image_path = f"{save_root_path}模特图.jpg"
-        
-        if os.path.isfile(save_image_path):
-            goods_art_dict_info["模特图"] = save_image_path
-            new_goods_dict[goods_art_no] = goods_art_dict_info
-            continue
-            
-        shutil.copy(ceshi_image_path, save_image_path)
-        
         try:
-            image_path = aigc_clazz.generateUpperShoes(
-                save_image_path, model_id, save_image_path
+            upper_footer_finish_progress += 1
+            upper_footer_progress = {
+                "status": "正在处理",
+                "goods_art_no": goods_art_no, 
+                "current": upper_footer_finish_progress, 
+                "total": upper_footer_total_progress, 
+                "error": upper_footer_error_progress
+            }
+            
+            await sendAsyncMessage(
+                msg="正在处理模特图",
+                goods_arts=[goods_art_no],
+                status="正在处理模特图",
+                msg_type="upper_footer_progress",
+                progress=upper_footer_progress
             )
+            goods_art_dict_info = goods_dict[goods_art_no]
+            first_goods_art_no_info = goods_art_dict_info.get("货号资料", [])[0]
+            first_pics = first_goods_art_no_info.get("pics")
+            gender = goods_art_dict_info.get("性别","女")
+            model_id = man_id if "男" in gender else women_id
+            ceshi_image_path = first_pics.get("侧视-抠图")
+            save_root_path = ceshi_image_path.split("阴影图处理")[0]
+            save_image_path = f"{save_root_path}模特图.jpg"
+            
+            if os.path.isfile(save_image_path):
+                goods_art_dict_info["模特图"] = save_image_path
+                new_goods_dict[goods_art_no] = goods_art_dict_info
+                continue
+                
+            shutil.copy(ceshi_image_path, save_image_path)
+        
+            # 添加超时控制
+            with concurrent.futures.ThreadPoolExecutor() as executor:
+                future = executor.submit(
+                    aigc_clazz.generateUpperShoes,
+                    save_image_path,
+                    model_id,
+                    save_image_path
+                )
+                # 设置70秒超时
+                image_path = future.result(timeout=70)
             
             goods_art_dict_info["模特图"] = image_path
             new_goods_dict[goods_art_no] = goods_art_dict_info
@@ -1241,7 +1250,7 @@ async def _process_model_images(aigc_clazz, run_main, return_data_check_before_d
                 progress=upper_footer_progress
             )
             
-        except Exception as e:
+        except (concurrent.futures.TimeoutError, Exception) as e:
             os.remove(save_image_path)
             upper_footer_error_progress += 1
             

+ 41 - 22
python/service/online_request/module_online_data.py

@@ -7,7 +7,9 @@ from utils.common import message_queue
 from middleware import UnicornException
 from PIL import Image
 import io, time
+from logger import logger
 
+# logger = logging.getLogger(__name__)
 
 class JsonEncoder(json.JSONEncoder):
     """Convert numpy classes to JSON serializable objects."""
@@ -186,26 +188,37 @@ class AIGCDataRequest(object):
 
     def searchProgress(self, id):
         """查询进度"""
-        url = settings.DOMAIN + "/api/ai_image/main/search_bacth_progress"
-        data = {"site": 1, "generate_ids": [id], "type": "aigc_pro"}
-        resultData = self.s.post(url, json=data, headers=self.post_headers)
-        resultData = resultData.json()
-        code = resultData.get("code", 0)
-        message = resultData.get("message", "")
-        if code != 0:
-            raise UnicornException(message)
-        data_result = resultData.get("data", [])
-        print("查询进度", data_result)
-        if len(data_result) == 0:
+        try:
+            url = settings.DOMAIN + "/api/ai_image/main/search_bacth_progress"
+            data = {"site": 1, "generate_ids": [id], "type": "aigc_pro"}
+            resultData = self.s.post(url, json=data, headers=self.post_headers, timeout=10)
+            resultData = resultData.json()
+            code = resultData.get("code", 0)
+            message = resultData.get("message", "")
+            if code != 0:
+                raise UnicornException(message)
+            data_result = resultData.get("data", [])
+            print("查询进度", data_result)
+            logger.info(f"查询进度:{data_result}")
+            if len(data_result) == 0:
+                return -1, None
+            data_item = data_result[0]
+            status = data_item.get("status", -1)
+            result_image = None
+            
+            # 只有在完成状态下才返回图片URL
+            if status == 2:  # 完成
+                result_image_urls = data_item.get("result_image_urls", [])
+                result_image_urls = [] if result_image_urls is None else result_image_urls
+                result_image = result_image_urls[0] if len(result_image_urls) > 0 else None
+                
+            return status, result_image
+        except requests.Timeout:
+            print("查询进度超时")
+            return -1, None
+        except Exception as e:
+            print(f"查询进度异常: {e}")
             return -1, None
-        data_item = data_result[0]
-        status = data_item.get("status", -1)
-        if status in [0,1]:
-            return status, None
-        result_image_urls = data_item.get("result_image_urls", [])
-        result_image_urls = [] if result_image_urls == None else result_image_urls
-        result_image = result_image_urls[0] if len(result_image_urls) > 0 else None
-        return status, result_image
 
     def generateUpperShoes(self, local_path, model_id, save_path):
         """生成上脚图"""
@@ -236,13 +249,19 @@ class AIGCDataRequest(object):
         result_image = None
         print("generate_id", generate_id)
         while search_times > 0:
-            print(f"查询第{search_times}次")
+            print(f"模特图查询第{search_times}次")
+            logger.info(f"模特图查询第{search_times}次")
             status, result_image = self.searchProgress(generate_id)
-            if status in [-1, 2]:
+            # status: -1=失败, 0=排队中, 1=进行中, 2=完成
+            if status == 2:  # 完成
+                break
+            if status == -1:  # 失败
                 break
+            # status为0(排队中)或1(进行中)时继续查询
             time.sleep(1)
             search_times -= 1
-        if not result_image:
+        # 循环结束后检查最终状态
+        if status == -1 or (status != 2 and search_times <= 0):
             raise UnicornException("模特图生成失败")
         save_image_path = download_image_with_pil(result_image, save_path)
         print("上脚图save_image_path",result_image, save_image_path)

+ 22 - 1
python/temp.py

@@ -1,5 +1,26 @@
 # from PIL import Image
 # from settings import recordDataPoint
+import time
 from service.online_request.module_online_data import OnlineDataRequest,AIGCDataRequest
 aigc = AIGCDataRequest("Bearer f99e72d818b504d23e0581ef1b1a2b4bb687c683")
-aigc.searchProgress(1127919)
+# status, result_image = aigc.searchProgress(1127984)
+# print(status,result_image)
+search_times = 60
+while search_times > 0:
+            print(f"模特图查询第{search_times}次")
+            # logger.info(f"模特图查询第{search_times}次")
+            status, result_image = aigc.searchProgress(1127989)
+            # status: -1=失败, 0=排队中, 1=进行中, 2=完成
+            if status == 2:  # 完成
+                break
+            if status == -1:  # 失败
+                break
+            # status为0(排队中)或1(进行中)时继续查询
+            time.sleep(1)
+            search_times -= 1
+        # 循环结束后检查最终状态
+if status == -1 or (status != 2 and search_times <= 0):
+    print("模特图生成失败")
+    exit()
+# save_image_path = download_image_with_pil(result_image, save_path)
+print("上脚图save_image_path",result_image)