语音翻译成不同语言

2024 年 10 月 21 日
在 Github 中打开

您是否曾想将播客翻译成您的母语?翻译和配音音频内容可以使其更易于全球受众访问。借助 GPT-4o 全新的音频输入和音频输出模态,此过程现在比以往任何时候都更加容易。

本指南将引导您完成使用 OpenAI 的 GPT-4o 音频模态 API 将英语音频文件翻译成印地语的过程。

GPT-4o 简化了音频内容的配音过程。以前,您必须先将音频转换为文本,然后将文本翻译成目标语言,然后再将其转换回音频。现在,借助 GPT-4o 的语音到语音功能,您可以通过音频输入和输出一步完成此操作。

关于本 Cookbook 中使用的关于语言和书面文字的语义注释。这些词语通常可以互换使用,但鉴于手头的任务,理解它们之间的区别非常重要。

- 语言指的是口语或书面交流系统。例如,印地语和马拉地语是不同的语言,但都使用天城文。同样,英语和法语是不同的语言,但都使用拉丁文字书写。

- 文字指的是用于书写语言的字符或符号集。例如,传统上用西里尔文字书写的塞尔维亚语,也用拉丁文字书写。

GPT-4o 音频输入和音频输出模态使通过一次 API 调用将音频从一种语言配音到另一种语言变得更加容易。

1. 转录使用 GPT-4o 将源音频文件转录为源语言文字。如果已拥有源音频内容的转录,则可以跳过此可选步骤。

2. 配音将音频文件从源语言直接配音到目标语言。

3. 获取翻译基准,使用 BLEU 或 ROUGE。

4. 解释和改进分数,根据需要调整步骤 1-3 中的提示参数。

在我们开始之前,请确保您已将 OpenAI API 密钥配置为环境变量,并安装了以下代码单元格中概述的必要软件包。

步骤 1:使用 GPT-4o 将音频转录为源语言文字

首先,让我们创建一个函数,该函数将音频文件发送到 OpenAI 的 GPT-4o API 进行处理,使用聊天完成 API 端点。

函数 process_audio_with_gpt_4o 接受三个输入

  1. base64 编码的音频文件 (base64_encoded_audio),将发送到 GPT-4o 模型。
  2. 所需的输出模态(例如文本,或文本和音频)。
  3. 系统提示,指示模型如何处理输入。

该函数向 OpenAI 的 chat/completions 端点发送 API 请求。请求标头包含用于授权的 API 密钥。数据负载包含模型类型 (gpt-4o-audio-preview)、选定的输出模态和音频详细信息,例如语音类型和格式(在本例中为“alloy”和“wav”)。它还包括系统提示和 base64 编码的音频文件作为“用户”消息的一部分。如果 API 请求成功(HTTP 状态 200),则以 JSON 格式返回响应。如果发生错误(非 200 状态),它会打印错误代码和消息。

此函数通过 OpenAI 的 GPT-4o API 启用音频处理,从而允许根据提供的输入执行配音、转录或翻译等任务。

# Make sure requests package is installed  
import requests 
import os
import json

# Load the API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")


def process_audio_with_gpt_4o(base64_encoded_audio, output_modalities, system_prompt):
    # Chat Completions API end point 
    url = "https://api.openai.com/v1/chat/completions"

    # Set the headers
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    # Construct the request data
    data = {
        "model": "gpt-4o-audio-preview",
        "modalities": output_modalities,
        "audio": {
            "voice": "alloy",
            "format": "wav"
        },
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": [
                    {
                        "type": "input_audio",
                        "input_audio": {
                            "data": base64_encoded_audio,
                            "format": "wav"
                        }
                    }
                ]
            }
        ]
    }
    
    request_response = requests.post(url, headers=headers, data=json.dumps(data))
    if request_response.status_code == 200:
        return request_response.json()
    else:  
        print(f"Error {request_response.status_code}: {request_response.text}")
        return
    

使用函数 process_audio_with_gpt_4o,我们将首先获得源音频的英语转录。如果您已经拥有源语言的转录,则可以跳过此步骤。

在此步骤中,我们

  1. 读取 WAV 文件并将其转换为 base64 编码。
  2. 将输出模态设置为 ["text"],因为我们只需要文本转录。
  3. 提供系统提示,指示模型专注于转录语音,并忽略鼓掌等背景噪音。
  4. 调用 process_audio_with_gpt_4o 函数来处理音频并返回转录。
import base64
audio_wav_path = "./sounds/keynote_recap.wav"

# Read the WAV file and encode it to base64
with open(audio_wav_path, "rb") as audio_file:
    audio_bytes = audio_file.read()
    english_audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')

modalities = ["text"]
prompt = "The user will provide an audio file in English. Transcribe the audio to English text, word for word. Only provide the language transcription, do not include background noises such as applause. "

response_json = process_audio_with_gpt_4o(english_audio_base64, modalities, prompt)

english_transcript = response_json['choices'][0]['message']['content']

print(english_transcript)
Hello and welcome to our first ever OpenAI DevDay. Today, we are launching a new model, GPT-4 Turbo. GPT-4 Turbo supports up to 128,000 tokens of context. We have a new feature called JSON mode, which ensures that the model will respond with valid JSON. You can now call many functions at once. And it will do better at following instructions in general. You want these models to be able to access better knowledge about the world, so do we. So we're launching retrieval in the platform. You can bring knowledge from outside documents or databases into whatever you're building. GPT-4 Turbo has knowledge about the world up to April of 2023, and we will continue to improve that over time. DALL-E 3, GPT-4 Turbo with Vision, and the new text-to-speech model are all going into the API today. Today, we're launching a new program called Custom Models. With Custom Models, our researchers will work closely with a company to help them make a great custom model, especially for them and their use case using our tools. Higher rate limits. We're doubling the tokens per minute for all of our established GPT-4 customers so that it's easier to do more, and you'll be able to request changes to further rate limits and quotas directly in your API account settings. And GPT-4 Turbo is considerably cheaper than GPT-4, by a factor of 3x for prompt tokens and 2x for completion tokens starting today. We're thrilled to introduce GPTs. GPTs are tailored versions of ChatGPT for a specific purpose. And because they combine instructions, expanded knowledge, and actions, they can be more helpful to you. They can work better in many contexts, and they can give you better control. We know that many people who want to build a GPT don't know how to code. We've made it so that you can program the GPT just by having a conversation. You can make private GPTs. You can share your creations publicly with a link for anyone to use. Or, if you're on ChatGPT Enterprise, you can make GPTs just for your company. And later this month, we're going to launch the GPT Store. So those are GPTs, and we can't wait to see what you'll build. We're bringing the same concept to the API. The Assistant API includes persistent threads so they don't have to figure out how to deal with long conversation history, built-in retrieval, code interpreter, a working Python interpreter in a sandbox environment, and, of course, the improved function calling. As intelligence gets integrated everywhere, we will all have superpowers on demand. We're excited to see what you all will do with this technology and to discover the new future that we're all going to architect together. We hope when you come back next year, what we launch today is going to look very quaint relative to what we're busy creating for you now. Thank you for all you do. Thanks for coming here today.

此英语转录将作为我们的基准,用于在步骤 3 中评估印地语配音的质量。

glossary_of_terms_to_keep_in_original_language = "Turbo, OpenAI, token, GPT, Dall-e, Python"

modalities = ["text", "audio"]
prompt = f"The user will provide an audio file in English. Dub the complete audio, word for word in Hindi. Keep certain words in English for which a direct translation in Hindi does not exist such as  ${glossary_of_terms_to_keep_in_original_language}."

response_json = process_audio_with_gpt_4o(english_audio_base64, modalities, prompt)

message = response_json['choices'][0]['message']

在以下代码片段中,我们将从 GPT-4o 响应中检索印地语转录和配音音频。以前,这将是一个多步骤过程,需要多次 API 调用才能先转录,然后翻译,最后生成目标语言的音频。借助 GPT-4o,我们现在可以通过一次 API 调用完成此操作。

# Make sure pydub is installed 
from pydub import AudioSegment
from pydub.playback import play
from io import BytesIO

# Get the transcript from the model. This will vary depending on the modality you are using. 
hindi_transcript = message['audio']['transcript']

print(hindi_transcript)

# Get the audio content from the response 
hindi_audio_data_base64 = message['audio']['data']
स्वागत है हमारे पहले OpenAI DevDay में।

आज हम एक नए मॉडल का लॉन्च कर रहे हैं, GPT-4 Turbo। GPT-4 Turbo अब 1,28,000 टोकens के कॉन्टेक्स्ट को सपोर्ट करता है। हमारे पास एक नया फीचर है जिसे JSON मोड कहा जाता है, जो सुनिश्चित करता है कि मॉडल वैध JSON के साथ प्रतिक्रिया करेगा। अब आप कई फंक्शन्स को एक साथ कॉल कर सकते हैं। और ये सामान्य रूप से इंस्ट्रक्शंस का पालन करने में बेहतर करेगा। आप चाहते हैं कि ये मॉडल दुनिया के बारे में बेहतर जानकारी तक पहुंच सकें, हम भी। इसलिए हम प्लैटफॉर्म में Retrieval लॉन्च कर रहे हैं। आप बाहरी दस्तावेज़ या डेटाबेस से जो भी आप बना रहे हैं, उसमें ज्ञान ला सकते हैं। GPT-4 Turbo को अप्रैल 2023 तक की दुनिया की जानकारी है, और हम इसे समय के साथ और बेहतर बनाना जारी रखेंगे। DALL·E 3, GPT-4 Turbo with vision, और नया Text-to-Speech मॉडल सभी को आज उपलब्ध कर रहे हैं एपीआई में। आज हम एक नए प्रोग्राम का लॉन्च कर रहे हैं जिसे Custom Models कहा जाता है। Custom Models के साथ, हमारे शोधकर्ता एक कंपनी के साथ निकटता से काम करेंगे ताकि वे एक महान Custom Model बना सकें, विशेष रूप से उनके और उनके उपयोग के मामले के लिए, हमारे Tools का उपयोग करके। उच्च दर लिमिट्स, हम सभी मौजूदा GPT-4 ग्राहकों के लिए Tokens प्रति मिनट को दोगुना कर रहे हैं ताकि अधिक करना आसान हों। और आप अपने एपीआई खाता सेटिंग्स में सीधे दर की सीमाओं और कोटों में बदलाव के लिए अनुरोध कर सकेंगे। और GPT-4 Turbo जीपीटी-4 की तुलना में काफी सस्ता है; प्रॉम्प्ट टोकन्स के लिए 3x और कम्पलीटेशन टोकन्स के लिए 2x से, आज से।

हम जीपीटीस पेश कर रहे हैं। GPTs चैट GPT के कस्टमाइज़्ड संसकरण हैं, एक विशिष्ट उद्देश्य के लिए। और क्योंकि वे इंस्ट्रक्शंस, विस्तारित ज्ञान, और कार्रवाइयों को जोड़ते हैं, वे आपके लिए अधिक मददगार हो सकते हैं। वे कई सामाजीक उपयोग में बेहतर काम कर सकते हैं और आपको बेहतर नियंत्रण दे सकते हैं। हम जानते हैं कि कई लोग जो GPT बनाना चाहते हैं, उन्हें कोडिंग का ज्ञान नहीं है। हमने इसे एसे बनाया है कि आप GPT को केवल एक बातचीत से प्रोग्राम कर सकते हैं। आप प्राइवेट GPT बना सकते हैं। आप अपनी creation को किसी भी के लिए उपयोग करने के लिए लिंक के साथ सार्वजनिक रूप से शेयर कर सकते हैं। या, अगर आप ChatGPT एंटरप्राइज पर हैं, तो आप केवल अपनी कंपनी के लिए GPT बना सकते हैं। और इस महीने के बाद में हम GPT स्टोर लॉन्च करेंगे। तो ये हैं GPTs, और हम उत्सुक हैं देखने के लिए कि आप क्या बनाएंगे।

हम एपीआई में वही संस्कल्पना ला रहे हैं। सहायक एपीआई में persistent threads शामिल हैं, ताकि उन्हें लंबी बातचीत के इतिहास से निपटने का तरीका पता न करना पड़े। बिल्ट-इन Retrieval, कोड इंटरप्रेटर, एक काम करने वाला Python इंटरप्रेटर एक सैंडबॉक्स वातावरण में, और of course, सुधरा हुआ फंक्शन कॉलिंग भी शामिल है।

जैसे-जैसे बुद्धिमत्ता हर जगह एकीकृत होती जाएगी, हम सभी के पास मांग पर सुपर पावर्स होंगे। हम देखने के लिए उत्साहित हैं कि आप सब इस तकनीक के साथ क्या कर पाएंगे और उस नए भविष्य की खोज, जिसे हम सब मिलकर बनाने वाले हैं।

हम आशा करते हैं कि आप अगले साल फिर आएंगे क्योंकि आज हमने जो लॉन्च किया है, वह उस परिप्रेक्ष्य से बहुत मामूली लगेगा जो हम अब आपके लिए बना रहे हैं। आप सभी के तरीके लिए धन्यवाद। आज यहां आने के लिए धन्यवाद।


转录的文本是印地语和英语的组合,以各自的文字表示:印地语为天城文,英语为拉丁文。这种方法确保了更自然的语音,并且两种语言的单词发音正确。我们将使用 pydub 模块来播放音频,如下面的代码所示。

# Play the audio 
audio_data_bytes = base64.b64decode(hindi_audio_data_base64)
audio_segment = AudioSegment.from_file(BytesIO(audio_data_bytes), format="wav")

play(audio_segment)

步骤 3. 获取翻译基准(例如,BLEU 或 ROUGE)

我们可以通过使用 BLEU 和 ROUGE 等评估指标将其与参考翻译进行比较来评估翻译文本的质量。

BLEU(双语评估互译质量评估):衡量候选翻译和参考翻译之间 n-gram 的重叠程度。分数范围为 0 到 100,分数越高表示质量越好。

ROUGE(用于要点评估的召回率导向的互译质量评估):常用于摘要评估。衡量候选文本和参考文本之间 n-gram 和最长公共子序列的重叠程度。

理想情况下,需要原始文本的参考翻译(人工翻译版本)才能进行准确评估。但是,开发此类评估可能具有挑战性,因为它需要精通两种语言的双语人士花费时间和精力。

另一种方法是将目标语言的输出音频文件转录回原始语言,以使用 GPT-4o 评估翻译质量。

# Translate the audio output file generated by the model back into English and compare with the reference text 
modalities = ["text"]
prompt = "The user will provide an audio file in Hindi. Transcribe the audio to English text word for word. Only provide the language transcription, do not include background noises such as applause. "

response_json = process_audio_with_gpt_4o(hindi_audio_data_base64, modalities, prompt)

re_translated_english_text = response_json['choices'][0]['message']['content']

print(re_translated_english_text)
Welcome to our first OpenAI Dev Day. Today we are launching a new model, GPT-4 Turbo. GPT-4 Turbo now supports a context of 128,000 tokens. We have a new feature called JSON mode where the model will respond via JSON. Now you can call multiple functions simultaneously, and it will generally follow instructions better. You want this model to access external knowledge databases or documents to bring knowledge into what you are building. GPT-4 Turbo has knowledge of the world up to April 2023, and we'll continue to improve it over time.

DALL·E 3, GPT-4 Turbo with vision, and the new text-to-speech model are all being made available today in the API. Today, we are launching a new program called custom models. Custom models will work closely to make great custom models specifically for you and your use case. Utilizing our tools, we are doubling the rate limits for all existing GPT-4 customers to tokens per minute. You'll be able to directly request rate limit and quota changes in your API account settings.

And GPT-4 Turbo is much cheaper compared to GPT-4, 2x for completion tokens starting today. We are introducing GPTs. GPTs are custom versions of ChatGPT for a specific purpose, and since they incorporate instructions with broad knowledge and action capabilities, they can help you more. They can perform better in many social tasks. We know that many people who want to build GPTs don't know how to code. We've built it so that you can program a GPT with just one line.

You can create a private GPT. You can publish your creation publicly with a link for anyone to use, or if you have ChatGPT Enterprise, you can build GPTs just for your own company. We will be launching a GPT store. So that's GPTs, and we're excited to see what you build. We're bringing customization into the API. Assistance API includes persistent threads so that it doesn't have to figure out how to engage with history from long conversations. A built-in retriever, code interpreter, a working Python interpreter in a sandbox environment, and of course, improved function calling. As intelligence integrates everywhere, we'll all have superpowers on demand.

We're excited to see what you'll be able to build with this technology and explore this new future that we're all creating together. We hope you come back next year because what we're building for you now will make today seem very humble in that context. Thank you all for your approach. Thank you for being here today.

通过将音频从印地语转录回英语文字,我们可以通过将其与原始英语转录进行比较来运行评估指标。

# Make sure scarebleu package is installed 
import sacrebleu
# Make sure rouge-score package is installed 
from rouge_score import rouge_scorer 

# We'll use the original English transcription as the reference text 
reference_text = english_transcript

candidate_text = re_translated_english_text

# BLEU Score Evaluation
bleu = sacrebleu.corpus_bleu([candidate_text], [[reference_text]])
print(f"BLEU Score: {bleu.score}")

# ROUGE Score Evaluation
scorer = rouge_scorer.RougeScorer(['rouge1', 'rougeL'], use_stemmer=True)
scores = scorer.score(reference_text, candidate_text)
print(f"ROUGE-1 Score: {scores['rouge1'].fmeasure}")
print(f"ROUGE-L Score: {scores['rougeL'].fmeasure}")
BLEU Score: 35.27656890256424
ROUGE-1 Score: 0.8148148148148149
ROUGE-L Score: 0.6934156378600822

步骤 4. 解释和改进分数,根据需要在步骤 1-3 中调整提示参数

在本例中,BLEU 和 ROUGE 分数都表明语音翻译的质量非常好到优秀。

解释 BLEU 分数: 虽然没有普遍接受的量表,但一些解释表明

0 到 10:翻译质量差;存在重大错误且缺乏流畅性。

10 到 20:质量低;部分可以理解,但包含许多错误。

20 到 30:质量尚可;传达了大致含义,但缺乏精确度和流畅性。

30 到 40:质量良好;可以理解且相对准确,只有少量错误。

40 到 50:质量非常好;准确流畅,错误极少。

50 及以上:质量优秀;与人工翻译非常相似。

解释 ROUGE 分数: “良好”ROUGE 分数的解释可能因任务、数据集和领域而异。以下指南指示了良好的结果

ROUGE-1(unigram 重叠):对于抽象摘要任务,0.5 到 0.6 之间的分数通常被认为是良好的。

ROUGE-L(最长公共子序列):0.4 到 0.5 左右的分数通常被认为是良好的,反映了模型捕获参考文本结构的能力。

如果您的翻译分数不理想,请考虑以下问题

1. 源音频是否被准确转录?

如果转录包含错误,例如混淆发音相似的单词,您可以在步骤 1 的系统提示中提供此类术语的词汇表。这有助于模型避免误解,并确保准确转录特定术语。

2. 源音频是否没有语法错误?

如果源音频包含语法错误,请考虑使用 GPT 模型的后处理步骤,通过删除语法错误并添加适当的标点符号来改进转录。在此之后,您可以将更正后的转录与 GPT-4o 的文本输入和音频输出模态一起使用,而不是使用 GPT-4o 的音频输入和音频输出模态,以生成目标语言的音频。

3. 是否有单词保留原始语言更有意义?

某些术语或概念可能在目标语言中没有合适的翻译,或者以原始形式更容易理解。请重新查看您的 glossary_of_terms_to_keep_in_original_language 并包含任何此类术语,以保持清晰度和上下文。

结论

总之,本 cookbook 提供了一个清晰、循序渐进的音频翻译和配音流程,使内容更易于全球受众访问。使用 GPT-4o 的音频输入和输出功能,将音频文件从一种语言翻译和配音成另一种语言变得更加简单。我们的示例侧重于将音频文件从英语翻译成印地语。

该过程可以分解为以下步骤

1. 转录: 使用 GPT-4o 文本模态获取源语言音频到源语言文字的转录。

2. 配音: 使用 GPT-4o 的音频模态直接将音频文件配音到目标语言。

3. 翻译质量基准: 使用 BLEU 或 ROUGE 分数与参考文本进行比较,评估翻译的准确性。

4. 优化流程: 如果需要,调整提示参数以改进转录和配音结果。

本指南还强调了“语言”和“文字”之间至关重要的区别——这两个术语经常被混淆,但在翻译工作中至关重要。语言指的是交流系统,无论是口头的还是书面的,而文字是用于书写语言的字符集。理解这种差异对于有效的翻译和配音至关重要。

通过遵循本 cookbook 中的技术,您可以将各种内容(从播客和培训视频到整部电影)翻译和配音成多种语言。这种方法适用于娱乐、教育、商业和全球通信等行业,使创作者能够将其受众范围扩展到不同的语言受众。