|
|
Google Colab에서 실행
|
|
|
GitHub에서 소스 보기
|
Gemma 3n부터 오디오를 프롬프트와 워크플로에 직접 사용할 수 있습니다. 오디오와 음성 언어는 사용자 의도를 파악하고, 주변 세계에 관한 정보를 기록하고, 해결해야 할 특정 문제를 이해하는 데 유용한 데이터 소스입니다.
이 가이드에서는 Gemma 4의 오디오 처리 기능을 간략하게 설명합니다. 자동 음성 인식 (ASR), 번역, 일반 음성 이해 기능이 포함됩니다.
이 노트북은 T4 GPU에서 실행됩니다.
Python 패키지 설치
Gemma 모델을 실행하고 요청을 보내는 데 필요한 Hugging Face 라이브러리를 설치합니다.
# Install PyTorch & other librariespip install torch accelerate# Install the transformers librarypip install "transformers>=5.10.1"
모델 로드
다음 코드 예와 같이 transformers 라이브러리를 사용하여 AutoProcessor 및 AutoModelForImageTextToText 클래스를 사용하여 processor 및 model의 인스턴스를 만듭니다.
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]
오디오 데이터
디지털 오디오 데이터는 다양한 형식과 해상도로 제공될 수 있습니다. MP3 및 WAV 형식과 같이 Gemma에서 사용할 수 있는 실제 오디오 형식은 사운드 데이터를 텐서로 변환하는 데 선택한 프레임워크에 따라 결정됩니다. 다음은 Gemma로 처리하기 위해 오디오 데이터를 준비할 때 고려해야 할 몇 가지 구체적인 사항입니다.
- 토큰 비용: Gemma 4의 경우 오디오 1초당 토큰 25개입니다. (Gemma 3n의 경우 토큰 6.25개)
- 클립 길이: 오디오는 최대 30초의 길이를 지원합니다.
- 오디오 채널: 오디오 데이터는 단일 오디오 채널로 처리됩니다. 왼쪽 및 오른쪽 채널과 같은 다중 채널 오디오를 사용하는 경우 채널을 삭제하거나 사운드 데이터를 단일 채널로 결합하여 데이터를 단일 채널로 줄이는 것이 좋습니다.
- 기술 인코딩:
- 샘플링 레이트: 16kHz
- 비트 심도: 32비트 부동 소수점 형식으로, 샘플은 [-1, 1] 범위 내에서 정규화됩니다.
처리하려는 오디오 데이터가 특히 채널, 샘플링 레이트, 비트 심도 측면에서 입력 처리와 크게 다른 경우 오디오 데이터를 다시 샘플링하거나 트리밍하여 모델에서 처리하는 데이터 해상도와 일치시키는 것이 좋습니다.
오디오 인코딩
고급 라이브러리 (예: Hugging Face AutoProcessor)는 오디오 전처리를 자동으로 처리하는 경우가 많지만 때로는 커스텀 인코딩을 구현해야 할 수도 있습니다.
Gemma에서 사용할 자체 코드 구현으로 오디오 데이터를 인코딩할 때는 권장되는 변환 프로세스를 따라야 합니다. MP3 또는 WAV 인코딩 데이터와 같은 특정 형식으로 인코딩된 오디오 파일을 사용하는 경우 먼저 ffmpeg와 같은 라이브러리를 사용하여 샘플로 디코딩해야 합니다. 데이터가 디코딩되면 오디오를 [-1, 1] 범위의 모노 채널, 16kHz float32 파형으로 변환합니다. 예를 들어 44.1kHz에서 스테레오 서명된 16비트 PCM 정수 WAV 파일을 사용하는 경우 다음 단계를 따르세요.
- 오디오 데이터를 16kHz로 다시 샘플링합니다.
- 2개 채널의 평균을 구하여 스테레오에서 모노로 다운믹스합니다.
- int16에서 float32로 변환하고 32768.0으로 나누어 [-1, 1] 범위로 조정합니다.
음성 텍스트 변환
Gemma 4 E2B, E4B, 12B Unified는 다국어 음성 인식을 위해 학습되므로 다양한 언어로 오디오 입력을 텍스트로 변환할 수 있습니다.
오디오 음성 인식 (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.
다음 코드 예에서는 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|>
자동 통역
Gemma 4 E2B, E4B, 12B Unified는 다국어 통역 작업을 위해 학습되므로 음성 오디오를 다른 언어로 직접 번역할 수 있습니다.
자동 음성 번역 (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}.
다음 코드 예에서는 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|>
자동 음성 번역 / 자동 음성 인식
직접 사용해 보기
pip install ipywebrtc원 버튼을 누르고 말하기 시작합니다. 완료되면 원 버튼을 다시 클릭합니다. 위젯이 캡처한 내용을 즉시 재생하기 시작합니다.
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': …
PyTorch에서 이해할 수 있는 wav 형식으로 webm 파일을 변환합니다.
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|>
요약 및 다음 단계
이 가이드에서는 Gemma 4 모델을 사용하여 오디오를 처리하는 방법을 알아보았습니다. 이 예에서는 음성 언어를 변환하는 음성 텍스트 변환 (ASR)과 음성 오디오를 다른 언어로 직접 번역하는 자동 음성 번역 (AST)을 실행하는 방법을 보여주었습니다. 또한 처리할 노트북 환경에서 마이크의 오디오를 캡처하는 방법도 알아보았습니다.
자세한 내용은 다음 문서를 참고하세요.
Google Colab에서 실행
GitHub에서 소스 보기