Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,16 +5,14 @@ import gradio as gr
|
|
| 5 |
from threading import Thread
|
| 6 |
from PIL import Image
|
| 7 |
import subprocess
|
| 8 |
-
import spaces
|
| 9 |
-
from parler_tts import ParlerTTSForConditionalGeneration
|
| 10 |
-
import soundfile as sf
|
| 11 |
|
| 12 |
# Install flash-attention
|
| 13 |
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
| 14 |
|
| 15 |
# Constants
|
| 16 |
-
TITLE = "<h1><center>Phi 3.5 Multimodal (Text + Vision
|
| 17 |
-
DESCRIPTION = "# Phi-3.5 Multimodal Demo (Text + Vision
|
| 18 |
|
| 19 |
# Model configurations
|
| 20 |
TEXT_MODEL_ID = "microsoft/Phi-3.5-mini-instruct"
|
|
@@ -48,11 +46,6 @@ vision_model = AutoModelForCausalLM.from_pretrained(
|
|
| 48 |
|
| 49 |
vision_processor = AutoProcessor.from_pretrained(VISION_MODEL_ID, trust_remote_code=True)
|
| 50 |
|
| 51 |
-
# Load Parler-TTS model
|
| 52 |
-
tts_device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 53 |
-
tts_model = ParlerTTSForConditionalGeneration.from_pretrained("parler-tts/parler-tts-large-v1").to(tts_device)
|
| 54 |
-
tts_tokenizer = AutoTokenizer.from_pretrained("parler-tts/parler-tts-large-v1")
|
| 55 |
-
|
| 56 |
# Helper functions
|
| 57 |
@spaces.GPU
|
| 58 |
def stream_text_chat(message, history, system_prompt, temperature=0.8, max_new_tokens=1024, top_p=1.0, top_k=20):
|
|
@@ -85,64 +78,24 @@ def stream_text_chat(message, history, system_prompt, temperature=0.8, max_new_t
|
|
| 85 |
buffer = ""
|
| 86 |
for new_text in streamer:
|
| 87 |
buffer += new_text
|
| 88 |
-
yield history + [[message, buffer]]
|
| 89 |
-
|
| 90 |
-
# Generate speech for the final response
|
| 91 |
-
audio_path = generate_speech(buffer, "A clear and concise voice reads out the response.")
|
| 92 |
-
yield history + [[message, buffer]], audio_path
|
| 93 |
|
| 94 |
-
@spaces.GPU
|
| 95 |
-
def process_vision_query(image, text_input
|
| 96 |
prompt = f"<|user|>\n<|image_1|>\n{text_input}<|end|>\n<|assistant|>\n"
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
# Check if image is already a PIL Image
|
| 99 |
-
if isinstance(image, Image.Image):
|
| 100 |
-
pil_image = image
|
| 101 |
-
elif isinstance(image, np.ndarray):
|
| 102 |
-
pil_image = Image.fromarray(image).convert("RGB")
|
| 103 |
-
else:
|
| 104 |
-
raise ValueError("Unsupported image type. Expected PIL Image or numpy array.")
|
| 105 |
-
|
| 106 |
-
inputs = vision_processor(prompt, pil_image, return_tensors="pt").to(device)
|
| 107 |
-
|
| 108 |
-
try:
|
| 109 |
-
with torch.no_grad():
|
| 110 |
-
generate_ids = vision_model.generate(
|
| 111 |
-
**inputs,
|
| 112 |
-
max_new_tokens=1000,
|
| 113 |
-
eos_token_id=vision_processor.tokenizer.eos_token_id
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
|
| 117 |
-
response = vision_processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 118 |
-
|
| 119 |
-
if generate_speech:
|
| 120 |
-
audio_path = generate_speech_from_text(response)
|
| 121 |
-
return response, audio_path
|
| 122 |
-
else:
|
| 123 |
-
return response, None
|
| 124 |
-
except RuntimeError as e:
|
| 125 |
-
if "CUDA out of memory" in str(e):
|
| 126 |
-
error_message = "Error: GPU out of memory. Try processing a smaller image or freeing up GPU resources."
|
| 127 |
-
return error_message, None
|
| 128 |
-
else:
|
| 129 |
-
raise e
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
def generate_speech_from_text(text, description="A clear voice reads out the response."):
|
| 133 |
-
input_ids = tts_tokenizer(description, return_tensors="pt").input_ids.to(tts_device)
|
| 134 |
-
prompt_input_ids = tts_tokenizer(text, return_tensors="pt").input_ids.to(tts_device)
|
| 135 |
-
|
| 136 |
with torch.no_grad():
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
sf.write(output_path, audio_arr, tts_model.config.sampling_rate)
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
# Custom CSS
|
| 148 |
custom_css = """
|
|
@@ -165,7 +118,7 @@ footer { text-align: center; margin-top: 2rem; color: #64748b;}
|
|
| 165 |
custom_header = """
|
| 166 |
<div id="custom-header">
|
| 167 |
<h1><span class="blue">Phi 3.5</span> <span class="pink">Multimodal Assistant</span></h1>
|
| 168 |
-
<h2>Text
|
| 169 |
</div>
|
| 170 |
"""
|
| 171 |
|
|
@@ -181,8 +134,8 @@ custom_suggestions = """
|
|
| 181 |
<p>Analyze Images with Vision Model</p>
|
| 182 |
</div>
|
| 183 |
<div class="suggestion">
|
| 184 |
-
<span class="suggestion-icon"
|
| 185 |
-
<p>
|
| 186 |
</div>
|
| 187 |
<div class="suggestion">
|
| 188 |
<span class="suggestion-icon">🔍</span>
|
|
@@ -216,45 +169,22 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Base().set(
|
|
| 216 |
|
| 217 |
submit_btn = gr.Button("Submit", variant="primary")
|
| 218 |
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
| 219 |
-
audio_output = gr.Audio(label="AI Response Audio")
|
| 220 |
|
| 221 |
-
submit_btn.click(stream_text_chat,
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
with gr.Tab("Vision Model with TTS (Phi-3.5-vision)"):
|
| 227 |
with gr.Row():
|
| 228 |
-
|
| 229 |
with gr.Column(scale=1):
|
| 230 |
-
|
| 231 |
vision_input_img = gr.Image(label="Upload an Image", type="pil")
|
| 232 |
vision_text_input = gr.Textbox(label="Ask a question about the image", placeholder="What do you see in this image?")
|
| 233 |
-
vision_submit_btn = gr.Button("Analyze Image
|
| 234 |
with gr.Column(scale=1):
|
| 235 |
vision_output_text = gr.Textbox(label="AI Analysis", lines=10)
|
| 236 |
-
vision_output_audio = gr.Audio(label="Generated Speech")
|
| 237 |
-
|
| 238 |
-
vision_submit_btn.click(process_vision_query,
|
| 239 |
-
inputs=[vision_input_img, vision_text_input],
|
| 240 |
-
outputs=[vision_output_text, vision_output_audio])
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
with gr.Tab("Text-to-Speech (Parler-TTS)"):
|
| 246 |
-
with gr.Row():
|
| 247 |
-
|
| 248 |
-
with gr.Column(scale=1):
|
| 249 |
-
tts_prompt = gr.Textbox(label="Text to Speak", placeholder="Enter the text you want to convert to speech...")
|
| 250 |
-
tts_description = gr.Textbox(label="Voice Description", value="A female speaker delivers a slightly expressive and animated speech with a moderate speed and pitch. The recording is of very high quality, with the speaker's voice sounding clear and very close up.", lines=3)
|
| 251 |
-
tts_submit_btn = gr.Button("Generate Speech", variant="primary")
|
| 252 |
-
with gr.Column(scale=1):
|
| 253 |
-
tts_output_audio = gr.Audio(label="Generated Speech")
|
| 254 |
|
| 255 |
-
|
| 256 |
|
| 257 |
-
gr.HTML("<footer>Powered by Phi 3.5 Multimodal AI
|
| 258 |
|
| 259 |
if __name__ == "__main__":
|
| 260 |
demo.launch()
|
|
|
|
| 5 |
from threading import Thread
|
| 6 |
from PIL import Image
|
| 7 |
import subprocess
|
| 8 |
+
import spaces # Add this import
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# Install flash-attention
|
| 11 |
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
| 12 |
|
| 13 |
# Constants
|
| 14 |
+
TITLE = "<h1><center>Phi 3.5 Multimodal (Text + Vision)</center></h1>"
|
| 15 |
+
DESCRIPTION = "# Phi-3.5 Multimodal Demo (Text + Vision)"
|
| 16 |
|
| 17 |
# Model configurations
|
| 18 |
TEXT_MODEL_ID = "microsoft/Phi-3.5-mini-instruct"
|
|
|
|
| 46 |
|
| 47 |
vision_processor = AutoProcessor.from_pretrained(VISION_MODEL_ID, trust_remote_code=True)
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
# Helper functions
|
| 50 |
@spaces.GPU
|
| 51 |
def stream_text_chat(message, history, system_prompt, temperature=0.8, max_new_tokens=1024, top_p=1.0, top_k=20):
|
|
|
|
| 78 |
buffer = ""
|
| 79 |
for new_text in streamer:
|
| 80 |
buffer += new_text
|
| 81 |
+
yield history + [[message, buffer]]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
@spaces.GPU # Add this decorator
|
| 84 |
+
def process_vision_query(image, text_input):
|
| 85 |
prompt = f"<|user|>\n<|image_1|>\n{text_input}<|end|>\n<|assistant|>\n"
|
| 86 |
+
image = Image.fromarray(image).convert("RGB")
|
| 87 |
+
inputs = vision_processor(prompt, image, return_tensors="pt").to(device)
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
with torch.no_grad():
|
| 90 |
+
generate_ids = vision_model.generate(
|
| 91 |
+
**inputs,
|
| 92 |
+
max_new_tokens=1000,
|
| 93 |
+
eos_token_id=vision_processor.tokenizer.eos_token_id
|
| 94 |
+
)
|
|
|
|
| 95 |
|
| 96 |
+
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
|
| 97 |
+
response = vision_processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 98 |
+
return response
|
| 99 |
|
| 100 |
# Custom CSS
|
| 101 |
custom_css = """
|
|
|
|
| 118 |
custom_header = """
|
| 119 |
<div id="custom-header">
|
| 120 |
<h1><span class="blue">Phi 3.5</span> <span class="pink">Multimodal Assistant</span></h1>
|
| 121 |
+
<h2>Text and Vision AI at Your Service</h2>
|
| 122 |
</div>
|
| 123 |
"""
|
| 124 |
|
|
|
|
| 134 |
<p>Analyze Images with Vision Model</p>
|
| 135 |
</div>
|
| 136 |
<div class="suggestion">
|
| 137 |
+
<span class="suggestion-icon">🤖</span>
|
| 138 |
+
<p>Get AI-generated responses</p>
|
| 139 |
</div>
|
| 140 |
<div class="suggestion">
|
| 141 |
<span class="suggestion-icon">🔍</span>
|
|
|
|
| 169 |
|
| 170 |
submit_btn = gr.Button("Submit", variant="primary")
|
| 171 |
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
|
|
|
| 172 |
|
| 173 |
+
submit_btn.click(stream_text_chat, [msg, chatbot, system_prompt, temperature, max_new_tokens, top_p, top_k], [chatbot])
|
| 174 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
| 175 |
+
|
| 176 |
+
with gr.Tab("Vision Model (Phi-3.5-vision)"):
|
|
|
|
|
|
|
| 177 |
with gr.Row():
|
|
|
|
| 178 |
with gr.Column(scale=1):
|
|
|
|
| 179 |
vision_input_img = gr.Image(label="Upload an Image", type="pil")
|
| 180 |
vision_text_input = gr.Textbox(label="Ask a question about the image", placeholder="What do you see in this image?")
|
| 181 |
+
vision_submit_btn = gr.Button("Analyze Image", variant="primary")
|
| 182 |
with gr.Column(scale=1):
|
| 183 |
vision_output_text = gr.Textbox(label="AI Analysis", lines=10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
vision_submit_btn.click(process_vision_query, [vision_input_img, vision_text_input], [vision_output_text])
|
| 186 |
|
| 187 |
+
gr.HTML("<footer>Powered by Phi 3.5 Multimodal AI</footer>")
|
| 188 |
|
| 189 |
if __name__ == "__main__":
|
| 190 |
demo.launch()
|