PushkarA07 commited on
Commit
e520534
·
1 Parent(s): 386d22a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
3
+ from diffusers import LDMTextToImagePipeline
4
+ import gradio as gr
5
+ import PIL.Image
6
+ import numpy as np
7
+ import random
8
+ import torch
9
+ import subprocess
10
+ from transformers import Wav2Vec2Processor, Wav2Vec2Tokenizer
11
+ from transformers import AutoModelWithLMHead, AutoModelForCausalLM, AutoTokenizer
12
+ from transformers import WhisperForConditionalGeneration, WhisperConfig, WhisperProcessor
13
+ import torchaudio
14
+ import nltk
15
+ from pydub import AudioSegment
16
+ import re
17
+ from datasets import load_dataset
18
+ from transformers import AutoModelWithLMHead, AutoTokenizer, set_seed, pipeline
19
+ import torch
20
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
21
+ import torch
22
+ from diffusers import StableDiffusionPipeline, AutoencoderKL, UNet2DConditionModel, PNDMScheduler, DPMSolverMultistepScheduler, LMSDiscreteScheduler
23
+ from transformers import CLIPTextModel, CLIPTokenizer
24
+ from tqdm.auto import tqdm
25
+ from torch import autocast
26
+ from PIL import Image
27
+ torch_device = "cuda" if torch.cuda.is_available() else "cpu"
28
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
29
+
30
+ def generate_lyrics(sample):
31
+ model_name = "openai/whisper-tiny.en"
32
+ model_config = WhisperConfig.from_pretrained(model_name)
33
+ processor = WhisperProcessor.from_pretrained(model_name)
34
+ asr_model = WhisperForConditionalGeneration.from_pretrained(model_name, config=model_config)
35
+ asr_model.eval()
36
+ input_features = processor(sample["array"], sampling_rate=sample["sampling_rate"], return_tensors="pt").input_features
37
+ transcript = asr_model.generate(input_features)
38
+ predicted_ids = asr_model.generate(input_features)
39
+ transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
40
+ lyrics = transcription[0]
41
+ return lyrics
42
+
43
+ def generate_summary(lyrics):
44
+ summarizer = pipeline("summarization", model="philschmid/bart-large-cnn-samsum")
45
+ summary = summarizer(lyrics)
46
+ return summary
47
+
48
+ def generate_prompt(summary):
49
+ model_name = 'gpt2'
50
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
51
+ model = GPT2LMHeadModel.from_pretrained(model_name)
52
+ model = model.to(device)
53
+ prompt = f"Create an image that represents the feeling of '{summary}'"
54
+ input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
55
+ output = model.generate(input_ids, do_sample=True, max_length=100, temperature=0.7)
56
+ prompt_text = tokenizer.decode(output[0], skip_special_tokens=True)
57
+ return prompt_text
58
+
59
+ def generate_image(prompt,
60
+ height = 512, # default height of Stable Diffusion
61
+ width = 512 , # default width of Stable Diffusion
62
+ num_inference_steps = 50 , # Number of denoising steps
63
+ guidance_scale = 7.5 , # Scale for classifier-free guidance
64
+ generator = torch.manual_seed(32), # Seed generator to create the inital latent noise
65
+ batch_size = 1,):
66
+ pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
67
+ pipe = pipe.to(torch_device)
68
+ vae = AutoencoderKL.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="vae")
69
+ tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
70
+ text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
71
+ unet = UNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="unet")
72
+ scheduler = DPMSolverMultistepScheduler.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="scheduler")
73
+ vae = vae.to(torch_device)
74
+ text_encoder = text_encoder.to(torch_device)
75
+ unet = unet.to(torch_device)
76
+ text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
77
+ with torch.no_grad():
78
+ text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
79
+ max_length = text_input.input_ids.shape[-1]
80
+ uncond_input = tokenizer([""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt")
81
+ with torch.no_grad():
82
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
83
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
84
+ latents = torch.randn((batch_size, unet.in_channels, height // 8, width // 8), generator=generator,)
85
+ latents = latents.to(torch_device)
86
+ scheduler.set_timesteps(num_inference_steps)
87
+ latents = latents * scheduler.init_noise_sigma
88
+ for t in tqdm(scheduler.timesteps):
89
+ latent_model_input = torch.cat([latents] * 2)
90
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
91
+ with torch.no_grad():
92
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
93
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
94
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
95
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
96
+ latents = 1 / 0.18215 * latents
97
+ with torch.no_grad():
98
+ image = vae.decode(latents).sample
99
+ image = (image / 2 + 0.5).clamp(0, 1)
100
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
101
+ images = (image * 255).round().astype("uint8")
102
+ pil_images = [Image.fromarray(image) for image in images]
103
+ f_images = pil_images
104
+ return f_images
105
+
106
+ def predict(audio, steps=100, seed=42, guidance_scale=6.0):
107
+ generator = torch.manual_seed(seed)
108
+ lyrics = generate_lyrics(audio)
109
+ summary_1 = generate_summary(lyrics)
110
+ prompt_text_1 = generate_prompt(summary_1[0]['summary_text'])
111
+ images = generate_image(prompt= prompt_text_1, generator= generator, num_inference_steps=steps, guidance_scale=guidance_scale)
112
+ return images[0]
113
+
114
+ random_seed = random.randint(0, 2147483647)
115
+ gr.Interface(
116
+ predict,
117
+ inputs=[
118
+ gr.Audio(source="upload", type="filepath"),
119
+ # gr.inputs.Textbox(label='Text', default='a chalk pastel drawing of a llama wearing a wizard hat'),
120
+ gr.inputs.Slider(1, 100, label='Inference Steps', default=50, step=1),
121
+ gr.inputs.Slider(0, 2147483647, label='Seed', default=random_seed, step=1),
122
+ gr.inputs.Slider(1.0, 20.0, label='Guidance Scale - how much the prompt will influence the results', default=6.0, step=0.1),
123
+ ],
124
+ examples=[[load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")][0]["audio"]],
125
+ outputs=gr.Image(shape=[256,256], type="pil", elem_id="output_image"),
126
+ css="#output_image{width: 256px}",
127
+ title="Cover Generator (audio-to-image)",
128
+ description="Application of OpenAI tools such as Whisper, ChatGPT, and DALL-E to produce covers for the given audio",
129
+ ).launch()