Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,143 +1,530 @@
|
|
1 |
-
import torch
|
2 |
-
import numpy as np
|
3 |
-
import gradio as gr
|
4 |
-
from PIL import Image
|
5 |
-
from omegaconf import OmegaConf
|
6 |
-
from pathlib import Path
|
7 |
-
from vocoder.bigvgan.models import VocoderBigVGAN
|
8 |
-
from ldm.models.diffusion.ddim import DDIMSampler
|
9 |
-
from ldm.util import instantiate_from_config
|
10 |
-
from wav_evaluation.models.CLAPWrapper import CLAPWrapper
|
11 |
-
|
12 |
-
SAMPLE_RATE = 16000
|
13 |
-
|
14 |
-
torch.set_grad_enabled(False)
|
15 |
-
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
16 |
-
|
17 |
-
|
18 |
-
def initialize_model(config, ckpt):
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
sampler = initialize_model('configs/text_to_audio/txt2audio_args.yaml', 'useful_ckpts/ta40multi_epoch=000085.ckpt')
|
32 |
-
vocoder = VocoderBigVGAN('vocoder/logs/bigv16k53w',device=device)
|
33 |
-
clap_model = CLAPWrapper('useful_ckpts/CLAP/CLAP_weights_2022.pth','useful_ckpts/CLAP/config.yml',use_cuda=torch.cuda.is_available())
|
34 |
-
|
35 |
-
def select_best_audio(prompt,wav_list):
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
def txt2audio(sampler,vocoder,prompt, seed, scale, ddim_steps, n_samples=1, W=624, H=80):
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
wav_list = []
|
70 |
-
for idx,spec in enumerate(x_samples_ddim):
|
71 |
-
wav = vocoder.vocode(spec)
|
72 |
-
wav_list.append((SAMPLE_RATE,wav))
|
73 |
-
best_wav = select_best_audio(prompt,wav_list)
|
74 |
-
return best_wav
|
75 |
-
|
76 |
-
|
77 |
-
def predict(prompt, ddim_steps, num_samples, scale, seed):# 经过试验,这个input_image需要是256x256、512x512的大小效果才正常,实际应该resize一下,输出再resize回去,但是他们使用的是pad,不知道为什么
|
78 |
-
melbins,mel_len = 80,624
|
79 |
-
with torch.no_grad():
|
80 |
-
result = txt2audio(
|
81 |
-
sampler=sampler,
|
82 |
-
vocoder=vocoder,
|
83 |
-
prompt=prompt,
|
84 |
-
seed=seed,
|
85 |
-
scale=scale,
|
86 |
-
ddim_steps=ddim_steps,
|
87 |
-
n_samples=num_samples,
|
88 |
-
H=melbins, W=mel_len
|
89 |
-
)
|
90 |
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import torch
|
2 |
+
# import numpy as np
|
3 |
+
# import gradio as gr
|
4 |
+
# from PIL import Image
|
5 |
+
# from omegaconf import OmegaConf
|
6 |
+
# from pathlib import Path
|
7 |
+
# from vocoder.bigvgan.models import VocoderBigVGAN
|
8 |
+
# from ldm.models.diffusion.ddim import DDIMSampler
|
9 |
+
# from ldm.util import instantiate_from_config
|
10 |
+
# from wav_evaluation.models.CLAPWrapper import CLAPWrapper
|
11 |
+
|
12 |
+
# SAMPLE_RATE = 16000
|
13 |
+
|
14 |
+
# torch.set_grad_enabled(False)
|
15 |
+
# device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
16 |
+
|
17 |
+
|
18 |
+
# def initialize_model(config, ckpt):
|
19 |
+
# config = OmegaConf.load(config)
|
20 |
+
# model = instantiate_from_config(config.model)
|
21 |
+
# model.load_state_dict(torch.load(ckpt,map_location='cpu')["state_dict"], strict=False)
|
22 |
+
|
23 |
+
# model = model.to(device)
|
24 |
+
# model.cond_stage_model.to(model.device)
|
25 |
+
# model.cond_stage_model.device = model.device
|
26 |
+
# print(model.device,device,model.cond_stage_model.device)
|
27 |
+
# sampler = DDIMSampler(model)
|
28 |
+
|
29 |
+
# return sampler
|
30 |
+
|
31 |
+
# sampler = initialize_model('configs/text_to_audio/txt2audio_args.yaml', 'useful_ckpts/ta40multi_epoch=000085.ckpt')
|
32 |
+
# vocoder = VocoderBigVGAN('vocoder/logs/bigv16k53w',device=device)
|
33 |
+
# clap_model = CLAPWrapper('useful_ckpts/CLAP/CLAP_weights_2022.pth','useful_ckpts/CLAP/config.yml',use_cuda=torch.cuda.is_available())
|
34 |
+
|
35 |
+
# def select_best_audio(prompt,wav_list):
|
36 |
+
# text_embeddings = clap_model.get_text_embeddings([prompt])
|
37 |
+
# score_list = []
|
38 |
+
# for data in wav_list:
|
39 |
+
# sr,wav = data
|
40 |
+
# audio_embeddings = clap_model.get_audio_embeddings([(torch.FloatTensor(wav),sr)], resample=True)
|
41 |
+
# score = clap_model.compute_similarity(audio_embeddings, text_embeddings,use_logit_scale=False).squeeze().cpu().numpy()
|
42 |
+
# score_list.append(score)
|
43 |
+
# max_index = np.array(score_list).argmax()
|
44 |
+
# print(score_list,max_index)
|
45 |
+
# return wav_list[max_index]
|
46 |
+
|
47 |
+
# def txt2audio(sampler,vocoder,prompt, seed, scale, ddim_steps, n_samples=1, W=624, H=80):
|
48 |
+
# prng = np.random.RandomState(seed)
|
49 |
+
# start_code = prng.randn(n_samples, sampler.model.first_stage_model.embed_dim, H // 8, W // 8)
|
50 |
+
# start_code = torch.from_numpy(start_code).to(device=device, dtype=torch.float32)
|
51 |
|
52 |
+
# uc = None
|
53 |
+
# if scale != 1.0:
|
54 |
+
# uc = sampler.model.get_learned_conditioning(n_samples * [""])
|
55 |
+
# c = sampler.model.get_learned_conditioning(n_samples * [prompt])# shape:[1,77,1280],即还没有变成句子embedding,仍是每个单词的embedding
|
56 |
+
# shape = [sampler.model.first_stage_model.embed_dim, H//8, W//8] # (z_dim, 80//2^x, 848//2^x)
|
57 |
+
# samples_ddim, _ = sampler.sample(S=ddim_steps,
|
58 |
+
# conditioning=c,
|
59 |
+
# batch_size=n_samples,
|
60 |
+
# shape=shape,
|
61 |
+
# verbose=False,
|
62 |
+
# unconditional_guidance_scale=scale,
|
63 |
+
# unconditional_conditioning=uc,
|
64 |
+
# x_T=start_code)
|
65 |
+
|
66 |
+
# x_samples_ddim = sampler.model.decode_first_stage(samples_ddim)
|
67 |
+
# x_samples_ddim = torch.clamp((x_samples_ddim+1.0)/2.0, min=0.0, max=1.0) # [0, 1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
+
# wav_list = []
|
70 |
+
# for idx,spec in enumerate(x_samples_ddim):
|
71 |
+
# wav = vocoder.vocode(spec)
|
72 |
+
# wav_list.append((SAMPLE_RATE,wav))
|
73 |
+
# best_wav = select_best_audio(prompt,wav_list)
|
74 |
+
# return best_wav
|
75 |
|
76 |
|
77 |
+
# def predict(prompt, ddim_steps, num_samples, scale, seed):# 经过试验,这个input_image需要是256x256、512x512的大小效果才正常,实际应该resize一下,输出再resize回去,但是他们使用的是pad,不知道为什么
|
78 |
+
# melbins,mel_len = 80,624
|
79 |
+
# with torch.no_grad():
|
80 |
+
# result = txt2audio(
|
81 |
+
# sampler=sampler,
|
82 |
+
# vocoder=vocoder,
|
83 |
+
# prompt=prompt,
|
84 |
+
# seed=seed,
|
85 |
+
# scale=scale,
|
86 |
+
# ddim_steps=ddim_steps,
|
87 |
+
# n_samples=num_samples,
|
88 |
+
# H=melbins, W=mel_len
|
89 |
+
# )
|
90 |
|
91 |
+
# return result
|
92 |
+
|
93 |
+
|
94 |
+
# with gr.Blocks() as demo:
|
95 |
+
# with gr.Row():
|
96 |
+
# gr.Markdown("## Make-An-Audio: Text-to-Audio Generation")
|
97 |
+
|
98 |
+
# with gr.Row():
|
99 |
+
# with gr.Column():
|
100 |
+
# prompt = gr.Textbox(label="Prompt: Input your text here. ")
|
101 |
+
# run_button = gr.Button(label="Run")
|
102 |
|
103 |
|
104 |
+
# with gr.Accordion("Advanced options", open=False):
|
105 |
+
# num_samples = gr.Slider(
|
106 |
+
# label="Select from audios num.This number control the number of candidates \
|
107 |
+
# (e.g., generate three audios and choose the best to show you). A Larger value usually lead to \
|
108 |
+
# better quality with heavier computation", minimum=1, maximum=10, value=3, step=1)
|
109 |
+
# # num_samples = 1
|
110 |
+
# ddim_steps = gr.Slider(label="Steps", minimum=1,
|
111 |
+
# maximum=150, value=100, step=1)
|
112 |
+
# scale = gr.Slider(
|
113 |
+
# label="Guidance Scale:(Large => more relevant to text but the quality may drop)", minimum=0.1, maximum=4.0, value=1.5, step=0.1
|
114 |
+
# )
|
115 |
+
# seed = gr.Slider(
|
116 |
+
# label="Seed:Change this value (any integer number) will lead to a different generation result.",
|
117 |
+
# minimum=0,
|
118 |
+
# maximum=2147483647,
|
119 |
+
# step=1,
|
120 |
+
# value=44,
|
121 |
+
# )
|
122 |
+
|
123 |
+
# with gr.Column():
|
124 |
+
# # audio_list = []
|
125 |
+
# # for i in range(int(num_samples)):
|
126 |
+
# # audio_list.append(gr.outputs.Audio())
|
127 |
+
# outaudio = gr.Audio()
|
128 |
+
|
129 |
+
|
130 |
+
# run_button.click(fn=predict, inputs=[
|
131 |
+
# prompt,ddim_steps, num_samples, scale, seed], outputs=[outaudio])# inputs的参数只能传gr.xxx
|
132 |
+
# with gr.Row():
|
133 |
+
# with gr.Column():
|
134 |
+
# gr.Examples(
|
135 |
+
# examples = [['a dog barking and a bird chirping',100,3,1.5,55],['fireworks pop and explode',100,3,1.5,55],
|
136 |
+
# ['piano and violin plays',100,3,1.5,55],['wind thunder and rain falling',100,3,1.5,55],['music made by drum kit',100,3,1.5,55]],
|
137 |
+
# inputs = [prompt,ddim_steps, num_samples, scale, seed],
|
138 |
+
# outputs = [outaudio]
|
139 |
+
# )
|
140 |
+
# with gr.Column():
|
141 |
+
# pass
|
142 |
+
|
143 |
+
# demo.launch()
|
144 |
+
from langchain.agents.initialize import initialize_agent
|
145 |
+
from langchain.agents.tools import Tool
|
146 |
+
from langchain.chains.conversation.memory import ConversationBufferMemory
|
147 |
+
from langchain.llms.openai import OpenAI
|
148 |
+
from audio_foundation_models import *
|
149 |
+
import gradio as gr
|
150 |
+
|
151 |
+
_DESCRIPTION = '# [AudioGPT](https://github.com/AIGC-Audio/AudioGPT)'
|
152 |
+
_DESCRIPTION += '\n<p>This is a demo to the work <a href="https://github.com/AIGC-Audio/AudioGPT" style="text-decoration: underline;" target="_blank">AudioGPT: Sending and Receiving Speech, Sing, Audio, and Talking head during chatting</a>. </p>'
|
153 |
+
_DESCRIPTION += '\n<p>This model can only be used for non-commercial purposes.'
|
154 |
+
if (SPACE_ID := os.getenv('SPACE_ID')) is not None:
|
155 |
+
_DESCRIPTION += f'\n<p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings. <a href="https://huggingface.co/spaces/{SPACE_ID}?duplicate=true"><img style="display: inline; margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space" /></a></p>'
|
156 |
+
|
157 |
+
|
158 |
+
AUDIO_CHATGPT_PREFIX = """AudioGPT
|
159 |
+
AudioGPT can not directly read audios, but it has a list of tools to finish different speech, audio, and singing voice tasks. Each audio will have a file name formed as "audio/xxx.wav". When talking about audios, AudioGPT is very strict to the file name and will never fabricate nonexistent files.
|
160 |
+
AudioGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the audio content and audio file name. It will remember to provide the file name from the last tool observation, if a new audio is generated.
|
161 |
+
Human may provide new audios to AudioGPT with a description. The description helps AudioGPT to understand this audio, but AudioGPT should use tools to finish following tasks, rather than directly imagine from the description.
|
162 |
+
Overall, AudioGPT is a powerful audio dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.
|
163 |
+
TOOLS:
|
164 |
+
------
|
165 |
+
AudioGPT has access to the following tools:"""
|
166 |
+
|
167 |
+
AUDIO_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
|
168 |
+
```
|
169 |
+
Thought: Do I need to use a tool? Yes
|
170 |
+
Action: the action to take, should be one of [{tool_names}]
|
171 |
+
Action Input: the input to the action
|
172 |
+
Observation: the result of the action
|
173 |
+
```
|
174 |
+
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
|
175 |
+
```
|
176 |
+
Thought: Do I need to use a tool? No
|
177 |
+
{ai_prefix}: [your response here]
|
178 |
+
```
|
179 |
+
"""
|
180 |
+
|
181 |
+
AUDIO_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if not exists.
|
182 |
+
You will remember to provide the audio file name loyally if it's provided in the last tool observation.
|
183 |
+
Begin!
|
184 |
+
Previous conversation history:
|
185 |
+
{chat_history}
|
186 |
+
New input: {input}
|
187 |
+
Thought: Do I need to use a tool? {agent_scratchpad}"""
|
188 |
+
|
189 |
+
def cut_dialogue_history(history_memory, keep_last_n_words = 500):
|
190 |
+
tokens = history_memory.split()
|
191 |
+
n_tokens = len(tokens)
|
192 |
+
print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")
|
193 |
+
if n_tokens < keep_last_n_words:
|
194 |
+
return history_memory
|
195 |
+
else:
|
196 |
+
paragraphs = history_memory.split('\n')
|
197 |
+
last_n_tokens = n_tokens
|
198 |
+
while last_n_tokens >= keep_last_n_words:
|
199 |
+
last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))
|
200 |
+
paragraphs = paragraphs[1:]
|
201 |
+
return '\n' + '\n'.join(paragraphs)
|
202 |
+
|
203 |
+
|
204 |
+
|
205 |
+
class ConversationBot:
|
206 |
+
def __init__(self, load_dict):
|
207 |
+
print("Initializing AudioGPT")
|
208 |
+
self.tools = []
|
209 |
+
self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
|
210 |
+
self.models = dict()
|
211 |
+
for class_name, device in load_dict.items():
|
212 |
+
self.models[class_name] = globals()[class_name](device=device)
|
213 |
+
|
214 |
+
def run_text(self, text, state):
|
215 |
+
print("===============Running run_text =============")
|
216 |
+
print("Inputs:", text, state)
|
217 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
218 |
+
self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
|
219 |
+
res = self.agent({"input": text})
|
220 |
+
if res['intermediate_steps'] == []:
|
221 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
222 |
+
response = res['output']
|
223 |
+
state = state + [(text, response)]
|
224 |
+
print("Outputs:", state)
|
225 |
+
return state, state, gr.Audio.update(visible=False), gr.Video.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
226 |
+
else:
|
227 |
+
tool = res['intermediate_steps'][0][0].tool
|
228 |
+
if tool == "Generate Image From User Input Text":
|
229 |
+
res['output'] = res['output'].replace("\\", "/")
|
230 |
+
response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])
|
231 |
+
state = state + [(text, response)]
|
232 |
+
print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"
|
233 |
+
f"Current Memory: {self.agent.memory.buffer}")
|
234 |
+
return state, state, gr.Audio.update(visible=False), gr.Video.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
235 |
+
elif tool == "Detect The Sound Event From The Audio":
|
236 |
+
image_filename = res['intermediate_steps'][0][1]
|
237 |
+
response = res['output'] + f"*{image_filename}*"
|
238 |
+
state = state + [(text, response)]
|
239 |
+
print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"
|
240 |
+
f"Current Memory: {self.agent.memory.buffer}")
|
241 |
+
return state, state, gr.Audio.update(visible=False), gr.Video.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
242 |
+
elif tool == "Generate Text From The Audio" or tool == "Transcribe speech" or tool == "Target Sound Detection":
|
243 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
244 |
+
response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])
|
245 |
+
image_filename = res['intermediate_steps'][0][1]
|
246 |
+
#response = res['output'] + f"*{image_filename}*"
|
247 |
+
state = state + [(text, response)]
|
248 |
+
print("Outputs:", state)
|
249 |
+
return state, state, gr.Audio.update(visible=False), gr.Video.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
250 |
+
elif tool == "Audio Inpainting":
|
251 |
+
audio_filename = res['intermediate_steps'][0][0].tool_input
|
252 |
+
image_filename = res['intermediate_steps'][0][1]
|
253 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
254 |
+
response = res['output']
|
255 |
+
state = state + [(text, response)]
|
256 |
+
print("Outputs:", state)
|
257 |
+
return state, state, gr.Audio.update(value=audio_filename,visible=True), gr.Video.update(visible=False), gr.Image.update(value=image_filename,visible=True), gr.Button.update(visible=True)
|
258 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
259 |
+
response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])
|
260 |
+
audio_filename = res['intermediate_steps'][0][1]
|
261 |
+
state = state + [(text, response)]
|
262 |
+
print("Outputs:", state)
|
263 |
+
return state, state, gr.Audio.update(value=audio_filename,visible=True), gr.Video.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
264 |
+
|
265 |
+
def run_image_or_audio(self, file, state, txt):
|
266 |
+
file_type = file.name[-3:]
|
267 |
+
if file_type == "wav":
|
268 |
+
print("===============Running run_audio =============")
|
269 |
+
print("Inputs:", file, state)
|
270 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
271 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
272 |
+
# audio_load = whisper.load_audio(file.name)
|
273 |
+
audio_load, sr = soundfile.read(file.name)
|
274 |
+
soundfile.write(audio_filename, audio_load, samplerate = sr)
|
275 |
+
description = self.models['A2T'].inference(audio_filename)
|
276 |
+
Human_prompt = "\nHuman: provide an audio named {}. The description is: {}. This information helps you to understand this audio, but you should use tools to finish following tasks, " \
|
277 |
+
"rather than directly imagine from my description. If you understand, say \"Received\". \n".format(audio_filename, description)
|
278 |
+
AI_prompt = "Received. "
|
279 |
+
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
|
280 |
+
# AI_prompt = "Received. "
|
281 |
+
# self.agent.memory.buffer = self.agent.memory.buffer + 'AI: ' + AI_prompt
|
282 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
283 |
+
#state = state + [(f"<audio src=audio_filename controls=controls></audio>*{audio_filename}*", AI_prompt)]
|
284 |
+
state = state + [(f"*{audio_filename}*", AI_prompt)]
|
285 |
+
print("Outputs:", state)
|
286 |
+
return state, state, gr.Audio.update(value=audio_filename,visible=True), gr.Video.update(visible=False)
|
287 |
+
else:
|
288 |
+
# print("===============Running run_image =============")
|
289 |
+
# print("Inputs:", file, state)
|
290 |
+
# print("======>Previous memory:\n %s" % self.agent.memory)
|
291 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
292 |
+
print("======>Auto Resize Image...")
|
293 |
+
img = Image.open(file.name)
|
294 |
+
width, height = img.size
|
295 |
+
ratio = min(512 / width, 512 / height)
|
296 |
+
width_new, height_new = (round(width * ratio), round(height * ratio))
|
297 |
+
width_new = int(np.round(width_new / 64.0)) * 64
|
298 |
+
height_new = int(np.round(height_new / 64.0)) * 64
|
299 |
+
img = img.resize((width_new, height_new))
|
300 |
+
img = img.convert('RGB')
|
301 |
+
img.save(image_filename, "PNG")
|
302 |
+
print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
|
303 |
+
description = self.models['ImageCaptioning'].inference(image_filename)
|
304 |
+
Human_prompt = "\nHuman: provide an audio named {}. The description is: {}. This information helps you to understand this audio, but you should use tools to finish following tasks, " \
|
305 |
+
"rather than directly imagine from my description. If you understand, say \"Received\". \n".format(image_filename, description)
|
306 |
+
AI_prompt = "Received. "
|
307 |
+
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
|
308 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
309 |
+
state = state + [(f"*{image_filename}*", AI_prompt)]
|
310 |
+
print(f"\nProcessed run_image, Input image: {image_filename}\nCurrent state: {state}\n"
|
311 |
+
f"Current Memory: {self.agent.memory.buffer}")
|
312 |
+
return state, state, gr.Audio.update(visible=False), gr.Video.update(visible=False)
|
313 |
+
|
314 |
+
def speech(self, speech_input, state):
|
315 |
+
input_audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
316 |
+
text = self.models['ASR'].translate_english(speech_input)
|
317 |
+
print("Inputs:", text, state)
|
318 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
319 |
+
self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
|
320 |
+
res = self.agent({"input": text})
|
321 |
+
if res['intermediate_steps'] == []:
|
322 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
323 |
+
response = res['output']
|
324 |
+
output_audio_filename = self.models['TTS'].inference(response)
|
325 |
+
state = state + [(text, response)]
|
326 |
+
print("Outputs:", state)
|
327 |
+
return gr.Audio.update(value=None), gr.Audio.update(value=output_audio_filename,visible=True), state, gr.Video.update(visible=False)
|
328 |
+
else:
|
329 |
+
tool = res['intermediate_steps'][0][0].tool
|
330 |
+
if tool == "Generate Image From User Input Text" or tool == "Generate Text From The Audio" or tool == "Target Sound Detection":
|
331 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
332 |
+
response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])
|
333 |
+
output_audio_filename = self.models['TTS'].inference(res['output'])
|
334 |
+
state = state + [(text, response)]
|
335 |
+
print("Outputs:", state)
|
336 |
+
return gr.Audio.update(value=None), gr.Audio.update(value=output_audio_filename,visible=True), state, gr.Video.update(visible=False)
|
337 |
+
elif tool == "Transcribe Speech":
|
338 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
339 |
+
output_audio_filename = self.models['TTS'].inference(res['output'])
|
340 |
+
response = res['output']
|
341 |
+
state = state + [(text, response)]
|
342 |
+
print("Outputs:", state)
|
343 |
+
return gr.Audio.update(value=None), gr.Audio.update(value=output_audio_filename,visible=True), state, gr.Video.update(visible=False)
|
344 |
+
elif tool == "Detect The Sound Event From The Audio":
|
345 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
346 |
+
image_filename = res['intermediate_steps'][0][1]
|
347 |
+
output_audio_filename = self.models['TTS'].inference(res['output'])
|
348 |
+
response = res['output'] + f"*{image_filename}*"
|
349 |
+
state = state + [(text, response)]
|
350 |
+
print("Outputs:", state)
|
351 |
+
return gr.Audio.update(value=None), gr.Audio.update(value=output_audio_filename,visible=True), state, gr.Video.update(visible=False)
|
352 |
+
elif tool == "Generate a talking human portrait video given a input Audio":
|
353 |
+
video_filename = res['intermediate_steps'][0][1]
|
354 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
355 |
+
response = res['output']
|
356 |
+
output_audio_filename = self.models['TTS'].inference(res['output'])
|
357 |
+
state = state + [(text, response)]
|
358 |
+
print("Outputs:", state)
|
359 |
+
return gr.Audio.update(value=None), gr.Audio.update(value=output_audio_filename,visible=True), state, gr.Video.update(value=video_filename,visible=True)
|
360 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
361 |
+
response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])
|
362 |
+
audio_filename = res['intermediate_steps'][0][1]
|
363 |
+
Res = "The audio file has been generated and the audio is "
|
364 |
+
output_audio_filename = merge_audio(self.models['TTS'].inference(Res), audio_filename)
|
365 |
+
print(output_audio_filename)
|
366 |
+
state = state + [(text, response)]
|
367 |
+
response = res['output']
|
368 |
+
print("Outputs:", state)
|
369 |
+
return gr.Audio.update(value=None), gr.Audio.update(value=output_audio_filename,visible=True), state, gr.Video.update(visible=False)
|
370 |
+
|
371 |
+
def inpainting(self, state, audio_filename, image_filename):
|
372 |
+
print("===============Running inpainting =============")
|
373 |
+
print("Inputs:", state)
|
374 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
375 |
+
new_image_filename, new_audio_filename = self.models['Inpaint'].predict(audio_filename, image_filename)
|
376 |
+
AI_prompt = "Here are the predict audio and the mel spectrum." + f"*{new_audio_filename}*" + f"*{new_image_filename}*"
|
377 |
+
self.agent.memory.buffer = self.agent.memory.buffer + 'AI: ' + AI_prompt
|
378 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
379 |
+
state = state + [(f"Audio Inpainting", AI_prompt)]
|
380 |
+
print("Outputs:", state)
|
381 |
+
return state, state, gr.Image.update(visible=False), gr.Audio.update(value=new_audio_filename, visible=True), gr.Button.update(visible=False)
|
382 |
+
def clear_audio(self):
|
383 |
+
return gr.Audio.update(value=None, visible=False)
|
384 |
+
def clear_input_audio(self):
|
385 |
+
return gr.Audio.update(value=None)
|
386 |
+
def clear_image(self):
|
387 |
+
return gr.Image.update(value=None, visible=False)
|
388 |
+
def clear_video(self):
|
389 |
+
return gr.Video.update(value=None, visible=False)
|
390 |
+
def clear_button(self):
|
391 |
+
return gr.Button.update(visible=False)
|
392 |
+
|
393 |
+
def init_agent(self, openai_api_key, interaction_type):
|
394 |
+
if interaction_type == "text":
|
395 |
+
for class_name, instance in self.models.items():
|
396 |
+
for e in dir(instance):
|
397 |
+
if e.startswith('inference'):
|
398 |
+
func = getattr(instance, e)
|
399 |
+
self.tools.append(Tool(name=func.name, description=func.description, func=func))
|
400 |
+
self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
|
401 |
+
self.agent = initialize_agent(
|
402 |
+
self.tools,
|
403 |
+
self.llm,
|
404 |
+
agent="conversational-react-description",
|
405 |
+
verbose=True,
|
406 |
+
memory=self.memory,
|
407 |
+
return_intermediate_steps=True,
|
408 |
+
agent_kwargs={'prefix': AUDIO_CHATGPT_PREFIX, 'format_instructions': AUDIO_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': AUDIO_CHATGPT_SUFFIX}, )
|
409 |
+
return gr.update(visible = False), gr.update(visible = True), gr.update(visible = True), gr.update(visible = False)
|
410 |
+
else:
|
411 |
+
for class_name, instance in self.models.items():
|
412 |
+
if class_name != 'T2A' and class_name != 'I2A' and class_name != 'Inpaint' and class_name != 'ASR' and class_name != 'SoundDetection' and class_name != 'Speech_Enh_SC' and class_name != 'Speech_SS':
|
413 |
+
for e in dir(instance):
|
414 |
+
if e.startswith('inference'):
|
415 |
+
func = getattr(instance, e)
|
416 |
+
self.tools.append(Tool(name=func.name, description=func.description, func=func))
|
417 |
+
|
418 |
+
self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
|
419 |
+
self.agent = initialize_agent(
|
420 |
+
self.tools,
|
421 |
+
self.llm,
|
422 |
+
agent="conversational-react-description",
|
423 |
+
verbose=True,
|
424 |
+
memory=self.memory,
|
425 |
+
return_intermediate_steps=True,
|
426 |
+
agent_kwargs={'prefix': AUDIO_CHATGPT_PREFIX, 'format_instructions': AUDIO_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': AUDIO_CHATGPT_SUFFIX}, )
|
427 |
+
return gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True)
|
428 |
+
|
429 |
+
|
430 |
+
|
431 |
+
if __name__ == '__main__':
|
432 |
+
bot = ConversationBot({'ImageCaptioning': 'cuda:0',
|
433 |
+
'T2A': 'cuda:0',
|
434 |
+
'I2A': 'cuda:0',
|
435 |
+
'TTS': 'cpu',
|
436 |
+
'T2S': 'cpu',
|
437 |
+
'ASR': 'cuda:0',
|
438 |
+
'A2T': 'cpu',
|
439 |
+
'Inpaint': 'cuda:0',
|
440 |
+
'SoundDetection': 'cpu',
|
441 |
+
'Binaural': 'cuda:0',
|
442 |
+
'SoundExtraction': 'cuda:0',
|
443 |
+
'TargetSoundDetection': 'cuda:0',
|
444 |
+
'Speech_Enh_SC': 'cuda:0',
|
445 |
+
'Speech_SS': 'cuda:0'
|
446 |
+
})
|
447 |
+
with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
|
448 |
+
with gr.Row():
|
449 |
+
gr.Markdown("## AudioGPT")
|
450 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="AudioGPT", visible=False)
|
451 |
+
state = gr.State([])
|
452 |
+
|
453 |
+
with gr.Row() as select_raws:
|
454 |
+
with gr.Column(scale=0.7):
|
455 |
+
interaction_type = gr.Radio(choices=['text', 'speech'], value='text', label='Interaction Type')
|
456 |
+
openai_api_key_textbox = gr.Textbox(
|
457 |
+
placeholder="Paste your OpenAI API key here to start AudioGPT(sk-...) and press Enter ↵️",
|
458 |
+
show_label=False,
|
459 |
+
lines=1,
|
460 |
+
type="password",
|
461 |
+
)
|
462 |
+
with gr.Row(visible=False) as text_input_raws:
|
463 |
+
with gr.Column(scale=0.7):
|
464 |
+
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)
|
465 |
+
with gr.Column(scale=0.1, min_width=0):
|
466 |
+
run = gr.Button("🏃♂️Run")
|
467 |
+
with gr.Column(scale=0.1, min_width=0):
|
468 |
+
clear_txt = gr.Button("🔄Clear️")
|
469 |
+
with gr.Column(scale=0.1, min_width=0):
|
470 |
+
btn = gr.UploadButton("🖼️Upload", file_types=["image","audio"])
|
471 |
+
|
472 |
+
with gr.Row():
|
473 |
+
outaudio = gr.Audio(visible=False)
|
474 |
+
with gr.Row():
|
475 |
+
with gr.Column(scale=0.3, min_width=0):
|
476 |
+
outvideo = gr.Video(visible=False)
|
477 |
+
with gr.Row():
|
478 |
+
show_mel = gr.Image(type="filepath",tool='sketch',visible=False)
|
479 |
+
with gr.Row():
|
480 |
+
run_button = gr.Button("Predict Masked Place",visible=False)
|
481 |
+
|
482 |
+
with gr.Row(visible=False) as speech_input_raws:
|
483 |
+
with gr.Column(scale=0.7):
|
484 |
+
speech_input = gr.Audio(source="microphone", type="filepath", label="Input")
|
485 |
+
with gr.Column(scale=0.15, min_width=0):
|
486 |
+
submit_btn = gr.Button("🏃♂️Submit")
|
487 |
+
with gr.Column(scale=0.15, min_width=0):
|
488 |
+
clear_speech = gr.Button("🔄Clear️")
|
489 |
+
with gr.Row():
|
490 |
+
speech_output = gr.Audio(label="Output",visible=False)
|
491 |
+
gr.Examples(
|
492 |
+
examples=["Generate a speech with text 'here we go'",
|
493 |
+
"Transcribe this speech",
|
494 |
+
"Transfer the mono speech to a binaural one",
|
495 |
+
"Generate an audio of a dog barking",
|
496 |
+
"Generate an audio of this uploaded image",
|
497 |
+
"Give me the description of this audio",
|
498 |
+
"I want to inpaint it",
|
499 |
+
"What events does this audio include?",
|
500 |
+
"When did the thunder happen in this audio?",
|
501 |
+
"Extract the thunder event from this audio",
|
502 |
+
"Generate a piece of singing voice. Text sequence is 小酒窝长睫毛AP是你最美的记号. Note sequence is C#4/Db4 | F#4/Gb4 | G#4/Ab4 | A#4/Bb4 F#4/Gb4 | F#4/Gb4 C#4/Db4 | C#4/Db4 | rest | C#4/Db4 | A#4/Bb4 | G#4/Ab4 | A#4/Bb4 | G#4/Ab4 | F4 | C#4/Db4. Note duration sequence is 0.407140 | 0.376190 | 0.242180 | 0.509550 0.183420 | 0.315400 0.235020 | 0.361660 | 0.223070 | 0.377270 | 0.340550 | 0.299620 | 0.344510 | 0.283770 | 0.323390 | 0.360340.",
|
503 |
+
],
|
504 |
+
inputs=txt
|
505 |
+
)
|
506 |
+
|
507 |
+
openai_api_key_textbox.submit(bot.init_agent, [openai_api_key_textbox, interaction_type], [select_raws, chatbot, text_input_raws, speech_input_raws])
|
508 |
+
|
509 |
+
txt.submit(bot.run_text, [txt, state], [chatbot, state, outaudio, outvideo, show_mel, run_button])
|
510 |
+
txt.submit(lambda: "", None, txt)
|
511 |
+
run.click(bot.run_text, [txt, state], [chatbot, state, outaudio, outvideo, show_mel, run_button])
|
512 |
+
run.click(lambda: "", None, txt)
|
513 |
+
btn.upload(bot.run_image_or_audio, [btn, state, txt], [chatbot, state, outaudio, outvideo])
|
514 |
+
run_button.click(bot.inpainting, [state, outaudio, show_mel], [chatbot, state, show_mel, outaudio, outvideo, run_button])
|
515 |
+
clear_txt.click(bot.memory.clear)
|
516 |
+
clear_txt.click(lambda: [], None, chatbot)
|
517 |
+
clear_txt.click(lambda: [], None, state)
|
518 |
+
clear_txt.click(lambda:None, None, txt)
|
519 |
+
clear_txt.click(bot.clear_button, None, run_button)
|
520 |
+
clear_txt.click(bot.clear_image, None, show_mel)
|
521 |
+
clear_txt.click(bot.clear_audio, None, outaudio)
|
522 |
+
clear_txt.click(bot.clear_video, None, outvideo)
|
523 |
+
|
524 |
+
submit_btn.click(bot.speech, [speech_input, state], [speech_input, speech_output, state, outvideo])
|
525 |
+
clear_speech.click(bot.clear_input_audio, None, speech_input)
|
526 |
+
clear_speech.click(bot.clear_audio, None, speech_output)
|
527 |
+
clear_speech.click(lambda: [], None, state)
|
528 |
+
clear_speech.click(bot.clear_video, None, outvideo)
|
529 |
+
|
530 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|