Spaces:
Runtime error
Runtime error
Commit ·
7cd61ef
0
Parent(s):
Duplicate from DGSpitzer/TXT-2-IMG-2-MUSIC-2-VIDEO-w-RIFFUSION
Browse filesCo-authored-by: DGSpitzer <DGSpitzer@users.noreply.huggingface.co>
- .gitattributes +33 -0
- README.md +14 -0
- app.py +597 -0
- constants.py +7 -0
- nsfw_placeholder.jpg +0 -0
- requirements.txt +21 -0
- share_btn.py +109 -0
- spectro.py +185 -0
- utils.py +50 -0
.gitattributes
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Txt 2 Img 2 Music 2 Video w Riffusion
|
| 3 |
+
emoji: ☯️🎨🎸🎞
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 3.8.2
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
duplicated_from: DGSpitzer/TXT-2-IMG-2-MUSIC-2-VIDEO-w-RIF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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import paddlehub as hub
|
| 7 |
+
import urllib
|
| 8 |
+
import cv2
|
| 9 |
+
import re
|
| 10 |
+
import os
|
| 11 |
+
import requests
|
| 12 |
+
|
| 13 |
+
from share_btn import community_icon_html, loading_icon_html, share_js
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from spectro import wav_bytes_from_spectrogram_image
|
| 18 |
+
from diffusers import StableDiffusionPipeline
|
| 19 |
+
from diffusers import EulerAncestralDiscreteScheduler
|
| 20 |
+
|
| 21 |
+
import io
|
| 22 |
+
from os import path
|
| 23 |
+
from pydub import AudioSegment
|
| 24 |
+
import moviepy.video.io.ImageSequenceClip
|
| 25 |
+
from moviepy.editor import *
|
| 26 |
+
import mutagen
|
| 27 |
+
from mutagen.mp3 import MP3
|
| 28 |
+
from mutagen.wave import WAVE
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
import time
|
| 32 |
+
import base64
|
| 33 |
+
import gradio as gr
|
| 34 |
+
from sentence_transformers import SentenceTransformer
|
| 35 |
+
|
| 36 |
+
import httpx
|
| 37 |
+
import json
|
| 38 |
+
|
| 39 |
+
from utils import get_tags_for_prompts, get_mubert_tags_embeddings, get_pat
|
| 40 |
+
|
| 41 |
+
minilm = SentenceTransformer('all-MiniLM-L6-v2')
|
| 42 |
+
mubert_tags_embeddings = get_mubert_tags_embeddings(minilm)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_track_by_tags(tags, pat, duration, maxit=20, loop=False):
|
| 46 |
+
if loop:
|
| 47 |
+
mode = "loop"
|
| 48 |
+
else:
|
| 49 |
+
mode = "track"
|
| 50 |
+
r = httpx.post('https://api-b2b.mubert.com/v2/RecordTrackTTM',
|
| 51 |
+
json={
|
| 52 |
+
"method": "RecordTrackTTM",
|
| 53 |
+
"params": {
|
| 54 |
+
"pat": pat,
|
| 55 |
+
"duration": duration,
|
| 56 |
+
"tags": tags,
|
| 57 |
+
"mode": mode
|
| 58 |
+
}
|
| 59 |
+
})
|
| 60 |
+
|
| 61 |
+
rdata = json.loads(r.text)
|
| 62 |
+
assert rdata['status'] == 1, rdata['error']['text']
|
| 63 |
+
trackurl = rdata['data']['tasks'][0]['download_link']
|
| 64 |
+
|
| 65 |
+
print('Generating track ', end='')
|
| 66 |
+
for i in range(maxit):
|
| 67 |
+
r = httpx.get(trackurl)
|
| 68 |
+
if r.status_code == 200:
|
| 69 |
+
return trackurl
|
| 70 |
+
time.sleep(1)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def generate_track_by_prompt(prompt):
|
| 74 |
+
try:
|
| 75 |
+
pat = get_pat("mail@mail.com")
|
| 76 |
+
_, tags = get_tags_for_prompts(minilm, mubert_tags_embeddings, [prompt, ])[0]
|
| 77 |
+
result = get_track_by_tags(tags, pat, int(30), loop=False)
|
| 78 |
+
print(result)
|
| 79 |
+
return result
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return str(e)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
img_to_text = gr.Blocks.load(name="spaces/fffiloni/CLIP-Interrogator-2")
|
| 85 |
+
#text_to_music = gr.Interface.load("spaces/fffiloni/text-2-music")
|
| 86 |
+
|
| 87 |
+
language_translation_model = hub.Module(name='baidu_translate')
|
| 88 |
+
language_recognition_model = hub.Module(name='baidu_language_recognition')
|
| 89 |
+
|
| 90 |
+
# style_list = ['古风', '油画', '水彩', '卡通', '二次元', '浮世绘', '蒸汽波艺术', 'low poly', '像素风格', '概念艺术', '未来主义', '赛博朋克', '写实风格', '洛丽塔风格', '巴洛克风格', '超现实主义', '默认']
|
| 91 |
+
style_list_EN = ['Chinese Ancient Style', 'Oil painting', 'Watercolor', 'Cartoon', 'Anime', 'Ukiyoe', 'Vaporwave', 'low poly', 'Pixel Style', 'Conceptual Art', 'Futurism', 'Cyberpunk', 'Realistic style', 'Lolita style', 'Baroque style', 'Surrealism', 'Detailed']
|
| 92 |
+
|
| 93 |
+
tips = {"en": "Tips: The input text will be translated into English for generation",
|
| 94 |
+
"jp": "ヒント: 入力テキストは生成のために中国語に翻訳されます",
|
| 95 |
+
"kor": "힌트: 입력 텍스트는 생성을 위해 중국어로 번역됩니다"}
|
| 96 |
+
|
| 97 |
+
count = 0
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
| 101 |
+
eulera = EulerAncestralDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
|
| 102 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, scheduler=eulera)
|
| 103 |
+
pipe = pipe.to("cuda")
|
| 104 |
+
|
| 105 |
+
model_id2 = "riffusion/riffusion-model-v1"
|
| 106 |
+
pipe2 = StableDiffusionPipeline.from_pretrained(model_id2, torch_dtype=torch.float16)
|
| 107 |
+
pipe2 = pipe2.to("cuda")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def translate_language_example(text_prompts, style_indx):
|
| 111 |
+
return translate_language(text_prompts)
|
| 112 |
+
|
| 113 |
+
def translate_language(text_prompts):
|
| 114 |
+
global count
|
| 115 |
+
try:
|
| 116 |
+
count += 1
|
| 117 |
+
tips_text = None
|
| 118 |
+
language_code = language_recognition_model.recognize(text_prompts)
|
| 119 |
+
if language_code != 'en':
|
| 120 |
+
text_prompts = language_translation_model.translate(text_prompts, language_code, 'en')
|
| 121 |
+
except Exception as e:
|
| 122 |
+
error_text = str(e)
|
| 123 |
+
return {status_text:error_text, language_tips_text:gr.update(visible=False), translated_language:text_prompts, trigger_component: gr.update(value=count, visible=False)}
|
| 124 |
+
if language_code in tips:
|
| 125 |
+
tips_text = tips[language_code]
|
| 126 |
+
else:
|
| 127 |
+
tips_text = tips['en']
|
| 128 |
+
if language_code == 'en':
|
| 129 |
+
return {language_tips_text:gr.update(visible=False), translated_language:text_prompts, trigger_component: gr.update(value=count, visible=False)}
|
| 130 |
+
else:
|
| 131 |
+
return {language_tips_text:gr.update(visible=True, value=tips_text), translated_language:text_prompts, trigger_component: gr.update(value=count, visible=False)}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_result(text_prompts, style_indx, musicAI_indx, duration):
|
| 136 |
+
style = style_list_EN[style_indx]
|
| 137 |
+
prompt = style + "," + text_prompts
|
| 138 |
+
|
| 139 |
+
sdresult = pipe(prompt, negative_prompt = "out of focus, scary, creepy, evil, disfigured, missing limbs, ugly, gross, missing fingers", num_inference_steps=50, guidance_scale=7, width=576, height=576)
|
| 140 |
+
image_output = sdresult.images[0] if not sdresult.nsfw_content_detected[0] else Image.open("nsfw_placeholder.jpg")
|
| 141 |
+
|
| 142 |
+
print("Generated image with prompt " + prompt)
|
| 143 |
+
|
| 144 |
+
# Encode your PIL Image as a JPEG without writing to disk
|
| 145 |
+
imagefile = "imageoutput.png"
|
| 146 |
+
#img_np = np.array(image_output[0])
|
| 147 |
+
#img_nparray= cv2.cvtColor(img_np, cv2.COLOR_BGR2RGBA)
|
| 148 |
+
#img_blue_correction = Image.fromarray(img_nparray)
|
| 149 |
+
#img_blue_correction.save(imagefile, img_blue_correction.format)
|
| 150 |
+
image_output.save(imagefile, image_output.format)
|
| 151 |
+
|
| 152 |
+
interrogate_prompt = prompt
|
| 153 |
+
#interrogate_prompt = img_to_text(imagefile, 'fast', 4, fn_index=1)[0]
|
| 154 |
+
print(interrogate_prompt)
|
| 155 |
+
spec_image, music_output = get_music(interrogate_prompt + ", " + style_list_EN[style_indx], musicAI_indx, duration)
|
| 156 |
+
|
| 157 |
+
video_merged = merge_video(music_output, image_output)
|
| 158 |
+
return {spec_result:spec_image, imgfile_result:image_output, musicfile_result:"audio.wav", video_result:video_merged, status_text:'Success', share_button:gr.update(visible=True), community_icon:gr.update(visible=True), loading_icon:gr.update(visible=True)}
|
| 159 |
+
|
| 160 |
+
def get_music(prompt, musicAI_indx, duration):
|
| 161 |
+
mp3file_name = "audio.mp3"
|
| 162 |
+
wavfile_name = "audio.wav"
|
| 163 |
+
if musicAI_indx == 0:
|
| 164 |
+
if duration == 5:
|
| 165 |
+
width_duration=512
|
| 166 |
+
else :
|
| 167 |
+
width_duration = 512 + ((int(duration)-5) * 128)
|
| 168 |
+
spec = pipe2(prompt, height=512, width=width_duration).images[0]
|
| 169 |
+
print(spec)
|
| 170 |
+
wav = wav_bytes_from_spectrogram_image(spec)
|
| 171 |
+
with open(wavfile_name, "wb") as f:
|
| 172 |
+
f.write(wav[0].getbuffer())
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
#Convert to mp3, for video merging function
|
| 176 |
+
wavfile = AudioSegment.from_wav(wavfile_name)
|
| 177 |
+
wavfile.export(mp3file_name, format="mp3")
|
| 178 |
+
return spec, mp3file_name
|
| 179 |
+
else:
|
| 180 |
+
#result = text_to_music(prompt, fn_index=0)
|
| 181 |
+
result = generate_track_by_prompt(prompt)
|
| 182 |
+
|
| 183 |
+
print(f"""—————
|
| 184 |
+
NEW RESULTS
|
| 185 |
+
prompt : {prompt}
|
| 186 |
+
music : {result}
|
| 187 |
+
———————
|
| 188 |
+
""")
|
| 189 |
+
|
| 190 |
+
url = result
|
| 191 |
+
|
| 192 |
+
data = urllib.request.urlopen(url)
|
| 193 |
+
|
| 194 |
+
f = open(mp3file_name,'wb')
|
| 195 |
+
f.write(data.read())
|
| 196 |
+
f.close()
|
| 197 |
+
|
| 198 |
+
#Convert to wav, for sharing function only supports wav file
|
| 199 |
+
mp3file = AudioSegment.from_mp3(mp3file_name)
|
| 200 |
+
mp3file.export(wavfile_name, format="wav")
|
| 201 |
+
|
| 202 |
+
return None, mp3file_name
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def merge_video(mp3file_name, image):
|
| 206 |
+
print('wav audio converted to mp3 audio' )
|
| 207 |
+
print('now getting duration of this mp3 audio' )
|
| 208 |
+
#getting audio clip's duration
|
| 209 |
+
audio_length = int(MP3(mp3file_name).info.length)
|
| 210 |
+
print('Audio length is :',audio_length)
|
| 211 |
+
|
| 212 |
+
file_name = 'video_no_audio.mp4'
|
| 213 |
+
fps = 12
|
| 214 |
+
slide_time = audio_length
|
| 215 |
+
fourcc = cv2.VideoWriter.fourcc(*'MJPG')
|
| 216 |
+
|
| 217 |
+
#W, H should be the same as input image
|
| 218 |
+
out = cv2.VideoWriter(file_name, fourcc, fps, (576, 576))
|
| 219 |
+
|
| 220 |
+
# for image in img_list:
|
| 221 |
+
# cv_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 222 |
+
# for _ in range(slide_time * fps):
|
| 223 |
+
# #cv_img = cv2.resize(np.array(cv_img), (1024, 1024))
|
| 224 |
+
# out.write(cv_img)
|
| 225 |
+
|
| 226 |
+
cv_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 227 |
+
for _ in range(slide_time * fps):
|
| 228 |
+
#cv_img = cv2.resize(np.array(cv_img),
|
| 229 |
+
out.write(cv_img)
|
| 230 |
+
|
| 231 |
+
out.release()
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
#String a list of images into a video and write to memory
|
| 235 |
+
print('video clip created successfully from images')
|
| 236 |
+
|
| 237 |
+
# loading video file
|
| 238 |
+
print('Starting video and audio merge')
|
| 239 |
+
videoclip = VideoFileClip(file_name) #("/content/gdrive/My Drive/AI/my_video1.mp4")
|
| 240 |
+
print('loading video-clip')
|
| 241 |
+
|
| 242 |
+
# loading audio file
|
| 243 |
+
audioclip = AudioFileClip(mp3file_name) #.subclip(0, 15)
|
| 244 |
+
print('loading mp3-format audio')
|
| 245 |
+
# adding audio to the video clip
|
| 246 |
+
mergedclip = videoclip.set_audio(audioclip)
|
| 247 |
+
print('video and audio merged successfully')
|
| 248 |
+
|
| 249 |
+
#Getting size and frame count of merged video file
|
| 250 |
+
print('Getting size and frame count of merged video file')
|
| 251 |
+
duration = mergedclip.duration
|
| 252 |
+
frame_count = mergedclip.fps
|
| 253 |
+
print('duration is:',duration)
|
| 254 |
+
print('frame count :', frame_count)
|
| 255 |
+
mergedclip.to_videofile('mergedvideo.mp4')
|
| 256 |
+
return 'mergedvideo.mp4'
|
| 257 |
+
|
| 258 |
+
def change_music_generator(current_choice):
|
| 259 |
+
if current_choice == 0:
|
| 260 |
+
return gr.update(visible=True)
|
| 261 |
+
return gr.update(visible=False)
|
| 262 |
+
|
| 263 |
+
title="文生图生音乐视频 Text to Image to Music to Video with Riffusion"
|
| 264 |
+
|
| 265 |
+
description="An AI art generation pipeline, which supports text-to-image-to-music task."
|
| 266 |
+
|
| 267 |
+
css = """
|
| 268 |
+
.gradio-container {
|
| 269 |
+
font-family: 'IBM Plex Sans', sans-serif;
|
| 270 |
+
}
|
| 271 |
+
.gr-button {
|
| 272 |
+
color: white;
|
| 273 |
+
border-color: black;
|
| 274 |
+
background: black;
|
| 275 |
+
}
|
| 276 |
+
input[type='range'] {
|
| 277 |
+
accent-color: black;
|
| 278 |
+
}
|
| 279 |
+
.dark input[type='range'] {
|
| 280 |
+
accent-color: #dfdfdf;
|
| 281 |
+
}
|
| 282 |
+
.container {
|
| 283 |
+
max-width: 730px;
|
| 284 |
+
margin: auto;
|
| 285 |
+
padding-top: 1.5rem;
|
| 286 |
+
}
|
| 287 |
+
#gallery {
|
| 288 |
+
min-height: 22rem;
|
| 289 |
+
margin-bottom: 15px;
|
| 290 |
+
margin-left: auto;
|
| 291 |
+
margin-right: auto;
|
| 292 |
+
border-bottom-right-radius: .5rem !important;
|
| 293 |
+
border-bottom-left-radius: .5rem !important;
|
| 294 |
+
}
|
| 295 |
+
#gallery>div>.h-full {
|
| 296 |
+
min-height: 20rem;
|
| 297 |
+
}
|
| 298 |
+
.details:hover {
|
| 299 |
+
text-decoration: underline;
|
| 300 |
+
}
|
| 301 |
+
.gr-button {
|
| 302 |
+
white-space: nowrap;
|
| 303 |
+
}
|
| 304 |
+
.gr-button:focus {
|
| 305 |
+
border-color: rgb(147 197 253 / var(--tw-border-opacity));
|
| 306 |
+
outline: none;
|
| 307 |
+
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
|
| 308 |
+
--tw-border-opacity: 1;
|
| 309 |
+
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
|
| 310 |
+
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
|
| 311 |
+
--tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
|
| 312 |
+
--tw-ring-opacity: .5;
|
| 313 |
+
}
|
| 314 |
+
.footer {
|
| 315 |
+
margin-bottom: 45px;
|
| 316 |
+
margin-top: 35px;
|
| 317 |
+
text-align: center;
|
| 318 |
+
border-bottom: 1px solid #e5e5e5;
|
| 319 |
+
}
|
| 320 |
+
.footer>p {
|
| 321 |
+
font-size: .8rem;
|
| 322 |
+
display: inline-block;
|
| 323 |
+
padding: 0 10px;
|
| 324 |
+
transform: translateY(10px);
|
| 325 |
+
background: white;
|
| 326 |
+
}
|
| 327 |
+
.dark .footer {
|
| 328 |
+
border-color: #303030;
|
| 329 |
+
}
|
| 330 |
+
.dark .footer>p {
|
| 331 |
+
background: #0b0f19;
|
| 332 |
+
}
|
| 333 |
+
.prompt h4{
|
| 334 |
+
margin: 1.25em 0 .25em 0;
|
| 335 |
+
font-weight: bold;
|
| 336 |
+
font-size: 115%;
|
| 337 |
+
}
|
| 338 |
+
#share-btn-container {
|
| 339 |
+
display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
|
| 340 |
+
}
|
| 341 |
+
#share-btn {
|
| 342 |
+
all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;right:0;
|
| 343 |
+
}
|
| 344 |
+
#share-btn * {
|
| 345 |
+
all: unset;
|
| 346 |
+
}
|
| 347 |
+
#share-btn-container div:nth-child(-n+2){
|
| 348 |
+
width: auto !important;
|
| 349 |
+
min-height: 0px !important;
|
| 350 |
+
}
|
| 351 |
+
#share-btn-container .wrap {
|
| 352 |
+
display: none !important;
|
| 353 |
+
}
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
block = gr.Blocks(css=css)
|
| 357 |
+
|
| 358 |
+
examples = [
|
| 359 |
+
[
|
| 360 |
+
'蒙娜丽莎,赛博朋克,宝丽来,33毫米',
|
| 361 |
+
'蒸汽波艺术(Vaporwave)'
|
| 362 |
+
],
|
| 363 |
+
[
|
| 364 |
+
'一条由闪电制成的令人敬畏的龙',
|
| 365 |
+
'概念艺术(Conceptual Art)'
|
| 366 |
+
],
|
| 367 |
+
[
|
| 368 |
+
'An awesome dragon made of lightning',
|
| 369 |
+
'概念艺术(Conceptual Art)'
|
| 370 |
+
],
|
| 371 |
+
[
|
| 372 |
+
'少女在时代广场,舞蹈',
|
| 373 |
+
'写实风格(Realistic style)'
|
| 374 |
+
],
|
| 375 |
+
[
|
| 376 |
+
'Peking Opera at New York',
|
| 377 |
+
'默认(Default)'
|
| 378 |
+
],
|
| 379 |
+
[
|
| 380 |
+
'古风少女',
|
| 381 |
+
'水彩(Watercolor)'
|
| 382 |
+
],
|
| 383 |
+
[
|
| 384 |
+
'辐射游戏角色',
|
| 385 |
+
'默认(Default)'
|
| 386 |
+
],
|
| 387 |
+
[
|
| 388 |
+
'Fallout game character',
|
| 389 |
+
'默认(Default)'
|
| 390 |
+
],
|
| 391 |
+
[
|
| 392 |
+
'Traditional Chinese Painting',
|
| 393 |
+
'古风(Ancient Style)'
|
| 394 |
+
],
|
| 395 |
+
[
|
| 396 |
+
'原神游戏截图,pixiv, 二次元绘画作品',
|
| 397 |
+
'二次元(Anime)'
|
| 398 |
+
],
|
| 399 |
+
[
|
| 400 |
+
'Genshin Impact Game Screenshot, pixiv, Anime Painting Artworks',
|
| 401 |
+
'二次元(Anime)'
|
| 402 |
+
],
|
| 403 |
+
[
|
| 404 |
+
'原神角色设定, 哪吒, pixiv, 二次元绘画',
|
| 405 |
+
'二次元(Anime)'
|
| 406 |
+
],
|
| 407 |
+
[
|
| 408 |
+
'Genshin Impact Character Design, Harry Potter, pixiv, Anime Painting',
|
| 409 |
+
'二次元(Anime)'
|
| 410 |
+
],
|
| 411 |
+
[
|
| 412 |
+
'巨狼,飘雪,蓝色大片烟雾,毛发细致,烟雾缭绕,高清,3d,cg感,侧面照',
|
| 413 |
+
'默认(Default)'
|
| 414 |
+
],
|
| 415 |
+
[
|
| 416 |
+
'汉服少女,中国山水画,青山绿水,溪水长流,古风,科技都市,丹青水墨,中国风',
|
| 417 |
+
'赛博朋克(Cyberpunk)'
|
| 418 |
+
],
|
| 419 |
+
[
|
| 420 |
+
'戴着墨镜的赛博朋克女孩肖像,在夕阳下的城市中, 油画风格',
|
| 421 |
+
'赛博朋克(Cyberpunk)'
|
| 422 |
+
],
|
| 423 |
+
[
|
| 424 |
+
'Portrait of a cyberpunk girl with sunglasses, in the city sunset, oil painting',
|
| 425 |
+
'赛博朋克(Cyberpunk)'
|
| 426 |
+
],
|
| 427 |
+
[
|
| 428 |
+
'暗黑破坏神',
|
| 429 |
+
'默认(Default)'
|
| 430 |
+
],
|
| 431 |
+
[
|
| 432 |
+
'火焰,凤凰,少女,未来感,高清,3d���精致面容,cg感,古风,唯美,毛发细致,上半身立绘',
|
| 433 |
+
'默认(Default)'
|
| 434 |
+
],
|
| 435 |
+
[
|
| 436 |
+
'浮世绘日本科幻哑光绘画,概念艺术,动漫风格神道寺禅园英雄动作序列,包豪斯',
|
| 437 |
+
'默认(Default)'
|
| 438 |
+
],
|
| 439 |
+
[
|
| 440 |
+
'一只猫坐在椅子上,戴着一副墨镜,海盗风格',
|
| 441 |
+
'默认(Default)'
|
| 442 |
+
],
|
| 443 |
+
[
|
| 444 |
+
'稲妻で作られた畏敬の念を抱かせる竜、コンセプトアート',
|
| 445 |
+
'油画(Oil painting)'
|
| 446 |
+
],
|
| 447 |
+
[
|
| 448 |
+
'번개로 만든 경외스러운 용, 개념 예술',
|
| 449 |
+
'油画(Oil painting)'
|
| 450 |
+
],
|
| 451 |
+
[
|
| 452 |
+
'梵高猫头鹰',
|
| 453 |
+
'蒸汽波艺术(Vaporwave)'
|
| 454 |
+
],
|
| 455 |
+
[
|
| 456 |
+
'萨尔瓦多·达利描绘古代文明的超现实主义梦幻油画',
|
| 457 |
+
'写实风格(Realistic style)'
|
| 458 |
+
],
|
| 459 |
+
[
|
| 460 |
+
'夕阳日落时,阳光落在云层上,海面波涛汹涌,风景,胶片感',
|
| 461 |
+
'默认(Default)'
|
| 462 |
+
],
|
| 463 |
+
[
|
| 464 |
+
'Sunset, the sun falls on the clouds, the sea is rough, the scenery is filmy',
|
| 465 |
+
'油画(Oil painting)'
|
| 466 |
+
],
|
| 467 |
+
[
|
| 468 |
+
'夕日が沈むと、雲の上に太陽の光が落ち、海面は波が荒く、風景、フィルム感',
|
| 469 |
+
'油画(Oil painting)'
|
| 470 |
+
],
|
| 471 |
+
[
|
| 472 |
+
'석양이 질 때 햇빛이 구름 위에 떨어지고, 해수면의 파도가 용솟음치며, 풍경, 필름감',
|
| 473 |
+
'油画(Oil painting)'
|
| 474 |
+
],
|
| 475 |
+
]
|
| 476 |
+
|
| 477 |
+
with block:
|
| 478 |
+
gr.HTML(
|
| 479 |
+
"""
|
| 480 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
| 481 |
+
<div
|
| 482 |
+
style="
|
| 483 |
+
display: inline-flex;
|
| 484 |
+
gap: 0.8rem;
|
| 485 |
+
font-size: 1.75rem;
|
| 486 |
+
margin-bottom: 10px;
|
| 487 |
+
margin-left: 220px;
|
| 488 |
+
justify-content: center;
|
| 489 |
+
"
|
| 490 |
+
>
|
| 491 |
+
</div>
|
| 492 |
+
<div
|
| 493 |
+
style="
|
| 494 |
+
display: inline-flex;
|
| 495 |
+
align-items: center;
|
| 496 |
+
gap: 0.8rem;
|
| 497 |
+
font-size: 1.75rem;
|
| 498 |
+
margin-bottom: 10px;
|
| 499 |
+
justify-content: center;
|
| 500 |
+
">
|
| 501 |
+
<h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 15px;">文生图生音乐视频</h1>
|
| 502 |
+
</div>
|
| 503 |
+
<div
|
| 504 |
+
style="
|
| 505 |
+
display: inline-flex;
|
| 506 |
+
align-items: center;
|
| 507 |
+
gap: 0.8rem;
|
| 508 |
+
font-size: 1.75rem;
|
| 509 |
+
margin-bottom: 10px;
|
| 510 |
+
justify-content: center;
|
| 511 |
+
">
|
| 512 |
+
<h1 style="font-weight: 900; margin-bottom: 7px;">Text to Image to Music to Video</h1>
|
| 513 |
+
</div>
|
| 514 |
+
<p style="margin-bottom: 10px; font-size: 94%">
|
| 515 |
+
Powered by <a href="https://huggingface.co/riffusion/riffusion-model-v1" target="_blank">Riffusion Model V1</a>, <a href="https://huggingface.co/spaces/Mubert/Text-to-Music" target="_blank">Mubert AI</a>, <a href="https://huggingface.co/spaces/runwayml/stable-diffusion-v1-5" target="_blank">Stable Diffusion V1.5</a>, <a href="https://huggingface.co/spaces/pharma/CLIP-Interrogator" target="_blank">CLIP Interrogator</a>, fffiloni's <a href="https://huggingface.co/spaces/fffiloni/spectrogram-to-music" target="_blank">Riffusion Text-to-Music</a> and Baidu Language Translation projects
|
| 516 |
+
</p>
|
| 517 |
+
</div>
|
| 518 |
+
"""
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
with gr.Group():
|
| 522 |
+
with gr.Box():
|
| 523 |
+
with gr.Row().style(mobile_collapse=False, equal_height=True):
|
| 524 |
+
text = gr.Textbox(
|
| 525 |
+
label="Prompt",
|
| 526 |
+
show_label=False,
|
| 527 |
+
max_lines=1,
|
| 528 |
+
placeholder="Enter your prompt, multiple languages are supported now.",
|
| 529 |
+
elem_id="input-prompt",
|
| 530 |
+
).style(
|
| 531 |
+
border=(True, False, True, True),
|
| 532 |
+
rounded=(True, False, False, True),
|
| 533 |
+
container=False,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
btn = gr.Button("Generate image").style(
|
| 537 |
+
margin=False,
|
| 538 |
+
rounded=(False, True, True, False),
|
| 539 |
+
)
|
| 540 |
+
language_tips_text = gr.Textbox(label="language tips", show_label=False, visible=False, max_lines=1)
|
| 541 |
+
styles = gr.Dropdown(label="风格(style)", choices=['古风(Ancient Style)', '油画(Oil painting)', '水彩(Watercolor)',
|
| 542 |
+
'卡通(Cartoon)', '二次元(Anime)', '浮世绘(Ukiyoe)', '蒸汽波艺术(Vaporwave)', 'low poly',
|
| 543 |
+
'像素风格(Pixel Style)', '概念艺术(Conceptual Art)', '未来主义(Futurism)', '赛博朋克(Cyberpunk)', '写实风格(Realistic style)',
|
| 544 |
+
'洛丽塔风格(Lolita style)', '巴洛克风格(Baroque style)', '超现实主义(Surrealism)', '默认(Default)'], value='默认(Default)', type="index")
|
| 545 |
+
musicAI = gr.Dropdown(label="音乐生成技术(AI Music Generator)", choices=['Riffusion', 'Mubert AI'], value='Riffusion', type="index")
|
| 546 |
+
duration_input = gr.Slider(label="Duration in seconds", minimum=5, maximum=10, step=1, value=5, elem_id="duration-slider", visible=True)
|
| 547 |
+
status_text = gr.Textbox(
|
| 548 |
+
label="处理状态(Process status)",
|
| 549 |
+
show_label=True,
|
| 550 |
+
max_lines=1,
|
| 551 |
+
interactive=False
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
with gr.Column(elem_id="col-container"):
|
| 556 |
+
with gr.Group(elem_id="share-btn-container"):
|
| 557 |
+
community_icon = gr.HTML(community_icon_html, visible=False)
|
| 558 |
+
loading_icon = gr.HTML(loading_icon_html, visible=False)
|
| 559 |
+
share_button = gr.Button("Share to community", elem_id="share-btn", visible=False)
|
| 560 |
+
|
| 561 |
+
share_button.click(None, [], [], _js=share_js)
|
| 562 |
+
|
| 563 |
+
video_result = gr.Video(type=None, label='Final Merged video', elem_id="output-video")
|
| 564 |
+
imgfile_result = gr.Image(label="Art Cover", elem_id="output-img")
|
| 565 |
+
musicfile_result = gr.Audio(type='filepath', label="Generated Music Track", elem_id="output-music")
|
| 566 |
+
spec_result = gr.Image(label="Spectrogram Image")
|
| 567 |
+
|
| 568 |
+
trigger_component = gr.Textbox(vaule="", visible=False) # This component is used for triggering inference funtion.
|
| 569 |
+
translated_language = gr.Textbox(vaule="", visible=False)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
ex = gr.Examples(examples=examples, fn=translate_language_example, inputs=[text, styles], outputs=[language_tips_text, status_text, trigger_component, translated_language], cache_examples=False)
|
| 573 |
+
ex.dataset.headers = [""]
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
musicAI.change(fn=change_music_generator, inputs=[musicAI], outputs=[duration_input])
|
| 577 |
+
text.submit(translate_language, inputs=[text], outputs=[language_tips_text, status_text, trigger_component, translated_language])
|
| 578 |
+
btn.click(translate_language, inputs=[text], outputs=[language_tips_text, status_text, trigger_component, translated_language])
|
| 579 |
+
trigger_component.change(fn=get_result, inputs=[translated_language, styles, musicAI, duration_input], outputs=[spec_result, imgfile_result, musicfile_result, video_result, status_text, share_button, community_icon, loading_icon])
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
gr.Markdown(
|
| 583 |
+
"""
|
| 584 |
+
Space by [@DGSpitzer](https://www.youtube.com/channel/UCzzsYBF4qwtMwJaPJZ5SuPg)❤️ [@大谷的游戏创作小屋](https://space.bilibili.com/176003)
|
| 585 |
+
[](https://twitter.com/DGSpitzer)
|
| 586 |
+

|
| 587 |
+
"""
|
| 588 |
+
)
|
| 589 |
+
gr.HTML('''
|
| 590 |
+
<div class="footer">
|
| 591 |
+
<p>Model:<a href="https://huggingface.co/riffusion/riffusion-model-v1" style="text-decoration: underline;" target="_blank">Riffusion</a>
|
| 592 |
+
</p>
|
| 593 |
+
</div>
|
| 594 |
+
''')
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
block.queue().launch()
|
constants.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
MUBERT_TAGS_STRING = 'tribal,action,kids,neo-classic,run 130,pumped,jazz / funk,ethnic,dubtechno,reggae,acid jazz,liquidfunk,funk,witch house,tech house,underground,artists,mystical,disco,sensorium,r&b,agender,psychedelic trance / psytrance,peaceful,run 140,piano,run 160,setting,meditation,christmas,ambient,horror,cinematic,electro house,idm,bass,minimal,underscore,drums,glitchy,beautiful,technology,tribal house,country pop,jazz & funk,documentary,space,classical,valentines,chillstep,experimental,trap,new jack swing,drama,post-rock,tense,corporate,neutral,happy,analog,funky,spiritual,sberzvuk special,chill hop,dramatic,catchy,holidays,fitness 90,optimistic,orchestra,acid techno,energizing,romantic,minimal house,breaks,hyper pop,warm up,dreamy,dark,urban,microfunk,dub,nu disco,vogue,keys,hardcore,aggressive,indie,electro funk,beauty,relaxing,trance,pop,hiphop,soft,acoustic,chillrave / ethno-house,deep techno,angry,dance,fun,dubstep,tropical,latin pop,heroic,world music,inspirational,uplifting,atmosphere,art,epic,advertising,chillout,scary,spooky,slow ballad,saxophone,summer,erotic,jazzy,energy 100,kara mar,xmas,atmospheric,indie pop,hip-hop,yoga,reggaeton,lounge,travel,running,folk,chillrave & ethno-house,detective,darkambient,chill,fantasy,minimal techno,special,night,tropical house,downtempo,lullaby,meditative,upbeat,glitch hop,fitness,neurofunk,sexual,indie rock,future pop,jazz,cyberpunk,melancholic,happy hardcore,family / kids,synths,electric guitar,comedy,psychedelic trance & psytrance,edm,psychedelic rock,calm,zen,bells,podcast,melodic house,ethnic percussion,nature,heavy,bassline,indie dance,techno,drumnbass,synth pop,vaporwave,sad,8-bit,chillgressive,deep,orchestral,futuristic,hardtechno,nostalgic,big room,sci-fi,tutorial,joyful,pads,minimal 170,drill,ethnic 108,amusing,sleepy ambient,psychill,italo disco,lofi,house,acoustic guitar,bassline house,rock,k-pop,synthwave,deep house,electronica,gabber,nightlife,sport & fitness,road trip,celebration,electro,disco house,electronic'
|
| 4 |
+
MUBERT_TAGS = np.array(MUBERT_TAGS_STRING.split(','))
|
| 5 |
+
MUBERT_LICENSE = "ttmmubertlicense#f0acYBenRcfeFpNT4wpYGaTQIyDI4mJGv5MfIhBFz97NXDwDNFHmMRsBSzmGsJwbTpP1A6i07AXcIeAHo5"
|
| 6 |
+
MUBERT_MODE = "loop"
|
| 7 |
+
MUBERT_TOKEN = "4951f6428e83172a4f39de05d5b3ab10d58560b8"
|
nsfw_placeholder.jpg
ADDED
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
paddlepaddle
|
| 2 |
+
paddlehub
|
| 3 |
+
requests
|
| 4 |
+
moviepy
|
| 5 |
+
mutagen
|
| 6 |
+
torch
|
| 7 |
+
torchaudio
|
| 8 |
+
typing
|
| 9 |
+
pydub
|
| 10 |
+
scipy
|
| 11 |
+
diffusers
|
| 12 |
+
transformers==4.21.2
|
| 13 |
+
accelerate
|
| 14 |
+
ftfy
|
| 15 |
+
regex
|
| 16 |
+
tqdm
|
| 17 |
+
timm
|
| 18 |
+
fairscale
|
| 19 |
+
open_clip_torch
|
| 20 |
+
httpx
|
| 21 |
+
sentence-transformers
|
share_btn.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
|
| 2 |
+
<path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
|
| 3 |
+
<path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
|
| 4 |
+
</svg>"""
|
| 5 |
+
|
| 6 |
+
loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
|
| 7 |
+
style="color: #ffffff;
|
| 8 |
+
"
|
| 9 |
+
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
|
| 10 |
+
|
| 11 |
+
share_js = """async () => {
|
| 12 |
+
async function uploadFile(file){
|
| 13 |
+
const UPLOAD_URL = 'https://huggingface.co/uploads';
|
| 14 |
+
const response = await fetch(UPLOAD_URL, {
|
| 15 |
+
method: 'POST',
|
| 16 |
+
headers: {
|
| 17 |
+
'Content-Type': file.type,
|
| 18 |
+
'X-Requested-With': 'XMLHttpRequest',
|
| 19 |
+
},
|
| 20 |
+
body: file, /// <- File inherits from Blob
|
| 21 |
+
});
|
| 22 |
+
const url = await response.text();
|
| 23 |
+
return url;
|
| 24 |
+
}
|
| 25 |
+
async function getInputVideoFile(videoEl){
|
| 26 |
+
const res = await fetch(videoEl.src);
|
| 27 |
+
const blob = await res.blob();
|
| 28 |
+
const videoId = Date.now() % 200;
|
| 29 |
+
const fileName = `sd-perception-${{videoId}}.mp4`;
|
| 30 |
+
return new File([blob], fileName, { type: 'video/mp4' });
|
| 31 |
+
}
|
| 32 |
+
async function getInputImgFile(imgEl){
|
| 33 |
+
const res = await fetch(imgEl.src);
|
| 34 |
+
const blob = await res.blob();
|
| 35 |
+
const imgId = Date.now() % 200;
|
| 36 |
+
const isPng = imgEl.src.startsWith(`data:image/png`);
|
| 37 |
+
if(isPng){
|
| 38 |
+
const fileName = `sd-perception-${{imgId}}.png`;
|
| 39 |
+
return new File([blob], fileName, { type: 'image/png' });
|
| 40 |
+
}else{
|
| 41 |
+
const fileName = `sd-perception-${{imgId}}.jpg`;
|
| 42 |
+
return new File([blob], fileName, { type: 'image/jpeg' });
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
async function getOutputMusicFile(audioEL){
|
| 46 |
+
const res = await fetch(audioEL.src);
|
| 47 |
+
const blob = await res.blob();
|
| 48 |
+
const audioId = Date.now() % 200;
|
| 49 |
+
const fileName = `spectro-music-${{audioId}}.wav`;
|
| 50 |
+
const musicBlob = new File([blob], fileName, { type: 'audio/wav' });
|
| 51 |
+
console.log(musicBlob);
|
| 52 |
+
return musicBlob;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
async function audioToBase64(audioFile) {
|
| 56 |
+
return new Promise((resolve, reject) => {
|
| 57 |
+
let reader = new FileReader();
|
| 58 |
+
reader.readAsDataURL(audioFile);
|
| 59 |
+
reader.onload = () => resolve(reader.result);
|
| 60 |
+
reader.onerror = error => reject(error);
|
| 61 |
+
|
| 62 |
+
});
|
| 63 |
+
}
|
| 64 |
+
const gradioEl = document.querySelector('body > gradio-app');
|
| 65 |
+
// const gradioEl = document.querySelector("gradio-app").shadowRoot;
|
| 66 |
+
const inputPromptEl = gradioEl.querySelector('#input-prompt input').value;
|
| 67 |
+
const outputVideoEl = gradioEl.querySelector('#output-video video');
|
| 68 |
+
const outputImgEl = gradioEl.querySelector('#output-img img');
|
| 69 |
+
const outputMusic = gradioEl.querySelector('#output-music audio');
|
| 70 |
+
const outputMusic_src = gradioEl.querySelector('#output-music audio').src;
|
| 71 |
+
|
| 72 |
+
let titleTxt = inputPromptEl;
|
| 73 |
+
//if(titleTxt.length > 100){
|
| 74 |
+
// titleTxt = titleTxt.slice(0, 100) + ' ...';
|
| 75 |
+
//}
|
| 76 |
+
const shareBtnEl = gradioEl.querySelector('#share-btn');
|
| 77 |
+
const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
|
| 78 |
+
const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
|
| 79 |
+
if(!outputVideoEl){
|
| 80 |
+
return;
|
| 81 |
+
};
|
| 82 |
+
shareBtnEl.style.pointerEvents = 'none';
|
| 83 |
+
shareIconEl.style.display = 'none';
|
| 84 |
+
loadingIconEl.style.removeProperty('display');
|
| 85 |
+
const outputVideo = await getInputVideoFile(outputVideoEl);
|
| 86 |
+
const urlOutputVideo = await uploadFile(outputVideo);
|
| 87 |
+
const outputImg = await getInputImgFile(outputImgEl);
|
| 88 |
+
const urlOutputImg = await uploadFile(outputImg);
|
| 89 |
+
const musicFile = await getOutputMusicFile(outputMusic);
|
| 90 |
+
const dataOutputMusic = await uploadFile(musicFile);
|
| 91 |
+
|
| 92 |
+
const descriptionMd = `#### Here is my AI generated art & music:
|
| 93 |
+
<img src='${urlOutputImg}' style='max-height: 512px;'>
|
| 94 |
+
|
| 95 |
+
<audio controls>
|
| 96 |
+
<source src="${dataOutputMusic}" type="audio/wav">
|
| 97 |
+
Your browser does not support the audio element.
|
| 98 |
+
</audio>
|
| 99 |
+
`;
|
| 100 |
+
const params = new URLSearchParams({
|
| 101 |
+
title: titleTxt,
|
| 102 |
+
description: descriptionMd,
|
| 103 |
+
});
|
| 104 |
+
const paramsStr = params.toString();
|
| 105 |
+
window.open(`https://huggingface.co/spaces/DGSpitzer/TXT-2-IMG-2-MUSIC-2-VIDEO-w-RIFFUSION/discussions/new?${paramsStr}`, '_blank');
|
| 106 |
+
shareBtnEl.style.removeProperty('pointer-events');
|
| 107 |
+
shareIconEl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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Audio processing tools to convert between spectrogram images and waveforms.
|
| 3 |
+
"""
|
| 4 |
+
import io
|
| 5 |
+
import typing as T
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pydub
|
| 10 |
+
from scipy.io import wavfile
|
| 11 |
+
import torch
|
| 12 |
+
import torchaudio
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def wav_bytes_from_spectrogram_image(image: Image.Image) -> T.Tuple[io.BytesIO, float]:
|
| 16 |
+
"""
|
| 17 |
+
Reconstruct a WAV audio clip from a spectrogram image. Also returns the duration in seconds.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
max_volume = 50
|
| 21 |
+
power_for_image = 0.25
|
| 22 |
+
Sxx = spectrogram_from_image(image, max_volume=max_volume, power_for_image=power_for_image)
|
| 23 |
+
|
| 24 |
+
sample_rate = 44100 # [Hz]
|
| 25 |
+
clip_duration_ms = 5000 # [ms]
|
| 26 |
+
|
| 27 |
+
bins_per_image = 512
|
| 28 |
+
n_mels = 512
|
| 29 |
+
|
| 30 |
+
# FFT parameters
|
| 31 |
+
window_duration_ms = 100 # [ms]
|
| 32 |
+
padded_duration_ms = 400 # [ms]
|
| 33 |
+
step_size_ms = 10 # [ms]
|
| 34 |
+
|
| 35 |
+
# Derived parameters
|
| 36 |
+
num_samples = int(image.width / float(bins_per_image) * clip_duration_ms) * sample_rate
|
| 37 |
+
n_fft = int(padded_duration_ms / 1000.0 * sample_rate)
|
| 38 |
+
hop_length = int(step_size_ms / 1000.0 * sample_rate)
|
| 39 |
+
win_length = int(window_duration_ms / 1000.0 * sample_rate)
|
| 40 |
+
|
| 41 |
+
samples = waveform_from_spectrogram(
|
| 42 |
+
Sxx=Sxx,
|
| 43 |
+
n_fft=n_fft,
|
| 44 |
+
hop_length=hop_length,
|
| 45 |
+
win_length=win_length,
|
| 46 |
+
num_samples=num_samples,
|
| 47 |
+
sample_rate=sample_rate,
|
| 48 |
+
mel_scale=True,
|
| 49 |
+
n_mels=n_mels,
|
| 50 |
+
max_mel_iters=200,
|
| 51 |
+
num_griffin_lim_iters=32,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
wav_bytes = io.BytesIO()
|
| 55 |
+
wavfile.write(wav_bytes, sample_rate, samples.astype(np.int16))
|
| 56 |
+
wav_bytes.seek(0)
|
| 57 |
+
|
| 58 |
+
duration_s = float(len(samples)) / sample_rate
|
| 59 |
+
|
| 60 |
+
return wav_bytes, duration_s
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def spectrogram_from_image(
|
| 64 |
+
image: Image.Image, max_volume: float = 50, power_for_image: float = 0.25
|
| 65 |
+
) -> np.ndarray:
|
| 66 |
+
"""
|
| 67 |
+
Compute a spectrogram magnitude array from a spectrogram image.
|
| 68 |
+
|
| 69 |
+
TODO(hayk): Add image_from_spectrogram and call this out as the reverse.
|
| 70 |
+
"""
|
| 71 |
+
# Convert to a numpy array of floats
|
| 72 |
+
data = np.array(image).astype(np.float32)
|
| 73 |
+
|
| 74 |
+
# Flip Y take a single channel
|
| 75 |
+
data = data[::-1, :, 0]
|
| 76 |
+
|
| 77 |
+
# Invert
|
| 78 |
+
data = 255 - data
|
| 79 |
+
|
| 80 |
+
# Rescale to max volume
|
| 81 |
+
data = data * max_volume / 255
|
| 82 |
+
|
| 83 |
+
# Reverse the power curve
|
| 84 |
+
data = np.power(data, 1 / power_for_image)
|
| 85 |
+
|
| 86 |
+
return data
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def spectrogram_from_waveform(
|
| 90 |
+
waveform: np.ndarray,
|
| 91 |
+
sample_rate: int,
|
| 92 |
+
n_fft: int,
|
| 93 |
+
hop_length: int,
|
| 94 |
+
win_length: int,
|
| 95 |
+
mel_scale: bool = True,
|
| 96 |
+
n_mels: int = 512,
|
| 97 |
+
) -> np.ndarray:
|
| 98 |
+
"""
|
| 99 |
+
Compute a spectrogram from a waveform.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
spectrogram_func = torchaudio.transforms.Spectrogram(
|
| 103 |
+
n_fft=n_fft,
|
| 104 |
+
power=None,
|
| 105 |
+
hop_length=hop_length,
|
| 106 |
+
win_length=win_length,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
waveform_tensor = torch.from_numpy(waveform.astype(np.float32)).reshape(1, -1)
|
| 110 |
+
Sxx_complex = spectrogram_func(waveform_tensor).numpy()[0]
|
| 111 |
+
|
| 112 |
+
Sxx_mag = np.abs(Sxx_complex)
|
| 113 |
+
|
| 114 |
+
if mel_scale:
|
| 115 |
+
mel_scaler = torchaudio.transforms.MelScale(
|
| 116 |
+
n_mels=n_mels,
|
| 117 |
+
sample_rate=sample_rate,
|
| 118 |
+
f_min=0,
|
| 119 |
+
f_max=10000,
|
| 120 |
+
n_stft=n_fft // 2 + 1,
|
| 121 |
+
norm=None,
|
| 122 |
+
mel_scale="htk",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
Sxx_mag = mel_scaler(torch.from_numpy(Sxx_mag)).numpy()
|
| 126 |
+
|
| 127 |
+
return Sxx_mag
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def waveform_from_spectrogram(
|
| 131 |
+
Sxx: np.ndarray,
|
| 132 |
+
n_fft: int,
|
| 133 |
+
hop_length: int,
|
| 134 |
+
win_length: int,
|
| 135 |
+
num_samples: int,
|
| 136 |
+
sample_rate: int,
|
| 137 |
+
mel_scale: bool = True,
|
| 138 |
+
n_mels: int = 512,
|
| 139 |
+
max_mel_iters: int = 200,
|
| 140 |
+
num_griffin_lim_iters: int = 32,
|
| 141 |
+
device: str = "cuda:0",
|
| 142 |
+
) -> np.ndarray:
|
| 143 |
+
"""
|
| 144 |
+
Reconstruct a waveform from a spectrogram.
|
| 145 |
+
|
| 146 |
+
This is an approximate inverse of spectrogram_from_waveform, using the Griffin-Lim algorithm
|
| 147 |
+
to approximate the phase.
|
| 148 |
+
"""
|
| 149 |
+
Sxx_torch = torch.from_numpy(Sxx).to(device)
|
| 150 |
+
|
| 151 |
+
# TODO(hayk): Make this a class that caches the two things
|
| 152 |
+
|
| 153 |
+
if mel_scale:
|
| 154 |
+
mel_inv_scaler = torchaudio.transforms.InverseMelScale(
|
| 155 |
+
n_mels=n_mels,
|
| 156 |
+
sample_rate=sample_rate,
|
| 157 |
+
f_min=0,
|
| 158 |
+
f_max=10000,
|
| 159 |
+
n_stft=n_fft // 2 + 1,
|
| 160 |
+
norm=None,
|
| 161 |
+
mel_scale="htk",
|
| 162 |
+
max_iter=max_mel_iters,
|
| 163 |
+
).to(device)
|
| 164 |
+
|
| 165 |
+
Sxx_torch = mel_inv_scaler(Sxx_torch)
|
| 166 |
+
|
| 167 |
+
griffin_lim = torchaudio.transforms.GriffinLim(
|
| 168 |
+
n_fft=n_fft,
|
| 169 |
+
win_length=win_length,
|
| 170 |
+
hop_length=hop_length,
|
| 171 |
+
power=1.0,
|
| 172 |
+
n_iter=num_griffin_lim_iters,
|
| 173 |
+
).to(device)
|
| 174 |
+
|
| 175 |
+
waveform = griffin_lim(Sxx_torch).cpu().numpy()
|
| 176 |
+
|
| 177 |
+
return waveform
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def mp3_bytes_from_wav_bytes(wav_bytes: io.BytesIO) -> io.BytesIO:
|
| 181 |
+
mp3_bytes = io.BytesIO()
|
| 182 |
+
sound = pydub.AudioSegment.from_wav(wav_bytes)
|
| 183 |
+
sound.export(mp3_bytes, format="mp3")
|
| 184 |
+
mp3_bytes.seek(0)
|
| 185 |
+
return mp3_bytes
|
utils.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import numpy as np
|
| 3 |
+
import httpx
|
| 4 |
+
|
| 5 |
+
from constants import MUBERT_TAGS, MUBERT_LICENSE, MUBERT_MODE, MUBERT_TOKEN
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_mubert_tags_embeddings(w2v_model):
|
| 9 |
+
return w2v_model.encode(MUBERT_TAGS)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_pat(email: str):
|
| 13 |
+
r = httpx.post('https://api-b2b.mubert.com/v2/GetServiceAccess',
|
| 14 |
+
json={
|
| 15 |
+
"method": "GetServiceAccess",
|
| 16 |
+
"params": {
|
| 17 |
+
"email": email,
|
| 18 |
+
"license": MUBERT_LICENSE,
|
| 19 |
+
"token": MUBERT_TOKEN,
|
| 20 |
+
"mode": MUBERT_MODE,
|
| 21 |
+
}
|
| 22 |
+
})
|
| 23 |
+
|
| 24 |
+
rdata = json.loads(r.text)
|
| 25 |
+
assert rdata['status'] == 1, "probably incorrect e-mail"
|
| 26 |
+
pat = rdata['data']['pat']
|
| 27 |
+
return pat
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def find_similar(em, embeddings, method='cosine'):
|
| 31 |
+
scores = []
|
| 32 |
+
for ref in embeddings:
|
| 33 |
+
if method == 'cosine':
|
| 34 |
+
scores.append(1 - np.dot(ref, em) / (np.linalg.norm(ref) * np.linalg.norm(em)))
|
| 35 |
+
if method == 'norm':
|
| 36 |
+
scores.append(np.linalg.norm(ref - em))
|
| 37 |
+
return np.array(scores), np.argsort(scores)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_tags_for_prompts(w2v_model, mubert_tags_embeddings, prompts, top_n=3, debug=False):
|
| 41 |
+
prompts_embeddings = w2v_model.encode(prompts)
|
| 42 |
+
ret = []
|
| 43 |
+
for i, pe in enumerate(prompts_embeddings):
|
| 44 |
+
scores, idxs = find_similar(pe, mubert_tags_embeddings)
|
| 45 |
+
top_tags = MUBERT_TAGS[idxs[:top_n]]
|
| 46 |
+
top_prob = 1 - scores[idxs[:top_n]]
|
| 47 |
+
if debug:
|
| 48 |
+
print(f"Prompt: {prompts[i]}\nTags: {', '.join(top_tags)}\nScores: {top_prob}\n\n\n")
|
| 49 |
+
ret.append((prompts[i], list(top_tags)))
|
| 50 |
+
return ret
|