#!/usr/bin/env python3
"""
诊断图片处理速度问题
"""
import sys
import time
from pathlib import Path
sys.path.insert(0, "C:\\Users\\15579\\doubao-image-mcp")
def diagnose_speed(file_path: str):
"""诊断速度问题"""
print("="*60)
print("图片处理速度诊断")
print("="*60)
path = Path(file_path)
# 检查 1: 文件大小
print("\n[检查 1] 文件大小")
size_bytes = path.stat().st_size
size_mb = size_bytes / (1024 * 1024)
print(f"文件大小: {size_bytes:,} 字节 ({size_mb:.2f} MB)")
if size_mb > 5:
print(f"⚠️ 文件较大!这可能导致:")
print(f" - Base64 编码慢: {size_mb * 2:.1f} 秒估算")
print(f" - 上传时间长")
print(f" - API 处理慢")
if size_mb > 10:
print(f"❌ 文件过大!强烈建议压缩到 < 2MB")
return False
# 检查 2: 图片尺寸
print("\n[检查 2] 图片尺寸")
try:
from PIL import Image
with Image.open(path) as img:
width, height = img.size
pixels = width * height
megapixels = pixels / 1_000_000
print(f"尺寸: {width} x {height}")
print(f"像素数: {pixels:,} ({megapixels:.2f} MP)")
if megapixels > 5:
print(f"⚠️ 分辨率较高!建议压缩到 2MP 以下")
print(f" 建议: 1920x1080 或更小")
except ImportError:
print("PIL 未安装,跳过尺寸检查")
# 检查 3: 编码时间测试
print("\n[检查 3] Base64 编码速度测试")
from server import encode_image_to_base64
start = time.time()
try:
base64_data = encode_image_to_base64(str(path))
encode_time = time.time() - start
print(f"编码完成,耗时: {encode_time:.2f} 秒")
print(f"Base64 长度: {len(base64_data):,} 字符")
if encode_time > 10:
print(f"❌ 编码时间过长!")
print(f" 建议: 压缩图片或使用更小的文件")
return False
elif encode_time > 5:
print(f"⚠️ 编码时间较长,可优化")
else:
print(f"✓ 编码速度正常")
except Exception as e:
print(f"❌ 编码失败: {e}")
return False
# 检查 4: API 调用估算
print("\n[检查 4] API 调用时间估算")
print(f"Base64 大小: {len(base64_data) / 1024:.1f} KB")
print(f"估算上传时间: {len(base64_data) / 1024 / 100:.1f} 秒 (假设 100 KB/s)")
print(f"估算 API 处理: 15-20 秒")
print(f"总计估算: {encode_time:.1f} + {len(base64_data) / 1024 / 100:.1f} + 17.5 = {encode_time + len(base64_data) / 1024 / 100 + 17.5:.1f} 秒")
# 建议
print("\n" + "="*60)
print("诊断结果")
print("="*60)
total_estimate = encode_time + len(base64_data) / 1024 / 100 + 17.5
if total_estimate > 60:
print(f"❌ 预计总时间: {total_estimate:.0f} 秒 ({total_estimate/60:.1f} 分钟)")
print(f"\n建议:")
print(f"1. 压缩图片到 < 1MB")
print(f"2. 调整分辨率到 1280x720 或更小")
print(f"3. 使用 JPEG 格式,质量 80-85%")
return False
elif total_estimate > 30:
print(f"⚠️ 预计总时间: {total_estimate:.0f} 秒")
print(f"\n建议: 压缩图片可提升速度")
else:
print(f"✓ 预计总时间: {total_estimate:.0f} 秒 - 正常范围")
return True
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
test_file = sys.argv[1]
else:
test_file = r"D:\download\下载.jpg"
print(f"\n测试文件: {test_file}")
print(f"使用方法: python diagnose_speed.py <图片路径>\n")
success = diagnose_speed(test_file)
if not success:
print("\n" + "="*60)
print("优化建议")
print("="*60)
print("\n使用图片编辑器:")
print("1. 调整尺寸到 1920x1080 或更小")
print("2. 保存为 JPEG 格式")
print("3. 质量设置 80-85%")
print("4. 确保文件 < 1MB")
print("\n在线工具:")
print("- https://tinypng.com/")
print("- https://squoosh.app/")