用代码穿越界线:Python、OpenAI和多语言冒险

潜入Python和OpenAI的世界。用几行代码将泰米尔短语翻译成英语,并为其配以语音。探索文字转语音的魔力。

Snippet: 摘录:


#Set your ‘OPENAI_API_KEY’ Environment Variable via the cmd prompt
#setx OPENAI_API_KEY “<yourkey>”

import openai # Import OpenAI library for text generation and translation

# Initialize OpenAI client
client = openai.OpenAI()

# Specify file path for generated audio
speech_file_path = "TamiltoEnglish.mp3"

# Enter the Tamil text you want to translate
tamil_text = "வெற்றி பெற வேண்டும் என்ற பதற்றம் இல்லாமல் இருப்பது தான் வெற்றி பெறுவதற்கான சிறந்த வழி"

# Set the source and target languages for translation
source_language = "Tamil"
target_language = "English"


# Use the gpt-3.5-turbo-instruct model for accurate and informative translations
translated_text = client.completions.create(
model="gpt-3.5-turbo-instruct",
prompt=f"Translate this text from {source_language} to {target_language}: {tamil_text}",
max_tokens=300, # Allow for comprehensive translation
)

# Print the translated English text from the first completion
print(translated_text.choices[0].text)


# Combine the Tamil and English text for a smooth audio experience
merge_text = (
f"{tamil_text}. Now listen to the Tamil word translated into English: {translated_text.choices[0].text}"
)

# Generate an audio file using the tts-1 model with a natural-sounding voice
response = client.audio.speech.create(
model="tts-1",
voice="onyx",
input=merge_text,
)

# Save the generated audio to a file for playback
response.stream_to_file(speech_file_pathNote)

注:以下您将听到的音频示例是由人工智能生成的,而不是真实的人员。

2024-01-13 04:21:40 AI中文站翻译自原文