openai/openai-python
Publicmirrored fromhttps://github.com/openai/openai-pythonAvailable
examples/audio.py
38lines · modecode
| 1 | #!/usr/bin/env python |
| 2 | |
| 3 | from pathlib import Path |
| 4 | |
| 5 | from openai import OpenAI |
| 6 | |
| 7 | # gets OPENAI_API_KEY from your environment variables |
| 8 | openai = OpenAI() |
| 9 | |
| 10 | speech_file_path = Path(__file__).parent / "speech.mp3" |
| 11 | |
| 12 | |
| 13 | def main() -> None: |
| 14 | # Create text-to-speech audio file |
| 15 | with openai.audio.speech.with_streaming_response.create( |
| 16 | model="tts-1", |
| 17 | voice="alloy", |
| 18 | input="the quick brown fox jumped over the lazy dogs", |
| 19 | ) as response: |
| 20 | response.stream_to_file(speech_file_path) |
| 21 | |
| 22 | # Create transcription from audio file |
| 23 | transcription = openai.audio.transcriptions.create( |
| 24 | model="whisper-1", |
| 25 | file=speech_file_path, |
| 26 | ) |
| 27 | print(transcription.text) |
| 28 | |
| 29 | # Create translation from audio file |
| 30 | translation = openai.audio.translations.create( |
| 31 | model="whisper-1", |
| 32 | file=speech_file_path, |
| 33 | ) |
| 34 | print(translation.text) |
| 35 | |
| 36 | |
| 37 | if __name__ == "__main__": |
| 38 | main() |
| 39 | |