Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,102 +1,157 @@
|
|
1 |
-
from transformers import MllamaForConditionalGeneration, AutoProcessor, TextIteratorStreamer
|
2 |
-
from PIL import Image
|
3 |
-
import requests
|
4 |
-
import torch
|
5 |
-
from threading import Thread
|
6 |
import gradio as gr
|
7 |
-
from gradio import FileData
|
8 |
-
import time
|
9 |
import spaces
|
|
|
|
|
10 |
import os
|
|
|
|
|
11 |
token=os.environ.get("key_")
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
|
|
|
|
|
|
|
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
@spaces.GPU
|
19 |
-
def
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
elif isinstance(history[i-1][0], str) and isinstance(msg[0], str): # text only turn
|
37 |
-
messages.append({"role": "user", "content": [{"type": "text", "text": msg[0]}]})
|
38 |
-
messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
|
39 |
-
|
40 |
-
# add current message
|
41 |
-
if len(message["files"]) == 1:
|
42 |
-
|
43 |
-
if isinstance(message["files"][0], str): # examples
|
44 |
-
image = Image.open(message["files"][0]).convert("RGB")
|
45 |
-
else: # regular input
|
46 |
-
image = Image.open(message["files"][0]["path"]).convert("RGB")
|
47 |
-
images.append(image)
|
48 |
-
messages.append({"role": "user", "content": [{"type": "text", "text": txt}, {"type": "image"}]})
|
49 |
-
else:
|
50 |
-
messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
|
51 |
-
|
52 |
-
|
53 |
-
texts = processor.apply_chat_template(messages, add_generation_prompt=True)
|
54 |
-
|
55 |
-
if images == []:
|
56 |
-
inputs = processor(text=texts, return_tensors="pt").to("cuda")
|
57 |
-
else:
|
58 |
-
inputs = processor(text=texts, images=images, return_tensors="pt").to("cuda")
|
59 |
-
streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
|
60 |
-
|
61 |
-
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
|
62 |
-
generated_text = ""
|
63 |
-
|
64 |
-
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
65 |
-
thread.start()
|
66 |
-
buffer = ""
|
67 |
-
|
68 |
-
for new_text in streamer:
|
69 |
-
buffer += new_text
|
70 |
-
generated_text_without_prompt = buffer
|
71 |
-
time.sleep(0.01)
|
72 |
-
yield buffer
|
73 |
-
|
74 |
-
|
75 |
-
demo = gr.ChatInterface(fn=bot_streaming, title="Multimodal Llama", examples=[
|
76 |
-
[{"text": "Which era does this piece belong to? Give details about the era.", "files":["./examples/rococo.jpg"]},
|
77 |
-
200],
|
78 |
-
[{"text": "Where do the droughts happen according to this diagram?", "files":["./examples/weather_events.png"]},
|
79 |
-
250],
|
80 |
-
[{"text": "What happens when you take out white cat from this chain?", "files":["./examples/ai2d_test.jpg"]},
|
81 |
-
250],
|
82 |
-
[{"text": "How long does it take from invoice date to due date? Be short and concise.", "files":["./examples/invoice.png"]},
|
83 |
-
250],
|
84 |
-
[{"text": "Where to find this monument? Can you give me other recommendations around the area?", "files":["./examples/wat_arun.jpg"]},
|
85 |
-
250],
|
86 |
-
],
|
87 |
-
textbox=gr.MultimodalTextbox(),
|
88 |
-
additional_inputs = [gr.Slider(
|
89 |
-
minimum=10,
|
90 |
-
maximum=500,
|
91 |
-
value=250,
|
92 |
-
step=10,
|
93 |
-
label="Maximum number of new tokens to generate",
|
94 |
-
)
|
95 |
-
],
|
96 |
-
cache_examples=False,
|
97 |
-
description="Try Multimodal Llama by Meta with transformers in this demo. Upload an image, and start chatting about it, or simply try one of the examples below. To learn more about Llama Vision, visit [our blog post](https://huggingface.co/blog/llama32). ",
|
98 |
-
stop_btn="Stop Generation",
|
99 |
-
fill_height=True,
|
100 |
-
multimodal=True)
|
101 |
|
102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
import spaces
|
3 |
+
import torch
|
4 |
+
from transformers import AutoTokenizer,VitsModel
|
5 |
import os
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
token=os.environ.get("key_")
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained("wasmdashai/vtk",token=token)
|
10 |
+
models= {}
|
11 |
+
|
12 |
+
import noisereduce as nr
|
13 |
+
|
14 |
+
import torch
|
15 |
+
from typing import Any, Callable, Optional, Tuple, Union,Iterator
|
16 |
+
|
17 |
+
import torch.nn as nn # Import the missing module
|
18 |
+
def remove_noise_nr(audio_data,sr=16000):
|
19 |
+
reduced_noise = nr.reduce_noise(y=audio_data,hop_length=256, sr=sr)
|
20 |
+
return reduced_noise
|
21 |
+
|
22 |
+
def _inference_forward_stream(
|
23 |
+
self,
|
24 |
+
input_ids: Optional[torch.Tensor] = None,
|
25 |
+
attention_mask: Optional[torch.Tensor] = None,
|
26 |
+
speaker_embeddings: Optional[torch.Tensor] = None,
|
27 |
+
output_attentions: Optional[bool] = None,
|
28 |
+
output_hidden_states: Optional[bool] = None,
|
29 |
+
return_dict: Optional[bool] = None,
|
30 |
+
padding_mask: Optional[torch.Tensor] = None,
|
31 |
+
chunk_size: int = 32, # Chunk size for streaming output
|
32 |
+
is_streaming: bool = True,
|
33 |
+
) -> Iterator[torch.Tensor]:
|
34 |
+
"""Generates speech waveforms in a streaming fashion."""
|
35 |
+
if attention_mask is not None:
|
36 |
+
padding_mask = attention_mask.unsqueeze(-1).float()
|
37 |
+
else:
|
38 |
+
padding_mask = torch.ones_like(input_ids).unsqueeze(-1).float()
|
39 |
+
|
40 |
+
|
41 |
+
|
42 |
+
text_encoder_output = self.text_encoder(
|
43 |
+
input_ids=input_ids,
|
44 |
+
padding_mask=padding_mask,
|
45 |
+
attention_mask=attention_mask,
|
46 |
+
output_attentions=output_attentions,
|
47 |
+
output_hidden_states=output_hidden_states,
|
48 |
+
return_dict=return_dict,
|
49 |
+
)
|
50 |
+
hidden_states = text_encoder_output[0] if not return_dict else text_encoder_output.last_hidden_state
|
51 |
+
hidden_states = hidden_states.transpose(1, 2)
|
52 |
+
input_padding_mask = padding_mask.transpose(1, 2)
|
53 |
+
|
54 |
+
prior_means = text_encoder_output[1] if not return_dict else text_encoder_output.prior_means
|
55 |
+
prior_log_variances = text_encoder_output[2] if not return_dict else text_encoder_output.prior_log_variances
|
56 |
+
|
57 |
+
if self.config.use_stochastic_duration_prediction:
|
58 |
+
log_duration = self.duration_predictor(
|
59 |
+
hidden_states,
|
60 |
+
input_padding_mask,
|
61 |
+
speaker_embeddings,
|
62 |
+
reverse=True,
|
63 |
+
noise_scale=self.noise_scale_duration,
|
64 |
+
)
|
65 |
+
else:
|
66 |
+
log_duration = self.duration_predictor(hidden_states, input_padding_mask, speaker_embeddings)
|
67 |
+
|
68 |
+
length_scale = 1.0 / self.speaking_rate
|
69 |
+
duration = torch.ceil(torch.exp(log_duration) * input_padding_mask * length_scale)
|
70 |
+
predicted_lengths = torch.clamp_min(torch.sum(duration, [1, 2]), 1).long()
|
71 |
+
|
72 |
|
73 |
+
# Create a padding mask for the output lengths of shape (batch, 1, max_output_length)
|
74 |
+
indices = torch.arange(predicted_lengths.max(), dtype=predicted_lengths.dtype, device=predicted_lengths.device)
|
75 |
+
output_padding_mask = indices.unsqueeze(0) < predicted_lengths.unsqueeze(1)
|
76 |
+
output_padding_mask = output_padding_mask.unsqueeze(1).to(input_padding_mask.dtype)
|
77 |
|
78 |
+
# Reconstruct an attention tensor of shape (batch, 1, out_length, in_length)
|
79 |
+
attn_mask = torch.unsqueeze(input_padding_mask, 2) * torch.unsqueeze(output_padding_mask, -1)
|
80 |
+
batch_size, _, output_length, input_length = attn_mask.shape
|
81 |
+
cum_duration = torch.cumsum(duration, -1).view(batch_size * input_length, 1)
|
82 |
+
indices = torch.arange(output_length, dtype=duration.dtype, device=duration.device)
|
83 |
+
valid_indices = indices.unsqueeze(0) < cum_duration
|
84 |
+
valid_indices = valid_indices.to(attn_mask.dtype).view(batch_size, input_length, output_length)
|
85 |
+
padded_indices = valid_indices - nn.functional.pad(valid_indices, [0, 0, 1, 0, 0, 0])[:, :-1]
|
86 |
+
attn = padded_indices.unsqueeze(1).transpose(2, 3) * attn_mask
|
87 |
+
|
88 |
+
# Expand prior distribution
|
89 |
+
prior_means = torch.matmul(attn.squeeze(1), prior_means).transpose(1, 2)
|
90 |
+
prior_log_variances = torch.matmul(attn.squeeze(1), prior_log_variances).transpose(1, 2)
|
91 |
+
|
92 |
+
prior_latents = prior_means + torch.randn_like(prior_means) * torch.exp(prior_log_variances) * self.noise_scale
|
93 |
+
latents = self.flow(prior_latents, output_padding_mask, speaker_embeddings, reverse=True)
|
94 |
+
|
95 |
+
spectrogram = latents * output_padding_mask
|
96 |
+
if is_streaming:
|
97 |
+
|
98 |
+
for i in range(0, spectrogram.size(-1), chunk_size):
|
99 |
+
with torch.no_grad():
|
100 |
+
wav=self.decoder(spectrogram[:,:,i : i + chunk_size] ,speaker_embeddings)
|
101 |
+
yield wav.squeeze().cpu().numpy()
|
102 |
+
else:
|
103 |
+
|
104 |
+
wav=self.decoder(spectrogram,speaker_embeddings)
|
105 |
+
yield wav.squeeze().cpu().numpy()
|
106 |
@spaces.GPU
|
107 |
+
def get_model(name_model):
|
108 |
+
global models
|
109 |
+
if name_model in models:
|
110 |
+
return models[name_model]
|
111 |
+
models[name_model]=VitsModel.from_pretrained(name_model,token=token).cuda()
|
112 |
+
models[name_model].decoder.apply_weight_norm()
|
113 |
+
# torch.nn.utils.weight_norm(self.decoder.conv_pre)
|
114 |
+
# torch.nn.utils.weight_norm(self.decoder.conv_post)
|
115 |
+
for flow in models[name_model].flow.flows:
|
116 |
+
torch.nn.utils.weight_norm(flow.conv_pre)
|
117 |
+
torch.nn.utils.weight_norm(flow.conv_post)
|
118 |
+
return models[name_model]
|
119 |
|
120 |
+
|
121 |
+
zero = torch.Tensor([0]).cuda()
|
122 |
+
print(zero.device) # <-- 'cpu' 🤔
|
123 |
+
import torch
|
124 |
+
TXT="""السلام عليكم ورحمة الله وبركاتة يا هلا وسهلا ومراحب بالغالي اخباركم طيبين ان شاء الله ارحبوا على العين والراس """
|
125 |
+
@spaces.GPU
|
126 |
+
def modelspeech(text=TXT,name_model="wasmdashai/vits-ar-sa-huba-v2",speaking_rate=16000):
|
127 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
+
inputs = tokenizer(text, return_tensors="pt")
|
130 |
+
model=get_model(name_model)
|
131 |
+
model.speaking_rate=speaking_rate
|
132 |
+
with torch.no_grad():
|
133 |
+
wav=list(_inference_forward_stream(model,input_ids=inputs.input_ids.cuda(),attention_mask=inputs.attention_mask.cuda(),speaker_embeddings= None,is_streaming=False))[0]
|
134 |
+
# with torch.no_grad():
|
135 |
+
# wav = model(input_ids=inputs["input_ids"].cuda()).waveform.cpu().numpy().reshape(-1)#.detach()
|
136 |
+
|
137 |
+
return (model.config.sampling_rate,wav)
|
138 |
+
|
139 |
+
model_choices = gr.Dropdown(
|
140 |
+
choices=[
|
141 |
+
|
142 |
+
"wasmdashai/vits-ar-sa-huba-v1",
|
143 |
+
"wasmdashai/vits-ar-sa-huba-v2",
|
144 |
+
|
145 |
+
"wasmdashai/vits-ar-sa-A",
|
146 |
+
"wasmdashai/vits-ar-ye-sa",
|
147 |
+
"wasmdashai/vits-ar-sa-M-v1"
|
148 |
+
|
149 |
+
|
150 |
+
],
|
151 |
+
label="اختر النموذج",
|
152 |
+
value="wasmdashai/vits-ar-sa-huba-v2",
|
153 |
+
)
|
154 |
+
|
155 |
+
demo = gr.Interface(fn=modelspeech, inputs=["text",model_choices,gr.Slider(0.1, 1, step=0.1,value=0.8)], outputs=["audio"])
|
156 |
+
demo.queue()
|
157 |
+
demo.launch()
|