Python 豆包AI实战:图片内容翻译成文字
·
介绍
下面介绍火山方舟豆包AI各种将图片中的内容翻译成更种语言文字的实现
准备
- 安装python3.14
- 夸克网盘:https://pan.quark.cn/s/b88e55905e7b
- 百度网盘:https://pan.baidu.com/s/1d22gCHP_qWq5_L_Ik-tvNg?pwd=f8ah
- 火山引擎注册账号,地址:https://console.volcengine.com/home
- 火山引擎访问控制,https://console.volcengine.com/iam/identitymanage/user
- 新建用户 -> 添加权限(机器翻译) -> 复制密钥
开始
- 安装依赖包
- SDK:pip install volcengine-python-sdk
- 项目配置,config.py 配置文件,未配置或配置错误无法运行
- access_key_id,访问控制密钥
- secret_access_key,访问控制密钥
- 项目执行,main.py 主文件
- python main.py
代码
- 配置,config.py
# 火山引擎用户密钥 Access Key ID
access_key_id = ""
# 火山引擎用户密钥 Secret Access Key
secret_access_key = ""
- 模型调用,model.py
from typing import Any
import config as config
import volcenginesdkcore
import volcenginesdktranslate20250301
configuration = volcenginesdkcore.Configuration()
configuration.ak = config.access_key_id
configuration.sk = config.secret_access_key
configuration.region = "cn-beijing"
volcenginesdkcore.Configuration.set_default(configuration)
api_instance = volcenginesdktranslate20250301.TRANSLATE20250301Api()
def execute(target_language: str, image: str):
try:
translate_image_request = volcenginesdktranslate20250301.TranslateImageRequest(
target_language=target_language, image=image
)
translate_image_response: Any = api_instance.translate_image(translate_image_request)
return translate_image_response.text_blocks
except Exception as e:
print(f"翻译失败,失败原因:{str(e)}")
return ""
- 主方法,main.py
import config as config
import model as model
import util.image_util as image_util
import sys
from typing import Any
if config.access_key_id == "" or config.secret_access_key == "":
print(f"火山引擎用户密钥未配置")
sys.exit()
print("=====我是你的翻译助手,请选择需要翻译成什么语言:=====\n")
target = input("1、英文 2、中文 3、韩文 4、日文\n").strip()
target_language = ""
target_language_text = ""
if target == "2":
target_language = "zh"
target_language_text = "中文"
elif target == "3":
target_language = "ko"
target_language_text = "韩文"
elif target == "4":
target_language = "ja"
target_language_text = "日文"
else:
target_language = "en"
target_language_text = "英文"
print(f"你想翻译成:{target_language_text}\n")
print("选择一张图片吧")
base64_result = image_util.img_to_base64()
if base64_result is None or base64_result == "":
print("没有选择任何图片哦")
sys.exit()
print("\nAI正在翻译,请稍候...\n")
result_list: Any = model.execute(target_language, base64_result["base64"])
if result_list is None or len(result_list) == 0:
print("翻译失败,请重试")
sys.exit()
print(f"AI翻译结果:")
for result in result_list:
print(f"\n{result.text} -> {result.translation}")
成功展示


注意
- 火山引擎注册会送很多免费的token,刚开始测试都是不需要费用的
- 完整的代码下载:https://download.csdn.net/download/lazy_uu/93064573
更多推荐



所有评论(0)