Views
No views yet
pip install -U -q keras-hub
pip install -U -q keras| Preset name | Parameters | Description |
|---|---|---|
| moonshine_base_en | 61.5M | For real-time transcription, Moonshine Base is a portable, powerful English voice recognition model. It is perfect for applications where accuracy and speed are crucial since it provides excellent accuracy with extremely low latency. |
| moonshine_tiny_en | 27.1M | For real-time transcription, Moonshine Tiny is a compact and efficient English voice recognition model. It’s ideal for resource-constrained applications where low latency and reliable accuracy are essential. |
1import os
2
3import keras
4import keras_hub
5import numpy as np
6import librosa
7import tensorflow as tf
8
9from keras_hub.src.models.moonshine.moonshine_audio_to_text import (
10 MoonshineAudioToText,
11)
12
13# Custom backbone.
14backbone = keras_hub.models.MoonshineBackbone(
15 vocabulary_size=10000,
16 filter_dim=256,
17 encoder_num_layers=6,
18 decoder_num_layers=6,
19 hidden_dim=256,
20 intermediate_dim=512,
21 encoder_num_heads=8,
22 decoder_num_heads=8,
23 feedforward_expansion_factor=4,
24 decoder_use_swiglu_activation=True,
25 encoder_use_swiglu_activation=False,
26)
27# Audio features as input (e.g., from MoonshineAudioConverter).
28outputs = backbone(
29 {
30 "encoder_input_values": np.zeros((1, 16000, 1)),
31 "encoder_padding_mask": np.ones((1, 16000), dtype=bool),
32 "decoder_token_ids": np.zeros((1, 20), dtype=np.int32),
33 "decoder_padding_mask": np.ones((1, 20), dtype=bool),
34 }
35)
36
37# Config for test.
38BATCH_SIZE = 2
39AUDIO_PATH = "path/to/audio_file.wav"
40
41# Load and prepare audio data.
42audio, sr = librosa.load(AUDIO_PATH, sr=16000, mono=True)
43audio_tensor = tf.expand_dims(audio, axis=-1)
44audio_tensor = tf.convert_to_tensor(audio_tensor, dtype=tf.float32)
45single_audio_input_batched = tf.expand_dims(audio_tensor, axis=0)
46audio_batch = tf.repeat(single_audio_input_batched, BATCH_SIZE, axis=0)
47dummy_texts = ["Sample transcription.", "Another sample transcription."]
48
49# Create tf.data.Dataset.
50audio_ds = tf.data.Dataset.from_tensor_slices(audio_batch)
51text_ds = tf.data.Dataset.from_tensor_slices(dummy_texts)
52audio_dataset = (
53 tf.data.Dataset.zip((audio_ds, text_ds))
54 .map(lambda audio, txt: {"audio": audio, "text": txt})
55 .batch(BATCH_SIZE)
56)
57print("Audio dataset created.")
58
59# Load pretrained Moonshine model.
60audio_to_text = MoonshineAudioToText.from_preset("moonshine_tiny_en")
61
62# Generation examples.
63generated_text_single = audio_to_text.generate(
64 {"audio": single_audio_input_batched}
65)
66print(f"Generated text (single audio): {generated_text_single}")
67
68generated_text_batch = audio_to_text.generate({"audio": audio_batch})
69print(f"Generated text (batch audio): {generated_text_batch}")
70
71# Compile the generate() function with a custom sampler.
72audio_to_text.compile(sampler="top_k")
73generated_text_top_k = audio_to_text.generate(
74 {"audio": single_audio_input_batched}
75)
76print(f"Generated text (top_k sampler): {generated_text_top_k}")
77
78audio_to_text.compile(sampler="greedy")
79generated_text_greedy = audio_to_text.generate(
80 {"audio": single_audio_input_batched}
81)
82print(f"Generated text (greedy sampler): {generated_text_greedy}")
83
84# Fine-tuning example.
85audio_to_text.compile(
86 optimizer=keras.optimizers.Adam(learning_rate=1e-5),
87 loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
88 weighted_metrics=[keras.metrics.SparseCategoricalAccuracy()],
89)
90history = audio_to_text.fit(audio_dataset, steps_per_epoch=1, epochs=1)
91print(f"Fine-tuning completed. Training history: {history.history}")
92
93# Detached preprocessing.
94original_preprocessor = audio_to_text.preprocessor
95audio_to_text.preprocessor = None
96preprocessed_batch = original_preprocessor.generate_preprocess(
97 {"audio": audio_batch}
98)
99print(f"Preprocessed batch keys: {preprocessed_batch.keys()}")
100stop_ids = (original_preprocessor.tokenizer.end_token_id,)
101generated_batch_tokens = audio_to_text.generate(
102 preprocessed_batch, stop_token_ids=stop_ids
103)
104print(f"Generated tokens keys: {generated_batch_tokens.keys()}")
105final_strings = original_preprocessor.generate_postprocess(
106 generated_batch_tokens
107)
108print(f"Final generated strings (detached): {final_strings}")
109audio_to_text.preprocessor = original_preprocessor
110print("Preprocessor reattached.")1import os
2
3import keras
4import keras_hub
5import numpy as np
6import librosa
7import tensorflow as tf
8
9from keras_hub.src.models.moonshine.moonshine_audio_to_text import (
10 MoonshineAudioToText,
11)
12
13# Custom backbone.
14backbone = keras_hub.models.MoonshineBackbone(
15 vocabulary_size=10000,
16 filter_dim=256,
17 encoder_num_layers=6,
18 decoder_num_layers=6,
19 hidden_dim=256,
20 intermediate_dim=512,
21 encoder_num_heads=8,
22 decoder_num_heads=8,
23 feedforward_expansion_factor=4,
24 decoder_use_swiglu_activation=True,
25 encoder_use_swiglu_activation=False,
26)
27# Audio features as input (e.g., from MoonshineAudioConverter).
28outputs = backbone(
29 {
30 "encoder_input_values": np.zeros((1, 16000, 1)),
31 "encoder_padding_mask": np.ones((1, 16000), dtype=bool),
32 "decoder_token_ids": np.zeros((1, 20), dtype=np.int32),
33 "decoder_padding_mask": np.ones((1, 20), dtype=bool),
34 }
35)
36
37# Config for test.
38BATCH_SIZE = 2
39AUDIO_PATH = "path/to/audio_file.wav"
40
41# Load and prepare audio data.
42audio, sr = librosa.load(AUDIO_PATH, sr=16000, mono=True)
43audio_tensor = tf.expand_dims(audio, axis=-1)
44audio_tensor = tf.convert_to_tensor(audio_tensor, dtype=tf.float32)
45single_audio_input_batched = tf.expand_dims(audio_tensor, axis=0)
46audio_batch = tf.repeat(single_audio_input_batched, BATCH_SIZE, axis=0)
47dummy_texts = ["Sample transcription.", "Another sample transcription."]
48
49# Create tf.data.Dataset.
50audio_ds = tf.data.Dataset.from_tensor_slices(audio_batch)
51text_ds = tf.data.Dataset.from_tensor_slices(dummy_texts)
52audio_dataset = (
53 tf.data.Dataset.zip((audio_ds, text_ds))
54 .map(lambda audio, txt: {"audio": audio, "text": txt})
55 .batch(BATCH_SIZE)
56)
57print("Audio dataset created.")
58
59# Load pretrained Moonshine model.
60audio_to_text = MoonshineAudioToText.from_preset("hf://keras/moonshine_tiny_en")
61
62# Generation examples.
63generated_text_single = audio_to_text.generate(
64 {"audio": single_audio_input_batched}
65)
66print(f"Generated text (single audio): {generated_text_single}")
67
68generated_text_batch = audio_to_text.generate({"audio": audio_batch})
69print(f"Generated text (batch audio): {generated_text_batch}")
70
71# Compile the generate() function with a custom sampler.
72audio_to_text.compile(sampler="top_k")
73generated_text_top_k = audio_to_text.generate(
74 {"audio": single_audio_input_batched}
75)
76print(f"Generated text (top_k sampler): {generated_text_top_k}")
77
78audio_to_text.compile(sampler="greedy")
79generated_text_greedy = audio_to_text.generate(
80 {"audio": single_audio_input_batched}
81)
82print(f"Generated text (greedy sampler): {generated_text_greedy}")
83
84# Fine-tuning example.
85audio_to_text.compile(
86 optimizer=keras.optimizers.Adam(learning_rate=1e-5),
87 loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
88 weighted_metrics=[keras.metrics.SparseCategoricalAccuracy()],
89)
90history = audio_to_text.fit(audio_dataset, steps_per_epoch=1, epochs=1)
91print(f"Fine-tuning completed. Training history: {history.history}")
92
93# Detached preprocessing.
94original_preprocessor = audio_to_text.preprocessor
95audio_to_text.preprocessor = None
96preprocessed_batch = original_preprocessor.generate_preprocess(
97 {"audio": audio_batch}
98)
99print(f"Preprocessed batch keys: {preprocessed_batch.keys()}")
100stop_ids = (original_preprocessor.tokenizer.end_token_id,)
101generated_batch_tokens = audio_to_text.generate(
102 preprocessed_batch, stop_token_ids=stop_ids
103)
104print(f"Generated tokens keys: {generated_batch_tokens.keys()}")
105final_strings = original_preprocessor.generate_postprocess(
106 generated_batch_tokens
107)
108print(f"Final generated strings (detached): {final_strings}")
109audio_to_text.preprocessor = original_preprocessor
110print("Preprocessor reattached.")