-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.py
127 lines (105 loc) · 5.11 KB
/
translate.py
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
import os
import json
import requests
# Load your OpenAI API key from environment variables
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
raise ValueError("API key is missing. Set the OPENAI_API_KEY environment variable.")
translations_path = 'translations.json'
lang_dir = 'lang'
# Ensure the lang directory exists
os.makedirs(lang_dir, exist_ok=True)
def translate_content(content, target_lang):
prompt = f"Translate the following JSON content to {target_lang} organically with SEO optimization and maintain the JSON structure: {json.dumps(content)}"
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
data = {
'model': 'gpt-4o-mini',
'messages': [
{'role': 'system', 'content': 'You are a professional SEO product translator for great product marketing. Keep the JSON structure, translate the content and IMPORTANT: for the local language section find inside information for the dedicated language / market. Make sure to include the aisummary part.'},
{'role': 'user', 'content': prompt}
]
}
response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=data)
try:
response.raise_for_status()
response_data = response.json()
if 'choices' in response_data and response_data['choices']:
translated_text = response_data['choices'][0]['message']['content'].strip()
# Remove backticks if the content is wrapped in a code block
if translated_text.startswith("```json"):
translated_text = translated_text.strip("```json").strip("```").strip()
try:
return json.loads(translated_text)
except json.JSONDecodeError:
print("Failed to parse JSON from translated content. Attempting to clean it up.")
print(f"Translated text: {translated_text}")
return None
else:
print(f"Unexpected response structure: {response_data}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response content: {response.text}")
except Exception as err:
print(f"An error occurred: {err}")
print(f"Response content: {response.text}")
return None
def translate_file():
try:
with open(translations_path, 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
print(f"Translation file not found: {translations_path}")
return
except json.JSONDecodeError as json_err:
print(f"Error loading JSON file: {json_err}")
return
# Load the current version and languages
current_version_path = 'current_version.json'
try:
with open(current_version_path, 'r', encoding='utf-8') as file:
current_data = json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
current_data = {}
current_version = current_data.get('version')
current_languages = current_data.get('languages', [])
new_version = data.get('version')
new_languages = data.get('languages', [])
# Check if the version has changed or if there are new languages
if new_version != current_version or len(new_languages) != len(current_languages):
# Update the current version and languages
with open(current_version_path, 'w', encoding='utf-8') as file:
json.dump({'version': new_version, 'languages': new_languages}, file, ensure_ascii=False, indent=2)
content = data.get('content')
for lang in new_languages:
lang_code = lang.get('code')
if not lang_code:
print("Language code missing in configuration.")
continue
lang_file_path = os.path.join(lang_dir, f"{lang_code}.json")
if os.path.exists(lang_file_path):
try:
with open(lang_file_path, 'r', encoding='utf-8') as lang_file:
lang_data = json.load(lang_file)
if lang_data.get('version') == new_version:
print(f"Language file for {lang_code} is already up-to-date.")
continue
except json.JSONDecodeError:
print(f"Error reading language file for {lang_code}. Proceeding with translation.")
translated_content = translate_content(content, lang_code)
if translated_content:
translated_content['version'] = new_version
with open(lang_file_path, 'w', encoding='utf-8') as file:
json.dump(translated_content, file, ensure_ascii=False, indent=2)
print(f"Translated content written to {lang_file_path}")
else:
print(f"Failed to translate content for {lang_code}.")
else:
print("No updates needed. Version and languages are unchanged.")
if __name__ == '__main__':
try:
translate_file()
except Exception as e:
print(f"An error occurred: {e}")