如何实现Python3中多API集成,以实现图片文字识别及翻译功能?
- 内容介绍
- 文章标签
- 相关问答
在跨语言信息处理的场景里使用者常面临多 API 集成困难识别/翻译错误率高还有性能瓶颈等痛点。下面给出一个完整的 Python3 方法,方便你实现图片文字识别与翻译功能。
一、痛点拆解与需求概述
痛点 1:多 API 调用耦合度高,维护成本大。
痛点 2:单次识别或翻译失败后缺乏容错机制,业务中断。
痛点 3:批量图片处理时响应慢,使用者体验差。
这里通过统一包装层、异步请求与缓存策略,解决掉上述问题。老实说,
二、技术选型与主要 API
2.1 百度 AI OCR
Baidu AI OCR 提供高精度中文识别。并支持多语言,说到示例调用,
from aip import AipOcr
import base64
def baidu_ocr:
client = AipOcr
with open as f:
image = base64.b64encode).decode
result = client.basicGeneral
if 'words_result' in result:
return ''.join
return "识别失败"
2.2 百度翻译 API
Baidu 翻译支持多语言互译,调用方式如下:
import hashlib
import requests
import random
import json
def baidu_translate:
url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
salt = str)
sign_str = f'{app_id}{text}{salt}{key}'
sign = hashlib.md5).hexdigest
params = {
至于'q',text,'from': from_lang,'to': to_lang,'appid': app_id,'salt': salt,'sign': sign
}
resp = requests.get
data = resp.json
if 'trans_result' in data:
return ''.join
return "翻译失败"
2.3 有道翻译 API
Youdao 一样提供免费接口,可作为备选方案:
def youdao_translate:
url = 'https://fanyi.youdao.com/openapi.do'
salt = str * 1000))
sign_str = f'{app_key}{text}{salt}{app_secret}'
sign = hashlib.md5).hexdigest
params = {
说到'q',text,'from': 'auto','to': 'en','appKey': app_key,'salt': salt,'sign': sign,'signType': 'v3'
}
resp = requests.get
data = resp.json
if data.get:
return data
return "翻译失败"
三、统一封装类实现多 API 集成
3.1 代码实现
import os
import json
import base64
from aip import AipOcr
class ImageTranslator:
def __init__(self。baidu_ocr_appid=None,baidu_ocr_secret=None,baidu_trans_appid=None,baidu_trans_secret=None,youdao_appkey=None,youdao_secret=None):
# OCR 初始化
self._ocr_client = AipOcr
# 百度翻译配置
self._baidu_trans_id = baidu_trans_appid or ''
self._baidu_trans_key = baidu_trans_secret or ''
# 有道配置
self._youdao_appkey = youdao_appkey or ''
self._youdao_secret = youdao_secret or ''
def _load_image_base64:
with open as f:
return base64.b64encode).decode
def recognize_text:
image_b64 = self._load_image_base64
result = self._ocr_client.basicGeneral
if 'words_result' in result:
return ''.join
return None
def translate_text:
if translator == 'baidu':
至于try,return baidu_translate(
text=text,app_id=self._baidu_trans_id,key=self._baidu_trans_key,from_lang='auto',to_lang=to_lang)
except Exception as e:
print
return None
elif translator == 'youdao':
说到try,return youdao_translate(
text=text,app_key=self._youdao_appkey,app_secret=self._youdao_secret)
except Exception as e:
print
return None
说到else,raise ValueError
def process_image :
txt= self.recognize_text
if not txt :
print
return
translated= self.translate_text
if translated is None :
print
return
# 输出文这篇文章件
with open as f :
f.write
# 简单 Excel 保存
try :
import openpyxl;wb=openpyxl.Workbook;ws=wb.active;ws.title='Result';ws.cell,ws.cell;ws.cell,ws.cell;wb.save,except Exception as e :
print {e}")
# 示例使用 -------------------------------------------------
if __name__ == '__main__':
translator=ImageTranslator(
baidu_ocr_appid='your_baidu_ocr_id',baidu_ocr_secret='your_baidu_ocr_key',baidu_trans_appid='your_baidu_tid',baidu_trans_secret='your_baidu_tkey',youdao_appkey='your_youdao_k'。
youdao_secret='your_youdao_s')
translator.process_image(
img_path="/path/to/image.jpg",to_lang="jp",translator="youdao",output_txt="/tmp/output.txt",output_excel="/tmp/output.xlsx")
使用者痛点补救:
- API 错误易捕获: try/except 块捕捉网络或返回格式错误,避免程序崩溃。
- 一次性输出多个格式: 同时生成 .txt 与 .xlsx,让后期数据处理更灵活。
- 可切换服务商: 一行代码即可从百度切到有道,以应对额度限制或价格波动。
- 批量处理时可 至于异步。 后续可接入 asyncio + aiohttp 实现并发调用,提高吞吐量。
- 本地缓存策略: 对相同图片方法使用 MD5 做缓存,避免重复请求。
四、性能调整建议
import asyncio
import aiohttp
async def async_fetch:
async with session.get as r :
return await r.json
async def async_process:
async with aiohttp.ClientSession as session :
tasks=
for img in images :
tasks.append)
results=await asyncio.gar
# 结果后续处理...
# 用法:
# asyncio.run)
import pickle。time,json
CACHEFILE =&'imagecache.pkl'
def load_cache: if os.path.exists : with open as f :return pickle.load return {}
def save_cache: with open as f :pickle.dump
def get_cached:
item=dct.get
if item and time.time-item
python
def safe_call:
for i in range:
try这方面,return func
except Exception as e :
print
time.sleep
raise RuntimeError
将 recognize_text 与 translate_text 包装为 safe_call 可明显提高程序鲁棒性。
- **多语言循环**:循环调用不同目标语言,实现一次性全语种输出。
- **保持原始格式**:结合 Pillow 或 pytesseract 的布局信息,将文字位置与字体写入 Excel 或 PDF。其实,
- **GUI 界面**:借助 PyQt5 或 Streamlit 快速搭建图形化工具。让非技术人员也能使用此功能。
- **监控日志**:集成 logging + Sentry 捕获异常并推送告警。
"把复杂的多 API 调用变得像呼吸一样自然"
在跨语言信息处理的场景里使用者常面临多 API 集成困难识别/翻译错误率高还有性能瓶颈等痛点。下面给出一个完整的 Python3 方法,方便你实现图片文字识别与翻译功能。
一、痛点拆解与需求概述
痛点 1:多 API 调用耦合度高,维护成本大。
痛点 2:单次识别或翻译失败后缺乏容错机制,业务中断。
痛点 3:批量图片处理时响应慢,使用者体验差。
这里通过统一包装层、异步请求与缓存策略,解决掉上述问题。老实说,
二、技术选型与主要 API
2.1 百度 AI OCR
Baidu AI OCR 提供高精度中文识别。并支持多语言,说到示例调用,
from aip import AipOcr
import base64
def baidu_ocr:
client = AipOcr
with open as f:
image = base64.b64encode).decode
result = client.basicGeneral
if 'words_result' in result:
return ''.join
return "识别失败"
2.2 百度翻译 API
Baidu 翻译支持多语言互译,调用方式如下:
import hashlib
import requests
import random
import json
def baidu_translate:
url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
salt = str)
sign_str = f'{app_id}{text}{salt}{key}'
sign = hashlib.md5).hexdigest
params = {
至于'q',text,'from': from_lang,'to': to_lang,'appid': app_id,'salt': salt,'sign': sign
}
resp = requests.get
data = resp.json
if 'trans_result' in data:
return ''.join
return "翻译失败"
2.3 有道翻译 API
Youdao 一样提供免费接口,可作为备选方案:
def youdao_translate:
url = 'https://fanyi.youdao.com/openapi.do'
salt = str * 1000))
sign_str = f'{app_key}{text}{salt}{app_secret}'
sign = hashlib.md5).hexdigest
params = {
说到'q',text,'from': 'auto','to': 'en','appKey': app_key,'salt': salt,'sign': sign,'signType': 'v3'
}
resp = requests.get
data = resp.json
if data.get:
return data
return "翻译失败"
三、统一封装类实现多 API 集成
3.1 代码实现
import os
import json
import base64
from aip import AipOcr
class ImageTranslator:
def __init__(self。baidu_ocr_appid=None,baidu_ocr_secret=None,baidu_trans_appid=None,baidu_trans_secret=None,youdao_appkey=None,youdao_secret=None):
# OCR 初始化
self._ocr_client = AipOcr
# 百度翻译配置
self._baidu_trans_id = baidu_trans_appid or ''
self._baidu_trans_key = baidu_trans_secret or ''
# 有道配置
self._youdao_appkey = youdao_appkey or ''
self._youdao_secret = youdao_secret or ''
def _load_image_base64:
with open as f:
return base64.b64encode).decode
def recognize_text:
image_b64 = self._load_image_base64
result = self._ocr_client.basicGeneral
if 'words_result' in result:
return ''.join
return None
def translate_text:
if translator == 'baidu':
至于try,return baidu_translate(
text=text,app_id=self._baidu_trans_id,key=self._baidu_trans_key,from_lang='auto',to_lang=to_lang)
except Exception as e:
print
return None
elif translator == 'youdao':
说到try,return youdao_translate(
text=text,app_key=self._youdao_appkey,app_secret=self._youdao_secret)
except Exception as e:
print
return None
说到else,raise ValueError
def process_image :
txt= self.recognize_text
if not txt :
print
return
translated= self.translate_text
if translated is None :
print
return
# 输出文这篇文章件
with open as f :
f.write
# 简单 Excel 保存
try :
import openpyxl;wb=openpyxl.Workbook;ws=wb.active;ws.title='Result';ws.cell,ws.cell;ws.cell,ws.cell;wb.save,except Exception as e :
print {e}")
# 示例使用 -------------------------------------------------
if __name__ == '__main__':
translator=ImageTranslator(
baidu_ocr_appid='your_baidu_ocr_id',baidu_ocr_secret='your_baidu_ocr_key',baidu_trans_appid='your_baidu_tid',baidu_trans_secret='your_baidu_tkey',youdao_appkey='your_youdao_k'。
youdao_secret='your_youdao_s')
translator.process_image(
img_path="/path/to/image.jpg",to_lang="jp",translator="youdao",output_txt="/tmp/output.txt",output_excel="/tmp/output.xlsx")
使用者痛点补救:
- API 错误易捕获: try/except 块捕捉网络或返回格式错误,避免程序崩溃。
- 一次性输出多个格式: 同时生成 .txt 与 .xlsx,让后期数据处理更灵活。
- 可切换服务商: 一行代码即可从百度切到有道,以应对额度限制或价格波动。
- 批量处理时可 至于异步。 后续可接入 asyncio + aiohttp 实现并发调用,提高吞吐量。
- 本地缓存策略: 对相同图片方法使用 MD5 做缓存,避免重复请求。
四、性能调整建议
import asyncio
import aiohttp
async def async_fetch:
async with session.get as r :
return await r.json
async def async_process:
async with aiohttp.ClientSession as session :
tasks=
for img in images :
tasks.append)
results=await asyncio.gar
# 结果后续处理...
# 用法:
# asyncio.run)
import pickle。time,json
CACHEFILE =&'imagecache.pkl'
def load_cache: if os.path.exists : with open as f :return pickle.load return {}
def save_cache: with open as f :pickle.dump
def get_cached:
item=dct.get
if item and time.time-item
python
def safe_call:
for i in range:
try这方面,return func
except Exception as e :
print
time.sleep
raise RuntimeError
将 recognize_text 与 translate_text 包装为 safe_call 可明显提高程序鲁棒性。
- **多语言循环**:循环调用不同目标语言,实现一次性全语种输出。
- **保持原始格式**:结合 Pillow 或 pytesseract 的布局信息,将文字位置与字体写入 Excel 或 PDF。其实,
- **GUI 界面**:借助 PyQt5 或 Streamlit 快速搭建图形化工具。让非技术人员也能使用此功能。
- **监控日志**:集成 logging + Sentry 捕获异常并推送告警。
"把复杂的多 API 调用变得像呼吸一样自然"

