tarek-liquid commited on
Commit
c46bbab
·
verified ·
1 Parent(s): 1144693

Add readme, license, demo and example

Browse files
Files changed (4) hide show
  1. LICENSE +41 -0
  2. README.md +89 -0
  3. demo.mp4 +3 -0
  4. liquid_audio_chat.py +554 -0
LICENSE ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE TEXT
2
+
3
+
4
+
5
+
6
+ LFM Open License v1.0
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+ 1. Definitions.
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
10
+ "Licensor" shall mean Liquid AI, Inc.
11
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
12
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
13
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
14
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
15
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
16
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
17
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
18
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
19
+ "Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
20
+ "Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
21
+ "Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
22
+ "Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
23
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
24
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
25
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
26
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
27
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
28
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
29
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
30
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
31
+ 5. Commercial Use Limitation.
32
+ (a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
33
+ (b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
34
+ (c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
35
+ 6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
36
+ 7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
37
+ 8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
38
+ 9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
39
+ 10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
40
+ 11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
41
+ END OF TERMS AND CONDITIONS
README.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: lfm1.0
4
+ license_link: LICENSE
5
+ language:
6
+ - en
7
+ tags:
8
+ - liquid
9
+ - lfm2.5
10
+ - edge
11
+ - llama.cpp
12
+ - audio
13
+ - speech
14
+ - gguf
15
+ base_model:
16
+ - LiquidAI/LFM2.5-Audio-1.5B
17
+ ---
18
+
19
+ <div align="center">
20
+ <img
21
+ src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png"
22
+ alt="Liquid AI"
23
+ style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;"
24
+ />
25
+ <div style="display: flex; justify-content: center; gap: 0.5em; margin-bottom: 1em;">
26
+ <a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> •
27
+ <a href="https://docs.liquid.ai/lfm"><strong>Documentation</strong></a> •
28
+ <a href="https://leap.liquid.ai/"><strong>LEAP</strong></a>
29
+ </div>
30
+ </div>
31
+
32
+ # LFM2.5-Audio-1.5B
33
+
34
+ Find more details in the original model card: https://huggingface.co/LiquidAI/LFM2.5-Audio-1.5B
35
+
36
+ ## Runners
37
+
38
+ `runners` folder contains runners for various architectures including
39
+
40
+ - llama-liquid-audio-cli
41
+ - llama-liquid-audio-server
42
+
43
+ # 🏃 How to run LFM2.5
44
+
45
+ ## CLI
46
+
47
+ Set env variables.
48
+ ```
49
+ export CKPT=/path/to/LFM2.5-Audio-1.5B-GGUF
50
+ export INPUT_WAV=/path/to/input.wav
51
+ export OUTPUT_WAV=/path/to/output.wav
52
+ ```
53
+
54
+ ### ASR (audio -> text)
55
+
56
+ ```bash
57
+ ./llama-liquid-audio-cli -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf -sys "Perform ASR." --audio $INPUT_WAV
58
+ ```
59
+
60
+ ### TTS (text -> audio)
61
+
62
+ ```bash
63
+ ./llama-liquid-audio-cli -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf -sys "Perform TTS." -p "Hi, how are you?" --output $OUTPUT_WAV
64
+ ```
65
+
66
+ ### Interleaved (audio/text -> audio + text)
67
+
68
+ ```bash
69
+ ./llama-liquid-audio-cli -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf -sys "Respond with interleaved text and audio." --audio $INPUT_WAV --output $OUTPUT_WAV
70
+ ```
71
+
72
+
73
+ ## Server
74
+
75
+ Start server
76
+ ```
77
+ export CKPT=/path/to/LFM2.5-Audio-1.5B-GGUF
78
+ ./llama-liquid-audio-server -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf
79
+ ```
80
+
81
+ Use `liquid_audio_chat.py` script to communicate with the server.
82
+
83
+ ```bash
84
+ uv run liquid_audio_chat.py
85
+ ```
86
+
87
+ # Demo
88
+
89
+ <video controls src="demo.mp4"></video>
demo.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b43013964e179460e36fe5f6a4166df031a753f6988b699c1f194c5e697a9bb
3
+ size 41272798
liquid_audio_chat.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = [
5
+ # "numpy",
6
+ # "pyaudio",
7
+ # "soundfile",
8
+ # "openai",
9
+ # "prompt_toolkit",
10
+ # ]
11
+ # ///
12
+ """Interactive CLI chat tool for LFM2.5-Audio server."""
13
+
14
+ import argparse
15
+ import base64
16
+ import io
17
+ import os
18
+ import shutil
19
+ import struct
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import threading
24
+ import time
25
+ from queue import Queue
26
+
27
+ import numpy as np
28
+ import pyaudio
29
+ import soundfile as sf
30
+ from openai import OpenAI
31
+ from prompt_toolkit import prompt
32
+ from prompt_toolkit.history import InMemoryHistory
33
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
34
+
35
+ # Suppress ALSA/JACK warnings during PyAudio init
36
+ import os
37
+ import contextlib
38
+
39
+ @contextlib.contextmanager
40
+ def suppress_stderr():
41
+ """Temporarily redirect stderr to /dev/null."""
42
+ devnull = os.open(os.devnull, os.O_WRONLY)
43
+ old_stderr = os.dup(2)
44
+ os.dup2(devnull, 2)
45
+ try:
46
+ yield
47
+ finally:
48
+ os.dup2(old_stderr, 2)
49
+ os.close(devnull)
50
+ os.close(old_stderr)
51
+
52
+
53
+ class AudioPlayer:
54
+ """Streams audio samples to speakers via PyAudio (non-blocking)."""
55
+
56
+ def __init__(self, sample_rate=24000):
57
+ self.sample_rate = sample_rate
58
+ self.all_samples = []
59
+ self.pyaudio = None
60
+ self.stream = None
61
+ self.queue = Queue()
62
+ self.thread = None
63
+ self.running = False
64
+
65
+ def _playback_thread(self):
66
+ """Background thread that writes audio to the stream."""
67
+ while self.running or not self.queue.empty():
68
+ try:
69
+ pcm_data = self.queue.get(timeout=0.1)
70
+ if self.stream:
71
+ self.stream.write(pcm_data)
72
+ except:
73
+ pass
74
+
75
+ def start(self):
76
+ """Start the audio stream."""
77
+ self.all_samples = []
78
+ self.running = True
79
+ with suppress_stderr():
80
+ self.pyaudio = pyaudio.PyAudio()
81
+ self.stream = self.pyaudio.open(
82
+ format=pyaudio.paFloat32,
83
+ channels=1,
84
+ rate=self.sample_rate,
85
+ output=True,
86
+ )
87
+ self.thread = threading.Thread(target=self._playback_thread, daemon=True)
88
+ self.thread.start()
89
+
90
+ def add_samples(self, samples):
91
+ """Add samples to playback queue (non-blocking)."""
92
+ self.all_samples.extend(samples)
93
+ pcm_data = np.array(samples, dtype=np.float32).tobytes()
94
+ self.queue.put(pcm_data)
95
+
96
+ def stop(self, output_file="output.wav"):
97
+ """Stop the audio stream."""
98
+ self.running = False
99
+ if self.thread:
100
+ self.thread.join()
101
+ self.thread = None
102
+ if self.stream:
103
+ self.stream.stop_stream()
104
+ self.stream.close()
105
+ self.stream = None
106
+ if self.pyaudio:
107
+ self.pyaudio.terminate()
108
+ self.pyaudio = None
109
+
110
+
111
+ class AudioRecorder:
112
+ """Records audio from microphone using PyAudio."""
113
+
114
+ def __init__(self, sample_rate=16000):
115
+ self.sample_rate = sample_rate
116
+ self.recording = False
117
+ self.samples = []
118
+ self.available = self._check_available()
119
+
120
+ def _check_available(self):
121
+ """Check if audio input is available."""
122
+ try:
123
+ with suppress_stderr():
124
+ p = pyaudio.PyAudio()
125
+ has_input = p.get_default_input_device_info() is not None
126
+ p.terminate()
127
+ return has_input
128
+ except Exception:
129
+ return False
130
+
131
+ def record(self, duration=None):
132
+ """Record audio. Press Enter to stop if duration is None."""
133
+ if not self.available:
134
+ print("[No microphone available. Use /wav to load audio files.]")
135
+ return None
136
+
137
+ self.samples = []
138
+ self.recording = True
139
+
140
+ print("Recording... (Press Enter to stop)")
141
+
142
+ # Start recording in background
143
+ stop_event = threading.Event()
144
+
145
+ def record_audio():
146
+ try:
147
+ with suppress_stderr():
148
+ p = pyaudio.PyAudio()
149
+ stream = p.open(
150
+ format=pyaudio.paFloat32,
151
+ channels=1,
152
+ rate=self.sample_rate,
153
+ input=True,
154
+ frames_per_buffer=1024,
155
+ )
156
+ while not stop_event.is_set():
157
+ data = stream.read(1024, exception_on_overflow=False)
158
+ samples = np.frombuffer(data, dtype=np.float32)
159
+ self.samples.extend(samples.tolist())
160
+ stream.stop_stream()
161
+ stream.close()
162
+ p.terminate()
163
+ except Exception as e:
164
+ print(f"[Recording error: {e}]")
165
+
166
+ record_thread = threading.Thread(target=record_audio)
167
+ record_thread.start()
168
+
169
+ # Wait for Enter key
170
+ input()
171
+ stop_event.set()
172
+ record_thread.join()
173
+
174
+ self.recording = False
175
+ if self.samples:
176
+ print(f"Recorded {len(self.samples) / self.sample_rate:.2f}s of audio")
177
+
178
+ return self.samples if self.samples else None
179
+
180
+ def to_wav_bytes(self):
181
+ """Convert recorded samples to WAV bytes."""
182
+ if not self.samples:
183
+ return None
184
+ buffer = io.BytesIO()
185
+ sf.write(buffer, np.array(self.samples), self.sample_rate, format="WAV")
186
+ buffer.seek(0)
187
+ return buffer.read()
188
+
189
+
190
+ SYSTEM_PROMPTS = {
191
+ "asr": "Perform ASR.",
192
+ "tts": "Perform TTS. Use the UK female voice.",
193
+ "interleaved": "Respond with interleaved text and audio.",
194
+ }
195
+
196
+
197
+ def create_text_message(text):
198
+ """Create a text user message."""
199
+ return {"role": "user", "content": text}
200
+
201
+
202
+ def create_audio_message(wav_data):
203
+ """Create an audio user message."""
204
+ encoded = base64.b64encode(wav_data).decode("utf-8")
205
+ return {
206
+ "role": "user",
207
+ "content": [
208
+ {
209
+ "type": "input_audio",
210
+ "input_audio": {"data": encoded, "format": "wav"},
211
+ }
212
+ ],
213
+ }
214
+
215
+
216
+ def create_stream_single_shot(client, mode, text=None, wav_data=None, max_tokens=512):
217
+ """Create a single-shot request for ASR/TTS (always resets context)."""
218
+ messages = [{"role": "system", "content": SYSTEM_PROMPTS[mode]}]
219
+
220
+ if mode == "asr" and wav_data:
221
+ messages.append(create_audio_message(wav_data))
222
+ elif mode == "tts" and text:
223
+ messages.append(create_text_message(text))
224
+
225
+ return client.chat.completions.create(
226
+ model="",
227
+ messages=messages,
228
+ stream=True,
229
+ max_tokens=max_tokens,
230
+ extra_body={"reset_context": True},
231
+ )
232
+
233
+
234
+ def create_stream_chat(client, messages, max_tokens=512, reset_context=False):
235
+ """Create a chat request for interleaved mode (maintains context)."""
236
+ return client.chat.completions.create(
237
+ model="",
238
+ messages=messages,
239
+ stream=True,
240
+ max_tokens=max_tokens,
241
+ extra_body={"reset_context": reset_context},
242
+ )
243
+
244
+
245
+ def process_stream(stream, audio_player=None):
246
+ """Process streaming response, playing audio and printing text."""
247
+ t0 = time.time()
248
+ ttft = None
249
+ text_chunks = []
250
+ audio_chunks = []
251
+ total_samples = 0
252
+ completed = False
253
+
254
+ for chunk in stream:
255
+ if chunk.choices[0].finish_reason == "stop":
256
+ completed = True
257
+ break
258
+
259
+ delta = chunk.choices[0].delta
260
+
261
+ # Handle text
262
+ if text := delta.content:
263
+ if ttft is None:
264
+ ttft = time.time() - t0
265
+ text_chunks.append((time.time(), text))
266
+ print(text, end="", flush=True)
267
+
268
+ # Handle audio
269
+ if hasattr(delta, "audio_chunk") and delta.audio_chunk:
270
+ if ttft is None:
271
+ ttft = time.time() - t0
272
+ chunk_data = delta.audio_chunk["data"]
273
+ pcm_bytes = base64.b64decode(chunk_data)
274
+ samples = struct.unpack(f"<{len(pcm_bytes) // 4}f", pcm_bytes)
275
+ audio_chunks.append((time.time(), samples))
276
+ total_samples += len(samples)
277
+
278
+ # Print note symbol for audio progress
279
+ print("♪", end="", flush=True)
280
+
281
+ if audio_player:
282
+ audio_player.add_samples(samples)
283
+
284
+ if text_chunks or audio_chunks:
285
+ print() # Newline after output
286
+
287
+ if not completed:
288
+ print("[Warning: Server disconnected before completion]")
289
+
290
+ # Calculate and display stats (single line)
291
+ total_time = time.time() - t0
292
+ full_text = "".join(t for _, t in text_chunks)
293
+
294
+ stats = []
295
+ if ttft is not None:
296
+ stats.append(f"ttft {ttft:.3f}s")
297
+
298
+ if text_chunks and len(text_chunks) > 1:
299
+ text_duration = text_chunks[-1][0] - text_chunks[0][0]
300
+ if text_duration > 0:
301
+ stats.append(f"text {len(text_chunks)} tok @ {len(text_chunks)/text_duration:.1f} tok/s")
302
+
303
+ if audio_chunks:
304
+ # Calculate from ttft to last chunk for accurate throughput
305
+ first_audio_time = audio_chunks[0][0]
306
+ last_audio_time = audio_chunks[-1][0]
307
+ audio_duration = last_audio_time - first_audio_time
308
+ audio_secs = total_samples / 24000
309
+ stats.append(f"audio {audio_secs:.1f}s @ {total_samples/audio_duration:.0f} samples/s")
310
+
311
+ stats.append(f"total {total_time:.3f}s")
312
+ print(f"\n[{' | '.join(stats)}]")
313
+
314
+ return full_text, total_samples
315
+
316
+
317
+ def print_help():
318
+ """Print help information."""
319
+ print(
320
+ """
321
+ Commands:
322
+ /mode <asr|tts|interleaved> - Switch mode
323
+ /reset - Reset context (interleaved mode only)
324
+ /record - Record and transcribe/process audio
325
+ /wav <path> - Load and transcribe/process audio file
326
+ /help - Show this help
327
+ /quit or /exit - Exit the program
328
+
329
+ Modes:
330
+ ASR (single-shot):
331
+ - Use /record or /wav to transcribe audio
332
+ - Each request is independent
333
+
334
+ TTS (single-shot):
335
+ - Type text to synthesize audio
336
+ - Each request is independent
337
+
338
+ Interleaved (chat):
339
+ - Type text or use /record or /wav
340
+ - Context is maintained across requests
341
+ - Use /reset to start fresh
342
+ """
343
+ )
344
+
345
+
346
+ def main():
347
+ parser = argparse.ArgumentParser(description="Interactive LFM2.5-Audio chat client")
348
+ parser.add_argument(
349
+ "--base-url",
350
+ type=str,
351
+ default="http://127.0.0.1:8080/v1",
352
+ help="Server base URL",
353
+ )
354
+ parser.add_argument(
355
+ "--mode",
356
+ type=str,
357
+ choices=["asr", "tts", "interleaved"],
358
+ default="interleaved",
359
+ help="Initial mode",
360
+ )
361
+ parser.add_argument(
362
+ "--max-tokens",
363
+ type=int,
364
+ default=512,
365
+ help="Maximum tokens to generate",
366
+ )
367
+ parser.add_argument(
368
+ "--no-audio-playback",
369
+ action="store_true",
370
+ help="Disable audio playback (save to file instead)",
371
+ )
372
+ args = parser.parse_args()
373
+
374
+ client = OpenAI(base_url=args.base_url, api_key="dummy")
375
+ recorder = AudioRecorder()
376
+ mode = args.mode
377
+ wav_data = None
378
+ enable_playback = not args.no_audio_playback
379
+
380
+ # Check audio capabilities
381
+ audio_input_ok = recorder.available
382
+
383
+ # Track if first message in interleaved mode (need to send system prompt)
384
+ is_first_message = True
385
+
386
+ # Command history for prompt_toolkit
387
+ cmd_history = InMemoryHistory()
388
+
389
+ print("=" * 50)
390
+ print("LFM2.5-Audio Interactive Chat")
391
+ print("=" * 50)
392
+ print(f"Server: {args.base_url}")
393
+ print("Audio output: pyaudio")
394
+ print(f"Audio input: {'microphone' if audio_input_ok else 'file only (/wav)'}")
395
+ print("Type /help for commands")
396
+ print("=" * 50)
397
+ print(f"Mode: {mode}" + (" (single-shot)" if mode in ("asr", "tts") else " (chat)"))
398
+
399
+ while True:
400
+ try:
401
+ # Show prompt with mode indicator
402
+ mode_indicator = {"asr": "[ASR]", "tts": "[TTS]", "interleaved": "[INT]"}
403
+ audio_indicator = " [audio]" if wav_data else ""
404
+
405
+ prompt_str = f"{mode_indicator[mode]}{audio_indicator}> "
406
+ user_input = prompt(
407
+ prompt_str,
408
+ history=cmd_history,
409
+ auto_suggest=AutoSuggestFromHistory(),
410
+ ).strip()
411
+
412
+ if not user_input:
413
+ if mode == "asr" and wav_data:
414
+ # In ASR mode with audio, pressing Enter transcribes
415
+ pass
416
+ else:
417
+ continue
418
+
419
+ # Handle commands
420
+ if user_input.startswith("/"):
421
+ parts = user_input.split(maxsplit=1)
422
+ cmd = parts[0].lower()
423
+ arg = parts[1] if len(parts) > 1 else None
424
+
425
+ if cmd in ("/quit", "/exit"):
426
+ print("Goodbye!")
427
+ break
428
+
429
+ elif cmd == "/help":
430
+ print_help()
431
+ continue
432
+
433
+ elif cmd == "/mode":
434
+ if arg in ("asr", "tts", "interleaved"):
435
+ if arg != mode:
436
+ mode = arg
437
+ is_first_message = True
438
+ print(f"Mode: {mode}" + (" (single-shot)" if mode in ("asr", "tts") else " (chat)"))
439
+ else:
440
+ print(f"Already in {mode} mode")
441
+ else:
442
+ print("Usage: /mode <asr|tts|interleaved>")
443
+ continue
444
+
445
+ elif cmd == "/reset":
446
+ if mode != "interleaved":
447
+ print("Reset only available in interleaved mode")
448
+ continue
449
+ is_first_message = True
450
+ print("Context reset")
451
+ continue
452
+
453
+ elif cmd == "/record":
454
+ if mode == "tts":
455
+ print("Recording not available in TTS mode")
456
+ continue
457
+ samples = recorder.record()
458
+ if samples:
459
+ wav_data = recorder.to_wav_bytes()
460
+ # Start inference immediately
461
+ user_input = ""
462
+ else:
463
+ continue
464
+
465
+ elif cmd == "/wav":
466
+ if mode == "tts":
467
+ print("Audio input not available in TTS mode")
468
+ continue
469
+ if arg:
470
+ try:
471
+ with open(arg, "rb") as f:
472
+ wav_data = f.read()
473
+ # Start inference immediately
474
+ user_input = ""
475
+ except Exception as e:
476
+ print(f"Error loading file: {e}")
477
+ continue
478
+ else:
479
+ print("Usage: /wav <path>")
480
+ continue
481
+
482
+ else:
483
+ print(f"Unknown command: {cmd}")
484
+ continue
485
+
486
+ # Prepare request based on mode
487
+ text_input = user_input if user_input and not user_input.startswith("/") else None
488
+
489
+ if mode == "asr":
490
+ if not wav_data:
491
+ print("ASR mode requires audio. Use /record or /wav first.")
492
+ continue
493
+ text_input = None # ASR ignores text input
494
+ elif mode == "tts":
495
+ if not text_input:
496
+ print("TTS mode requires text input.")
497
+ continue
498
+ wav_data = None # TTS ignores audio input
499
+
500
+ # Create audio player if needed
501
+ audio_player = None
502
+ if enable_playback:
503
+ audio_player = AudioPlayer()
504
+ audio_player.start()
505
+
506
+ try:
507
+ print() # Blank line before response
508
+
509
+ if mode in ("asr", "tts"):
510
+ # Single-shot mode: system + one message, always reset
511
+ stream = create_stream_single_shot(
512
+ client, mode, text=text_input, wav_data=wav_data, max_tokens=args.max_tokens
513
+ )
514
+ else:
515
+ # Interleaved chat mode: only send new messages
516
+ messages = []
517
+
518
+ # First message needs system prompt and reset
519
+ if is_first_message:
520
+ messages.append({"role": "system", "content": SYSTEM_PROMPTS["interleaved"]})
521
+
522
+ # Add user message(s)
523
+ if text_input:
524
+ messages.append(create_text_message(text_input))
525
+ if wav_data:
526
+ messages.append(create_audio_message(wav_data))
527
+
528
+ stream = create_stream_chat(
529
+ client, messages, max_tokens=args.max_tokens, reset_context=is_first_message
530
+ )
531
+ is_first_message = False
532
+
533
+ response_text, _ = process_stream(stream, audio_player)
534
+
535
+ except Exception as e:
536
+ print(f"Error: {e}")
537
+
538
+ finally:
539
+ if audio_player:
540
+ audio_player.stop()
541
+
542
+ # Clear audio after use
543
+ if wav_data:
544
+ wav_data = None
545
+
546
+ except KeyboardInterrupt:
547
+ print("\nUse /quit to exit")
548
+ except EOFError:
549
+ print("\nGoodbye!")
550
+ break
551
+
552
+
553
+ if __name__ == "__main__":
554
+ main()