Spaces:
Build error
Build error
Upload 2 files
Browse files- app.py +245 -0
- audio_foundation_models.py +444 -0
app.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.agents.initialize import initialize_agent
|
2 |
+
from langchain.agents.tools import Tool
|
3 |
+
from langchain.chains.conversation.memory import ConversationBufferMemory
|
4 |
+
from langchain.llms.openai import OpenAI
|
5 |
+
from audio_foundation_models import *
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
AUDIO_CHATGPT_PREFIX = """Audio ChatGPT
|
9 |
+
AUdio ChatGPT can not directly read audios, but it has a list of tools to finish different audio synthesis tasks. Each audio will have a file name formed as "audio/xxx.wav". When talking about audios, Audio ChatGPT is very strict to the file name and will never fabricate nonexistent files.
|
10 |
+
AUdio ChatGPT 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.
|
11 |
+
Human may provide Audio ChatGPT with a description. Audio ChatGPT should generate audios according to this description rather than directly imagine from memory or yourself."
|
12 |
+
TOOLS:
|
13 |
+
------
|
14 |
+
Audio ChatGPT has access to the following tools:"""
|
15 |
+
|
16 |
+
AUDIO_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
|
17 |
+
```
|
18 |
+
Thought: Do I need to use a tool? Yes
|
19 |
+
Action: the action to take, should be one of [{tool_names}]
|
20 |
+
Action Input: the input to the action
|
21 |
+
Observation: the result of the action
|
22 |
+
```
|
23 |
+
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:
|
24 |
+
```
|
25 |
+
Thought: Do I need to use a tool? No
|
26 |
+
{ai_prefix}: [your response here]
|
27 |
+
```
|
28 |
+
"""
|
29 |
+
|
30 |
+
AUDIO_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if not exists.
|
31 |
+
You will remember to provide the audio file name loyally if it's provided in the last tool observation.
|
32 |
+
Begin!
|
33 |
+
Previous conversation history:
|
34 |
+
{chat_history}
|
35 |
+
New input: {input}
|
36 |
+
Thought: Do I need to use a tool? {agent_scratchpad}"""
|
37 |
+
|
38 |
+
def cut_dialogue_history(history_memory, keep_last_n_words = 500):
|
39 |
+
tokens = history_memory.split()
|
40 |
+
n_tokens = len(tokens)
|
41 |
+
print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")
|
42 |
+
if n_tokens < keep_last_n_words:
|
43 |
+
return history_memory
|
44 |
+
else:
|
45 |
+
paragraphs = history_memory.split('\n')
|
46 |
+
last_n_tokens = n_tokens
|
47 |
+
while last_n_tokens >= keep_last_n_words:
|
48 |
+
last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))
|
49 |
+
paragraphs = paragraphs[1:]
|
50 |
+
return '\n' + '\n'.join(paragraphs)
|
51 |
+
|
52 |
+
class ConversationBot:
|
53 |
+
def __init__(self):
|
54 |
+
print("Initializing AudioChatGPT")
|
55 |
+
self.llm = OpenAI(temperature=0)
|
56 |
+
self.t2i = T2I(device="cuda:0")
|
57 |
+
self.i2t = ImageCaptioning(device="cuda:1")
|
58 |
+
self.t2a = T2A(device="cuda:0")
|
59 |
+
self.tts = TTS(device="cuda:0")
|
60 |
+
self.t2s = T2S(device="cuda:2")
|
61 |
+
self.i2a = I2A(device="cuda:1")
|
62 |
+
self.a2t = A2T(device="cuda:2")
|
63 |
+
self.asr = ASR(device="cuda:1")
|
64 |
+
self.inpaint = Inpaint(device="cuda:0")
|
65 |
+
#self.tts_ood = TTS_OOD(device="cuda:0")
|
66 |
+
self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
|
67 |
+
self.tools = [
|
68 |
+
Tool(name="Generate Image From User Input Text", func=self.t2i.inference,
|
69 |
+
description="useful for when you want to generate an image from a user input text and it saved it to a file. like: generate an image of an object or something, or generate an image that includes some objects. "
|
70 |
+
"The input to this tool should be a string, representing the text used to generate image. "),
|
71 |
+
Tool(name="Get Photo Description", func=self.i2t.inference,
|
72 |
+
description="useful for when you want to know what is inside the photo. receives image_path as input. "
|
73 |
+
"The input to this tool should be a string, representing the image_path. "),
|
74 |
+
Tool(name="Generate Audio From User Input Text", func=self.t2a.inference,
|
75 |
+
description="useful for when you want to generate an audio from a user input text and it saved it to a file."
|
76 |
+
"The input to this tool should be a string, representing the text used to generate audio."),
|
77 |
+
# Tool(
|
78 |
+
# name="Generate human speech with style derived from a speech reference and user input text and save it to a file", func= self.tts_ood.inference,
|
79 |
+
# description="useful for when you want to generate speech samples with styles (e.g., timbre, emotion, and prosody) derived from a reference custom voice."
|
80 |
+
# "Like: Generate a speech with style transferred from this voice. The text is xxx., or speak using the voice of this audio. The text is xxx."
|
81 |
+
# "The input to this tool should be a comma seperated string of two, representing reference audio path and input text."),
|
82 |
+
Tool(name="Generate singing voice From User Input Text, Note and Duration Sequence", func= self.t2s.inference,
|
83 |
+
description="useful for when you want to generate a piece of singing voice (Optional: from User Input Text, Note and Duration Sequence) and save it to a file."
|
84 |
+
"If Like: Generate a piece of singing voice, the input to this tool should be \"\" since there is no User Input Text, Note and Duration Sequence ."
|
85 |
+
"If Like: Generate a piece of singing voice. Text: xxx, Note: xxx, Duration: xxx. "
|
86 |
+
"Or Like: Generate a piece of singing voice. Text is xxx, note is xxx, duration is xxx."
|
87 |
+
"The input to this tool should be a comma seperated string of three, representing text, note and duration sequence since User Input Text, Note and Duration Sequence are all provided."),
|
88 |
+
Tool(name="Synthesize Speech Given the User Input Text", func=self.tts.inference,
|
89 |
+
description="useful for when you want to convert a user input text into speech audio it saved it to a file."
|
90 |
+
"The input to this tool should be a string, representing the text used to be converted to speech."),
|
91 |
+
Tool(name="Generate Audio From The Image", func=self.i2a.inference,
|
92 |
+
description="useful for when you want to generate an audio based on an image."
|
93 |
+
"The input to this tool should be a string, representing the image_path. "),
|
94 |
+
Tool(name="Generate Text From The Audio", func=self.a2t.inference,
|
95 |
+
description="useful for when you want to describe an audio in text, receives audio_path as input."
|
96 |
+
"The input to this tool should be a string, representing the audio_path."),
|
97 |
+
Tool(name="Audio Inpainting", func=self.inpaint.show_mel_fn,
|
98 |
+
description="useful for when you want to inpaint a mel spectrum of an audio and predict this audio, this tool will generate a mel spectrum and you can inpaint it, receives audio_path as input, "
|
99 |
+
"The input to this tool should be a string, representing the audio_path."),
|
100 |
+
Tool(name="Transcribe speech", func=self.asr.inference,
|
101 |
+
description="useful for when you want to know the text corresponding to a human speech, receives audio_path as input."
|
102 |
+
"The input to this tool should be a string, representing the audio_path.")]
|
103 |
+
self.agent = initialize_agent(
|
104 |
+
self.tools,
|
105 |
+
self.llm,
|
106 |
+
agent="conversational-react-description",
|
107 |
+
verbose=True,
|
108 |
+
memory=self.memory,
|
109 |
+
return_intermediate_steps=True,
|
110 |
+
agent_kwargs={'prefix': AUDIO_CHATGPT_PREFIX, 'format_instructions': AUDIO_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': AUDIO_CHATGPT_SUFFIX}, )
|
111 |
+
|
112 |
+
def run_text(self, text, state):
|
113 |
+
print("===============Running run_text =============")
|
114 |
+
print("Inputs:", text, state)
|
115 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
116 |
+
self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
|
117 |
+
res = self.agent({"input": text})
|
118 |
+
if res['intermediate_steps'] == []:
|
119 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
120 |
+
response = res['output']
|
121 |
+
state = state + [(text, response)]
|
122 |
+
print("Outputs:", state)
|
123 |
+
return state, state, gr.Audio.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
124 |
+
else:
|
125 |
+
tool = res['intermediate_steps'][0][0].tool
|
126 |
+
if tool == "Generate Image From User Input Text" or tool == "Generate Text From The Audio" or tool == "Transcribe speech":
|
127 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
128 |
+
response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
|
129 |
+
state = state + [(text, response)]
|
130 |
+
print("Outputs:", state)
|
131 |
+
return state, state, gr.Audio.update(visible=False), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
132 |
+
elif tool == "Audio Inpainting":
|
133 |
+
audio_filename = res['intermediate_steps'][0][0].tool_input
|
134 |
+
image_filename = res['intermediate_steps'][0][1]
|
135 |
+
# self.is_visible(True)
|
136 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
137 |
+
print(res)
|
138 |
+
response = res['output']
|
139 |
+
state = state + [(text, response)]
|
140 |
+
print("Outputs:", state)
|
141 |
+
return state, state, gr.Audio.update(value=audio_filename,visible=True), gr.Image.update(value=image_filename,visible=True), gr.Button.update(visible=True)
|
142 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
143 |
+
response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
|
144 |
+
audio_filename = res['intermediate_steps'][0][1]
|
145 |
+
state = state + [(text, response)]
|
146 |
+
print("Outputs:", state)
|
147 |
+
return state, state, gr.Audio.update(value=audio_filename,visible=True), gr.Image.update(visible=False), gr.Button.update(visible=False)
|
148 |
+
|
149 |
+
def run_image_or_audio(self, file, state, txt):
|
150 |
+
file_type = file.name[-3:]
|
151 |
+
if file_type == "wav":
|
152 |
+
print("===============Running run_audio =============")
|
153 |
+
print("Inputs:", file, state)
|
154 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
155 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
156 |
+
audio_load = whisper.load_audio(file.name)
|
157 |
+
soundfile.write(audio_filename, audio_load, samplerate = 16000)
|
158 |
+
description = self.a2t.inference(audio_filename)
|
159 |
+
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, " \
|
160 |
+
"rather than directly imagine from my description. If you understand, say \"Received\". \n".format(audio_filename, description)
|
161 |
+
AI_prompt = "Received. "
|
162 |
+
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
|
163 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
164 |
+
#state = state + [(f"<audio src=audio_filename controls=controls></audio>*{audio_filename}*", AI_prompt)]
|
165 |
+
state = state + [(f"*{audio_filename}*", AI_prompt)]
|
166 |
+
print("Outputs:", state)
|
167 |
+
return state, state, txt + ' ' + audio_filename + ' ', gr.Audio.update(value=audio_filename,visible=True)
|
168 |
+
else:
|
169 |
+
print("===============Running run_image =============")
|
170 |
+
print("Inputs:", file, state)
|
171 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
172 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
173 |
+
print("======>Auto Resize Image...")
|
174 |
+
img = Image.open(file.name)
|
175 |
+
width, height = img.size
|
176 |
+
ratio = min(512 / width, 512 / height)
|
177 |
+
width_new, height_new = (round(width * ratio), round(height * ratio))
|
178 |
+
img = img.resize((width_new, height_new))
|
179 |
+
img = img.convert('RGB')
|
180 |
+
img.save(image_filename, "PNG")
|
181 |
+
print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
|
182 |
+
description = self.i2t.inference(image_filename)
|
183 |
+
Human_prompt = "\nHuman: provide a figure named {}. The description is: {}. This information helps you to understand this image, but you should use tools to finish following tasks, " \
|
184 |
+
"rather than directly imagine from my description. If you understand, say \"Received\". \n".format(image_filename, description)
|
185 |
+
AI_prompt = "Received. "
|
186 |
+
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
|
187 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
188 |
+
state = state + [(f"![](/file={image_filename})*{image_filename}*", AI_prompt)]
|
189 |
+
print("Outputs:", state)
|
190 |
+
return state, state, txt + ' ' + image_filename + ' ', gr.Audio.update(visible=False)
|
191 |
+
|
192 |
+
def inpainting(self, state, audio_filename, image_filename):
|
193 |
+
print("===============Running inpainting =============")
|
194 |
+
print("Inputs:", state)
|
195 |
+
print("======>Previous memory:\n %s" % self.agent.memory)
|
196 |
+
inpaint = Inpaint(device="cuda:0")
|
197 |
+
new_image_filename, new_audio_filename = inpaint.inference(audio_filename, image_filename)
|
198 |
+
AI_prompt = "Here are the predict audio and the mel spectrum." + f"*{new_audio_filename}*" + f"![](/file={new_image_filename})*{new_image_filename}*"
|
199 |
+
self.agent.memory.buffer = self.agent.memory.buffer + 'AI: ' + AI_prompt
|
200 |
+
print("======>Current memory:\n %s" % self.agent.memory)
|
201 |
+
state = state + [(f"Audio Inpainting", AI_prompt)]
|
202 |
+
print("Outputs:", state)
|
203 |
+
return state, state, gr.Image.update(visible=False), gr.Audio.update(value=new_audio_filename, visible=True), gr.Button.update(visible=False)
|
204 |
+
def clear_audio(self):
|
205 |
+
return gr.Audio.update(value=None, visible=False)
|
206 |
+
def clear_image(self):
|
207 |
+
return gr.Image.update(value=None, visible=False)
|
208 |
+
def clear_button(self):
|
209 |
+
return gr.Button.update(visible=False)
|
210 |
+
|
211 |
+
|
212 |
+
if __name__ == '__main__':
|
213 |
+
bot = ConversationBot()
|
214 |
+
with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
|
215 |
+
with gr.Row():
|
216 |
+
gr.Markdown("## Audio ChatGPT")
|
217 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="Audio ChatGPT")
|
218 |
+
state = gr.State([])
|
219 |
+
with gr.Row():
|
220 |
+
with gr.Column(scale=0.7):
|
221 |
+
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)
|
222 |
+
with gr.Column(scale=0.15, min_width=0):
|
223 |
+
clear = gr.Button("Clear️")
|
224 |
+
with gr.Column(scale=0.15, min_width=0):
|
225 |
+
btn = gr.UploadButton("Upload", file_types=["image","audio"])
|
226 |
+
with gr.Column():
|
227 |
+
outaudio = gr.Audio(visible=False)
|
228 |
+
with gr.Row():
|
229 |
+
with gr.Column():
|
230 |
+
show_mel = gr.Image(type="filepath",tool='sketch',visible=False)
|
231 |
+
run_button = gr.Button("Predict Masked Place",visible=False)
|
232 |
+
|
233 |
+
|
234 |
+
txt.submit(bot.run_text, [txt, state], [chatbot, state, outaudio, show_mel, run_button])
|
235 |
+
txt.submit(lambda: "", None, txt)
|
236 |
+
btn.upload(bot.run_image_or_audio, [btn, state, txt], [chatbot, state, txt, outaudio])
|
237 |
+
run_button.click(bot.inpainting, [state, outaudio, show_mel], [chatbot, state, show_mel, outaudio, run_button])
|
238 |
+
clear.click(bot.memory.clear)
|
239 |
+
clear.click(lambda: [], None, chatbot)
|
240 |
+
clear.click(lambda: [], None, state)
|
241 |
+
clear.click(lambda:None, None, txt)
|
242 |
+
clear.click(bot.clear_button, None, run_button)
|
243 |
+
clear.click(bot.clear_image, None, show_mel)
|
244 |
+
clear.click(bot.clear_audio, None, outaudio)
|
245 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
audio_foundation_models.py
ADDED
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
|
4 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
|
5 |
+
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'text_to_sing/DiffSinger'))
|
6 |
+
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'text_to_audio/Make_An_Audio'))
|
7 |
+
import matplotlib
|
8 |
+
import librosa
|
9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation
|
10 |
+
import torch
|
11 |
+
from diffusers import StableDiffusionPipeline
|
12 |
+
from diffusers import StableDiffusionInstructPix2PixPipeline, EulerAncestralDiscreteScheduler
|
13 |
+
import re
|
14 |
+
import uuid
|
15 |
+
import soundfile
|
16 |
+
from diffusers import StableDiffusionInpaintPipeline
|
17 |
+
from PIL import Image
|
18 |
+
import numpy as np
|
19 |
+
from omegaconf import OmegaConf
|
20 |
+
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
|
21 |
+
import cv2
|
22 |
+
import einops
|
23 |
+
from einops import repeat
|
24 |
+
from pytorch_lightning import seed_everything
|
25 |
+
import random
|
26 |
+
from ldm.util import instantiate_from_config
|
27 |
+
from ldm.data.extract_mel_spectrogram import TRANSFORMS_16000
|
28 |
+
from pathlib import Path
|
29 |
+
from vocoder.hifigan.modules import VocoderHifigan
|
30 |
+
from vocoder.bigvgan.models import VocoderBigVGAN
|
31 |
+
from ldm.models.diffusion.ddim import DDIMSampler
|
32 |
+
from wav_evaluation.models.CLAPWrapper import CLAPWrapper
|
33 |
+
from inference.svs.ds_e2e import DiffSingerE2EInfer
|
34 |
+
from audio_to_text.inference_waveform import AudioCapModel
|
35 |
+
import whisper
|
36 |
+
from text_to_speech.TTS_binding import TTSInference
|
37 |
+
from inference.svs.ds_e2e import DiffSingerE2EInfer
|
38 |
+
from inference.tts.GenerSpeech import GenerSpeechInfer
|
39 |
+
from utils.hparams import set_hparams
|
40 |
+
from utils.hparams import hparams as hp
|
41 |
+
from utils.os_utils import move_file
|
42 |
+
import scipy.io.wavfile as wavfile
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
def initialize_model(config, ckpt, device):
|
47 |
+
config = OmegaConf.load(config)
|
48 |
+
model = instantiate_from_config(config.model)
|
49 |
+
model.load_state_dict(torch.load(ckpt,map_location='cpu')["state_dict"], strict=False)
|
50 |
+
|
51 |
+
model = model.to(device)
|
52 |
+
model.cond_stage_model.to(model.device)
|
53 |
+
model.cond_stage_model.device = model.device
|
54 |
+
sampler = DDIMSampler(model)
|
55 |
+
return sampler
|
56 |
+
|
57 |
+
def initialize_model_inpaint(config, ckpt):
|
58 |
+
config = OmegaConf.load(config)
|
59 |
+
model = instantiate_from_config(config.model)
|
60 |
+
model.load_state_dict(torch.load(ckpt,map_location='cpu')["state_dict"], strict=False)
|
61 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
62 |
+
model = model.to(device)
|
63 |
+
print(model.device,device,model.cond_stage_model.device)
|
64 |
+
sampler = DDIMSampler(model)
|
65 |
+
return sampler
|
66 |
+
def select_best_audio(prompt,wav_list):
|
67 |
+
clap_model = CLAPWrapper('useful_ckpts/CLAP/CLAP_weights_2022.pth','useful_ckpts/CLAP/config.yml',use_cuda=torch.cuda.is_available())
|
68 |
+
text_embeddings = clap_model.get_text_embeddings([prompt])
|
69 |
+
score_list = []
|
70 |
+
for data in wav_list:
|
71 |
+
sr,wav = data
|
72 |
+
audio_embeddings = clap_model.get_audio_embeddings([(torch.FloatTensor(wav),sr)], resample=True)
|
73 |
+
score = clap_model.compute_similarity(audio_embeddings, text_embeddings,use_logit_scale=False).squeeze().cpu().numpy()
|
74 |
+
score_list.append(score)
|
75 |
+
max_index = np.array(score_list).argmax()
|
76 |
+
print(score_list,max_index)
|
77 |
+
return wav_list[max_index]
|
78 |
+
|
79 |
+
|
80 |
+
class T2I:
|
81 |
+
def __init__(self, device):
|
82 |
+
print("Initializing T2I to %s" % device)
|
83 |
+
self.device = device
|
84 |
+
self.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
|
85 |
+
self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
|
86 |
+
self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
|
87 |
+
self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model, tokenizer=self.text_refine_tokenizer, device=self.device)
|
88 |
+
self.pipe.to(device)
|
89 |
+
|
90 |
+
def inference(self, text):
|
91 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
92 |
+
refined_text = self.text_refine_gpt2_pipe(text)[0]["generated_text"]
|
93 |
+
print(f'{text} refined to {refined_text}')
|
94 |
+
image = self.pipe(refined_text).images[0]
|
95 |
+
image.save(image_filename)
|
96 |
+
print(f"Processed T2I.run, text: {text}, image_filename: {image_filename}")
|
97 |
+
return image_filename
|
98 |
+
|
99 |
+
class ImageCaptioning:
|
100 |
+
def __init__(self, device):
|
101 |
+
print("Initializing ImageCaptioning to %s" % device)
|
102 |
+
self.device = device
|
103 |
+
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
104 |
+
self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(self.device)
|
105 |
+
|
106 |
+
def inference(self, image_path):
|
107 |
+
inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device)
|
108 |
+
out = self.model.generate(**inputs)
|
109 |
+
captions = self.processor.decode(out[0], skip_special_tokens=True)
|
110 |
+
return captions
|
111 |
+
|
112 |
+
class T2A:
|
113 |
+
def __init__(self, device):
|
114 |
+
print("Initializing Make-An-Audio to %s" % device)
|
115 |
+
self.device = device
|
116 |
+
self.sampler = initialize_model('configs/text-to-audio/txt2audio_args.yaml', 'useful_ckpts/ta40multi_epoch=000085.ckpt', device=device)
|
117 |
+
self.vocoder = VocoderBigVGAN('text_to_audio/Make_An_Audio/vocoder/logs/bigv16k53w',device=device)
|
118 |
+
|
119 |
+
def txt2audio(self, text, seed = 55, scale = 1.5, ddim_steps = 100, n_samples = 3, W = 624, H = 80):
|
120 |
+
SAMPLE_RATE = 16000
|
121 |
+
prng = np.random.RandomState(seed)
|
122 |
+
start_code = prng.randn(n_samples, self.sampler.model.first_stage_model.embed_dim, H // 8, W // 8)
|
123 |
+
start_code = torch.from_numpy(start_code).to(device=self.device, dtype=torch.float32)
|
124 |
+
uc = self.sampler.model.get_learned_conditioning(n_samples * [""])
|
125 |
+
c = self.sampler.model.get_learned_conditioning(n_samples * [text])
|
126 |
+
shape = [self.sampler.model.first_stage_model.embed_dim, H//8, W//8] # (z_dim, 80//2^x, 848//2^x)
|
127 |
+
samples_ddim, _ = self.sampler.sample(S = ddim_steps,
|
128 |
+
conditioning = c,
|
129 |
+
batch_size = n_samples,
|
130 |
+
shape = shape,
|
131 |
+
verbose = False,
|
132 |
+
unconditional_guidance_scale = scale,
|
133 |
+
unconditional_conditioning = uc,
|
134 |
+
x_T = start_code)
|
135 |
+
|
136 |
+
x_samples_ddim = self.sampler.model.decode_first_stage(samples_ddim)
|
137 |
+
x_samples_ddim = torch.clamp((x_samples_ddim+1.0)/2.0, min=0.0, max=1.0) # [0, 1]
|
138 |
+
|
139 |
+
wav_list = []
|
140 |
+
for idx,spec in enumerate(x_samples_ddim):
|
141 |
+
wav = self.vocoder.vocode(spec)
|
142 |
+
wav_list.append((SAMPLE_RATE,wav))
|
143 |
+
best_wav = select_best_audio(text, wav_list)
|
144 |
+
return best_wav
|
145 |
+
|
146 |
+
def inference(self, text, seed = 55, scale = 1.5, ddim_steps = 100, n_samples = 3, W = 624, H = 80):
|
147 |
+
melbins,mel_len = 80,624
|
148 |
+
with torch.no_grad():
|
149 |
+
result = self.txt2audio(
|
150 |
+
text = text,
|
151 |
+
H = melbins,
|
152 |
+
W = mel_len
|
153 |
+
)
|
154 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
155 |
+
soundfile.write(audio_filename, result[1], samplerate = 16000)
|
156 |
+
print(f"Processed T2I.run, text: {text}, audio_filename: {audio_filename}")
|
157 |
+
return audio_filename
|
158 |
+
|
159 |
+
class I2A:
|
160 |
+
def __init__(self, device):
|
161 |
+
print("Initializing Make-An-Audio-Image to %s" % device)
|
162 |
+
self.device = device
|
163 |
+
self.sampler = initialize_model('text_to_audio/Make_An_Audio_img/configs/img_to_audio/img2audio_args.yaml', 'text_to_audio/Make_An_Audio_img/useful_ckpts/ta54_epoch=000216.ckpt', device=device)
|
164 |
+
self.vocoder = VocoderBigVGAN('text_to_audio/Make_An_Audio_img/vocoder/logs/bigv16k53w',device=device)
|
165 |
+
def img2audio(self, image, seed = 55, scale = 3, ddim_steps = 100, W = 624, H = 80):
|
166 |
+
SAMPLE_RATE = 16000
|
167 |
+
n_samples = 1 # only support 1 sample
|
168 |
+
prng = np.random.RandomState(seed)
|
169 |
+
start_code = prng.randn(n_samples, self.sampler.model.first_stage_model.embed_dim, H // 8, W // 8)
|
170 |
+
start_code = torch.from_numpy(start_code).to(device=self.device, dtype=torch.float32)
|
171 |
+
uc = self.sampler.model.get_learned_conditioning(n_samples * [""])
|
172 |
+
#image = Image.fromarray(image)
|
173 |
+
image = Image.open(image)
|
174 |
+
image = self.sampler.model.cond_stage_model.preprocess(image).unsqueeze(0)
|
175 |
+
image_embedding = self.sampler.model.cond_stage_model.forward_img(image)
|
176 |
+
c = image_embedding.repeat(n_samples, 1, 1)# shape:[1,77,1280],即还没有变成句子embedding,仍是每个单词的embedding
|
177 |
+
shape = [self.sampler.model.first_stage_model.embed_dim, H//8, W//8] # (z_dim, 80//2^x, 848//2^x)
|
178 |
+
samples_ddim, _ = self.sampler.sample(S=ddim_steps,
|
179 |
+
conditioning=c,
|
180 |
+
batch_size=n_samples,
|
181 |
+
shape=shape,
|
182 |
+
verbose=False,
|
183 |
+
unconditional_guidance_scale=scale,
|
184 |
+
unconditional_conditioning=uc,
|
185 |
+
x_T=start_code)
|
186 |
+
|
187 |
+
x_samples_ddim = self.sampler.model.decode_first_stage(samples_ddim)
|
188 |
+
x_samples_ddim = torch.clamp((x_samples_ddim+1.0)/2.0, min=0.0, max=1.0) # [0, 1]
|
189 |
+
wav_list = []
|
190 |
+
for idx,spec in enumerate(x_samples_ddim):
|
191 |
+
wav = self.vocoder.vocode(spec)
|
192 |
+
wav_list.append((SAMPLE_RATE,wav))
|
193 |
+
best_wav = wav_list[0]
|
194 |
+
return best_wav
|
195 |
+
def inference(self, image, seed = 55, scale = 3, ddim_steps = 100, W = 624, H = 80):
|
196 |
+
melbins,mel_len = 80,624
|
197 |
+
with torch.no_grad():
|
198 |
+
result = self.img2audio(
|
199 |
+
image=image,
|
200 |
+
H=melbins,
|
201 |
+
W=mel_len
|
202 |
+
)
|
203 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
204 |
+
soundfile.write(audio_filename, result[1], samplerate = 16000)
|
205 |
+
print(f"Processed I2a.run, image_filename: {image}, audio_filename: {audio_filename}")
|
206 |
+
return audio_filename
|
207 |
+
|
208 |
+
class TTS:
|
209 |
+
def __init__(self, device=None):
|
210 |
+
self.inferencer = TTSInference(device)
|
211 |
+
|
212 |
+
def inference(self, text):
|
213 |
+
global temp_audio_filename
|
214 |
+
inp = {"text": text}
|
215 |
+
out = self.inferencer.infer_once(inp)
|
216 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
217 |
+
soundfile.write(audio_filename, out, samplerate = 22050)
|
218 |
+
return audio_filename
|
219 |
+
|
220 |
+
class T2S:
|
221 |
+
def __init__(self, device= None):
|
222 |
+
if device is None:
|
223 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
224 |
+
print("Initializing DiffSinger to %s" % device)
|
225 |
+
self.device = device
|
226 |
+
self.exp_name = 'checkpoints/0831_opencpop_ds1000'
|
227 |
+
self.config= 'text_to_sing/DiffSinger/usr/configs/midi/e2e/opencpop/ds1000.yaml'
|
228 |
+
self.set_model_hparams()
|
229 |
+
self.pipe = DiffSingerE2EInfer(self.hp, device)
|
230 |
+
self.default_inp = {
|
231 |
+
'text': '你 说 你 不 SP 懂 为 何 在 这 时 牵 手 AP',
|
232 |
+
'notes': 'D#4/Eb4 | D#4/Eb4 | D#4/Eb4 | D#4/Eb4 | rest | D#4/Eb4 | D4 | D4 | D4 | D#4/Eb4 | F4 | D#4/Eb4 | D4 | rest',
|
233 |
+
'notes_duration': '0.113740 | 0.329060 | 0.287950 | 0.133480 | 0.150900 | 0.484730 | 0.242010 | 0.180820 | 0.343570 | 0.152050 | 0.266720 | 0.280310 | 0.633300 | 0.444590'
|
234 |
+
}
|
235 |
+
|
236 |
+
def set_model_hparams(self):
|
237 |
+
set_hparams(config=self.config, exp_name=self.exp_name, print_hparams=False)
|
238 |
+
self.hp = hp
|
239 |
+
|
240 |
+
def inference(self, inputs):
|
241 |
+
self.set_model_hparams()
|
242 |
+
val = inputs.split(",")
|
243 |
+
key = ['text', 'notes', 'notes_duration']
|
244 |
+
if inputs == '' or len(val) < len(key):
|
245 |
+
inp = self.default_inp
|
246 |
+
else:
|
247 |
+
inp = {k:v for k,v in zip(key,val)}
|
248 |
+
wav = self.pipe.infer_once(inp)
|
249 |
+
wav *= 32767
|
250 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
251 |
+
wavfile.write(audio_filename, self.hp['audio_sample_rate'], wav.astype(np.int16))
|
252 |
+
print(f"Processed T2S.run, audio_filename: {audio_filename}")
|
253 |
+
return audio_filename
|
254 |
+
|
255 |
+
class TTS_OOD:
|
256 |
+
def __init__(self, device):
|
257 |
+
if device is None:
|
258 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
259 |
+
print("Initializing GenerSpeech to %s" % device)
|
260 |
+
self.device = device
|
261 |
+
self.exp_name = 'checkpoints/GenerSpeech'
|
262 |
+
self.config = 'text_to_sing/DiffSinger/modules/GenerSpeech/config/generspeech.yaml'
|
263 |
+
self.set_model_hparams()
|
264 |
+
self.pipe = GenerSpeechInfer(self.hp, device)
|
265 |
+
|
266 |
+
def set_model_hparams(self):
|
267 |
+
set_hparams(config=self.config, exp_name=self.exp_name, print_hparams=False)
|
268 |
+
f0_stats_fn = f'{hp["binary_data_dir"]}/train_f0s_mean_std.npy'
|
269 |
+
if os.path.exists(f0_stats_fn):
|
270 |
+
hp['f0_mean'], hp['f0_std'] = np.load(f0_stats_fn)
|
271 |
+
hp['f0_mean'] = float(hp['f0_mean'])
|
272 |
+
hp['f0_std'] = float(hp['f0_std'])
|
273 |
+
hp['emotion_encoder_path'] = 'checkpoints/Emotion_encoder.pt'
|
274 |
+
self.hp = hp
|
275 |
+
|
276 |
+
def inference(self, inputs):
|
277 |
+
self.set_model_hparams()
|
278 |
+
key = ['ref_audio', 'text']
|
279 |
+
val = inputs.split(",")
|
280 |
+
inp = {k: v for k, v in zip(key, val)}
|
281 |
+
print(inp)
|
282 |
+
wav = self.pipe.infer_once(inp)
|
283 |
+
wav *= 32767
|
284 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
285 |
+
wavfile.write(audio_filename, self.hp['audio_sample_rate'], wav.astype(np.int16))
|
286 |
+
print(
|
287 |
+
f"Processed GenerSpeech.run. Input text:{val[1]}. Input reference audio: {val[0]}. Output Audio_filename: {audio_filename}")
|
288 |
+
return audio_filename
|
289 |
+
|
290 |
+
class Inpaint:
|
291 |
+
def __init__(self, device):
|
292 |
+
print("Initializing Make-An-Audio-inpaint to %s" % device)
|
293 |
+
self.device = device
|
294 |
+
self.sampler = initialize_model_inpaint('text_to_audio/Make_An_Audio_inpaint/configs/inpaint/txt2audio_args.yaml', 'text_to_audio/Make_An_Audio_inpaint/useful_ckpts/inpaint7_epoch00047.ckpt')
|
295 |
+
self.vocoder = VocoderBigVGAN('./vocoder/logs/bigv16k53w',device=device)
|
296 |
+
self.cmap_transform = matplotlib.cm.viridis
|
297 |
+
def make_batch_sd(self, mel, mask, num_samples=1):
|
298 |
+
|
299 |
+
mel = torch.from_numpy(mel)[None,None,...].to(dtype=torch.float32)
|
300 |
+
mask = torch.from_numpy(mask)[None,None,...].to(dtype=torch.float32)
|
301 |
+
masked_mel = (1 - mask) * mel
|
302 |
+
|
303 |
+
mel = mel * 2 - 1
|
304 |
+
mask = mask * 2 - 1
|
305 |
+
masked_mel = masked_mel * 2 -1
|
306 |
+
|
307 |
+
batch = {
|
308 |
+
"mel": repeat(mel.to(device=self.device), "1 ... -> n ...", n=num_samples),
|
309 |
+
"mask": repeat(mask.to(device=self.device), "1 ... -> n ...", n=num_samples),
|
310 |
+
"masked_mel": repeat(masked_mel.to(device=self.device), "1 ... -> n ...", n=num_samples),
|
311 |
+
}
|
312 |
+
return batch
|
313 |
+
def gen_mel(self, input_audio_path):
|
314 |
+
SAMPLE_RATE = 16000
|
315 |
+
sr, ori_wav = wavfile.read(input_audio_path)
|
316 |
+
print("gen_mel")
|
317 |
+
print(sr,ori_wav.shape,ori_wav)
|
318 |
+
ori_wav = ori_wav.astype(np.float32, order='C') / 32768.0 # order='C'是以C语言格式存储,不用管
|
319 |
+
if len(ori_wav.shape)==2:# stereo
|
320 |
+
ori_wav = librosa.to_mono(ori_wav.T)# gradio load wav shape could be (wav_len,2) but librosa expects (2,wav_len)
|
321 |
+
print(sr,ori_wav.shape,ori_wav)
|
322 |
+
ori_wav = librosa.resample(ori_wav,orig_sr = sr,target_sr = SAMPLE_RATE)
|
323 |
+
|
324 |
+
mel_len,hop_size = 848,256
|
325 |
+
input_len = mel_len * hop_size
|
326 |
+
if len(ori_wav) < input_len:
|
327 |
+
input_wav = np.pad(ori_wav,(0,mel_len*hop_size),constant_values=0)
|
328 |
+
else:
|
329 |
+
input_wav = ori_wav[:input_len]
|
330 |
+
|
331 |
+
mel = TRANSFORMS_16000(input_wav)
|
332 |
+
return mel
|
333 |
+
def gen_mel_audio(self, input_audio):
|
334 |
+
SAMPLE_RATE = 16000
|
335 |
+
sr,ori_wav = input_audio
|
336 |
+
print("gen_mel_audio")
|
337 |
+
print(sr,ori_wav.shape,ori_wav)
|
338 |
+
|
339 |
+
ori_wav = ori_wav.astype(np.float32, order='C') / 32768.0 # order='C'是以C语言格式存储,不用管
|
340 |
+
if len(ori_wav.shape)==2:# stereo
|
341 |
+
ori_wav = librosa.to_mono(ori_wav.T)# gradio load wav shape could be (wav_len,2) but librosa expects (2,wav_len)
|
342 |
+
print(sr,ori_wav.shape,ori_wav)
|
343 |
+
ori_wav = librosa.resample(ori_wav,orig_sr = sr,target_sr = SAMPLE_RATE)
|
344 |
+
|
345 |
+
mel_len,hop_size = 848,256
|
346 |
+
input_len = mel_len * hop_size
|
347 |
+
if len(ori_wav) < input_len:
|
348 |
+
input_wav = np.pad(ori_wav,(0,mel_len*hop_size),constant_values=0)
|
349 |
+
else:
|
350 |
+
input_wav = ori_wav[:input_len]
|
351 |
+
mel = TRANSFORMS_16000(input_wav)
|
352 |
+
return mel
|
353 |
+
def show_mel_fn(self, input_audio_path):
|
354 |
+
crop_len = 500 # the full mel cannot be showed due to gradio's Image bug when using tool='sketch'
|
355 |
+
crop_mel = self.gen_mel(input_audio_path)[:,:crop_len]
|
356 |
+
color_mel = self.cmap_transform(crop_mel)
|
357 |
+
image = Image.fromarray((color_mel*255).astype(np.uint8))
|
358 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
359 |
+
image.save(image_filename)
|
360 |
+
return image_filename
|
361 |
+
def inpaint(self, batch, seed, ddim_steps, num_samples=1, W=512, H=512):
|
362 |
+
model = self.sampler.model
|
363 |
+
|
364 |
+
prng = np.random.RandomState(seed)
|
365 |
+
start_code = prng.randn(num_samples, model.first_stage_model.embed_dim, H // 8, W // 8)
|
366 |
+
start_code = torch.from_numpy(start_code).to(device=self.device, dtype=torch.float32)
|
367 |
+
|
368 |
+
c = model.get_first_stage_encoding(model.encode_first_stage(batch["masked_mel"]))
|
369 |
+
cc = torch.nn.functional.interpolate(batch["mask"],
|
370 |
+
size=c.shape[-2:])
|
371 |
+
c = torch.cat((c, cc), dim=1) # (b,c+1,h,w) 1 is mask
|
372 |
+
|
373 |
+
shape = (c.shape[1]-1,)+c.shape[2:]
|
374 |
+
samples_ddim, _ = self.sampler.sample(S=ddim_steps,
|
375 |
+
conditioning=c,
|
376 |
+
batch_size=c.shape[0],
|
377 |
+
shape=shape,
|
378 |
+
verbose=False)
|
379 |
+
x_samples_ddim = model.decode_first_stage(samples_ddim)
|
380 |
+
|
381 |
+
|
382 |
+
mask = batch["mask"]# [-1,1]
|
383 |
+
mel = torch.clamp((batch["mel"]+1.0)/2.0,min=0.0, max=1.0)
|
384 |
+
mask = torch.clamp((batch["mask"]+1.0)/2.0,min=0.0, max=1.0)
|
385 |
+
predicted_mel = torch.clamp((x_samples_ddim+1.0)/2.0,min=0.0, max=1.0)
|
386 |
+
inpainted = (1-mask)*mel+mask*predicted_mel
|
387 |
+
inpainted = inpainted.cpu().numpy().squeeze()
|
388 |
+
inapint_wav = self.vocoder.vocode(inpainted)
|
389 |
+
|
390 |
+
return inpainted, inapint_wav
|
391 |
+
def inference(self, input_audio, mel_and_mask, seed = 55, ddim_steps = 100):
|
392 |
+
SAMPLE_RATE = 16000
|
393 |
+
torch.set_grad_enabled(False)
|
394 |
+
mel_img = Image.open(mel_and_mask['image'])
|
395 |
+
mask_img = Image.open(mel_and_mask["mask"])
|
396 |
+
show_mel = np.array(mel_img.convert("L"))/255 # 由于展示的mel只展示了一部分,所以需要重新从音频生成mel
|
397 |
+
mask = np.array(mask_img.convert("L"))/255
|
398 |
+
mel_bins,mel_len = 80,848
|
399 |
+
input_mel = self.gen_mel_audio(input_audio)[:,:mel_len]# 由于展示的mel只展示了一部分,所以需要重新从音频生成mel
|
400 |
+
mask = np.pad(mask,((0,0),(0,mel_len-mask.shape[1])),mode='constant',constant_values=0)# 将mask填充到原来的mel的大小
|
401 |
+
print(mask.shape,input_mel.shape)
|
402 |
+
with torch.no_grad():
|
403 |
+
batch = self.make_batch_sd(input_mel,mask,num_samples=1)
|
404 |
+
inpainted,gen_wav = self.inpaint(
|
405 |
+
batch=batch,
|
406 |
+
seed=seed,
|
407 |
+
ddim_steps=ddim_steps,
|
408 |
+
num_samples=1,
|
409 |
+
H=mel_bins, W=mel_len
|
410 |
+
)
|
411 |
+
inpainted = inpainted[:,:show_mel.shape[1]]
|
412 |
+
color_mel = self.cmap_transform(inpainted)
|
413 |
+
input_len = int(input_audio[1].shape[0] * SAMPLE_RATE / input_audio[0])
|
414 |
+
gen_wav = (gen_wav * 32768).astype(np.int16)[:input_len]
|
415 |
+
image = Image.fromarray((color_mel*255).astype(np.uint8))
|
416 |
+
image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
|
417 |
+
image.save(image_filename)
|
418 |
+
audio_filename = os.path.join('audio', str(uuid.uuid4())[0:8] + ".wav")
|
419 |
+
soundfile.write(audio_filename, gen_wav, samplerate = 16000)
|
420 |
+
return image_filename, audio_filename
|
421 |
+
|
422 |
+
class ASR:
|
423 |
+
def __init__(self, device):
|
424 |
+
print("Initializing Whisper to %s" % device)
|
425 |
+
self.device = device
|
426 |
+
self.model = whisper.load_model("base", device=device)
|
427 |
+
def inference(self, audio_path):
|
428 |
+
audio = whisper.load_audio(audio_path)
|
429 |
+
audio = whisper.pad_or_trim(audio)
|
430 |
+
mel = whisper.log_mel_spectrogram(audio).to(self.device)
|
431 |
+
_, probs = self.model.detect_language(mel)
|
432 |
+
options = whisper.DecodingOptions()
|
433 |
+
result = whisper.decode(self.model, mel, options)
|
434 |
+
return result.text
|
435 |
+
|
436 |
+
class A2T:
|
437 |
+
def __init__(self, device):
|
438 |
+
print("Initializing Audio-To-Text Model to %s" % device)
|
439 |
+
self.device = device
|
440 |
+
self.model = AudioCapModel("audio_to_text/audiocaps_cntrstv_cnn14rnn_trm")
|
441 |
+
def inference(self, audio_path):
|
442 |
+
audio = whisper.load_audio(audio_path)
|
443 |
+
caption_text = self.model(audio)
|
444 |
+
return caption_text[0]
|