#!/usr/bin/env python # -*- coding: utf-8 -*- """ 百度图像搜索API模拟类 用于在没有有效API密钥的情况下进行测试 """ class MockBaiduImageSearch: """模拟百度相似图片搜索API的类""" def __init__(self): """初始化模拟API""" self.access_token = "mock_access_token_12345678900987654321" self.images = {} # 存储模拟图片数据 print("已初始化模拟百度图像搜索API") def add_image(self, image_path=None, image_base64=None, url=None, brief=None, tags=None): """ 模拟添加图片到图库 Args: image_path: 本地图片路径 image_base64: 图片的base64编码 url: 图片URL brief: 图片摘要信息 tags: 分类信息 Returns: dict: 模拟API返回的结果 """ # 生成一个唯一的图片ID import uuid cont_sign = str(uuid.uuid4()) # 存储图片信息 self.images[cont_sign] = { 'brief': brief, 'tags': tags, 'url': url or image_path or "模拟图片路径", 'add_time': '2025-04-09 11:00:00' } return { 'log_id': 123456789, 'cont_sign': cont_sign, 'error_code': 0, 'error_msg': 'success' } def search_image(self, image_path=None, image_base64=None, url=None, tags=None, tag_logic=None, pn=0, rn=300): """ 模拟搜索相似图片 Args: image_path: 本地图片路径 image_base64: 图片的base64编码 url: 图片URL tags: 分类信息 tag_logic: 标签逻辑,'AND'或'OR' pn: 分页起始位置 rn: 返回结果数量 Returns: dict: 模拟API返回的结果 """ # 模拟搜索结果 result_list = [] # 如果有图片,则返回它们作为搜索结果 for cont_sign, image_info in self.images.items(): # 如果指定了标签,则进行标签过滤 if tags: image_tags = image_info.get('tags', '') if tag_logic == 'AND': # 所有标签都必须匹配 if not all(tag in image_tags for tag in tags.split(',')): continue else: # 任意标签匹配即可 if not any(tag in image_tags for tag in tags.split(',')): continue # 添加到结果列表 result_list.append({ 'cont_sign': cont_sign, 'score': 0.95, # 模拟相似度分数 'brief': image_info.get('brief', '') }) return { 'log_id': 987654321, 'result_num': len(result_list), 'result': result_list, 'has_more': False, 'error_code': 0, 'error_msg': 'success' } def update_image(self, cont_sign, brief=None, tags=None): """ 模拟更新图片信息 Args: cont_sign: 图片ID brief: 新的图片摘要信息 tags: 新的分类信息 Returns: dict: 模拟API返回的结果 """ if cont_sign not in self.images: return { 'log_id': 135792468, 'error_code': 222202, 'error_msg': '图片不存在' } # 更新图片信息 if brief: self.images[cont_sign]['brief'] = brief if tags: self.images[cont_sign]['tags'] = tags return { 'log_id': 135792468, 'error_code': 0, 'error_msg': 'success' } def delete_image(self, cont_sign): """ 模拟删除图片 Args: cont_sign: 图片ID Returns: dict: 模拟API返回的结果 """ if cont_sign not in self.images: return { 'log_id': 246813579, 'error_code': 222202, 'error_msg': '图片不存在' } # 删除图片 del self.images[cont_sign] return { 'log_id': 246813579, 'error_code': 0, 'error_msg': 'success' }