[Python] Openai Issue, trying te generated Speech but always getting error

Discussão em 'Python' iniciado por Stack, Novembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I am working on a app that can describe data into narration and then convert it into audio by using openai but always facing error while it creating the audio file, don't know where i am lacking

    Narrater.py

    import openai



    def parse(narration):
    output = []
    lines = narration.split("/n")
    for line in lines:
    if line.startswith('Background: '):
    background = line.replace("Background:","Background: ")
    output.append({
    "type":"image",
    "description":background
    })

    elif line.startswith("Narration:"):
    text = line.replace("Narration:","Narration:")
    output.append({
    "type":"text",
    "content":text
    })
    return output


    def create(data,output_path="output_audio.mp3"):
    narration = "" # Initialize the narration variable as an empty string
    for element in data:
    if element["type"] != 'text':
    continue
    narration += element["content"] + "\n\n"
    audio = openai.audio.speech.create(
    model="tts-1",
    input = narration,
    voice="alloy"
    )
    audio.stream_to_file(output_path)


    transcripter.py





    # Read the source material from a file
    with open("source_material.txt", "r") as f:
    source_material = f.read()

    # Create the chat completion
    response = openai.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
    {
    "role": "system",
    "content": """You are a short Video Narratorthat reads the data and explains
    it. You generate 30S TO 1 minutes of narration.
    The short you create has a background that fades from image to image as the narration is going on.

    Respond in the following manner, repeating until the end of the short:
    Background: Description of background image based on the narration for AI Image Generation and also add the data
    Narration: A few sentences of narration based on the data in detail

    Background: Description of background image based on the narration for AI Image Generation with data and also add the data
    Narration: A few sentences of narration based on the data in detail

    Background: Description of background image based on the narration for AI Image Generation with data and also add the data
    Narration: A few sentences of narration based on the data in detail

    Background: Description of background image based on the narration for AI Image Generation with data and also add the data
    Narration: A few sentences of narration based on the data in detail

    Background: Description of background image based on the narration for AI Image Generation with data and also add the data
    Narration: A few sentences of narration based on the data in detail


    The short MUST be 6 sentences maximum.
    """
    },
    {
    "role": "user",
    "content": f"Create a short video narrator based on the following source material:\n\n{source_material}"
    }
    ]
    )

    # Extract the generated content from the response
    generated_content = response.choices[0].message.content

    # Print the generated content
    data = narrator.parse(generated_content)
    print(data)
    audio = narrator.create(data, "narration.mp3")


    (myenv) PS D:\Python Data To Video\AppTest\Transcripter\myenv\DataTOVideo> python .\Transcripter.py [{'type': 'image', 'description': "Background: A dynamic and modern digital marketing office space with screens showing colorful graphs and charts related to advertising performance data.\nNarration: Analyzing the ad campaign performance data reveals a steady increase in impressions, clicks, and conversions over the course of five days. Costs also rise as the campaign expands, but so does revenue, indicating a positive return on investment.\n\nBackground: A sleek data analysis room with futuristic holographic displays showcasing various calculated metrics.\nNarration: By diving into the calculated metrics, we can see that the click-through rate remains relatively stable around 1.5%, while the cost per click fluctuates slightly. The conversion rate shows an upward trend, peaking on the third day, leading to a consistent return on ad spend (ROAS) above 2.00.\n\nBackground: An innovative marketing agency setting with screens displaying detailed performance breakdowns and key metrics.\nNarration: Through a closer examination of the data, it's evident that the ad campaign is performing well overall, with a healthy balance between cost-efficiency and conversion optimization. The trends indicate potential areas for further optimization to maximize results and drive even higher ROAS.\n\nBackground: A futuristic control center environment with real-time updates on ad campaign performance metrics.\nNarration: The ad campaign's success is reflected in the calculated metrics, showcasing a solid click-through rate alongside a cost per click that remains competitive. With conversion rates on the rise and a stable ROAS above 2.00, the data highlights a well-executed and profitable advertising strategy.\n\nBackground: A high-tech data visualization room with interactive screens illustrating the impact of various advertising strategies.\nNarration: Overall, the ad campaign's performance data and calculated metrics paint a picture of a well-managed and effective marketing initiative. The consistent growth in key metrics, paired with a positive return on ad spend, underscores the success of the campaign in driving both engagement and revenue for the business."}] Traceback (most recent call last): File "D:\Python Data To Video\AppTest\Transcripter\myenv\DataTOVideo\Transcripter.py", line 56, in audio = narrator.create(data, "narration.mp3") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python Data To Video\AppTest\Transcripter\myenv\DataTOVideo\narrator.py", line 42, in create audio = openai.audio.speech.create( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python Data To Video\AppTest\Transcripter\myenv\Lib\site-packages\openai\resources\audio\speech.py", line 96, in create return self._post( stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python Data To Video\AppTest\Transcripter\myenv\Lib\site-packages\openai_base_client.py", line 957, in request return self._request( ^^^^^^^^^^^^^^ File "D:\Python Data To Video\AppTest\Transcripter\myenv\Lib\site-packages\openai_base_client.py", line 1061, in _request raise self._make_status_error_from_response(err.response) from None openai.BadRequestError: Error code: 400 - {'error': {'message': "[{'type': 'string_too_short', 'loc': ('body', 'input'), 'msg': 'String should have at least 1 character', 'input': '', 'ctx': {'min_length': 1}}]", 'type': 'invalid_request_error', 'param': None, 'code': None}} (myenv) PS D:\Python Data To Video\AppTest\Transcripter\myenv\DataTOVideo>

    I tried to downgrade the openai but it didn't work therefore i went to default

    Continue reading...

Compartilhe esta Página