# BaiduFanyiView 文档 ## 📄 **文件位置** `api/views/BaiduFanyiView.py` ### **概述** 使用百度翻译 API 提供全面的翻译和语言识别服务。所有视图都已转换为异步操作,以获得更好的 Daphne ASGI 服务器性能。 ### **类结构** ```python @permission_classes([AllowAny]) class BaiduFanyiView(APIView): async def post(self, request): # 文本翻译 @permission_classes([AllowAny]) class RecognizeLangTypeViews(APIView): async def post(self, request): # 语言识别 @permission_classes([AllowAny]) class PictureRecognizeViews(APIView): parser_classes = [MultiPartParser, FormParser] async def post(self, request): # 图片翻译 @permission_classes([AllowAny]) class SpeechRecognitionView(APIView): parser_classes = [MultiPartParser, FormParser] async def post(self, request): # 语音识别 ``` #### **权限** - **访问级别**: 公共(无需认证) - **认证**: 无 (`@permission_classes([AllowAny])`) ### **方法详情** --- ### **1. BaiduFanyiView (文本翻译)** #### **端点**: `POST /api/translate/` ##### **描述** 使用百度翻译 API 在支持的语言之间翻译文本内容。 ##### **参数** ```json { "q": "要翻译的文本", // 必需:文本内容(最多 3000 字符) "from_lang": "en", // 必需:源语言代码 "to_lang": "zh" // 必需:目标语言代码 } ``` ##### **支持的语言** 从 `info.baidu_lang_info` 加载语言: - 查看 `languages` 获取支持的语言对 - 使用 `"auto"` 自动检测源语言 ##### **响应格式** ```json { "message": "Success", "code": "10000", "data": { "trans_result": [ { "src": "Hello world", "dst": "你好世界" } ], "from": "en", "to": "zh" } } ``` ##### **错误响应** | 代码 | 状态 | 描述 | |------|------|------| | 400 | Bad Request | 无效的语言代码或缺少参数 | | 400 | Bad Request | 文本长度超过 3000 字符 | | 503 | Service Unavailable | 百度 API 暂时不可用 | --- ### **2. RecognizeLangTypeViews (语言识别)** #### **端点**: `POST /api/recognize-language/` ##### **描述** 自动检测提供的文本内容的语言。 ##### **参数** ```json { "q": "要识别的文本" // 必需:要识别语言的文本 } ``` ##### **响应格式** ```json { "message": "Success", "code": "10000", "data": { "lang": "en", "confidence": 0.98 } } ``` ##### **错误响应** | 代码 | 状态 | 描述 | |------|------|------| | 400 | Bad Request | 文本长度超过 3000 字符 | | 400 | Bad Request | 语言不在支持范围内 | | 503 | Service Unavailable | 百度 API 暂时不可用 | --- ### **3. PictureRecognizeViews (图片翻译)** #### **端点**: `POST /api/picture-translate/` ##### **描述** 使用百度的 OCR 和翻译功能翻译图像中的文本。 ##### **请求格式** 多部分表单数据,包含文件上传和查询参数。 ##### **参数** **表单数据:** - `file`: 图像文件 (必需) **查询参数:** - `from_lang`: 源语言代码 (必需) - `to_lang`: 目标语言代码 (必需) - `picture`: 图像格式类型 (必需, 如 "jpg", "png") ##### **请求示例** ```bash curl -X POST http://your-api.com/api/picture-translate/ \ -H "Content-Type: multipart/form-data" \ -F "file=@image.jpg" \ -G --data-urlencode "from_lang=en" \ --data-urlencode "to_lang=zh" \ --data-urlencode "picture=jpg" ``` ##### **响应格式** ```json { "message": "Success", "code": "10000", "data": { "words_result_num": 2, "words_result": [ { "words": "Hello World" }, { "words": "Welcome" } ] } } ``` ##### **错误响应** | 代码 | 状态 | 描述 | |------|------|------| | 400 | Bad Request | 无效的语言代码 | | 400 | Bad Request | 不支持的图像格式 | | 503 | Service Unavailable | 百度 API 暂时不可用 | --- ### **4. SpeechRecognitionView (语音识别)** #### **端点**: `POST /api/speech-recognition/` ##### **描述** 识别和翻译语音/音频内容。 ##### **请求格式** 多部分表单数据,包含语音文件上传和查询参数。 ##### **参数** **表单数据:** - `voice`: 音频文件 (必需) **查询参数:** - `speech_type`: 音频格式 (必需, 如 "pcm") - `from_lang`: 源语言代码 (必需) - `to_lang`: 目标语言代码 (必需) ##### **请求示例** ```bash curl -X POST http://your-api.com/api/speech-recognition/ \ -H "Content-Type: multipart/form-data" \ -F "voice=@audio.wav" \ -G --data-urlencode "speech_type=pcm" \ --data-urlencode "from_lang=en" \ --data-urlencode "to_lang=zh" ``` ##### **响应格式** ```json { "message": "Success", "code": "10000", "data": { "result": "你好世界", "corpus_no": "123456789", "status": 0 } } ``` ##### **错误响应** | 代码 | 状态 | 描述 | |------|------|------| | 400 | Bad Request | 不支持的语音类型 | | 400 | Bad Request | 无效的语言代码 | | 503 | Service Unavailable | 百度 API 暂时不可用 | --- ### **实现详情** #### **异步操作** 所有视图都使用 `aiohttp` 进行非阻塞 HTTP 请求: ```python async with aiohttp.ClientSession() as session: async with session.post(url, params=payload, headers=headers) as response: result = await response.json() ``` #### **回退机制** 如果 `aiohttp` 不可用,视图会回退到同步 `requests`: ```python if aiohttp: # 使用异步 aiohttp else: # 回退到同步 requests ``` #### **配置** 百度 API 配置从以下位置加载: - `info.baidu_fanyi_appid.py`: appid, appkey, endpoint - `info.baidu_lang_info.py`: languages, auto_lang, cuid, mac --- ### **安全与性能** #### **速率限制** - 遵守百度 API 速率限制 - 未实现额外的速率限制 - 考虑在客户端侧实现速率限制 #### **输入验证** - 文本长度限制: 3000 字符 - 语言代码验证 - 媒体端点的文件格式验证 #### **错误处理** - 综合 try-catch 块 - 有意义的错误消息 - 优雅的降级当服务不可用时 --- ### **使用示例** #### **Python 客户端** ```python import aiohttp import asyncio async def translate_text(): async with aiohttp.ClientSession() as session: payload = {'q': 'Hello', 'from_lang': 'en', 'to_lang': 'zh'} async with session.post('http://api/translate/', json=payload) as resp: return await resp.json() # 运行异步操作 result = asyncio.run(translate_text()) ``` #### **JavaScript 前端** ```javascript // 文本翻译 const translate = async (text, fromLang, toLang) => { const response = await fetch('/api/translate/', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({q: text, from_lang: fromLang, to_lang: toLang}) }); return await response.json(); }; ``` #### **测试端点** ```bash # 测试文本翻译 curl -X POST http://localhost:8000/api/translate/ \ -H "Content-Type: application/json" \ -d '{"q":"Hello world","from_lang":"en","to_lang":"zh"}' # 测试语言识别 curl -X POST http://localhost:8000/api/recognize-language/ \ -H "Content-Type: application/json" \ -d '{"q":"Hello world"}' ``` --- ### **监控与调试** #### **日志记录** - 请求数据通过 `print(request.data)` 记录 - API 响应通过 `print(sign)` 在语音识别中记录 - 考虑为生产环境添加结构化日志记录 #### **性能指标** - 异步操作减少阻塞时间 - 高效处理并发请求 - 尽可能使用流式传输优化内存使用 #### **健康检查** - 可通过 API 状态检查服务可用性 - 考虑实现健康检查端点 --- ### **集成说明** #### **Django 集成** ```python # urls.py from django.urls import path from api.views import BaiduFanyiView, RecognizeLangTypeViews, PictureRecognizeViews, SpeechRecognitionView urlpatterns = [ path('translate/', BaiduFanyiView.as_view(), name='translate'), path('recognize-language/', RecognizeLangTypeViews.as_view(), name='recognize-language'), path('picture-translate/', PictureRecognizeViews.as_view(), name='picture-translate'), path('speech-recognition/', SpeechRecognitionView.as_view(), name='speech-recognition'), ] ``` #### **使用 Daphne 运行** ```bash pip install aiohttp daphne chunyu_project.asgi:application --port 8000 ``` --- **最后更新**: 当前会话 **版本**: 1.0