Pemahaman audio

Lihat di ai.google.dev Jalankan di Google Colab Jalankan di Kaggle Buka di Vertex AI Lihat sumber di GitHub

Mulai dari Gemma 3n, Anda dapat menggunakan audio langsung ke dalam perintah dan alur kerja. Audio dan bahasa lisan adalah sumber data yang kaya untuk menangkap maksud pengguna, merekam informasi tentang dunia di sekitar kita, dan memahami masalah tertentu yang akan diselesaikan.

Panduan ini memberikan ringkasan kemampuan pemrosesan audio Gemma 4, termasuk pengenalan ucapan otomatis (ASR), terjemahan, dan pemahaman ucapan umum.

Notebook ini akan berjalan di GPU T4.

Menginstal paket Python

Instal library Hugging Face yang diperlukan untuk menjalankan model Gemma dan membuat permintaan.

# Install PyTorch & other libraries
pip install torch accelerate

# Install the transformers library
pip install "transformers>=5.10.1"

Memuat Model

Gunakan library transformers untuk membuat instance processor dan model menggunakan class AutoProcessor dan AutoModelForImageTextToText seperti yang ditunjukkan dalam contoh kode berikut:

MODEL_ID = "google/gemma-4-E2B-it" # @param ["google/gemma-4-E2B-it","google/gemma-4-E4B-it", "google/gemma-4-12B-it"]

from transformers import pipeline

pipe = pipeline(
    task="any-to-any",
    model=MODEL_ID,
    device_map="auto",
    dtype="auto"
)
config.json:   0%|          | 0.00/4.95k [00:00<?, ?B/s]
model.safetensors:   0%|          | 0.00/10.2G [00:00<?, ?B/s]
Loading weights:   0%|          | 0/1951 [00:00<?, ?it/s]
generation_config.json:   0%|          | 0.00/208 [00:00<?, ?B/s]
processor_config.json:   0%|          | 0.00/1.69k [00:00<?, ?B/s]
chat_template.jinja:   0%|          | 0.00/17.3k [00:00<?, ?B/s]
tokenizer_config.json:   0%|          | 0.00/2.10k [00:00<?, ?B/s]
tokenizer.json:   0%|          | 0.00/32.2M [00:00<?, ?B/s]

Data audio

Data audio digital dapat hadir dalam berbagai format dan tingkat resolusi. Format audio sebenarnya yang dapat Anda gunakan dengan Gemma, seperti format MP3 dan WAV, ditentukan oleh framework yang Anda pilih untuk mengonversi data suara menjadi tensor. Berikut beberapa pertimbangan khusus untuk menyiapkan data audio untuk diproses dengan Gemma:

  • Biaya token: Setiap detik audio adalah 25 token untuk Gemma 4. (6,25 token untuk Gemma 3n).
  • Panjang klip: Audio mendukung panjang maksimum 30 detik.
  • Saluran audio: Data audio diproses sebagai satu saluran audio. Jika Anda menggunakan audio multi-saluran, seperti saluran kiri dan kanan, pertimbangkan untuk mengurangi data menjadi satu saluran dengan menghapus saluran atau menggabungkan data suara menjadi satu saluran.
  • Encoding Teknis:
    • Frekuensi Sampel: 16 kHz
    • Kedalaman Bit: Format float 32-bit, dengan sampel yang dinormalisasi dalam rentang [-1, 1].

Jika data audio yang Anda rencanakan untuk diproses jauh berbeda dengan pemrosesan input, terutama dalam hal saluran, frekuensi sampel, dan kedalaman bit, pertimbangkan untuk mengambil ulang sampel atau memangkas data audio agar sesuai dengan resolusi data yang ditangani oleh model.

Encoding audio

Meskipun library tingkat tinggi (seperti Hugging Face AutoProcessor) sering kali menangani pra-pemrosesan audio secara otomatis, Anda mungkin terkadang perlu menerapkan encoding kustom.

Saat mengenkode data audio dengan penerapan kode Anda sendiri untuk digunakan dengan Gemma, Anda harus mengikuti proses konversi yang direkomendasikan. Jika Anda menggunakan file audio yang dienkode dalam format tertentu, seperti data yang dienkode MP3 atau WAV, Anda harus mendekode file tersebut terlebih dahulu ke sampel menggunakan library seperti ffmpeg. Setelah data didekode, konversi audio menjadi bentuk gelombang float32 16 kHz satu saluran dalam rentang [-1, 1]. Misalnya, jika Anda menggunakan file WAV PCM integer 16-bit stereo yang ditandatangani pada 44,1 kHz, ikuti langkah-langkah berikut:

  • Ambil ulang sampel data audio ke 16 kHz
  • Downmix dari stereo ke mono dengan menghitung rata-rata 2 saluran
  • Konversi dari int16 ke float32, dan bagi dengan 32768.0 untuk menskalakan ke rentang [-1, 1]

Speech-to-text

Gemma 4 E2B, E4B, dan 12B Unified dilatih untuk pengenalan ucapan multibahasa, sehingga Anda dapat mentranskripsikan input audio dalam berbagai bahasa ke dalam teks.

Gunakan struktur perintah berikut untuk Pengenalan Ucapan Audio (ASR).

Transcribe the following speech segment in {LANGUAGE} into {LANGUAGE} text.

Follow these specific instructions for formatting the answer:
*   Only output the transcription, with no newlines.
*   When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three.

Contoh kode berikut menunjukkan cara meminta model untuk mentranskripsikan teks dari file audio menggunakan Hugging Face Transformers:

from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 64
gen_kwargs = dict(generation_config=config)

RESOURCE_URL_PREFIX = "https://raw.githubusercontent.com/google-gemma/cookbook/refs/heads/main/apps/sample-data/"

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Transcribe the following speech segment in its original language. Follow these specific instructions for formatting the answer:\n* Only output the transcription, with no newlines.\n* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three."},
            #{"type": "text", "text": "Transcribe the following speech segment in English into English text. Follow these specific instructions for formatting the answer:\n* Only output the transcription, with no newlines.\n* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three."},
            {"type": "audio", "audio": f"{RESOURCE_URL_PREFIX}journal1.wav"},
        ]
    }
]

outputs = pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs)
print(outputs[0]['generated_text'])
I woke up early today feeling really fresh the morning light was beautiful and I enjoyed a nice cup of coffee<turn|>
from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 1024
gen_kwargs = dict(generation_config=config)

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Give me a concise overview of these audio files."},
            {"type": "text", "text": "journal1:"},
            {"type": "audio", "audio": f"{RESOURCE_URL_PREFIX}journal1.wav"},
            {"type": "text", "text": "journal2:"},
            {"type": "audio", "audio": f"{RESOURCE_URL_PREFIX}journal2.wav"},
            {"type": "text", "text": "journal3:"},
            {"type": "audio", "audio": f"{RESOURCE_URL_PREFIX}journal3.wav"},
            {"type": "text", "text": "journal4:"},
            {"type": "audio", "audio": f"{RESOURCE_URL_PREFIX}journal4.wav"},
            {"type": "text", "text": "journal5:"},
            {"type": "audio", "audio": f"{RESOURCE_URL_PREFIX}journal5.wav"},
        ]
    }
]

outputs = pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs)
print(outputs[0]['generated_text'])
Here is a concise overview of each audio file:

**journal1:** The speaker describes a fresh and peaceful day, enjoying a cup of coffee.
**journal2:** The speaker had a perfect day at the park, including a walk and watching cherry blossoms.
**journal3:** The speaker finished the day with a good book, feeling grateful for simple moments.
**journal4:** The speaker returned from work and noted the beautiful night sky and a clear view from the train.
**journal5:** The speaker had a great lunch with an old friend, which was a pleasant way to catch up and made their day.
<turn|>

Terjemahan ucapan otomatis

Gemma 4 E2B, E4B, dan 12B Unified dilatih untuk tugas terjemahan ucapan multibahasa, sehingga Anda dapat menerjemahkan audio lisan langsung ke bahasa lain.

Gunakan struktur perintah berikut untuk Terjemahan Ucapan Otomatis (AST).

Transcribe the following speech segment in {SOURCE_LANGUAGE}, then translate it into {TARGET_LANGUAGE}.
When formatting the answer, first output the transcription in {SOURCE_LANGUAGE}, then one newline, then output the string '{TARGET_LANGUAGE}: ', then the translation in {TARGET_LANGUAGE}.

Contoh kode berikut menunjukkan cara meminta model untuk menerjemahkan audio lisan ke dalam teks menggunakan Hugging Face Transformers:

from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 64
gen_kwargs = dict(generation_config=config)

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Transcribe the following speech segment in English, then translate it into Korean. When formatting the answer, first output the transcription in English, then one newline, then output the string 'Korean: ', then the translation in Korean."},
            {"type": "audio", "audio": "https://ai.google.dev/gemma/docs/audio/roses-are.wav"},
        ]
    }
]

outputs = pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs)
print(outputs[0]['generated_text'])
Roses are red, violets are blue.
Korean: 장미는 빨갛고, 제비꽃은 파랗다.<turn|>

Terjemahan Ucapan Otomatis / Pengenalan Ucapan Otomatis

Coba lakukan ini sendiri

pip install ipywebrtc

Tekan tombol lingkaran dan mulai berbicara. Klik tombol lingkaran lagi setelah selesai. Widget akan segera mulai memutar kembali apa yang direkam.

from google.colab import output
output.enable_custom_widget_manager()

from ipywebrtc import AudioRecorder, CameraStream

camera = CameraStream(constraints={'audio': True,'video':False})
recorder = AudioRecorder(stream=camera)
recorder
AudioRecorder(audio=Audio(value=b'', format='webm'), stream=CameraStream(constraints={'audio': True, 'video': …

Konversi file webm ke format wav yang dapat dipahami PyTorch.

with open('/content/recording.webm', 'wb') as f:
    f.write(recorder.audio.value)
!ffmpeg -i /content/recording.webm /content/recording.wav -y
ffmpeg version 4.4.2-0ubuntu0.22.04.1 Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 11 (Ubuntu 11.2.0-19ubuntu1)
  configuration: --prefix=/usr --extra-version=0ubuntu0.22.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libdav1d --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librabbitmq --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzimg --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opencl --enable-opengl --enable-sdl2 --enable-pocketsphinx --enable-librsvg --enable-libmfx --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
  libavutil      56. 70.100 / 56. 70.100
  libavcodec     58.134.100 / 58.134.100
  libavformat    58. 76.100 / 58. 76.100
  libavdevice    58. 13.100 / 58. 13.100
  libavfilter     7.110.100 /  7.110.100
  libswscale      5.  9.100 /  5.  9.100
  libswresample   3.  9.100 /  3.  9.100
  libpostproc    55.  9.100 / 55.  9.100
Input #0, matroska,webm, from '/content/recording.webm':
  Metadata:
    encoder         : Chrome
  Duration: 00:00:03.00, start: 0.000000, bitrate: 132 kb/s
  Stream #0:0(eng): Audio: opus, 48000 Hz, mono, fltp (default)
Stream mapping:
  Stream #0:0 -> #0:0 (opus (native) -> pcm_s16le (native))
Press [q] to stop, [?] for help
Output #0, wav, to '/content/recording.wav':
  Metadata:
    ISFT            : Lavf58.76.100
  Stream #0:0(eng): Audio: pcm_s16le ([1][0][0][0] / 0x0001), 48000 Hz, mono, s16, 768 kb/s (default)
    Metadata:
      encoder         : Lavc58.134.100 pcm_s16le
size=     287kB time=00:00:02.99 bitrate= 783.7kbits/s speed=79.4x    
video:0kB audio:287kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.026552%

ASR

from transformers import GenerationConfig
config = GenerationConfig.from_pretrained(MODEL_ID)
config.max_new_tokens = 64
gen_kwargs = dict(generation_config=config)

messages = [{
  "role": "user",
  "content": [
    {"type": "text", "text": "Transcribe the following speech segment in its original language. Follow these specific instructions for formatting the answer:\n* Only output the transcription, with no newlines.\n* When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three."},
    {"type": "audio", "audio": "/content/recording.wav"},
  ]
}]

outputs = pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs)
print(outputs[0]['generated_text'])
How can I get to the station?<turn|>

AST

messages = [{
  "role": "user",
  "content": [
    {"type": "text", "text": "Transcribe the following speech segment in English, then translate it into Korean. When formatting the answer, first output the transcription in English, then one newline, then output the string 'Korean: ', then the translation in Korean."},
    {"type": "audio", "audio": "/content/recording.wav"},
  ]
}]

outputs = pipe(messages, return_full_text=False, generate_kwargs=gen_kwargs)
print(outputs[0]['generated_text'])
How can I get to the station?
Korean: 역에 어떻게 가나요?<turn|>

Ringkasan dan langkah berikutnya

Dalam panduan ini, Anda telah mempelajari cara memproses audio menggunakan model Gemma 4. Contohnya menunjukkan cara melakukan Speech-to-Text (ASR) untuk mentranskripsikan bahasa lisan, serta Terjemahan Ucapan Otomatis (AST) untuk menerjemahkan audio lisan langsung ke bahasa lain. Anda juga telah melihat cara merekam audio dari mikrofon di lingkungan notebook untuk diproses.

Lihat dokumentasi berikut untuk bacaan lebih lanjut.