0
# File Translation
1
2
Document translation supporting multiple formats (PDF, DOCX, PPTX, XLSX, TXT, XML, HTML, Markdown, Properties) with asynchronous processing and progress tracking. File translation operates as a two-step process: submit translation task and retrieve results.
3
4
## Capabilities
5
6
### Submit File Translation Task
7
8
Submits a document for translation and returns a task ID for tracking. Supports both URL-based and direct file upload methods.
9
10
```python { .api }
11
def FileTranslate(self, request: models.FileTranslateRequest) -> models.FileTranslateResponse:
12
"""
13
Submit a file translation task.
14
15
Args:
16
request: FileTranslateRequest with file and translation parameters
17
18
Returns:
19
FileTranslateResponse with task ID for tracking
20
21
Raises:
22
TencentCloudSDKException: For various error conditions
23
"""
24
```
25
26
**Usage Example:**
27
28
```python
29
from tencentcloud.common import credential
30
from tencentcloud.tmt.v20180321.tmt_client import TmtClient
31
from tencentcloud.tmt.v20180321 import models
32
33
# Initialize client
34
cred = credential.Credential("SecretId", "SecretKey")
35
client = TmtClient(cred, "ap-beijing")
36
37
# Submit file translation via URL
38
req = models.FileTranslateRequest()
39
req.Source = "en"
40
req.Target = "zh"
41
req.DocumentType = "pdf"
42
req.SourceType = 0 # URL source
43
req.Url = "https://example.com/document.pdf"
44
req.BasicDocumentType = "pdf"
45
46
# Submit translation task
47
resp = client.FileTranslate(req)
48
task_id = resp.Data.TaskId
49
print(f"Translation task submitted: {task_id}")
50
```
51
52
### Retrieve File Translation Results
53
54
Retrieves translation results using the task ID. Supports both callback and polling methods for result retrieval.
55
56
```python { .api }
57
def GetFileTranslate(self, request: models.GetFileTranslateRequest) -> models.GetFileTranslateResponse:
58
"""
59
Retrieve file translation results by task ID.
60
61
Args:
62
request: GetFileTranslateRequest with task ID
63
64
Returns:
65
GetFileTranslateResponse with translation status and results
66
67
Raises:
68
TencentCloudSDKException: For various error conditions
69
"""
70
```
71
72
**Usage Example:**
73
74
```python
75
import time
76
77
# Check translation status and retrieve results
78
def wait_for_translation(client, task_id, max_wait_time=300):
79
"""Wait for translation completion and return results."""
80
start_time = time.time()
81
82
while time.time() - start_time < max_wait_time:
83
req = models.GetFileTranslateRequest()
84
req.TaskId = task_id
85
86
resp = client.GetFileTranslate(req)
87
88
if resp.Data.Status == "success":
89
return resp.Data.Url # URL to download translated file
90
elif resp.Data.Status == "failed":
91
raise Exception(f"Translation failed: {resp.Data.ErrorMsg}")
92
elif resp.Data.Status in ["waiting", "processing"]:
93
print(f"Translation status: {resp.Data.Status}")
94
time.sleep(5) # Wait 5 seconds before next check
95
96
raise Exception("Translation timeout")
97
98
# Use the function
99
try:
100
result_url = wait_for_translation(client, task_id)
101
print(f"Translation completed: {result_url}")
102
except Exception as e:
103
print(f"Translation error: {e}")
104
```
105
106
## Request/Response Models
107
108
### FileTranslateRequest
109
110
```python { .api }
111
class FileTranslateRequest:
112
"""
113
Request parameters for file translation.
114
115
Attributes:
116
Source (str): Source language code
117
Target (str): Target language code
118
DocumentType (str): File format (pdf, docx, pptx, xlsx, txt, xml, html, markdown, properties)
119
SourceType (int): Data source type (0: URL, 1: file data)
120
Url (str): File URL when SourceType=0
121
Data (str): Base64 encoded file data when SourceType=1
122
BasicDocumentType (str): Basic document type for processing
123
CallbackUrl (str): Optional callback URL for result notification
124
ProjectId (int): Project ID (default: 0)
125
"""
126
```
127
128
### FileTranslateResponse
129
130
```python { .api }
131
class FileTranslateResponse:
132
"""
133
Response from file translation submission.
134
135
Attributes:
136
Data (Task): File translation task data containing TaskId
137
RequestId (str): Unique request identifier
138
"""
139
```
140
141
### GetFileTranslateRequest
142
143
```python { .api }
144
class GetFileTranslateRequest:
145
"""
146
Request parameters for retrieving file translation results.
147
148
Attributes:
149
TaskId (str): Task ID returned from FileTranslate
150
"""
151
```
152
153
### GetFileTranslateResponse
154
155
```python { .api }
156
class GetFileTranslateResponse:
157
"""
158
Response from file translation result retrieval.
159
160
Attributes:
161
Data (GetFileTranslateData): Translation result data
162
RequestId (str): Unique request identifier
163
"""
164
```
165
166
### Task
167
168
```python { .api }
169
class Task:
170
"""
171
File translation task data.
172
173
Attributes:
174
TaskId (str): Task ID for tracking translation status
175
"""
176
```
177
178
### GetFileTranslateData
179
180
```python { .api }
181
class GetFileTranslateData:
182
"""
183
File translation result data.
184
185
Attributes:
186
TaskId (str): Task ID for this translation
187
Status (str): Task status (init, wait, success, fail)
188
FileData (str): Translation result data when successful
189
Message (str): Status message
190
Progress (int): Translation progress (0-100)
191
UsedAmount (int): Characters consumed for billing
192
"""
193
```
194
195
## Supported File Formats
196
197
### Document Formats
198
- **PDF**: Portable Document Format files
199
- **DOCX**: Microsoft Word documents
200
- **PPTX**: Microsoft PowerPoint presentations
201
- **XLSX**: Microsoft Excel spreadsheets
202
203
### Text Formats
204
- **TXT**: Plain text files
205
- **XML**: Structured XML documents
206
- **HTML**: Web page documents
207
- **Markdown**: Markdown formatted text
208
- **Properties**: Java properties files
209
210
## Translation Workflow
211
212
### Asynchronous Processing
213
214
File translation uses an asynchronous workflow:
215
216
1. **Submit Task**: Call `FileTranslate()` to submit file for translation
217
2. **Get Task ID**: Receive task ID for tracking progress
218
3. **Poll/Wait**: Use `GetFileTranslate()` to check status
219
4. **Retrieve Results**: Download translated file when status is "success"
220
221
### Result Retrieval Methods
222
223
**Polling Method:**
224
- Periodically call `GetFileTranslate()` with task ID
225
- Check status field: "waiting", "processing", "success", "failed"
226
- Retrieve result URL when status is "success"
227
228
**Callback Method:**
229
- Provide CallbackUrl in FileTranslateRequest
230
- Receive POST notification when translation completes
231
- Parse callback data for result URL
232
233
## Data Retention
234
235
Translation task data is retained for 7 days after completion. Ensure you download results within this timeframe as data will be permanently deleted afterward.
236
237
## Error Handling
238
239
Common error scenarios for file translation:
240
241
- **FAILEDOPERATION_SUBMISSIONLIMITREACHED**: Daily task limit exceeded
242
- **FAILEDOPERATION_TOOMANYWAITPROCESS**: Too many pending tasks
243
- **UNSUPPORTEDOPERATION**: Unsupported file format or language pair
244
- **INVALIDPARAMETER**: Invalid file URL or parameters
245
- **FAILEDOPERATION_DOWNLOADERR**: File download error
246
247
Example error handling:
248
249
```python
250
try:
251
resp = client.FileTranslate(req)
252
task_id = resp.Data.TaskId
253
except TencentCloudSDKException as e:
254
if e.code == "FAILEDOPERATION_SUBMISSIONLIMITREACHED":
255
print("Daily translation limit reached")
256
elif e.code == "FAILEDOPERATION_TOOMANYWAITPROCESS":
257
print("Too many pending tasks, try again later")
258
else:
259
print(f"Translation error: {e.code} - {e.message}")
260
```