Repository navigation
Expand file tree
/
Copy pathlocalization.py
More file actions
345 lines (327 loc) · 28.3 KB
/
Copy pathlocalization.py
File metadata and controls
345 lines (327 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"""Localized user-facing errors for the local HTTP boundary.
Domain code keeps its Chinese copy for CLI and Agent traces. The HTTP boundary
chooses an English message from the stable error code when the caller asks for
English, so a missing translation never leaks Chinese into an English UI.
"""
import re
from fastapi import Request
from opendirector.domain.timeline_errors import timeline_error_message
from opendirector.domain.url_import import url_import_message
from opendirector.domain.creation.commands import CommandReceipt
from opendirector.domain.creation.contract_messages import contract_message
from opendirector.domain.capabilities import Capability
from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message
from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH
ENGLISH_BY_CODE = {
'model_storage_invalid': 'The object storage settings are not valid. Check the access key, secret key, bucket and region.',
'model_storage_incomplete': 'Object storage needs an access key, secret key, bucket and region. Fill in all four or leave them empty.',
'video_compression_preset': 'Choose a valid compression preset.',
'video_compression_source': 'Select one video to compress.',
**ASSET_DOWNLOAD_ENGLISH,
'keyframe_unsupported': 'This model or mode does not support keyframes. Clear the keyframe times or choose another model.',
'keyframe_mode': 'Keyframes work in Universal reference mode only, not with first/last frames, continuation or structure control.',
'keyframe_kind': 'A keyframe must be an image.',
'keyframe_count': 'There are more keyframes than this model accepts.',
'keyframe_needs_reference': 'Keyframes also need at least one ordinary reference image or video.',
'keyframe_time': 'Each keyframe needs its own time, earlier than the end of the video and at least 1/24 second from the others.',
'keyframe_image': 'A keyframe must be a PNG, JPEG or WebP image within the size limit.',
'higgsfield_model': 'Choose MAGI-2 with the official Higgsfield Open API address.',
'higgsfield_key': 'Enter your Higgsfield Open KEY_ID:KEY_SECRET.',
'higgsfield_output': 'MAGI-2 supports 1080p and whole-second durations from 4 to 30 seconds.',
'higgsfield_parameters': 'Choose an aspect ratio and audio option supported by MAGI-2.',
'higgsfield_mode': 'MAGI-2 supports first/last frames and reference media.',
'higgsfield_image': 'Use valid JPEG, PNG, WebP, or GIF images, each smaller than 30 MB.',
'higgsfield_format': 'Use MP4 video and WAV audio references. Convert MOV to MP4 and MP3 to WAV before uploading.',
'higgsfield_media_size': 'Each reference video must be at most 200 MB; each audio file at most 15 MB.',
'higgsfield_duration': 'Each reference video or audio clip must be 2–30 seconds. The total for each media type cannot exceed 30 seconds.',
'higgsfield_reference_count': 'MAGI-2 accepts up to 10 images, 5 videos, and 5 audio references.',
'higgsfield_reference_changed': 'A reference asset changed. Review the inputs before submitting again.',
'higgsfield_frames': 'Each frame slot accepts one image. A last frame requires a first frame.',
'higgsfield_references': 'Reference mode requires at least one image, video, or audio clip. Check the reference roles.',
'higgsfield_prompt': 'MAGI-2 prompts allow up to 15,000 characters. Text-to-video requires a prompt.',
"desktop_auth_required": "The desktop connection has expired. Reopen the application.",
'prompt_optimization_empty': 'Enter a prompt to optimize.',
'prompt_optimization_refs': 'Prompt references changed. Try again.',
'prompt_optimization_node': 'Select an image or video node.',
'prompt_optimization_model': 'Choose an available chat model in the Agent panel.',
'prompt_optimization_vision': 'The selected chat model cannot use these visual references. Choose an Agent model with image or video input.',
'prompt_optimization_cli': 'The selected Agent CLI could not optimize the prompt. Check its installation, login, and model.',
'prompt_optimization_cli_unsupported': 'The selected Agent CLI does not support standalone prompt optimization. Switch the Agent or model in the Agent panel.',
'prompt_optimization_media': 'The video reference duration is invalid.',
'prompt_optimization_too_large': 'The references are too large for prompt optimization. Reduce their size or number and try again.',
'prompt_optimization_result': 'The model did not return a usable prompt. Your original text was kept.',
'prompt_optimization_provider': 'The text model could not optimize the prompt. Check its settings and try again. Your original text was kept.',
'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.',
'audio_music_unsupported': 'Seed Audio creates narration and dialogue only. Use a music model for instrumental music.',
'audio_mode_required': 'Seed Audio needs the all-purpose dubbing mode.',
'audio_task_unsupported': 'This Seed Audio adapter does not implement that audio task yet.',
'seed_audio_base_url': 'Seed Audio 1.5 needs the Ark content-generation base URL ending in /api/v3. Add the Seed Audio preset instead.',
'audio_reference_image': 'That reference cannot be sent: Seed Audio takes PNG, JPEG or WEBP images within the size limit.',
'audio_reference_audio': 'Voice references must be WAV or MP3 and 2 to 30 seconds long.',
'audio_reference_count': 'Seed Audio takes at most one image, one video, or six voice references up to 180 seconds in total.',
'audio_reference_mix': 'Seed Audio cannot combine these inputs: send one image, one video with optional voice clips, or voice clips alone.',
'audio_reference_video': 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.',
'audio_dubbing_video': 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.',
'audio_dubbing_source': 'Dubbing needs a source video to re-voice.',
'audio_separation_video': 'Track separation takes one audio input and no video.',
'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.',
'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.',
'audio_subtitle_encoding': 'The subtitle file must use UTF-8 encoding.',
'audio_subtitle_format': 'The subtitle must be valid SRT: each cue needs a start --> end timing line.',
'audio_subtitle_order': 'Subtitle cue start times must increase in file order.',
'audio_subtitle_range': 'The subtitle timeline must fall within the referenced video duration.',
'audio_subtitle_transport': 'A subtitle file needs a fetchable address: configure object storage before dubbing with subtitles.',
'seed_audio_storage': 'This task needs media the provider can fetch. Configure the model account object storage first.',
'seed_audio_storage_rejected': 'Object storage rejected the upload. Check the bucket, region and access keys.',
'seed_audio_storage_timeout': 'The object storage upload timed out. Check the network and try again.',
'seed_audio_storage_unreachable': 'Object storage could not be reached. Check the endpoint, network and proxy settings.',
'audio_voice_scope': 'Voice selection applies to speech or voice-reference generation only. Dubbing keeps the source voice and separation has no voice.',
'audio_output_video_scope': 'A playable re-voiced video needs a referenced video with speech or voice-reference generation.',
'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.',
'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.',
'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.',
'bigmodel_video_frames': 'Use text, one first-frame image, or an explicit first/last pair. Each frame slot accepts one image; a last frame requires a first frame. Reference and continuation modes are not supported.',
'bigmodel_video_prompt': 'CogVideoX-3 prompts allow up to 512 characters. Provide a prompt or frame image.',
'bigmodel_video_cancel': 'Remote BigModel video cancellation is not connected. The task may continue running and incur charges.',
'execution_file_link': 'Execution files must not have hard links.',
'kling_model': 'This Kling protocol does not support the selected model.',
'kling_mode': 'Kling currently supports first/last frames and image-reference generation.',
'kling_image': 'Kling requires valid PNG or JPEG images up to 30 MB, at least 300 pixels on each edge, with an aspect ratio of 0.4–2.5. Video and audio references are not supported here.',
'kling_frames': 'Choose frame inputs supported by the selected Kling model. Each slot accepts one image, and a last frame requires a first frame. Flash accepts only a first frame.',
'kling_prompt': 'Enter a Kling prompt. English allows 26,000 characters and other text 11,000 characters; mixed text shares these limits proportionally.',
'kling_aspect': 'Kling keyframe generation follows the image framing. Choose Auto for frames, or a supported ratio for text and image references.',
'kling_output': 'Choose an output resolution and integer duration supported by the selected Kling model.',
'kling_cancel': 'Remote Kling cancellation is not connected. The task may continue running and incur charges.',
'capability_unavailable': 'This request is not supported.',
'capability_paused': 'Service paused. Resume it and try again.',
'image_input_count': 'Too many input images.',
'image_input_bytes': 'The input images exceed the size limit.',
'image_input_mask': 'Check the image selection.',
'tool_source_count': 'Check the number of source images.',
'tool_source_type': 'Source assets must be images.',
'capability_connection_changed': 'The model connection changed during the capability check. Submit again.',
'tool_concept_translation': 'Use a short English subject description, or add a chat model in Models to translate it automatically.',
'tool_no_video_match': 'The requested subject was not found in the video. Try a different description.',
'tool_structure_reference_duration': 'Structure reference needs a clip no longer than 30 seconds. Trim the video first.',
'tool_structure_reference_frames': 'Structure reference processes at most 2048 frames at a time. Trim the video or lower its frame rate first.',
'tool_structure_reference_misaligned': 'Tracking or depth returned a different number of frames than the video, so the frames cannot be aligned. Try again.',
'tool_blockout_duration': 'Video blockout needs a clip no longer than 30 seconds. Trim the video first.',
'tool_blockout_frames': 'Video blockout processes at most 2048 frames at a time. Trim the video or lower its frame rate first.',
'tool_blockout_people': 'Video blockout handles at most 8,192 person-frames (each person on each frame counts once) at a time. Trim the video or use a shot with fewer people.',
'tool_blockout_misaligned': 'Tracking and the video differ in frame count or picture size, so they cannot be aligned frame by frame. Re-export the video as a constant-frame-rate H.264 MP4 and process that.',
'voice_upload_type': 'Upload the voice recording using multipart/form-data.',
'voice_upload_form': 'Check the recording, form fields and text lengths, then try the upload again.',
'voice_model_unsupported': 'This checkpoint does not accept uploaded voices. Choose a Base model for voice cloning or a compatible built-in voice.',
'voice_library_unsupported': 'This model does not have a confirmed voice library. Select a supported speech model.',
'voice_connection_changed': 'The voice service or account changed. Reopen the library and select a voice again.',
'voice_reference_required': 'This model needs a registered reference recording. Upload and select a voice; default cannot replace a recording.',
'voice_transcript_required': 'This model needs an accurate recording transcript. Enter the transcript and create the voice again.',
'voice_transcript_too_long': 'The recording transcript must be at most 100,000 characters.',
'voice_description_too_long': 'The speaker description must be at most 4,000 characters.',
'voice_not_found': 'The selected voice no longer exists. Refresh the library and select another voice.',
'voice_delete_unsupported': 'This voice cannot be deleted. Only supported uploaded voices can be deleted.',
'voice_consent_required': 'Enter the consent recording ID for this voice.',
'voice_name_invalid': 'Enter a valid voice name without path separators or control characters.',
'voice_audio_invalid': 'The recording could not be decoded. Check the actual audio format and file integrity.',
'voice_format': 'This recording format is unsupported. Choose a listed format.',
'voice_size': 'The recording exceeds the service file size limit.',
'voice_duration': 'The recording duration is outside the service limits. Trim it and try again.',
'voice_provider_protocol': 'The voice service returned an invalid response or pagination did not finish. Check its API version.',
'voice_provider_error': 'The voice service request failed. Check the connection and account permissions.',
'voice_provider_timeout': 'The voice service timed out. Check its status and try again.',
'voice_name_taken': 'This account already has a voice with that name. Choose another name.',
'voice_provider_quota': 'The voice service account has insufficient balance or resource packages. Top up and try again.',
"moss_speech_text": "Enter the text to read aloud.",
"moss_speech_voice": "Enter a Voice ID available to your MOSS account.",
"moss_speech_reference": "MOSS speech generation does not accept references. Enter speech text and a Voice ID.",
"zhipu_speech_text": "Enter the text to read aloud, at most 1,024 characters per GLM-TTS request.",
"zhipu_speech_voice": "Select a voice available to your Zhipu account.",
"zhipu_speech_reference": "GLM-TTS does not accept references. Enter speech text and select a voice.",
"moss_prompt_limit": "MOSS requires a nonempty prompt of at most 4,000 characters, including text references.",
"image_decode": "The image could not be decoded. Check its actual format and file integrity.",
"asset_preview_unsupported": "This asset type does not support this preview format.",
"video_compat_ffmpeg_missing": "Compatible video conversion requires FFmpeg. Install FFmpeg, ensure ffmpeg and ffprobe are in PATH, and restart the server.",
"video_compat_missing_item": "This video node no longer exists.",
"video_compat_missing_asset": "This video node has no video asset to convert.",
"video_compat_task_missing": "This video conversion task does not exist.",
"video_compat_unsupported_video_codec": "This video codec cannot be remuxed into MP4 without re-encoding. Convert it to H.264 or HEVC first.",
"video_compat_timeout": "Video conversion timed out. Retry later or convert the file locally before importing.",
"video_compat_failed": "Could not convert the video into a browser-compatible version. Check the source file format and integrity.",
"asset_text_api_unavailable": "canvas text show requires a running API to read the complete Markdown source. Start the API and check OPENDIRECTOR_API_URL.",
"image_pixel_limit": "Images must contain no more than 25 million pixels.",
"minimax_image_reference": "MiniMax H3 references must be PNG, JPEG, WebP, HEIC, or HEIF, with edges of 128–8192 pixels and a long-to-short edge ratio of at most 4:1.",
"minimax_image_count": "MiniMax H3 image editing accepts up to 16 reference images.",
"minimax_image_bytes": "MiniMax H3 image reference requests cannot exceed 64 MiB.",
"minimax_speech_text": "Enter the text to read aloud, up to 3,000 characters.",
"minimax_speech_model": "Unsupported MiniMax speech model. Choose a model from the preset.",
"minimax_speech_voice": "Choose a voice available to your MiniMax account from the voice library.",
"minimax_speech_reference": "MiniMax speech synthesis does not accept references. Enter the text to read aloud and choose a voice.",
"moss_image_size": "MOSS image dimensions must be 256–2048, multiples of 16, and no more than 2,097,152 pixels in total.",
"moss_image_reference": "MOSS image generation does not accept image references or editing inputs.",
"bigmodel_image_reference": "GLM-Image accepts text-to-image requests only. Remove image references or editing inputs.",
"bigmodel_image_prompt": "Enter a GLM-Image prompt.",
"bigmodel_image_size": "GLM-Image requires a preset size, or dimensions of 1024–2048 in multiples of 32.",
"moss_layout_reference": "MOSS layout JSON does not accept additional text references. Put the requirements in the JSON or remove the text references.",
"antigravity_login": "Antigravity CLI is not signed in or its sign-in expired. Run agy in a terminal to sign in, then try again.",
"antigravity_models": "Could not read the Antigravity model list. Check the local agy installation.",
"antigravity_failed": "Antigravity did not finish this turn. Check its sign-in, the selected model, or the native trace.",
"antigravity_denied": "Antigravity requested a tool outside OpenDirector's allowed scope. It was denied and this turn has no reply.",
"antigravity_empty": "Antigravity returned no reply for this turn. Check the native trace.",
"agent_dependency_unavailable": "Bundled Agent is unavailable. Reinstall with pip install --force-reinstall opendirector; for a source checkout, use pip install -e .",
"motion_model_missing": "No chat/agent model is configured. Add an Agent model in Model Settings first.",
"motion_media_missing": "One or more connected media assets referenced by this composition are missing or unreadable. Reconnect the media node and try again.",
"motion_chrome_not_found": "Chrome or Chromium is required for Web Motion MP4 export. Install Google Chrome or set OPENDIRECTOR_CHROME_BIN.",
"motion_ffmpeg_not_found": "FFmpeg is required for Web Motion MP4 export. Install ffmpeg and ensure it is on PATH.",
"motion_render_not_found": "Render job not found.",
"motion_render_not_ready": "Render job is not finished yet.",
"motion_render_missing": "Rendered video file is missing.",
"motion_render_failed": "Web Motion MP4 render failed.",
"motion_render_cancelled": "Web Motion MP4 render was cancelled.",
"motion_render_project_mismatch": "Render job does not belong to the target project.",
"motion_inspect_failed": "Frame inspection failed. Please try again.",
"motion_inspect_cancelled": "Frame inspection was cancelled.",
"motion_inspect_timeout": "Frame inspection timed out. Please try again.",
"motion_chat_failed": "Motion Director chat failed. Please try again.",
"motion_api_unavailable": "Motion commands require a running API. Start the API and check OPENDIRECTOR_API_URL.",
"motion_provider_input": "The model service rejected the input or parameters. Check your request and model capabilities.",
"motion_provider_reference": "The model service rejected the reference media. Replace the reference asset and try again.",
"motion_provider_authentication": "Model service authentication failed. Check the API key in Model Settings.",
"motion_provider_permission": "The model service denied access. Check your API key, model permissions, and safety policy.",
"motion_provider_quota": "Model account balance or quota is insufficient. Check your account quota and try again.",
"motion_provider_rate_limit": "The model service is busy or rate-limited. Wait a moment and try again.",
"motion_provider_temporary": "The model service is temporarily unavailable. Please try again later.",
"motion_provider_protocol": "The model service returned an invalid response. Check the model configuration and try again.",
"motion_provider_error": "The model service could not complete the request. Please try again.",
"motion_empty_message": "Enter a motion instruction before sending.",
"motion_output_length_limit": "The generated motion code exceeded the model's single-turn output limit and was truncated. Try lowering Thinking effort (or turning it off), or break the request into smaller steps.",
"motion_thinking_length_limit": "Model reasoning exhausted the single-turn output limit before producing motion code. Lower Thinking effort to Off or Low and try again.",
"chat_thinking_length_limit": "The model's reasoning exhausted the maximum output token limit before producing a reply. Increase the max output tokens or lower the thinking effort and try again.",
"chat_output_length_limit": "The model response reached the maximum output token limit and was truncated. Increase the max output tokens and try again.",
"chat_content_filtered": "The model response was blocked by the provider's content safety rules. Adjust the prompt and try again.",
"chat_incomplete_response": "The model response did not finish normally (it may have hit a length limit or content filter). Any generated content has been preserved.",
"invalid_input": "The request is invalid. Check the required fields and their formats.",
"invalid_project": "The project or asset identifier is invalid.",
"command_conflict": "This operation ID was already used with different input. Use a new operation ID for changed input, or inspect the original receipt.",
"missing_receipt": "No committed receipt was found for this command or operation ID.",
"missing_object": "The requested item no longer exists.",
"not_found": "The requested item no longer exists.",
"revision_conflict": "This item changed since it was loaded. Reload it and try again.",
"preview_expired": "The preview expired. Generate it again.",
"reference_invalid": "A reference is no longer valid. Select it again and retry.",
"role_restricted": "This item does not allow that operation.",
"result_not_adoptable": "A side artifact such as an audio track or subtitle cannot replace the adopted result. Generate again or adopt the primary output.",
"canvas_run_layout_extent": "Canvas positions or dimensions are too large to arrange. Resize the affected items.",
"canvas_run_layout_group": "Run layout is only available for top-level groups.",
"canvas_run_layout_conflict": "Locked Run areas overlap. Unlock one of the groups and try again.",
"canvas_run_layout_shared_object": "Two Runs use the same editable object. Copy the configuration or editor document and try again.",
"storage_unavailable": "A stored file is missing or has changed. Restore the file and try again.",
"capability_unsupported": "This capability is not supported yet.",
"model_list_http_error": "Could not load the model list from the service.",
"operation_rejected": "The operation was rejected. Reload the item and try again.",
"storage_busy": "Project storage is busy. Try again shortly.",
"project_open_elsewhere": "This project is open in another window. Close it there and try again.",
"session_expired": "This project was closed or its session expired. Reopen it and save again.",
"local_only": "Only this computer can access the project service.",
"cross_origin": "File access from another site is not allowed.",
"invalid_local_request": "This is not a valid local app request.",
}
ENGLISH_BY_STATUS = {
400: "The request is invalid. Check the values and try again.",
401: "Authentication is required. Sign in again and retry.",
403: "This operation is not allowed.",
404: "The requested item no longer exists.",
409: "The item changed or is busy. Reload it and try again.",
413: "The file or request is too large.",
422: "The request could not be applied to the current project state.",
500: "The local service hit an unexpected error. Check the terminal for details.",
501: "This capability is not supported yet.",
502: "The upstream service failed. Check its configuration and try again.",
503: "The local service is unavailable. Check the terminal and try again.",
504: "The upstream service timed out. Check the service and try again.",
}
def wants_english_language(value: str | None) -> bool:
"""Use the primary Accept-Language tag, matching the browser decision."""
value = (value or "").strip()
if not value:
return False
primary = value.split(",", 1)[0].split(";", 1)[0].strip().lower()
return not primary.startswith("zh")
def wants_english(request: Request) -> bool:
return wants_english_language(request.headers.get("accept-language"))
def localized_error_for_language(
language: str | None,
*,
chinese: str,
status: int,
code: str = "operation_rejected",
required_capability: Capability | None = None,
) -> str:
specific = (timeline_error_message(code, language) or url_import_message(code, language, chinese)
or contract_message(code, language, chinese))
if specific is not None:
return specific
if not wants_english_language(language):
return chinese
if code == 'tool_model_missing':
return missing_tool_model_message(required_capability, english=True)
if code == 'model_list_http_error':
upstream_status = re.search(r'HTTP ([0-9]{3})', chinese)
if upstream_status:
return f'Could not load the model list (HTTP {upstream_status[1]}).'
if code.startswith(('capability_', 'image_input_', 'tool_source_')):
translated = english_capability_message(chinese)
if translated:
return translated
if code == 'command_conflict' and chinese == '该工程标识已经使用。':
return 'This project ID is already in use.'
if code == 'invalid_input' and chinese == '聊天引用超过数量上限,请移除部分引用。':
return 'The chat reference limit was exceeded. Remove some references and retry.'
if code == 'invalid_input' and chinese == '视频裁切需要视频来源节点。':
return 'Select a video canvas node as the source for this trim.'
if code == 'invalid_input' and chinese == '裁切结束时间超出来源视频时长。':
return 'The trim ends after the source video. Choose an end time within the source duration.'
if status == 409 and chinese == '此视频裁切正在进行,请等待结果。':
return 'This trim is already running. Wait for its result.'
if status == 409 and chinese == '此动效发布正在进行,请等待结果。':
return 'This motion publication is already running. Wait for its result.'
if code == 'reference_invalid':
chat = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 的来源或素材版本已失效,请重新选择此引用。', chinese)
if chat:
return f'Chat reference {chat[1]} has a stale source or asset version. Select it again and retry.'
unknown = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 不属于当前对话。', chinese)
if unknown:
return f'Chat reference {unknown[1]} does not belong to the current conversation.'
# A generic operation code must not hide a more specific HTTP status.
generic = code in {"operation_rejected", "invalid_input"}
if generic and status in {413, 502, 504}:
return ENGLISH_BY_STATUS[status]
specific = None if code == "operation_rejected" else ENGLISH_BY_CODE.get(code)
if code == 'voice_provider_error':
from opendirector.domain.voices import VOICE_MESSAGES
detail = chinese.removeprefix(VOICE_MESSAGES[code]).strip()
return specific + (' ' + detail if detail else '')
return (
specific
or ENGLISH_BY_STATUS.get(status)
or ENGLISH_BY_CODE["operation_rejected"]
)
def localized_error(
request: Request,
*,
chinese: str,
status: int,
code: str = "operation_rejected",
required_capability: Capability | None = None,
) -> str:
return localized_error_for_language(
request.headers.get("accept-language"),
chinese=chinese,
status=status,
code=code,
required_capability=required_capability,
)
def localized_receipt(request: Request, receipt: CommandReceipt) -> CommandReceipt:
return receipt.model_copy(update={'issues': tuple(
issue.model_copy(update={'message': localized_error(request, chinese=issue.message, status=422, code=issue.code)})
for issue in receipt.issues
)})