smejak commited on
Commit
b569211
·
1 Parent(s): 30284dd
Files changed (1) hide show
  1. main.py +39 -0
main.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from PIL import Image
3
+ import scipy
4
+ from transformers import BlipProcessor, BlipForConditionalGeneration, AutoProcessor, MusicgenForConditionalGeneration
5
+ import streamlit as st
6
+
7
+ def image_to_music(raw_image):
8
+ img_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
9
+ img_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
10
+
11
+ inputs = img_processor(raw_image, return_tensors="pt")
12
+
13
+ out = img_model.generate(**inputs)
14
+ txt = img_processor.decode(out[0], skip_special_tokens=True)
15
+
16
+ audio_processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
17
+ audio_model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
18
+
19
+ inputs = audio_processor(
20
+ text=[txt],
21
+ padding=True,
22
+ return_tensors="pt",
23
+ )
24
+
25
+ audio_values = audio_model.generate(**inputs, max_new_tokens=256)
26
+ sampling_rate = audio_model.config.audio_encoder.sampling_rate
27
+ scipy.io.wavfile.write("music.wav", rate=sampling_rate, data=audio_values[0, 0].numpy())
28
+
29
+ st.header("VisTune: an AI Image-to-Music generator")
30
+
31
+ uploaded_image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
32
+
33
+ if uploaded_image:
34
+ st.image(uploaded_image, caption="Uploaded Image.", use_column_width=True)
35
+
36
+ if st.button("Generate Music") and uploaded_image:
37
+ raw_image = Image.open(uploaded_image).convert('RGB')
38
+ image_to_music(raw_image)
39
+ st.audio("music.wav")