RasmusLH commited on
Commit
fae6f68
1 Parent(s): e06f1a7

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -0
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import transformers
5
+ import torch
6
+ from huggingface_hub import login
7
+ from dotenv import load_dotenv
8
+ import os
9
+
10
+ # Import data
11
+ music_data = pd.read_csv("Spotify_Youtube.csv")
12
+
13
+ # Login to HuggingFace Hub
14
+ load_dotenv()
15
+ HUGGINGFACE_API_KEY = os.environ.get("HUGGINGFACE_API_KEY")
16
+ login(HUGGINGFACE_API_KEY)
17
+
18
+ # Load Meta LLaMA model
19
+ model_id = "meta-llama/Meta-Llama-3-8B-Instruct"
20
+ pipeline = transformers.pipeline(
21
+ "text-generation",
22
+ model=model_id,
23
+ model_kwargs={"torch_dtype": torch.bfloat16},
24
+ device_map="auto"
25
+ )
26
+
27
+ # Function to parse user input using Meta LLaMA model
28
+ def parse_user_input(user_input):
29
+ messages = [
30
+ {
31
+ "role": "system",
32
+ "content": """You will be provided with an input: '{user_input}', and your task is to determine the following:
33
+ - Valence: a number that is equal to the mood. Positive moods are closer to 1 and negative moods are closer to 0.
34
+ - Number of songs: the number of songs the user requests.
35
+ - Tempo: the tempo of the songs.
36
+ - Danceability: the danceability of the songs.
37
+
38
+ Provide this information in the following format with each value separated by a space:
39
+ 'valence number_of_songs tempo danceability'
40
+ Example: '0.5 20 120 0.8'
41
+ """
42
+ },
43
+ {
44
+ "role": "user",
45
+ "content": user_input
46
+ },
47
+ ]
48
+
49
+ prompt = pipeline.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
50
+
51
+ terminators = [
52
+ pipeline.tokenizer.eos_token_id,
53
+ pipeline.tokenizer.convert_tokens_to_ids("")
54
+ ]
55
+
56
+ outputs = pipeline(
57
+ prompt,
58
+ max_new_tokens=256,
59
+ eos_token_id=terminators,
60
+ do_sample=True,
61
+ temperature=0.6,
62
+ top_p=0.9,
63
+ )
64
+ return outputs[0]["generated_text"][len(prompt):]
65
+
66
+ # Function to create a new dataframe from the music dataframe based on valence, number of tracks, tempo, and danceability
67
+ def get_tracks_by_artist_and_danceability(music_data, valence, num_tracks, tempo, danceability):
68
+ filtered_tracks = music_data[
69
+ (music_data['Valence'].between(valence - 0.1, valence + 0.1)) &
70
+ (music_data['Tempo'].between(tempo - 30, tempo + 30)) &
71
+ (music_data['Danceability'].between(danceability - 0.2, danceability + 0.2))
72
+ ]
73
+ return filtered_tracks.head(num_tracks)[['Track', 'Artist']]
74
+
75
+ # Streamlit Application
76
+ logo = "music_logo.png"
77
+
78
+ # Sidebar
79
+ with st.sidebar:
80
+ st.image(logo, width=100)
81
+ st.header("Navigation")
82
+ tab_selection = st.sidebar.radio("Go to", ["Music Generator", "Browse Music", "About Us"])
83
+
84
+ # Music generator page
85
+ if tab_selection == "Music Generator":
86
+ st.header("Mood Playlist Generator")
87
+ st.write("Enter your music preferences in a detailed format and receive a personalized playlist based on your mood")
88
+ user_prompt = st.text_input("Example: 'I want 20 happy songs with high tempo that I can dance to!'")
89
+
90
+ if st.button("Generate Playlist"):
91
+ try:
92
+ with st.spinner("Processing your request..."):
93
+ parsed_input = parse_user_input(user_prompt)
94
+ # st.write(f"Parsed input: {parsed_input}")
95
+
96
+ # Extract parameters from the parsed input
97
+ valence, num_tracks, tempo, danceability = parsed_input.split()
98
+ valence = float(valence)
99
+ num_tracks = int(num_tracks)
100
+ tempo = int(tempo)
101
+ danceability = float(danceability)
102
+
103
+ # st.write(f"Number of tracks: {num_tracks}, Valence: {valence}, Tempo: {tempo}, Danceability: {danceability}")
104
+
105
+ tracks = get_tracks_by_artist_and_danceability(music_data, valence, num_tracks, tempo, danceability)
106
+ # st.write(f"Found {len(tracks)} tracks.")
107
+
108
+ if tracks.empty:
109
+ st.write("No tracks found. Please try a different query.")
110
+ else:
111
+ st.write("Here are your recommended playlist:")
112
+ st.table(tracks)
113
+ st.button("Add playlist to Spotify")
114
+ except ValueError:
115
+ st.write("Error: Unable to parse the input. Please make sure the format is correct.")
116
+
117
+ # Browse music page
118
+ elif tab_selection == "Browse Music":
119
+ st.header("Browse Music")
120
+ st.write("Explore the music data used for generating your playlists.")
121
+ df = pd.read_csv("Spotify_Youtube.csv")
122
+ st.dataframe(df)
123
+
124
+ # About us page
125
+ elif tab_selection == "About Us":
126
+ st.header("About Us")