Build and refine your audio technology end-to-end with Gemini 1.5 Pro

Build and refine your audio technology end-to-end with Gemini 1.5 Pro

Generative AI is giving individuals new methods to expertise audio content material, from podcasts to audio summaries. For instance, customers are embracing NotebookLM’s current Audio Overview function, which turns paperwork into audio conversations. With one click on, two AI hosts begin up a full of life “deep dive” dialogue based mostly on the sources you present. They summarize your materials, make connections between matters, and focus on backwards and forwards. 

While Notebook LM provides unimaginable advantages for making sense of complicated info, some customers need extra management over producing  distinctive audio experiences – for instance, creating their very own podcasts. Podcasts are an more and more common medium for creators, enterprise leaders, and customers to hearken to what pursuits them. Today, we’ll share how Gemini 1.5 Pro and the Text-to-Speech API on Google Cloud may help you create conversations with various voices and generate podcast scripts with customized prompts.

aside_block
<ListValue: [StructValue([(‘title’, ‘$300 in free credit to try Google Cloud AI and ML’), (‘body’, <wagtail.rich_text.RichText object at 0x3ef643e5f8b0>), (‘btn_text’, ‘Start building for free’), (‘href’, ‘https://ift.tt/MOuzIne’), (‘image’, None)])]>

The strategy: Expand your attain with various audio codecs

A fantastic podcast begins with accessible audio content material. Gemini’s multimodal capabilities, mixed with our high-fidelity Text-to-Speech API, provides 380+ voices throughout 50+ languages and customized voice creation. This unlocks new methods for customers to expertise content material and broaden their attain by means of various audio codecs. 

This strategy additionally helps content material creators attain a wider viewers and streamline the content material creation course of, together with:

  • Expanded attain: Connect with an viewers phase that prefers audio content material.

  • Increased engagement:  Foster deeper connections with listeners by means of customized audio.

  • Content repurposing: Maximize the worth of present written content material by reworking it into a brand new format, reaching a wider viewers with out ranging from scratch.

Let’s check out how. 

The structure: Gemini 1.5 Pro and Text-to-Speech 

Our audio overview creation structure makes use of two highly effective companies from Google Cloud:

  • Gemini 1.5 Pro: This superior generative AI mannequin excels at understanding  and producing  human-like textual content. We’ll use Gemini 1.5 Pro to:

    • Generate participating scripts: Feed your podcast content material overview  to Gemini 1.5 Pro, and it could generate compelling conversational scripts, full with introductions, transitions, and calls to motion.

    • Adapt content material for audio: Gemini 1.5 Pro can optimize written content material for the audio format, guaranteeing a pure stream and interesting listening expertise. It can even alter the tone and magnificence to swimsuit any format similar to podcasts.

  • Text-to-Speech API: This API converts textual content into natural-sounding speech, giving a voice to your scripts. You can select from varied voices and languages to match your model and target market.

How to create an enticing podcast your self, step-by-step 

  • Content preparation: Prepare your podcast. Ensure it is well-structured and edited for readability. Consider dividing longer posts into a number of episodes for optimum listening length.

  • Gemini 1.5 Pro integration: Use Gemini 1.5 Pro to generate a conversational script out of your podcast. Experiment with prompts to fine-tune the output, attaining the specified fashion and tone. Example immediate: "Generate an enticing audio overview script from this podcast, together with an introduction, transitions, and a name to motion. Target viewers is technical builders, engineers, and cloud architects."

  • Section extraction: For complicated or prolonged podcasts, you may use Gemini 1.5 Pro to extract key sections and subsections as JSON, enabling a extra structured strategy to script technology.

A python operate that powers our podcast creation course of can look so simple as beneath:

code_block
<ListValue: [StructValue([(‘code’, ‘def extract_sections_and_subsections(document1: Part, project="<your-project-id>", location = "us-central1") -> str:rn """rn Extracts hierarchical sections and subsections from a Google Cloud blog postrn provided as a PDF document.rnrnrn This function uses the Gemini 1.5 Pro language model to analyze the structurern of a blog post and identify its key sections and subsections. The extractedrn information is returned in JSON format for easy parsing and use inrn various applications.rnrnrn This is particularly useful for:rnrnrn * **Large documents:** Breaking down content into manageable chunks forrn efficient processing and analysis.rn * **Podcast creation:** Generating multi-episode series where each episodern focuses on a specific section of the blog post.rnrnrn Args:rn document1 (Part): A Part object representing the PDF document,rn typically obtained using `Part.from_uri()`.rn For example:rn “`pythonrn document1 = Part.from_uri(rn mime_type="application/pdf",rn uri="gs://your-bucket/your-pdf.pdf"rn )rn “`rn location: The region of your Google Cloud project. Defaults to "us-central1".rn project: The ID of your Google Cloud project. Defaults to "<your-project-id>".rnrnrnrnrn Returns:rn str: A JSON string representing the extracted sections and subsections.rn Returns an empty string if there are issues with processing orrn the model output.rn """rnrnrn vertexai.init(project=project, location=location) # Initialize Vertex AIrn model = GenerativeModel("gemini-1.5-pro-002")rnrnrn prompt = """Analyze the following blog post and extract its sections and subsections. Represent this information in JSON format using the following structure:rn [rn {rn "section": "Section Title",rn "subsections": [rn "Subsection 1",rn "Subsection 2",rn // …rn ]rn },rn // … extra sectionsrn ]"""rnrnrn attempt:rn responses = mannequin.generate_content(rn ["""The pdf file contains a Google Cloud blog post required for podcast-style analysis:""", document1, prompt],rn generation_config=generation_config,rn safety_settings=safety_settings,rn stream=True, # Stream outcomes for higher efficiency with massive documentsrn )rnrnrn response_text = ""rn for response in responses:rn response_text += response.textrnrnrn return response_textrnrnrn besides Exception as e:rn print(f"Error throughout part extraction: {e}")rn return ""’), (‘language’, ”), (‘caption’, <wagtail.rich_text.WealthyText object at 0x3ef643e5fe50>)])]>

Then, use Gemini 1.5 Pro to generate the podcast script for every part. Again, present clear directions in your prompts, specifying target market, desired tone, and approximate episode size.

For every part and subsection you should use a operate like beneath to generate a script:

code_block
<ListValue: [StructValue([(‘code’, ‘def generate_podcast_content(section, subsection, document1:Part, targetaudience, guestname, hostname, project="<your-project-id>", location="us-central1") -> str:rn """Generates a podcast dialogue in JSON format from a blog post subsection.rnrnrn This function uses the Gemini model in Vertex AI to create a conversationrn between a host and a guest, covering the specified subsection content. It usesrn a provided PDF as source material and outputs the dialogue in JSON.rnrnrn Args:rn section: The blog post’s main section (e.g., "Introduction").rn subsection: The specific subsection (e.g., "Benefits of Gemini 1.5").rn document1: A `Part` object representing the source PDF (created usingrn `Part.from_uri(mime_type="application/pdf", uri="gs://your-bucket/your-pdf.pdf")`).rn targetaudience: The intended audience for the podcast.rn guestname: The name of the podcast guest.rn project: Your Google Cloud project ID.rn location: Your Google Cloud project location.rnrnrn Returns:rn A JSON string representing the generated podcast dialogue.rn """rn print(f"Processing section: {section} and subsection: {subsection}")rnrnrn prompt = f"""Create a podcast dialogue in JSON format based on a provided subsection of a Google Cloud blog post (found in the attached PDF).rn The dialogue should be a lively back-and-forth between a host (R) and a guest (S), presented as a series of turns.rn The host should guide the conversation by asking questions, while the guest provides informative and accessible answers.rn The script must fully cover all points within the given subsection.rn Use clear explanations and relatable analogies.rn Maintain a consistently positive and enthusiastic tone (e.g., "Movies, I love them. They’re like time machines…").rn Include only one introductory host greeting (e.g., "Welcome to our next episode…"). No music, sound effects, or production directions.rnrnrn JSON structure:rn , // R for host, S for guestrn // … more turnsrn ]rn }}rn }}rnrnrn Input Data:rn Section: "{part}"rn Subsections to cowl within the podcast: "{subsection}"rn Target Audience: "{targetaudience}"rn Guest title: "{guestname}"rn Host title: "{hostname}"rn """rnrnrn vertexai.init(mission=mission, location=location)rn mannequin = GenerativeMannequin("gemini-1.5-pro-002")rnrnrn responses = mannequin.generate_content(rn ["""The pdf file contains a Google Cloud blog post required for podcast-style analysis:""", document1, prompt],rn generation_config=generation_config, # Assuming these are outlined alreadyrn safety_settings=safety_settings, # Assuming these are outlined alreadyrn stream=True,rn )rnrnrn response_text = ""rn for response in responses:rn response_text += response.textrnrnrn return response_text’), (‘language’, ”), (‘caption’, <wagtail.rich_text.WealthyText object at 0x3ef643e5f3d0>)])]>

Next, feed the generated  script by Gemini to the Text-to-Speech API. Choose a voice and language acceptable in your target market and content material.

A operate as beneath can generate human high quality audio based mostly on textual content. For this we will use the superior text-to-speech API in Google Cloud.

code_block
<ListValue: [StructValue([(‘code’, ‘def generate_audio_from_text(input_json):rn """Generates audio using Google Text-to-Speech API.rnrnrn Args:rn input_json: A dictionary containing the ‘multiSpeakerMarkup’ for the TTS API. This is generated by the Gemini 1.5 Pro model in the buildPodCastContent() function. rnrnrn Returns:rn The audio data in bytes (MP3 format) if successful, None otherwise.rn """rnrnrn try:rn # Build the Text-to-Speech servicern service = build(‘texttospeech’, ‘v1beta1’)rnrnrn # Prepare synthesis inputrn synthesis_input = {rn ‘multiSpeakerMarkup’: input_json[‘multiSpeakerMarkup’]rn }rnrnrn # Configure voice and audio settingsrn voice = {rn ‘languageCode’: ‘en-US’,rn ‘title’: ‘en-US-Studio-MultiSpeaker’rn }rnrnrn audio_config = {rn ‘audioEncoding’: ‘MP3’,rn ‘pitch’: 0,rn ‘speakingRate’: 0,rn ‘resultsProfileId’: [‘small-bluetooth-speaker-class-device’]rn }rnrnrn # Make the API requestrn response = service.textual content().synthesize(rn physique={rn ‘enter’: synthesis_input,rn ‘voice’: voice,rn ‘audioConfig’: audio_configrn }rn ).execute()rnrnrn # Extract and return audio contentrn audio_content = response[‘audioContent’]rn return audio_contentrnrnrn besides Exception as e:rn print(f"Error: {e}") # More informative error messagern return None’), (‘language’, ”), (‘caption’, <wagtail.rich_text.WealthyText object at 0x3ef643e5fa30>)])]>

Finally, to retailer audio content material already encoded as base64 MP3 knowledge in Google Cloud Storage, you should use the google-cloud-storage Python library. This lets you decode the base64 string and add the ensuing bytes on to a chosen bucket, specifying the content material kind as ‘audio/mp3’.

Hear it for your self

While the Text-to-Speech API produces high-quality audio, you may additional improve your audio dialog with background music, sound results, {and professional} modifying utilizing instruments. Hear it for your self – obtain the audio dialog I created from this weblog utilizing Gemini 1.5 Pro and Text-to-Speech API.

To begin creating for your self, discover our full suite of audio technology options utilizing Google Cloud companies, similar to Text-to-Speech API  and Gemini fashions utilizing the free tier. We suggest experimenting with completely different modalities like textual content and picture prompts to expertise Gemini’s potential for content material creation.

HI-FI News

through AI & Machine Learning https://ift.tt/462tW3k

December 6, 2024 at 06:03PM