-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio_fetcher.py
More file actions
75 lines (57 loc) · 2.24 KB
/
Copy pathaudio_fetcher.py
File metadata and controls
75 lines (57 loc) · 2.24 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
import os
import asyncio
from googletrans import Translator
from gtts import gTTS
def load_words(file_path):
"""Load words from a text file."""
with open(file_path, "r", encoding="utf-8") as f:
words = [line.strip() for line in f if line.strip()]
return words
async def translate_word(word, translator):
"""Translate a word from English to Polish."""
try:
translation = await translator.translate(word, src="en", dest="pl")
return translation.text
except Exception as e:
print(f"Error translating '{word}': {e}")
return None
def generate_audio(word, translation, output_dir):
"""Generate an audio file for the Polish pronunciation."""
try:
tts = gTTS(word, lang="en")
audio_path = os.path.join(output_dir, f"{word}.mp3")
tts.save(audio_path)
return audio_path
except Exception as e:
print(f"Error generating audio for '{word}': {e}")
return None
async def main(input_file, output_dir):
# Initialize the async translator
translator = Translator()
# Load words from file
words = load_words(input_file)
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Process each word asynchronously
translations = {}
tasks = []
for word in words:
tasks.append(translate_word(word, translator))
results = await asyncio.gather(*tasks)
for word, translation in zip(words, results):
if translation:
translations[word] = translation
audio_path = generate_audio(word, translation, output_dir)
if audio_path:
print(f"Audio saved: {audio_path}")
# Save translations to a file
translations_file = os.path.join(output_dir, "translations.txt")
with open(translations_file, "w", encoding="utf-8") as f:
for word, translation in translations.items():
f.write(f"{word}: {translation}\n")
print(f"Translations and audio files saved to '{output_dir}'.")
if __name__ == "__main__":
input_file = "oxford5000.txt" # Replace with your input file
output_dir = "output" # Replace with your desired output directory
# Run the event loop
asyncio.run(main(input_file, output_dir))