I have been running this code and getting the same error over and over again:
import openai
from pathlib import Path
# Set your OpenAI API key
openai.api_key = 'xxxxxxxxxxx'
client = openai.api_key
# Function to generate a story based on a prompt
def generate_story(prompt):
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=500 # Adjust as needed
)
story = response.choices[0].text.strip()
return story
except Exception as e:
print("An error occurred in story generation:", e)
return None
# Function to convert text to speech and get the audio URL
def text_to_speech_and_get_url(text):
try:
response = openai.Audio.create(
input=text,
model="text-davinci-003",
response_format="audio"
)
audio_url = response['data']['url']
return audio_url
except Exception as e:
print(f"An error occurred in TTS conversion: {e}")
return None
# Function to download and save the audio file from URL
def download_and_save_audio(audio_url, file_name='story_audio.mp3'):
try:
r = requests.get(audio_url)
with open(file_name, 'wb') as f:
f.write(r.content)
print(f"Audio saved as {file_name}")
except Exception as e:
print(f"An error occurred while saving the audio file: {e}")
# Main function to get user prompt, generate and convert a story
def main():
# Get user input for the story prompt
prompt = input("Enter a prompt for the story: ")
# Generate the story
story = generate_story(prompt)
if story:
print("Generated Story:\n", story)
# Convert story to speech and get the audio URL
audio_url = text_to_speech_and_get_url(story)
if audio_url:
# Download and save the audio file
download_and_save_audio(audio_url)
if __name__ == "__main__":
main()
And I keep getting the same error.
“An error occurred in TTS conversion: type object ‘Audio’ has no attribute ‘create’”
Can someone help please?
Might I mention that this is my first python project, so please be patient.
import openai
import os
import requests
# Set your OpenAI API key
openai.api_key = 'xxx'
os.environ['OPENAI_API_KEY'] = 'xxx' # Set the API key in the environment
# Function to generate a story based on a prompt
def generate_story(prompt):
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=500 # Adjust as needed
)
story = response.choices[0].text.strip()
return story
except Exception as e:
print("An error occurred in story generation:", e)
return None
# Function to convert text to speech and save as an MP3 file
def text_to_speech_requests(text, file_name='story_audio.mp3', voice="nova"):
try:
response = requests.post(
"https://api.openai.com/v1/audio/speech",
headers={
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
},
json={
"model": "tts-1-1106",
"input": text,
"voice": voice,
},
)
if response.status_code == 200:
with open(file_name, 'wb') as f:
f.write(response.content)
print(f"Audio saved as {file_name}")
else:
print("Failed to generate audio. Status code:", response.status_code)
except Exception as e:
print(f"An error occurred in TTS conversion: {e}")
# Main function to get user prompt, generate and convert a story
def main():
# Get user input for the story prompt
prompt = input("Enter a prompt for the story: ")
# Generate the story
story = generate_story(prompt)
if story:
print("Generated Story:\n", story)
# Convert story to speech and save as MP3
text_to_speech_requests(story)
if __name__ == "__main__":
main()
Now this works as intended. I run a prompt in terminal, it generates the story and the audio file. My follow-up question is, how do I get this sent to an assistant? So when the user runs my story generator assistant, they get the story in both written and audio format?
#@title TTS last message from Assistant
from IPython.display import Audio
from openai import OpenAI
from datetime import datetime
# Initialize the OpenAI client
client = OpenAI()
# Retrieve the messages in the thread (assuming you've already defined `your_thread_id`)
thread_messages = client.beta.threads.messages.list(thread_id=your_thread_id)
# Find the first message from the assistant
assistant_response = None
for message in thread_messages.data:
if message.role == "assistant" and message.content[0].type == "text":
assistant_response = message.content[0].text.value
break
if assistant_response:
# Now, we'll use OpenAI TTS to convert this message to speech
response = client.audio.speech.create(
model="tts-1",
voice="onyx",
speed="0.75",
input=assistant_response # Use the assistant's message content as input for TTS
)
# Save the audio to a file
file_name = f"assistant_response_{message.id}.mp3"
response.stream_to_file(file_name)
else:
print("No assistant response found in the thread.")
# Print the first message
if first_message:
print("Assistant message:", message.content[0].text.value)
else:
print("No message found.")
# Use IPython's Audio class to play the audio within the notebook
Audio(file_name)