Files
Cloud-Tour-to-Libo/scripts/test_qwen_vl.py

58 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""测试通义千问多模态URL 图片 + 本地图片 两种用法。
用法:
export DASHSCOPE_API_KEY=sk-xxxx
python scripts/test_qwen_vl.py # 跑 URL 用例
python scripts/test_qwen_vl.py /path/to/local.jpg # 跑本地图片用例
"""
import os
import sys
from pathlib import Path
from dashscope import MultiModalConversation
def call(image_ref: str, prompt: str = "详细描述这张图片,并提取里面所有可见文字。") -> None:
resp = MultiModalConversation.call(
model="qwen-vl-max",
messages=[
{
"role": "user",
"content": [
{"image": image_ref},
{"text": prompt},
],
}
],
)
if resp.status_code != 200:
print(f"FAIL status={resp.status_code} code={resp.code} msg={resp.message}")
sys.exit(1)
# 兼容两种返回结构
content = resp.output.choices[0].message.content
if isinstance(content, list):
text = "".join(seg.get("text", "") for seg in content)
else:
text = content
print("OK\n" + text)
print(f"\n[usage] {resp.usage}")
def main() -> None:
if not os.getenv("DASHSCOPE_API_KEY"):
sys.exit("ERROR: 请先 export DASHSCOPE_API_KEY=sk-xxxx")
if len(sys.argv) > 1:
path = Path(sys.argv[1]).expanduser().resolve()
if not path.is_file():
sys.exit(f"文件不存在: {path}")
call(f"file://{path}")
else:
call("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg")
if __name__ == "__main__":
main()