Building an AI-Powered Mood Music Matcher
Table of contents
Introduction
The idea for Mood Music Matcher arose from my personal experience of searching for the perfect song to match my mood. I wanted to develop a tool that not only understands emotions but also curates' music to support mental well-being.
Solution
Mood Music Matcher addresses this by using advanced natural language processing (NLP) to analyze the sentiment of journal entries. It then suggests Spotify playlists tailored to the user's emotional needs.
GenAI Model: OpenAI API
Music Data Integration: Spotify API
Orchestration Framework: LangChain
App Framework: Streamlit
Github repository :mood-music-matcher
Deployed link :mood-music-matcher-maulcenter.streamlit.app
How to Use
Enter Your Journal Entry: Share your day or thoughts in the text area.
Analyze Mood: The app uses AI to determine your mood.
Get Music Suggestions: Discover songs that resonate with your mood.
Listen and Enjoy: Click the link to be automatically directed to Spotify and play the song.
Prerequisites
Set up a Spotify Developer Account
Go to the Spotify Developer Dashboard.
Create an application.
Collect your Client ID and Client Secret.
Set up a OpenAI Account
Go to the OpenAI website.
Sign up for an account.
Generate your API key in the dashboard.
Set up Environment Variables
In your development environment, set these as environment variables:
export CLIENT_ID='your_spotify_client_id'
export CLIENT_SECRET='your_spotify_client_secret'
export OPENAI_API_KEY='your_openai_api_key'
Code Overview
Here’s a brief look at the core functionalities:
Analyze Mood
The app utilizes OpenAI to determine the mood from your journal entry.
def analyze_mood(input_text):
llm = OpenAI(temperature=0.7, openai_api_key=openai_api_key)
mood_analysis = llm(f"Identify the mood of this text for music recommendation: {input_text}")
return mood_analysis.strip().lower()
Fetch Songs
It uses the Spotify API to fetch songs that match the identified mood.
def get_songs_for_mood(mood):
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(
client_id=spotify_client_id,
client_secret=spotify_client_secret))
results = sp.search(q=mood, type='track', limit=5, market='US')
return [(track['name'], track['artists'][0]['name'], track['external_urls']['spotify']) for track in results['tracks']['items']]
Explain Song Choice
OpenAI provides explanations for why each song fits your mood.
def explain_song_choice(mood, track_name, artist):
llm = OpenAI(temperature=0.2, openai_api_key=openai_api_key)
explanation = llm(f"Explain why the song '{track_name}' by {artist} matches the mood '{mood}' based on its musical style and mood, without referring to the lyrics.")
return explanation
User Interface
The app interface is built with Streamlit, allowing users to input their journal entries and receive song recommendations.
with st.form('journal_form'):
journal_text = st.text_area(
'✨ Describe Your Day, Today:',
placeholder='E.g., Today was quite challenging, but I managed to push through and complete my tasks...',
height=200
)
submitted = st.form_submit_button('Get Songs 🎶')
if submitted:
mood = analyze_mood(journal_text)
st.subheader("Your Mood 🎭")
st.write(f"It seems like you're feeling: **{mood}**")
song_list = get_songs_for_mood(mood)
st.subheader("Suggested Songs 🎵")
for idx, (name, artist, url) in enumerate(song_list, start=1):
explanation = explain_song_choice(mood, name, artist)
st.write(f"{idx}. **{name}** by {artist} - [Listen on Spotify]({url}) 🎧")
st.write(f"This song fits your mood because: {explanation}")
Conclusion
Mood Music Matcher is a unique way to connect with your emotions through music. By integrating AI and Spotify, it offers a seamless experience that makes your day brighter. Try it out and enjoy a personalized musical journey!
Feel free to customize further or ask if you need any more changes!
Special thanks to@HASHNODE
#AIForTomorrow #OpenAI #SpotifyAPI #Spotify
Subscribe to my newsletter
Read articles from Maulana Akbar Dwijaya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Maulana Akbar Dwijaya
Maulana Akbar Dwijaya
I'm an IT Consultant from ISGS