欢迎光临
我们一直在努力

千问3.5-2B实战教程:JSON接口自动化调用+Python requests封装+批量图处理脚本

千问3.5-2B实战教程:JSON接口自动化调用+Python requests封装+批量图处理脚本

1. 千问3.5-2B模型简介

千问3.5-2B是Qwen系列中的小型视觉语言模型,具备强大的图片理解与文本生成能力。这个模型可以:

  • 理解图片内容并生成描述
  • 识别图片中的主体对象
  • 辅助OCR文字识别
  • 回答关于图片场景的问题

与传统的纯文本模型不同,千问3.5-2B能够同时处理视觉和语言信息,这使得它在内容审核、电商商品描述生成、智能客服等场景中特别有用。

2. 环境准备与快速部署

2.1 访问在线服务

最简单的方式是直接使用预部署的在线服务:

https://gpu-hv221npax2-7860.web.gpu.csdn.net/

2.2 本地开发环境准备

要进行自动化调用,你需要准备:

  • Python 3.7或更高版本
  • requests库(用于HTTP请求)
  • Pillow库(用于图片处理)
  • 安装所需库:

    pip install requests pillow

    3. JSON接口调用基础

    3.1 接口基本信息

    千问3.5-2B提供了标准的JSON接口,主要参数如下:

    • 请求方式:POST
    • 接口地址:/api/v1/generate
    • 请求头:Content-Type: application/json
    • 请求体:包含图片和提示词的JSON数据

    3.2 基础调用示例

    import requests
    import base64

    def encode_image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

    url = "https://gpu-hv221npax2-7860.web.gpu.csdn.net/api/v1/generate"
    headers = {"Content-Type": "application/json"}

    image_base64 = encode_image_to_base64("test.jpg")

    data = {
    "image": image_base64,
    "prompt": "请描述图片中的主要内容",
    "max_length": 192,
    "temperature": 0.7
    }

    response = requests.post(url, headers=headers, json=data)
    print(response.json())

    4. Python requests封装实践

    4.1 基础封装类

    为了提高代码复用性,我们可以创建一个封装类:

    class QwenVLClient:
    def __init__(self, base_url):
    self.base_url = base_url
    self.headers = {"Content-Type": "application/json"}

    def _encode_image(self, image_path):
    with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

    def generate(self, image_path, prompt, max_length=192, temperature=0.7):
    image_base64 = self._encode_image(image_path)

    data = {
    "image": image_base64,
    "prompt": prompt,
    "max_length": max_length,
    "temperature": temperature
    }

    response = requests.post(
    f"{self.base_url}/api/v1/generate",
    headers=self.headers,
    json=data
    )

    return response.json()

    4.2 使用封装类

    client = QwenVLClient("https://gpu-hv221npax2-7860.web.gpu.csdn.net")

    # 单次调用
    result = client.generate("product.jpg", "请描述这个商品的特点")
    print(result)

    # 批量调用示例
    image_prompt_pairs = [
    ("image1.jpg", "图片中有什么人物?"),
    ("image2.jpg", "描述场景氛围"),
    ("image3.jpg", "读取图片中的文字")
    ]

    for image_path, prompt in image_prompt_pairs:
    result = client.generate(image_path, prompt)
    print(f"图片: {image_path}, 结果: {result}")

    5. 批量图片处理脚本开发

    5.1 基础批量处理脚本

    import os
    import json
    from datetime import datetime

    class BatchImageProcessor:
    def __init__(self, client, output_dir="results"):
    self.client = client
    self.output_dir = output_dir
    os.makedirs(output_dir, exist_ok=True)

    def process_folder(self, folder_path, prompt):
    results = []
    for filename in os.listdir(folder_path):
    if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
    image_path = os.path.join(folder_path, filename)
    try:
    result = self.client.generate(image_path, prompt)
    results.append({
    "image": filename,
    "result": result,
    "timestamp": datetime.now().isoformat()
    })
    except Exception as e:
    print(f"处理 {filename} 时出错: {str(e)}")

    # 保存结果
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_file = os.path.join(self.output_dir, f"results_{timestamp}.json")
    with open(output_file, "w", encoding="utf-8") as f:
    json.dump(results, f, ensure_ascii=False, indent=2)

    return output_file

    5.2 使用批量处理器

    client = QwenVLClient("https://gpu-hv221npax2-7860.web.gpu.csdn.net")
    processor = BatchImageProcessor(client)

    # 处理整个文件夹中的图片
    result_file = processor.process_folder(
    "product_images",
    "请描述这个商品的特点,适合什么人群使用"
    )

    print(f"处理完成,结果保存在: {result_file}")

    6. 高级功能与优化

    6.1 多提示词批量处理

    扩展批量处理器,支持为每张图片使用不同的提示词:

    def process_with_prompt_list(self, image_folder, prompts):
    results = []
    image_files = [f for f in os.listdir(image_folder)
    if f.lower().endswith(('.png', '.jpg', '.jpeg'))]

    for i, filename in enumerate(image_files):
    image_path = os.path.join(image_folder, filename)
    prompt = prompts[i % len(prompts)] # 循环使用提示词列表

    try:
    result = self.client.generate(image_path, prompt)
    results.append({
    "image": filename,
    "prompt": prompt,
    "result": result
    })
    except Exception as e:
    print(f"处理 {filename} 时出错: {str(e)}")

    return results

    6.2 结果分析与统计

    添加结果分析功能:

    def analyze_results(self, result_file):
    with open(result_file, "r", encoding="utf-8") as f:
    data = json.load(f)

    analysis = {
    "total_images": len(data),
    "success_count": sum(1 for item in data if "result" in item),
    "error_count": sum(1 for item in data if "error" in item),
    "avg_response_length": 0
    }

    if analysis["success_count"] > 0:
    total_length = sum(len(item["result"].get("text", ""))
    for item in data if "result" in item)
    analysis["avg_response_length"] = total_length / analysis["success_count"]

    return analysis

    7. 实战案例:电商商品图批量处理

    7.1 场景描述

    假设你有一个电商平台,需要为上千张商品图片自动生成描述文案。手动处理效率低下,我们可以用千问3.5-2B实现自动化。

    7.2 完整解决方案代码

    import os
    import json
    from concurrent.futures import ThreadPoolExecutor
    from tqdm import tqdm

    class EcommerceImageProcessor:
    def __init__(self, client, max_workers=4):
    self.client = client
    self.max_workers = max_workers

    def _process_single(self, args):
    image_path, prompt = args
    try:
    result = self.client.generate(image_path, prompt)
    return {
    "image": os.path.basename(image_path),
    "result": result,
    "status": "success"
    }
    except Exception as e:
    return {
    "image": os.path.basename(image_path),
    "error": str(e),
    "status": "failed"
    }

    def process_batch(self, image_folder, prompt, output_file="ecommerce_results.json"):
    image_files = [
    os.path.join(image_folder, f)
    for f in os.listdir(image_folder)
    if f.lower().endswith(('.png', '.jpg', '.jpeg'))
    ]

    tasks = [(img, prompt) for img in image_files]
    results = []

    with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
    futures = list(tqdm(
    executor.map(self._process_single, tasks),
    total=len(tasks),
    desc="处理图片"
    ))

    results = list(futures)

    with open(output_file, "w", encoding="utf-8") as f:
    json.dump(results, f, ensure_ascii=False, indent=2)

    return output_file

    7.3 使用示例

    client = QwenVLClient("https://gpu-hv221npax2-7860.web.gpu.csdn.net")
    processor = EcommerceImageProcessor(client, max_workers=8)

    # 为所有商品图生成营销描述
    result_file = processor.process_batch(
    "product_images",
    "请为这张商品图片生成一段吸引人的营销文案,突出产品特点和优势,适合在电商平台使用",
    "marketing_descriptions.json"
    )

    print(f"营销文案生成完成,结果保存在: {result_file}")

    8. 总结与最佳实践

    8.1 关键要点回顾

  • 千问3.5-2B提供了强大的图片理解和文本生成能力
  • 通过JSON接口可以轻松实现自动化调用
  • Python requests封装提高了代码复用性和可维护性
  • 批量处理脚本能够显著提高工作效率
  • 8.2 性能优化建议

  • 并发控制:适当增加线程数提高处理速度,但不要超过服务器负载能力
  • 错误处理:添加重试机制处理临时性网络问题
  • 结果缓存:对已处理的图片保存结果,避免重复处理
  • 提示词优化:根据实际需求精心设计提示词,提高结果质量
  • 8.3 扩展应用场景

  • 内容审核:自动识别图片中的敏感内容
  • 无障碍服务:为视障用户生成图片描述
  • 社交媒体管理:批量处理用户上传的图片内容
  • 教育领域:自动生成教学材料的辅助描述

  • 获取更多AI镜像

    想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

    赞(0)
    未经允许不得转载:171主机测评 » 千问3.5-2B实战教程:JSON接口自动化调用+Python requests封装+批量图处理脚本
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址