Преглед изворни кода

重构界面代码和功能代码

yangzeyu пре 11 месеци
родитељ
комит
be2070a3f0
6 измењених фајлова са 122 додато и 50 уклоњено
  1. 5 1
      agent/agent.py
  2. 2 1
      utils/__init__.py
  3. 61 5
      utils/service.py
  4. 16 1
      utils/utils.py
  5. 38 35
      webui.py
  6. 0 7
      webui_ori.py

+ 5 - 1
agent/agent.py

@@ -24,8 +24,12 @@ class Agent:
         response = self.glm.text_response(prompt)
         return response.content
     
-    def license_product_judgement(self, title, license_list_str):
+    def license_product_judgement(self, title, license_list):
         """判断是否为未授权商品"""
+        license_list_str = ""
+        for product in license_list:
+            license_list_str += f"{product}\n"
+            
         self.glm.set_modelname("glm-4-plus")
         prompt = KeyWordPrompt.LICENSE_LIST_FILTER + f"""
         请根据上述逻辑,分析以下商品是否为授权生产的,并输出结果:

+ 2 - 1
utils/__init__.py

@@ -1,6 +1,7 @@
-from utils.utils import image_to_base
+from utils.utils import image_to_base, load_image_from_url
 from utils.service import Service
 __all__ =[
     "image_to_base",
+    "load_image_from_url",
     "Service"
 ]

+ 61 - 5
utils/service.py

@@ -1,11 +1,17 @@
+from agent.agent import Agent
 from db import MongoDao
-from data import BrandInfo, ProductInfo
+from data import BrandInfo
 import gradio as gr
+import json
+import pandas as pd
+from utils import load_image_from_url
 
 product_dao = MongoDao("vbrand-ec")
+license_dao = MongoDao("ProductStandard")
 
 class Service:
     product_map = {}
+    agent = Agent()
     @staticmethod
     def get_brand_list():
         """获取数据库中存储的品牌列表"""
@@ -16,11 +22,15 @@ class Service:
     
     @staticmethod
     def get_init_state_product_list(brand_name):
-        """获取初始状态下的产品列表"""
+        """获取初始状态下的产品列表,并返回列表中第一个产品的信息"""
         brand_info = BrandInfo(brand_name)
         prodct_titles = [p.title for p in brand_info.product_list]
         Service.product_map[brand_name] = brand_info.product_list
-        return prodct_titles
+        
+        # 初始商品列表的第一个商品
+        init_product = brand_info.product_list[0]
+        # init_product.images = [load_image_from_url(image_url) for image_url in init_product.images]
+        return prodct_titles, init_product
     
     @staticmethod
     def on_brand_change(brand_name):
@@ -38,7 +48,7 @@ class Service:
             return [], [["商品未找到", ""]]
         
         # 加载图片
-        images = [image_url for image_url in product.iamges]
+        images = [load_image_from_url(image_url) for image_url in product.images]
         
         # 产品信息
         info = [
@@ -50,8 +60,54 @@ class Service:
             ["价格", product.price],
         ]
         
-        return images, info
+        product_df = pd.DataFrame(info, columns=["", ""])
+        
+        return images, product_df, product
     
+    @staticmethod
+    def get_license_list(brand_name):
+        """获取品牌方授权生成的商品列表"""
+        license_list = []
+        records = license_dao.get_records_by_query({"BrandName":brand_name})
+        for record in records:
+            if "ProductSeries" not in record.keys():
+                record["ProductSeries"] = ""
+            product = f"{record['ProductSeries']} {record['Category']}"
+            if product not in license_list:
+                license_list.append(product)
+        return license_list
+    
+    @staticmethod
+    def infringement_judgement(brand_name, product):
+        """侵权判定逻辑"""
+        # 关键词引流判定
+        # if brand_name not in product.title:
+        #     # 如果标题中不包含品牌名称,拿到该商品的品牌名称
+        key_word_judgement = json.loads(Service.agent.brand_key_word_judgement(brand_name, product.title))
+        
+        # 未授权商品判定
+        license_list = Service.get_license_list("李宁")
+        license_judgement = json.loads(Service.agent.license_product_judgement(product.title, license_list))
+        
+        # 商标侵权判定
+        logo_judgement = json.loads(Service.agent.image_logo_judgement("./logo/lining.jpg", product.images[0]))
+        
+        key_word_falg = key_word_judgement["key_word_flag"]
+        license_judgement_flag = license_judgement["in_list"]
+        
+        result = f"""
+            关键词引流: {key_word_falg}
+            是否为授权生产产品: {license_judgement_flag}
+            
+            产品LOGO图像判定:
+            图像中是否包含logo: {logo_judgement["is_contain_logo"]}
+        """
+        
+        if logo_judgement["is_contain_logo"]:
+            result += f"""是否是指定品牌LOGO: {logo_judgement["is_jugement_logo"]}
+            LOGO名称: {logo_judgement["brand_name"]}
+            """
+        return result
 
 if __name__ == "__main__":
     brand_list = Service.get_brand_list()

+ 16 - 1
utils/utils.py

@@ -1,6 +1,21 @@
 import base64
+from io import BytesIO
+from PIL import Image
+import requests
 
 def image_to_base(image_path):
     with open(image_path, 'rb') as image_file:
         image_base = base64.b64encode(image_file.read()).decode('utf-8')
-    return image_base
+    return image_base
+
+def load_image_from_url(image_url):
+    """根据url加载图像"""
+    headers = {
+        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
+        "Referer": "https://www.aliexpress.com/",
+        "Accept-Language": "en-US,en;q=0.9",
+    }
+    response = requests.get(image_url, headers=headers)
+    image = Image.open(BytesIO(response.content))
+    
+    return image

+ 38 - 35
webui.py

@@ -1,22 +1,22 @@
 import gradio as gr
-from db import MongoDao
-import requests
-from PIL import Image
-from io import BytesIO
-from agent.agent import Agent
 import json
+import os
 import pandas as pd
-from utils import Service
+from utils import Service, load_image_from_url
+
+# 手动设置 Gradio 临时目录
+os.environ["GRADIO_TEMP_DIR"] = "/home/yangzeyu/gradio_temp/brand"
+GRADIO_TEMP_DIR = os.environ["GRADIO_TEMP_DIR"]
 
 brand_list = Service.get_brand_list()
-init_product_list = Service.get_init_state_product_list(brand_list[0])
+init_product_list, init_product = Service.get_init_state_product_list(brand_list[0])
 
 with gr.Blocks() as demo:
     gr.Markdown("## 侵权识别系统", elem_id="header")
-    
+    selected_product = gr.State(value=init_product)
     with gr.Row():
         with gr.Column():  # 左侧控制面板
-            brand_state = gr.State(value=brand_list[0])
+            
             brand_dropdown = gr.Dropdown(
                 brand_list,
                 label="品牌选择", 
@@ -25,7 +25,7 @@ with gr.Blocks() as demo:
             
             product_dropdown = gr.Dropdown(
                 init_product_list,
-                value=init_product_list[0],
+                value=init_product.title,
                 label="商品列表",
                 interactive=True
             )
@@ -38,45 +38,48 @@ with gr.Blocks() as demo:
             )
         
         with gr.Column():  # 右侧展示面板
-            # 1. 图片展示区(顶部)
-            image_display = gr.Gallery(
-                label="商品图片",
-                columns=3,  # 每行显示3张图片
-                height="auto",
-                object_fit="contain",  # 保持图片比例
-                interactive=False,
-                show_share_button=False
-            )
-            
-            # # 2. 商品信息区(中部)
-            # product_info = gr.Textbox(
-            #     label="商品信息",
-            #     interactive=False,
-            #     lines=5  # 增加显示行数
-            # )
             product_info = gr.Dataframe(
                 headers=["", ""],
                 row_count=5,
                 col_count=2,
                 value=[
-                    ["商户名称", "某某专卖店"],
-                    ["商品ID", "SP20230001"],
-                    ["上架时间", "2023-05-15"],
-                    ["价格", "¥299"],
-                    ["销量", "1,208件"]
+                    ["商品链接", init_product.url],
+                    ["平台", init_product.platFormName],
+                    ["商户名称", init_product.shopTitle],
+                    ["颜色", init_product.colors],
+                    ["尺寸", init_product.sizes],
+                    ["价格", init_product.price],
                 ],
                 interactive=False  # 设为True可允许编辑
             )
             
-
+            image_display = gr.Gallery(
+                label="商品图片",
+                columns=2,  # 每行显示2张图片
+                height="auto",
+                object_fit="contain",  # 保持图片比例
+                value=[load_image_from_url(image_url) for image_url in init_product.images],
+                interactive=False,
+                show_share_button=False
+            )
     
-    # 事件绑定(保持不变)
+    # 事件绑定
     brand_dropdown.change(
         fn=Service.on_brand_change,
         inputs=brand_dropdown,
         outputs=product_dropdown
     )
-    # search_button.click(search_by_cust_id, inputs=search_box, outputs=[product_info, image_display])
-    # check_button.click(check_infringement, inputs=[...], outputs=infringement_result)
+    
+    product_dropdown.change(
+        fn=Service.on_product_change,
+        inputs=[product_dropdown, brand_dropdown],
+        outputs=[image_display, product_info, selected_product]
+    )
+    
+    check_button.click(
+        Service.infringement_judgement, 
+        inputs=[brand_dropdown, selected_product], 
+        outputs=infringement_result
+    )
 
 demo.launch(server_name="0.0.0.0", server_port=7860)

+ 0 - 7
webui_ori.py

@@ -59,13 +59,6 @@ def get_license_list():
     for record in records:
         if "ProductSeries" not in record.keys():
             record["ProductSeries"] = ""
-        # license_list.append(
-        #     {
-        #         "产品名称":record["ProductTitle"],
-        #         "产品分类":record["Category"],
-        #         "产品系列":record["ProductSeries"]
-        #     }
-        # )
         product = f"{record['ProductSeries']} {record['Category']}"
         if product not in license_list:
             license_list.append(product)