Skip to content

Commit

Permalink
update trans.py
Browse files Browse the repository at this point in the history
  • Loading branch information
naya1503 committed Mar 2, 2024
1 parent 32df9ae commit 8f9e718
Showing 1 changed file with 12 additions and 20 deletions.
32 changes: 12 additions & 20 deletions trans.py
Original file line number Diff line number Diff line change
@@ -1,54 +1,46 @@
import asyncio

import yaml
import asyncio
from gpytranslate import Translator


async def translate_yaml(input_file, output_file, target_language):
with open(input_file, "r", encoding="utf-8") as file:
with open(input_file, 'r', encoding='utf-8') as file:
data = yaml.safe_load(file)

translator = Translator()

for key, value in data.items():
if isinstance(value, str):
translated_value = await translate_text_within_quotes(
value, translator, target_language
)
translated_value = await translate_text_within_quotes(value, translator, target_language)
data[key] = translated_value
elif isinstance(value, list):
translated_list = []
for item in value:
if isinstance(item, str):
translated_item = await translate_text_within_quotes(
item, translator, target_language
)
translated_item = await translate_text_within_quotes(item, translator, target_language)
translated_list.append(translated_item)
else:
translated_list.append(item)
data[key] = translated_list

with open(output_file, "w", encoding="utf-8") as file:
with open(output_file, 'w', encoding='utf-8') as file:
yaml.dump(data, file, allow_unicode=True)


async def translate_text_within_quotes(text, translator, target_language):
parts = text.split('"')
translated_parts = []
for i, part in enumerate(parts):
if i % 2 == 0: # Not within quotes
translated_part = await translator.translate(
part, target_language=target_language
)
translated_parts.append(translated_part)
translated_part = await translator.translate(part, target_language=target_language)
if isinstance(translated_part, str):
translated_parts.append(translated_part)
else:
translated_parts.append(translated_part.text)
else: # Within quotes
translated_parts.append(part)
return "".join(translated_parts)

return ''.join(translated_parts)

async def main():
await translate_yaml("langs/strings/id.yml", "langs/strings/en.yml", "en")

await translate_yaml('langs/strings/id.yml', 'langs/strings/en.yml', 'en')

if __name__ == "__main__":
asyncio.run(main())

0 comments on commit 8f9e718

Please sign in to comment.