sync from local backup
This commit is contained in:
@@ -0,0 +1,369 @@
|
||||
# BaiduFanyiView Documentation
|
||||
|
||||
## 📄 **File Location**
|
||||
`api/views/BaiduFanyiView.py`
|
||||
|
||||
### **Overview**
|
||||
Provides comprehensive translation and language recognition services using Baidu Translate API. All views have been converted to asynchronous operations for optimal performance with Daphne ASGI server.
|
||||
|
||||
### **Class Details**
|
||||
|
||||
```python
|
||||
@permission_classes([AllowAny])
|
||||
class BaiduFanyiView(APIView):
|
||||
async def post(self, request): # Text translation
|
||||
|
||||
@permission_classes([AllowAny])
|
||||
class RecognizeLangTypeViews(APIView):
|
||||
async def post(self, request): # Language recognition
|
||||
|
||||
@permission_classes([AllowAny])
|
||||
class PictureRecognizeViews(APIView):
|
||||
parser_classes = [MultiPartParser, FormParser]
|
||||
async def post(self, request): # Picture translation
|
||||
|
||||
@permission_classes([AllowAny])
|
||||
class SpeechRecognitionView(APIView):
|
||||
parser_classes = [MultiPartParser, FormParser]
|
||||
async def post(self, request): # Speech recognition
|
||||
```
|
||||
|
||||
#### **Permissions**
|
||||
- **Access Level**: Public (no authentication required)
|
||||
- **Authentication**: None (`@permission_classes([AllowAny])`)
|
||||
|
||||
### **Method Details**
|
||||
|
||||
---
|
||||
|
||||
### **1. BaiduFanyiView (Text Translation)**
|
||||
|
||||
#### **Endpoint**: `POST /api/translate/`
|
||||
|
||||
##### **Description**
|
||||
Translates text content between supported languages using Baidu Translate API.
|
||||
|
||||
##### **Parameters**
|
||||
```json
|
||||
{
|
||||
"q": "text to translate", // Required: Text content (max 3000 characters)
|
||||
"from_lang": "en", // Required: Source language code
|
||||
"to_lang": "zh" // Required: Target language code
|
||||
}
|
||||
```
|
||||
|
||||
##### **Supported Languages**
|
||||
Languages are loaded from `info.baidu_lang_info`:
|
||||
- Check `languages` for supported language pairs
|
||||
- Use `"auto"` for automatic source language detection
|
||||
|
||||
##### **Response Format**
|
||||
```json
|
||||
{
|
||||
"message": "Success",
|
||||
"code": "10000",
|
||||
"data": {
|
||||
"trans_result": [
|
||||
{
|
||||
"src": "Hello world",
|
||||
"dst": "你好世界"
|
||||
}
|
||||
],
|
||||
"from": "en",
|
||||
"to": "zh"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### **Error Responses**
|
||||
|
||||
| Code | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| 400 | Bad Request | Invalid language codes or missing parameters |
|
||||
| 400 | Bad Request | Text length exceeds 3000 characters |
|
||||
| 503 | Service Unavailable | Baidu API temporarily unavailable |
|
||||
|
||||
---
|
||||
|
||||
### **2. RecognizeLangTypeViews (Language Recognition)**
|
||||
|
||||
#### **Endpoint**: `POST /api/recognize-language/`
|
||||
|
||||
##### **Description**
|
||||
Automatically detects the language of provided text content.
|
||||
|
||||
##### **Parameters**
|
||||
```json
|
||||
{
|
||||
"q": "text to recognize" // Required: Text content (max 3000 characters)
|
||||
}
|
||||
```
|
||||
|
||||
##### **Response Format**
|
||||
```json
|
||||
{
|
||||
"message": "Success",
|
||||
"code": "10000",
|
||||
"data": {
|
||||
"lang": "en",
|
||||
"confidence": 0.98
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### **Error Responses**
|
||||
|
||||
| Code | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| 400 | Bad Request | Text length exceeds 3000 characters |
|
||||
| 400 | Bad Request | Language not in supported range |
|
||||
| 503 | Service Unavailable | Baidu API temporarily unavailable |
|
||||
|
||||
---
|
||||
|
||||
### **3. PictureRecognizeViews (Picture Translation)**
|
||||
|
||||
#### **Endpoint**: `POST /api/picture-translate/`
|
||||
|
||||
##### **Description**
|
||||
Translates text within images using Baidu's OCR and translation capabilities.
|
||||
|
||||
##### **Request Format**
|
||||
Multipart form data with file upload and query parameters.
|
||||
|
||||
##### **Parameters**
|
||||
**Form Data:**
|
||||
- `file`: Image file (required)
|
||||
|
||||
**Query Parameters:**
|
||||
- `from_lang`: Source language code (required)
|
||||
- `to_lang`: Target language code (required)
|
||||
- `picture`: Image format type (required, e.g., "jpg", "png")
|
||||
|
||||
##### **Request Example**
|
||||
```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"
|
||||
```
|
||||
|
||||
##### **Response Format**
|
||||
```json
|
||||
{
|
||||
"message": "Success",
|
||||
"code": "10000",
|
||||
"data": {
|
||||
"words_result_num": 2,
|
||||
"words_result": [
|
||||
{
|
||||
"words": "Hello World"
|
||||
},
|
||||
{
|
||||
"words": "Welcome"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### **Error Responses**
|
||||
|
||||
| Code | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| 400 | Bad Request | Invalid language codes |
|
||||
| 400 | Bad Request | Unsupported image format |
|
||||
| 503 | Service Unavailable | Baidu API temporarily unavailable |
|
||||
|
||||
---
|
||||
|
||||
### **4. SpeechRecognitionView (Speech Recognition)**
|
||||
|
||||
#### **Endpoint**: `POST /api/speech-recognition/`
|
||||
|
||||
##### **Description**
|
||||
Recognizes and translates speech/audio content.
|
||||
|
||||
##### **Request Format**
|
||||
Multipart form data with voice file upload and query parameters.
|
||||
|
||||
##### **Parameters**
|
||||
**Form Data:**
|
||||
- `voice`: Audio file (required)
|
||||
|
||||
**Query Parameters:**
|
||||
- `speech_type`: Audio format (required, e.g., "pcm")
|
||||
- `from_lang`: Source language code (required)
|
||||
- `to_lang`: Target language code (required)
|
||||
|
||||
##### **Request Example**
|
||||
```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"
|
||||
```
|
||||
|
||||
##### **Response Format**
|
||||
```json
|
||||
{
|
||||
"message": "Success",
|
||||
"code": "10000",
|
||||
"data": {
|
||||
"result": "你好世界",
|
||||
"corpus_no": "123456789",
|
||||
"status": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### **Error Responses**
|
||||
|
||||
| Code | Status | Description |
|
||||
|------|--------|-------------|
|
||||
| 400 | Bad Request | Unsupported speech type |
|
||||
| 400 | Bad Request | Invalid language codes |
|
||||
| 503 | Service Unavailable | Baidu API temporarily unavailable |
|
||||
|
||||
---
|
||||
|
||||
### **Implementation Details**
|
||||
|
||||
#### **Async Operations**
|
||||
All views use `aiohttp` for non-blocking HTTP requests:
|
||||
|
||||
```python
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(url, params=payload, headers=headers) as response:
|
||||
result = await response.json()
|
||||
```
|
||||
|
||||
#### **Fallback Mechanism**
|
||||
If `aiohttp` is not available, views fall back to synchronous `requests`:
|
||||
|
||||
```python
|
||||
if aiohttp:
|
||||
# Use async aiohttp
|
||||
else:
|
||||
# Fallback to sync requests
|
||||
```
|
||||
|
||||
#### **Configuration**
|
||||
Baidu API configuration loaded from:
|
||||
- `info.baidu_fanyi_appid.py`: appid, appkey, endpoint
|
||||
- `info.baidu_lang_info.py`: languages, auto_lang, cuid, mac
|
||||
|
||||
---
|
||||
|
||||
### **Security & Performance**
|
||||
|
||||
#### **Rate Limiting**
|
||||
- Respects Baidu API rate limits
|
||||
- No additional rate limiting implemented
|
||||
- Consider implementing client-side rate limiting
|
||||
|
||||
#### **Input Validation**
|
||||
- Text length limit: 3000 characters
|
||||
- Language code validation
|
||||
- File format validation for media endpoints
|
||||
|
||||
#### **Error Handling**
|
||||
- Comprehensive try-catch blocks
|
||||
- Meaningful error messages
|
||||
- Graceful degradation when service unavailable
|
||||
|
||||
---
|
||||
|
||||
### **Usage Examples**
|
||||
|
||||
#### **Python Client**
|
||||
```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()
|
||||
|
||||
# Run async operation
|
||||
result = asyncio.run(translate_text())
|
||||
```
|
||||
|
||||
#### **JavaScript Frontend**
|
||||
```javascript
|
||||
// Text translation
|
||||
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();
|
||||
};
|
||||
```
|
||||
|
||||
#### **Testing Endpoints**
|
||||
```bash
|
||||
# Test text translation
|
||||
curl -X POST http://localhost:8000/api/translate/
|
||||
-H "Content-Type: application/json"
|
||||
-d '{"q":"Hello world","from_lang":"en","to_lang":"zh"}'
|
||||
|
||||
# Test language recognition
|
||||
curl -X POST http://localhost:8000/api/recognize-language/
|
||||
-H "Content-Type: application/json"
|
||||
-d '{"q":"Hello world"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### **Monitoring & Debugging**
|
||||
|
||||
#### **Logging**
|
||||
- Request data logged via `print(request.data)`
|
||||
- API responses logged via `print(sign)` in speech recognition
|
||||
- Consider adding structured logging for production
|
||||
|
||||
#### **Performance Metrics**
|
||||
- Async operations reduce blocking time
|
||||
- Concurrent requests handled efficiently
|
||||
- Memory usage optimized with streaming where possible
|
||||
|
||||
#### **Health Checks**
|
||||
- Service availability can be checked via API status
|
||||
- Consider implementing health check endpoints
|
||||
|
||||
---
|
||||
|
||||
### **Integration Notes**
|
||||
|
||||
#### **Django Integration**
|
||||
```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'),
|
||||
]
|
||||
```
|
||||
|
||||
#### **Running with Daphne**
|
||||
```bash
|
||||
pip install aiohttp
|
||||
daphne chunyu_project.asgi:application --port 8000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: Current Session
|
||||
**Version**: 1.0
|
||||
Reference in New Issue
Block a user