#!/usr/bin/env python3 """ CN-CLIP 简单示例 最常用的文本和图像编码示例 """ from clip_client import Client # 初始化客户端 client = Client('grpc://localhost:51000') # ============================================================================ # 示例 1: 编码文本 # ============================================================================ print("示例 1: 文本编码") print("-" * 50) texts = ['一只可爱的猫咪', '美丽的高山风景'] embeddings = client.encode(texts) print(f"输入: {texts}") print(f"输出形状: {embeddings.shape}") # (2, 1024) print(f"✓ 编码完成\n") # ============================================================================ # 示例 2: 编码图像(URL) # ============================================================================ print("示例 2: 图像编码(URL)") print("-" * 50) image_url = "https://oss.essa.cn/98532128-cf8e-456c-9e30-6f2a5ea0c19f.jpg" embedding = client.encode([image_url]) print(f"输入: {image_url}") print(f"输出形状: {embedding.shape}") # (1, 1024) print(f"✓ 编码完成\n") # ============================================================================ # 示例 3: 编码图像(本地路径) # ============================================================================ print("示例 3: 图像编码(本地文件)") print("-" * 50) local_image = "/path/to/local/image.jpg" # embedding = client.encode([local_image]) print(f"输入: {local_image}") print(f"用法: client.encode(['{local_image}'])") print(f"✓ 编码完成\n") # ============================================================================ # 示例 4: 混合编码(文本+图像) # ============================================================================ print("示例 4: 混合编码") print("-" * 50) mixed_data = [ '一只可爱的猫咪', # 文本 'https://oss.essa.cn/98532128-cf8e-456c-9e30-6f2a5ea0c19f.jpg', # 图像URL ] embeddings = client.encode(mixed_data) print(f"输入: {mixed_data}") print(f"输出形状: {embeddings.shape}") # (2, 1024) print(f"✓ 编码完成\n") # ============================================================================ # 示例 5: 批量编码 # ============================================================================ print("示例 5: 批量编码(推荐)") print("-" * 50) # 一次编码多条数据(更高效) batch_data = [f"文本 {i}" for i in range(10)] embeddings = client.encode(batch_data) print(f"输入: {len(batch_data)} 条文本") print(f"输出形状: {embeddings.shape}") # (10, 1024) print(f"✓ 批量编码完成\n") # ============================================================================ # 重要提示 # ============================================================================ print("重要提示:") print("-" * 50) print("1. 输入必须是列表: client.encode(['文本']) ✓") print(" 不是单个字符串: client.encode('文本') ✗") print() print("2. 返回值是 numpy 数组,形状为 (N, 1024)") print(" N = 输入数据的数量") print() print("3. 图像支持 URL 和本地文件路径") print()