[Feature]Basic version of supporting streaming output (#367)
Signed-off-by: Gaohan123 <hgaoaf@connect.ust.hk>
This commit is contained in:
1 parent
c94ce4d85f
commit
9c7de5373a
41 files changed
+1567
-243
No files matched your search
@@ -57,13 +57,92 @@ bash run_curl_multimodal_generation.sh mixed_modalities
|
||||
```
|
||||
|
||||
## Modality control
|
||||
If you want to control output modalities, e.g. only output text, you can run the command below:
|
||||
You can control output modalities to specify which types of output the model should generate. This is useful when you only need text output and want to skip audio generation stages for better performance.
|
||||
|
||||
### Supported modalities
|
||||
|
||||
| Modalities | Output |
|
||||
|------------|--------|
|
||||
| `["text"]` | Text only |
|
||||
| `["audio"]` | Text + Audio |
|
||||
| `["text", "audio"]` | Text + Audio |
|
||||
| Not specified | Text + Audio (default) |
|
||||
|
||||
### Using curl
|
||||
|
||||
#### Text only
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen2.5-Omni-7B",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["text"]
|
||||
}'
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen2.5-Omni-7B",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["audio"]
|
||||
}'
|
||||
```
|
||||
|
||||
### Using Python client
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type mixed_modalities \
|
||||
--modalities text
|
||||
```
|
||||
|
||||
### Using OpenAI Python SDK
|
||||
|
||||
#### Text only
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen2.5-Omni-7B",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["text"]
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen2.5-Omni-7B",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["audio"]
|
||||
)
|
||||
# Response contains two choices: one with text, one with audio
|
||||
print(response.choices[0].message.content) # Text response
|
||||
print(response.choices[1].message.audio) # Audio response
|
||||
|
||||
## Streaming Output
|
||||
If you want to enable streaming output, please set the argument as below. The final output will be obtained just after generated by corresponding stage. Now we only support text streaming output. Other modalities can output normally.
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type mixed_modalities \
|
||||
--stream
|
||||
```
|
||||
|
||||
## Run Local Web UI Demo
|
||||
|
||||
This Web UI demo allows users to interact with the model through a web browser.
|
||||
|
||||
@@ -23,16 +23,18 @@ SUPPORTED_MODELS: dict[str, dict[str, Any]] = {
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"max_tokens": 2048,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1,
|
||||
},
|
||||
"talker": {
|
||||
"temperature": 0.0,
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"temperature": 0.9,
|
||||
"top_p": 0.8,
|
||||
"top_k": 40,
|
||||
"max_tokens": 2048,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1,
|
||||
"repetition_penalty": 1.05,
|
||||
"stop_token_ids": [8294],
|
||||
},
|
||||
"code2wav": {
|
||||
@@ -40,6 +42,7 @@ SUPPORTED_MODELS: dict[str, dict[str, Any]] = {
|
||||
"top_p": 1.0,
|
||||
"top_k": -1,
|
||||
"max_tokens": 2048,
|
||||
"seed": SEED,
|
||||
"detokenize": True,
|
||||
"repetition_penalty": 1.1,
|
||||
},
|
||||
@@ -241,10 +244,12 @@ def run_inference_api(
|
||||
video_file: str | None = None,
|
||||
use_audio_in_video: bool = False,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
"""Run inference using OpenAI API client with multimodal support."""
|
||||
if not user_prompt.strip() and not audio_file and not image_file and not video_file:
|
||||
return "Please provide at least a text prompt or multimodal input.", None
|
||||
yield "Please provide at least a text prompt or multimodal input.", None
|
||||
return
|
||||
|
||||
try:
|
||||
# Build message content list
|
||||
@@ -324,7 +329,7 @@ def run_inference_api(
|
||||
extra_body["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
|
||||
# Parse output modalities
|
||||
if output_modalities is not None:
|
||||
if output_modalities and output_modalities.strip():
|
||||
output_modalities_list = [m.strip() for m in output_modalities.split(",")]
|
||||
else:
|
||||
output_modalities_list = None
|
||||
@@ -335,29 +340,71 @@ def run_inference_api(
|
||||
model=model,
|
||||
modalities=output_modalities_list,
|
||||
extra_body=extra_body,
|
||||
stream=stream,
|
||||
)
|
||||
|
||||
# Extract outputs
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
if not stream:
|
||||
# Non-streaming mode: extract outputs and yield once
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
yield text_response, audio_output
|
||||
else:
|
||||
# Streaming mode: yield incremental updates
|
||||
text_content = ""
|
||||
audio_output = None
|
||||
|
||||
for chunk in chat_completion:
|
||||
for choice in chunk.choices:
|
||||
if hasattr(choice, "delta"):
|
||||
content = getattr(choice.delta, "content", None)
|
||||
else:
|
||||
content = None
|
||||
|
||||
# Handle audio modality
|
||||
if getattr(chunk, "modality", None) == "audio" and content:
|
||||
try:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(content)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
# Yield current text and audio
|
||||
yield text_content if text_content else "", audio_output
|
||||
except Exception: # pylint: disable=broad-except
|
||||
# If audio processing fails, just yield text
|
||||
yield text_content if text_content else "", None
|
||||
|
||||
# Handle text modality
|
||||
elif getattr(chunk, "modality", None) == "text":
|
||||
if content:
|
||||
text_content += content
|
||||
# Yield updated text content (keep existing audio if any)
|
||||
yield text_content, audio_output
|
||||
|
||||
# Final yield with accumulated text and last audio (if any)
|
||||
yield text_content if text_content else "No text output.", audio_output
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
return text_response, audio_output
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
return f"Inference failed: {exc}", None
|
||||
error_msg = f"Inference failed: {exc}"
|
||||
yield error_msg, None
|
||||
|
||||
|
||||
def build_interface(
|
||||
@@ -374,8 +421,10 @@ def build_interface(
|
||||
video_file: str | None,
|
||||
use_audio_in_video: bool,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
return run_inference_api(
|
||||
# Always yield from the API function to maintain consistent generator behavior
|
||||
yield from run_inference_api(
|
||||
client,
|
||||
model,
|
||||
sampling_params_dict,
|
||||
@@ -385,6 +434,7 @@ def build_interface(
|
||||
video_file,
|
||||
use_audio_in_video,
|
||||
output_modalities,
|
||||
stream,
|
||||
)
|
||||
|
||||
css = """
|
||||
@@ -455,8 +505,15 @@ def build_interface(
|
||||
with gr.Row():
|
||||
output_modalities = gr.Textbox(
|
||||
label="Output Modalities",
|
||||
value=None,
|
||||
placeholder="For example: text, image, video. Use comma to separate multiple modalities.",
|
||||
lines=1,
|
||||
scale=2,
|
||||
)
|
||||
stream_checkbox = gr.Checkbox(
|
||||
label="Stream output",
|
||||
value=False,
|
||||
info="Enable streaming to see output as it's generated.",
|
||||
scale=1,
|
||||
)
|
||||
|
||||
@@ -474,7 +531,15 @@ def build_interface(
|
||||
|
||||
generate_btn.click(
|
||||
fn=run_inference,
|
||||
inputs=[input_box, audio_input, image_input, video_input, use_audio_in_video_checkbox, output_modalities],
|
||||
inputs=[
|
||||
input_box,
|
||||
audio_input,
|
||||
image_input,
|
||||
video_input,
|
||||
use_audio_in_video_checkbox,
|
||||
output_modalities,
|
||||
stream_checkbox,
|
||||
],
|
||||
outputs=[text_output, audio_output],
|
||||
)
|
||||
demo.queue()
|
||||
|
||||
+39
-10
@@ -354,19 +354,43 @@ def run_multimodal_generation(args) -> None:
|
||||
model=model_name,
|
||||
modalities=output_modalities,
|
||||
extra_body=extra_body,
|
||||
stream=args.stream,
|
||||
)
|
||||
|
||||
count = 0
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
with open(audio_file_path, "wb") as f:
|
||||
f.write(audio_data)
|
||||
print(f"Audio saved to {audio_file_path}")
|
||||
count += 1
|
||||
elif choice.message.content:
|
||||
print("Chat completion output from text:", choice.message.content)
|
||||
if not args.stream:
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
with open(audio_file_path, "wb") as f:
|
||||
f.write(audio_data)
|
||||
print(f"Audio saved to {audio_file_path}")
|
||||
count += 1
|
||||
elif choice.message.content:
|
||||
print("Chat completion output from text:", choice.message.content)
|
||||
else:
|
||||
printed_content = False
|
||||
for chunk in chat_completion:
|
||||
for choice in chunk.choices:
|
||||
if hasattr(choice, "delta"):
|
||||
content = getattr(choice.delta, "content", None)
|
||||
else:
|
||||
content = None
|
||||
|
||||
if getattr(chunk, "modality", None) == "audio" and content:
|
||||
audio_data = base64.b64decode(content)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
with open(audio_file_path, "wb") as f:
|
||||
f.write(audio_data)
|
||||
print(f"\nAudio saved to {audio_file_path}")
|
||||
count += 1
|
||||
|
||||
elif getattr(chunk, "modality", None) == "text":
|
||||
if not printed_content:
|
||||
printed_content = True
|
||||
print("\ncontent:", end="", flush=True)
|
||||
print(content, end="", flush=True)
|
||||
|
||||
|
||||
def parse_args():
|
||||
@@ -413,6 +437,11 @@ def parse_args():
|
||||
default=None,
|
||||
help="Output modalities to use for the prompts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--stream",
|
||||
action="store_true",
|
||||
help="Stream the response.",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
@@ -65,13 +65,92 @@ sudo apt install ffmpeg
|
||||
```
|
||||
|
||||
## Modality control
|
||||
If you want to control output modalities, e.g. only output text, you can run the command below:
|
||||
You can control output modalities to specify which types of output the model should generate. This is useful when you only need text output and want to skip audio generation stages for better performance.
|
||||
|
||||
### Supported modalities
|
||||
|
||||
| Modalities | Output |
|
||||
|------------|--------|
|
||||
| `["text"]` | Text only |
|
||||
| `["audio"]` | Text + Audio |
|
||||
| `["text", "audio"]` | Text + Audio |
|
||||
| Not specified | Text + Audio (default) |
|
||||
|
||||
### Using curl
|
||||
|
||||
#### Text only
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["text"]
|
||||
}'
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```bash
|
||||
curl http://localhost:8091/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
"messages": [{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
"modalities": ["audio"]
|
||||
}'
|
||||
```
|
||||
|
||||
### Using Python client
|
||||
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type use_image \
|
||||
--modalities text
|
||||
```
|
||||
|
||||
### Using OpenAI Python SDK
|
||||
|
||||
#### Text only
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["text"]
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
```
|
||||
|
||||
#### Text + Audio
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI(base_url="http://localhost:8091/v1", api_key="EMPTY")
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="Qwen/Qwen3-Omni-30B-A3B-Instruct",
|
||||
messages=[{"role": "user", "content": "Describe vLLM in brief."}],
|
||||
modalities=["audio"]
|
||||
)
|
||||
# Response contains two choices: one with text, one with audio
|
||||
print(response.choices[0].message.content) # Text response
|
||||
print(response.choices[1].message.audio) # Audio response
|
||||
|
||||
## Streaming Output
|
||||
If you want to enable streaming output, please set the argument as below. The final output will be obtained just after generated by corresponding stage. Now we only support text streaming output. Other modalities can output normally.
|
||||
```bash
|
||||
python openai_chat_completion_client_for_multimodal_generation.py \
|
||||
--query-type use_image \
|
||||
--stream
|
||||
```
|
||||
|
||||
## Run Local Web UI Demo
|
||||
|
||||
This Web UI demo allows users to interact with the model through a web browser.
|
||||
|
||||
@@ -244,10 +244,11 @@ def run_inference_api(
|
||||
video_file: str | None = None,
|
||||
use_audio_in_video: bool = False,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
"""Run inference using OpenAI API client with multimodal support."""
|
||||
if not user_prompt.strip() and not audio_file and not image_file and not video_file:
|
||||
return "Please provide at least a text prompt or multimodal input.", None
|
||||
yield "Please provide at least a text prompt or multimodal input.", None
|
||||
|
||||
try:
|
||||
# Build message content list
|
||||
@@ -327,7 +328,7 @@ def run_inference_api(
|
||||
extra_body["mm_processor_kwargs"] = mm_processor_kwargs
|
||||
|
||||
# Parse output modalities
|
||||
if output_modalities is not None:
|
||||
if output_modalities and output_modalities.strip():
|
||||
output_modalities_list = [m.strip() for m in output_modalities.split(",")]
|
||||
else:
|
||||
output_modalities_list = None
|
||||
@@ -338,29 +339,71 @@ def run_inference_api(
|
||||
model=model,
|
||||
modalities=output_modalities_list,
|
||||
extra_body=extra_body,
|
||||
stream=stream,
|
||||
)
|
||||
|
||||
# Extract outputs
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
if not stream:
|
||||
# Non-streaming mode: extract outputs and yield once
|
||||
text_outputs: list[str] = []
|
||||
audio_output = None
|
||||
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.content:
|
||||
text_outputs.append(choice.message.content)
|
||||
if choice.message.audio:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
yield text_response, audio_output
|
||||
else:
|
||||
# Streaming mode: yield incremental updates
|
||||
text_content = ""
|
||||
audio_output = None
|
||||
|
||||
for chunk in chat_completion:
|
||||
for choice in chunk.choices:
|
||||
if hasattr(choice, "delta"):
|
||||
content = getattr(choice.delta, "content", None)
|
||||
else:
|
||||
content = None
|
||||
|
||||
# Handle audio modality
|
||||
if getattr(chunk, "modality", None) == "audio" and content:
|
||||
try:
|
||||
# Decode base64 audio
|
||||
audio_data = base64.b64decode(content)
|
||||
# Load audio from bytes
|
||||
audio_np, sample_rate = sf.read(io.BytesIO(audio_data))
|
||||
# Convert to mono if needed
|
||||
if audio_np.ndim > 1:
|
||||
audio_np = audio_np[:, 0]
|
||||
audio_output = (int(sample_rate), audio_np.astype(np.float32))
|
||||
# Yield current text and audio
|
||||
yield text_content if text_content else "", audio_output
|
||||
except Exception: # pylint: disable=broad-except
|
||||
# If audio processing fails, just yield text
|
||||
yield text_content if text_content else "", None
|
||||
|
||||
# Handle text modality
|
||||
elif getattr(chunk, "modality", None) == "text":
|
||||
if content:
|
||||
text_content += content
|
||||
# Yield updated text content (keep existing audio if any)
|
||||
yield text_content, audio_output
|
||||
|
||||
# Final yield with accumulated text and last audio (if any)
|
||||
yield text_content if text_content else "No text output.", audio_output
|
||||
|
||||
text_response = "\n\n".join(text_outputs) if text_outputs else "No text output."
|
||||
return text_response, audio_output
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
return f"Inference failed: {exc}", None
|
||||
error_msg = f"Inference failed: {exc}"
|
||||
yield error_msg, None
|
||||
|
||||
|
||||
def build_interface(
|
||||
@@ -377,8 +420,10 @@ def build_interface(
|
||||
video_file: str | None,
|
||||
use_audio_in_video: bool,
|
||||
output_modalities: str | None = None,
|
||||
stream: bool = False,
|
||||
):
|
||||
return run_inference_api(
|
||||
# Always yield from the API function to maintain consistent generator behavior
|
||||
yield from run_inference_api(
|
||||
client,
|
||||
model,
|
||||
sampling_params_dict,
|
||||
@@ -388,6 +433,7 @@ def build_interface(
|
||||
video_file,
|
||||
use_audio_in_video,
|
||||
output_modalities,
|
||||
stream,
|
||||
)
|
||||
|
||||
css = """
|
||||
@@ -458,8 +504,15 @@ def build_interface(
|
||||
with gr.Row():
|
||||
output_modalities = gr.Textbox(
|
||||
label="Output Modalities",
|
||||
value=None,
|
||||
placeholder="For example: text, image, video. Use comma to separate multiple modalities.",
|
||||
lines=1,
|
||||
scale=2,
|
||||
)
|
||||
stream_checkbox = gr.Checkbox(
|
||||
label="Stream output",
|
||||
value=False,
|
||||
info="Enable streaming to see output as it's generated.",
|
||||
scale=1,
|
||||
)
|
||||
|
||||
@@ -477,7 +530,15 @@ def build_interface(
|
||||
|
||||
generate_btn.click(
|
||||
fn=run_inference,
|
||||
inputs=[input_box, audio_input, image_input, video_input, use_audio_in_video_checkbox, output_modalities],
|
||||
inputs=[
|
||||
input_box,
|
||||
audio_input,
|
||||
image_input,
|
||||
video_input,
|
||||
use_audio_in_video_checkbox,
|
||||
output_modalities,
|
||||
stream_checkbox,
|
||||
],
|
||||
outputs=[text_output, audio_output],
|
||||
)
|
||||
demo.queue()
|
||||
|
||||
+39
-10
@@ -395,19 +395,43 @@ def run_multimodal_generation(args) -> None:
|
||||
model=model_name,
|
||||
modalities=output_modalities,
|
||||
extra_body=extra_body,
|
||||
stream=args.stream,
|
||||
)
|
||||
|
||||
count = 0
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
with open(audio_file_path, "wb") as f:
|
||||
f.write(audio_data)
|
||||
print(f"Audio saved to {audio_file_path}")
|
||||
count += 1
|
||||
elif choice.message.content:
|
||||
print("Chat completion output from text:", choice.message.content)
|
||||
if not args.stream:
|
||||
for choice in chat_completion.choices:
|
||||
if choice.message.audio:
|
||||
audio_data = base64.b64decode(choice.message.audio.data)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
with open(audio_file_path, "wb") as f:
|
||||
f.write(audio_data)
|
||||
print(f"Audio saved to {audio_file_path}")
|
||||
count += 1
|
||||
elif choice.message.content:
|
||||
print("Chat completion output from text:", choice.message.content)
|
||||
else:
|
||||
printed_content = False
|
||||
for chunk in chat_completion:
|
||||
for choice in chunk.choices:
|
||||
if hasattr(choice, "delta"):
|
||||
content = getattr(choice.delta, "content", None)
|
||||
else:
|
||||
content = None
|
||||
|
||||
if getattr(chunk, "modality", None) == "audio" and content:
|
||||
audio_data = base64.b64decode(content)
|
||||
audio_file_path = f"audio_{count}.wav"
|
||||
with open(audio_file_path, "wb") as f:
|
||||
f.write(audio_data)
|
||||
print(f"\nAudio saved to {audio_file_path}")
|
||||
count += 1
|
||||
|
||||
elif getattr(chunk, "modality", None) == "text":
|
||||
if not printed_content:
|
||||
printed_content = True
|
||||
print("\ncontent:", end="", flush=True)
|
||||
print(content, end="", flush=True)
|
||||
|
||||
|
||||
def parse_args():
|
||||
@@ -461,6 +485,11 @@ def parse_args():
|
||||
default=None,
|
||||
help="Output modalities to use for the prompts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--stream",
|
||||
action="store_true",
|
||||
help="Stream the response.",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
Reference in new issue
Block a user