Generate audio clips with Gemini 2.0 Flash

Generate audio clips with Gemini 2.0 Flash

TL;DR:

Happy holidays! Google just lately "gifted" us the brand new Gemini 2.0 Flash mannequin, increasing on what’s accessible within the unique 1.x fashions. One of the brand new options is the power to generate text-based audio clips. Sure good ol’ common predictive AI’s text-to-speech performance is actually helpful, however this takes it to the subsequent stage, giving genAI customers "idea-to-speech" capabilities. Learn entry this new function from Python in the present day!

Build with Gemini

Introduction

Welcome to the weblog specializing in utilizing Google APIs from Python and generally Node.js. Today’s submit focuses on Gemini, however there’s loads of content material past Gemini:

This submit takes a break from the circulation of the earlier posts on this sequence masking the Gemini API by exploring one new function. While some could also be content material utilizing ChatGPT or Gemini on-line or through app, the Gemini API brings generative AI talents to your apps, so should you’re new or exploring, take a look at the opposite posts on get began in addition to see a few of its primary capabilities. This submit solely appears to be like at one function from the Gemini 2.0 Flash mannequin: text-based audio clip technology.

Prerequisites

New consumer library improves consumer expertise (UX)

You want a consumer library to speak to Gemini from code. While a number of consumer libraries exist already for Gemini, Google has just lately launched a brand new one. The new library options an improved UX, so I’ve to provide Google some credit score. In the first Gemini submit within the sequence, I lamented that making the API accessible from two completely different platforms confuses builders:

  1. Google AI
  2. GCP Vertex AI

Differing consumer libraries, quite a few code samples, documentation in numerous areas below completely different net domains, and many others., all add to a less-than-optimal UX. A alternative consumer library with the power to work throughout platforms permits customers to get began and experiment on Google AI then "improve" to Vertex AI, when prepared for manufacturing, with out altering their code.

💡 Yes, it is an "ifdef"
If you are like me and wish to dig round in code, you could be interested in how the brand new consumer library works throughout each Google AI and Vertex AI. It’s not magic, so you will discover if-else blocks the place it issues, like an "ifdef" (C/C++). In the brand new consumer library, any time you see mldev, assume Google AI, and as anticipated, vertex is Vertex AI.

One instance is discovered the Live API code whereas one other is within the fashions code. (NOTE: these hyperlinks will in all probability be improper when a brand new model is pushed, however I’ll replace them as soon as the library has an official launch)

At the time of this writing, the brand new consumer library is barely accessible in Python and Go. (Java and JS/Node.js are subsequent. Keep checking the Gemini API SDKs web page for the newest releases. The pattern app is barely accessible in Python^, however I’m pleased to discover a Golang PR should you get to an equal port earlier than I do.

^ — Python 3 solely; Python 2 help will not be accessible for the Gemini API

Installation and setup

Follow these steps to put in the consumer library and get arrange:

  1. Install the brand new consumer library: pip set up -U google-genai
  2. Create an API key (should you do not have already got one)
  3. Save API key as a string to settings.py as API_KEY = 'YOUR_API_KEY' (and observe the solutions within the sidebar under to guard it)

⚠️ WARNING: Keep API keys safe
Storing API keys in information (or hard-coding them to be used in precise code and even assigning to surroundings variables) is for prototyping and studying functions solely. When going to manufacturing, put them in surroundings variables or in a secrets and techniques supervisor. Files like settings.py or .env containing API keys are vulnerable. Under no circumstances do you have to add information like these to any public or non-public repo, have delicate information like that in TerraForm config information, add such information to Docker layers, and many others., as as soon as your API key leaks, everybody on the planet can use it.

If you are new to Google developer instruments, API keys are one of many credentials sorts supported by Google APIs, and so they’re the solely sort supported by Maps APIs. Other credentials sorts embrace OAuth consumer IDs, largely utilized by GWS APIs, and service accounts, largely utilized by Google Cloud (GCP) APIs. While this submit does not cowl Google Maps, the Maps crew put collectively an excellent information on API key finest practices, so test it out!

The app

The pattern app sends a immediate of Describe a cat in a number of sentences to Gemini and requests an audio clip in response, so the app’s performance is fairly temporary: make the request, get the response, and save the audio file.

The code

import asyncio
import contextlib
import wave

from google import genai
from settings import API_KEY

CLIENT = genai.Client(api_key=API_KEY, http_options={'api_version': 'v1alpha'})
MODEL = 'gemini-2.0-flash-exp'
CONFIG = {'generation_config': {'response_modalities': ['AUDIO']}}
PROMPT = 'Describe a cat in a number of sentences'
FILENAME = 'whatacatis.wav'

@contextlib.contextmanager
def wave_file(filename, channels=1, price=24000, sample_width=2):
    'arrange .wav file author'
    with wave.open(filename, 'wb') as wf:
        wf.setnchannels(channels)
        wf.setsampwidth(sample_width)
        wf.setframerate(price)
        yield wf

async def request_audio(immediate=PROMPT, filename=FILENAME):
    'request LLM generate audio file given immediate'
    print(f'n** LLM immediate: "{immediate}"')
    async with CLIENT.aio.stay.join(mannequin=MODEL, config=CONFIG) as session:
        with wave_file(filename) as f:
            await session.ship(immediate, end_of_turn=True)
            async for response in session.obtain():
                if response.information:
                    f.writeframes(response.information)
    print(f'** Saved audio to "{filename}"')

asyncio.run(request_audio())

[CODE] gem20-audio.py: Audio "Hello World!" pattern

 

App elements

There are 4 main chunks to this script:

  1. Imports
  2. Constants
  3. Audio file author
  4. Core performance

Imports

From the Python customary library, asyncio is required as a result of the Multimodal Live API is barely accessible asynchronously. The contextlib.contextmanager decorator is required so we are able to wrap and use the audio file-writer with Python’s with assertion. The final "stdlib" package deal used is wave, which processes WAVE audio information. This is adopted by importing Google’s new "genAI" consumer library.

Like in earlier code samples on this sequence, the API secret is saved to settings.py. Alternatively, it can save you your API key to the GOOGLE_API_KEY surroundings variable, or use the python-dotenv package deal, storing the API key in .env to extra intently mirror working in a Node.js surroundings. There’s additionally the GCP Secret Manager as but an alternative choice.

Constants and audio file author

Constants for the API consumer, generative giant language mannequin (genAI LLM), and mannequin configuration observe. The final pair of constants are the consumer’s immediate and filename to save lots of the generated audio to.

The WAV file (wave_file()) author simply units up the fundamental parameters as a generator and wraps it in a context supervisor, permitting it for use with the with assertion. You’ll discover nearly-identical code in varied samples and Notebooks within the Gemini 2.0 cookbook repo.

Core performance

All of the "actual work" takes place in request_audio(). It’s a single session utilizing the Gemini 2.0 Multimodal Live API, kicking it off by opening the WAV file for write and sending the immediate to the LLM. The remainder of it constantly waits for a server response, writing the chunks of audio information obtained till it has been exhausted, terminating the session.

This is minimal code required to do the job. In different examples from Google, you will discover reference to server_content, inline_data and writing out components. Most of this pertains to supporting a multi-turn dialog, however for a single request-response "cycle," much less code is much less complicated.

Running the script

Running the script produces an audio file together with the anticipated output:

$ python3 gem20-audio.py

** LLM immediate: "Describe a cat in a number of sentences"
** Saved audio to "whatacatis.wav"

Your mileage could range, however that is the audio observe I acquired from Gemini:

Summary

Developers are keen to leap into the world of AI/ML, particularly GenAI & LLMs, and accessing Google’s Gemini fashions through API is a part of that image. The earlier posts within the sequence acquired your foot within the door, and in the present day, we explored a brand new function accessible from Gemini 2.0 Flash. Next, we’ll proceed the journey from the earlier submit (hyperlink under) and present you deploy primary genAI net apps to Google Cloud!

If you discover errors or have solutions on content material you’d wish to see in future posts, additionally depart a remark under, and in case your group wants assist integrating Google applied sciences through its APIs, attain out to me by submitting a request at https://cyberwebconsulting.com. Thanks for studying, and I hope to satisfy you if I come by your group… you will discover my journey calendar on the backside of that web page as properly. Season’s greetings and see you subsequent 12 months!

PREV POST: Part 3: Gemini API 102a… Putting collectively primary GenAI net apps

NEXT POST: Part 5: Deploying primary GenAI net apps to Google Cloud (coming quickly)

References

Below are varied hyperlinks related to this submit:

Code samples

Gemini API (Google AI)

Gemini 2.0 Flash

Other Generative AI and Gemini sources

Other Gemini API content material by the creator


WESLEY CHUN, MSCS, is a Google Developer Expert (GDE) in Google Cloud (GCP) & Google Workspace (GWS), creator of Prentice Hall’s bestselling "Core Python" sequence, co-author of "Python Web Development with Django", and has written for Linux Journal & CNET. He runs CyberWeb specializing in GCP & GWS APIs and serverless platforms, Python & App Engine migrations, and Python coaching & engineering. Wesley was one of many unique Yahoo!Mail engineers and spent 13+ years on varied Google product groups, talking on behalf of their APIs, producing pattern apps, codelabs, and movies for serverless migration and GWS builders. He holds levels in Computer Science, Mathematics, and Music from the University of California, is a Fellow of the Python Software Foundation, and likes to journey to satisfy builders worldwide at conferences, consumer group occasions, and universities. Follow he/him @wescpy & his technical weblog. Find this content material helpful? Contact CyberWeb for skilled providers or purchase him a espresso (or tea)!

HI-FI News

through DEV Community https://dev.to

December 16, 2024 at 06:32PM