Spaces:
Runtime error
Runtime error
File size: 9,510 Bytes
16e6c68 a4da1b4 16e6c68 fd6d83c 16e6c68 fd6d83c 16e6c68 d95c97b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# -*- coding: utf-8 -*-
"""Untitled1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1yIRyQq7IUIqBQiXAPKoa0n2gT8Lr_qMw
"""
#!pip install openai
#!pip install imageio
#!pip install replicate
#!pip install gradio
"""## Importing Libraries"""
import openai
import re
import pandas as pd
import replicate
import pandas as pd
from PIL import Image
import requests
from io import BytesIO
import os
from IPython.display import Audio, display
import gradio as gr
import numpy
from PIL import ImageDraw
from PIL import ImageFont
import random
#!git clone https://github.com/Neelanjan-chakraborty/MelodyGen.git
#!ls MelodyGen
"""## Function To Generate Genre Based on Mood"""
def generate_genre_recommendations(mood,key):
openai.api_key=key
response = openai.Completion.create(
engine='text-davinci-003',
prompt=f"I'm feeling {mood} and I want only genre recommendations and not songs also please separate using comma.",
max_tokens=100,
n=1,
stop=None,
temperature=0.5
)
genres = set(response.choices[0].text.strip().split(',')) # Extract genres from response
#if len(genres) < 3:
# # Provide some default genre recommendations
# genres = {'Pop', 'Rock', 'Electronic'}
genre_recommendations = list(genres)[:3] # Limit to 3 unique genres
return ', '.join(genre_recommendations) # Return as comma-separated string
def recommend(user_mood,key):
genre_recommendations = generate_genre_recommendations(user_mood,key)
out = genre_recommendations.split(',')
return out
"""## Function to Generate Melody"""
def melodygen(api_token,prompt):
client = replicate.Client(api_token)
output = client.run(
"joehoover/musicgen:ba9bdc5a86f60525ba23590a03ae1e407b9a40f4a318a85af85748d641e6659f",
input={"model_version": "melody","prompt":prompt,"continuation_start": 0,"continuation_end": 30, "duration":30,
}
)
return output
#api_token='r8_Z30IhmLhqMoeJeNkl4S92JzSp8stlh82NZAnI'
#prompt=input("Enter your Genre : ")
#melodygen(api_token,prompt)
"""## Function To Generate a Song Name"""
def generate_song_name(mood,key):
openai.api_key=key
response = openai.Completion.create(
engine='text-davinci-003',
prompt=f"I'm feeling {mood} and I want only random ai generated Song Name and please separate these names using comma.",
max_tokens=100,
n=1,
stop=None,
temperature=0.5
)
names = set(response.choices[0].text.strip().split(',')) # Extract genres from response
get_names = list(names)[:3] # Limit to 3 unique genres
return ', '.join(get_names) # Return as comma-separated string(mood):
"""## Function To Generate Album Art and Album Art Animation"""
def albumart(user_mood,key,name):
openai.api_key=key
response = openai.Image.create(
prompt=f"Music album art of mood{user_mood}",
n=1,
size="512x512"
)
image_url = response['data'][0]['url']
# Fetch the image from the URL
response = requests.get(image_url)
response.raise_for_status()
# Load the image into a PIL Image object
image = Image.open(BytesIO(response.content))
# Load the font
font_path = "MelodyGen/Lobster-Regular.ttf"
font_size = 48
font = ImageFont.truetype(font_path, font_size)
position = (image.width // 2, image.height // 2)
# Create a new ImageDraw object
draw = ImageDraw.Draw(image)
# Get a random color
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# Calculate the position to center the text
text_width, text_height = draw.textsize(name, font=font)
text_position = (position[0] - text_width // 2, position[1] - text_height // 2)
# Add the text to the image
draw.text(text_position, name, font=font, fill=color)
path='album_art.jpg'
image.save(path)
return path
#overlay_images(background_image_path, foreground_image_path)
from PIL import Image, ImageSequence
def overlay_images(background_image_path):
foreground_image_path='MelodyGen/Mockup4.png'
num_frames=36
rotation_angle=10
# Open the background and foreground images
background_image = Image.open(background_image_path).resize((600, 600))
foreground_image = Image.open(foreground_image_path).resize((1024, 768)).convert("RGBA")
# Create a new image with transparency
final_image = Image.new("RGBA", (1024, 768))
# Calculate the position to paste the background image at the center
paste_x = int(100.50)
paste_y = int(100.50)
# Create a list to store the frames of the GIF animation
frames = []
# Calculate the center point of the background image
center_x = int(background_image.width / 2)
center_y = int(background_image.height / 2)
# Rotate the background image and create frames for the GIF animation
for angle in range(0, 360, rotation_angle):
# Create a copy of the background image
rotated_image = background_image.copy()
# Rotate the image by the specified angle around its center
rotated_image = rotated_image.rotate(angle, resample=Image.BICUBIC, center=(center_x, center_y))
# Overlay the rotated background image at the center of the final image
final_image.paste(rotated_image, (paste_x, paste_y))
# Overlay the foreground image on the background image
final_image.paste(foreground_image, (0, 0), mask=foreground_image)
# Append the current frame to the list of frames
frames.append(final_image.copy())
# Convert the image mode of frames to RGB (removing alpha channel)
frames_rgb = [frame.convert("RGB") for frame in frames]
# Save the frames as an animated GIF
output_path = "animation2.gif"
frames_rgb[0].save(output_path, save_all=True, append_images=frames_rgb[1:], loop=0, duration=100,optimize=True, quality=100)
# Return the output path of the animated GIF
return output_path
#background_image_path = "/content/input.png" # Path to the background image
#foreground_image_path = "/content/Mockup4.png" # Path to the foreground PNG image
#rotation_angle = 10
#overlay_images(background_image_path, foreground_image_path)
def main_func(user_mood,key,api_token,genre):
if genre is None:
out = recommend(user_mood, key)[0]
else:
out = genre
name=generate_song_name(user_mood,key).split(",")
image=albumart(user_mood ,key,name[0])
album_art=overlay_images(image)
song=melodygen(api_token,out[0])
return album_art,name[0],genre,song
"""## Gradio UI"""
css1= """.gradio-container{
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
background-size: 400% 400%;
animation: gradient 15s ease infinite;
height: 100vh;
}
@keyframes gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.mood {
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
background-size: 400% 400%;
animation: gradient 15s ease infinite;
height: 100vh;
}
@keyframes gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.OpenAI {
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab)!important;
animation: gradient 15s ease infinite!important;
}
@keyframes gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
}
"""
def check_box(check,ch):
if(check==True):
return gr.Dropdown.update(visible=True)
return gr.Dropdown.update(visible=False, value=None)
with gr.Blocks(css=css1,theme='freddyaboulton/dracula_revamped',title="🎵MoodMelody🤖 by Neelanjan",thumbnail="MelodyGen/Mood-Melody.jpg") as demo:
with gr.Row():
with gr.Column(scale=1):
Mood=textbox = gr.Textbox(label="Enter Your Mood",value="Happy",placeholder="How is Your Mood Now?", elem_id="warning", elem_classes="feedback")
Key=textbox = gr.Textbox(label="Enter Open AI Key",placeholder="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",elem_id="warning", elem_classes="feedback")
Key2=textbox = gr.Textbox(label="Enter Replicate Key",placeholder="r8-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",elem_id="warning", elem_classes="feedback")
check=gr.Checkbox(label="Custom Genre?", info="Select if you want custom Genres",value=True,elem_id="warning", elem_classes="feedback")
ch=gr.Dropdown(
[
"Acoustic","Alternative","Ambient","Blues","Classical","Country","Dance","Disco","Electronic","Folk","Funk","Gospel","Hip Hop","Indie","Jazz","Latin","Metal","Opera","Pop","Punk",
"R&B","Reggae","Rock","Soul","Techno","World",# Add more genres as needed
],max_choices=1,
multiselect=True,visible=True,
label="Music Genres",
info="Select only one genre of music"
)
check.change(check_box, check, ch)
btn = gr.Button(value="Generate Song")
with gr.Column(scale=4):
SongName=gr.Textbox(label="Song Name",placeholder="Song Name will appear Here")
Genres=gr.Textbox(label="Genre",placeholder="Genres")
AlbumArt=gr.Image(label="AI Generated Album Art")
MusicGen=gr.Audio(label="AI Generated Music",format="wav")
btn.click(main_func, inputs=[Mood,Key,Key2,ch], outputs=[AlbumArt,SongName,Genres,MusicGen])
if __name__ == "__main__":
demo.launch(show_error=True,debug=True)
|