img_query.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import base64
  2. import io
  3. import sys
  4. import requests
  5. from PIL import Image
  6. API_URL = "https://api.1808366.xyz/v1/chat/completions"
  7. MODEL = "qwen3.5-9b-uncensored-nothink"
  8. QUALITY = 85 # 高画质,保留绝大部分细节
  9. MAX_DIM = 1280 # 最长边上限,保证细节清晰的最小合理尺寸(一次缩放,不迭代)
  10. def img_to_data_url(path):
  11. img = Image.open(path).convert("RGB")
  12. # 仅在超长边过大时一次性缩到目标尺寸,保证细节清晰的同时控制体积
  13. if max(img.size) > MAX_DIM:
  14. ratio = MAX_DIM / max(img.size)
  15. img = img.resize(
  16. (int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS
  17. )
  18. buf = io.BytesIO()
  19. img.save(buf, format="JPEG", quality=QUALITY)
  20. b64 = base64.b64encode(buf.getvalue()).decode()
  21. return f"data:image/jpeg;base64,{b64}"
  22. def ask(path, question):
  23. payload = {
  24. "model": MODEL,
  25. "messages": [{
  26. "role": "user",
  27. "content": [
  28. {"type": "text", "text": question},
  29. {"type": "image_url", "image_url": {"url": img_to_data_url(path)}}
  30. ]
  31. }]
  32. }
  33. r = requests.post(API_URL, json=payload, timeout=120)
  34. r.raise_for_status()
  35. return r.json()["choices"][0]["message"]["content"]
  36. if __name__ == "__main__":
  37. if len(sys.argv) < 3:
  38. print("用法: python scripts/img_query.py <图片路径> <问题> [输出文件]")
  39. sys.exit(1)
  40. path, question = sys.argv[1], sys.argv[2]
  41. out = sys.argv[3] if len(sys.argv) > 3 else None
  42. result = ask(path, question)
  43. if out:
  44. with open(out, "w", encoding="utf-8") as f:
  45. f.write(result)
  46. else:
  47. sys.stdout.write(result)