File size: 7,154 Bytes
a424cb5
 
ee78b79
559b5d5
dda2b58
 
 
c9a570c
dda2b58
 
 
391fb3b
 
dda2b58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfc442
dda2b58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
871f141
 
dda2b58
871f141
dda2b58
851a67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dda2b58
 
 
 
b65c6c9
dda2b58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
851a67d
 
 
 
 
 
 
 
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
import os
os.system('pip install tf-keras keras==3.5.0 tensorflow transformers')
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

import streamlit as st
from transformers import pipeline
import emoji
import base64
import requests

# Convert Google Drive link to a direct image link
#logo_url = "https://drive.google.com/uc?export=view&id=1cKAxqifPx3ytEsjpzFuHs7NGe7Ml2toW"
logo_url = "https://imgur.com/a/sLfAPMX"  #imgur website

# Load the emotion detection pipeline (Hugging Face model)
emotion_detector = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")

# Function to convert emojis to text
def emoji_to_text(text):
    return emoji.demojize(text, delimiters=(" ", " "))  # Convert emojis to text descriptions

# Function to detect emotion from text
def detect_emotion(text):
    text_with_emojis = emoji_to_text(text)  # Convert emojis to text
    result = emotion_detector(text_with_emojis)[0]  # Use the emotion detection model
    return result['label']

# Function to append emoji to input text
def append_emoji(text, selected_emoji):
    return text + selected_emoji  # Append the selected emoji to the text input

# Function to get mood description from slider value
def get_mood_from_slider(mood_value):
    if mood_value < 0.1:
        return "very sad"
    elif mood_value < 0.2:
        return "sad"
    elif mood_value < 0.3:
        return "slightly sad"
    elif mood_value < 0.4:
        return "neutral"
    elif mood_value < 0.5:
        return "calm"
    elif mood_value < 0.6:
        return "slightly happy"
    elif mood_value < 0.7:
        return "happy"
    elif mood_value < 0.8:
        return "very happy"
    elif mood_value < 0.9:
        return "excited"
    else:
        return "ecstatic"

# Function to get tempo description from slider value
def get_tempo_from_slider(tempo_value):
    if tempo_value < 0.1:
        return "very slow"
    elif tempo_value < 0.2:
        return "slow"
    elif tempo_value < 0.3:
        return "moderately slow"
    elif tempo_value < 0.4:
        return "medium slow"
    elif tempo_value < 0.5:
        return "medium"
    elif tempo_value < 0.6:
        return "medium fast"
    elif tempo_value < 0.7:
        return "fast"
    elif tempo_value < 0.8:
        return "very fast"
    elif tempo_value < 0.9:
        return "rapid"
    else:
        return "extremely fast"

# Function to search YouTube for a video based on mood and tempo
def search_youtube_music(mood_value, tempo_value):
    mood_query = get_mood_from_slider(mood_value)
    tempo_query = get_tempo_from_slider(tempo_value)
    search_query = f"{mood_query} {tempo_query} music"
    
    # YouTube API request (API_KEY to be added if required)
    params = {
        "part": "snippet",
        "q": search_query,
        "key": "AIzaSyCI1PGvgm5fEXxSVLjEteQwxi90qe2nUtQ",  # Replace with a valid YouTube API key
        "type": "video",
        "videoCategoryId": "10",  # Music category
        "maxResults": 1  # Only get 1 result
    }
    
    response = requests.get("https://www.googleapis.com/youtube/v3/search", params=params)
    if response.status_code != 200:
        return "Error fetching YouTube data"
    
    json_response = response.json()
    if "items" not in json_response or len(json_response["items"]) == 0:
        return "No videos found"
    
    video_id = json_response["items"][0]["id"]["videoId"]
    video_url = f"https://www.youtube.com/embed/{video_id}"
    
    youtube_video_link = f"https://www.youtube.com/watch?v={video_id}"
    iframe_html = f'<iframe width="560" height="315" src="{video_url}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'

    download_link_html = f'<a href="https://www.y2mate.com/youtube/{video_id}" target="_blank">Download Video or Audio</a>'
    
    return iframe_html + "<br>" + download_link_html


# Spotify Authentication Function
SPOTIFY_CLIENT_ID = "d4925860a6894ce68c72a6ff4b69f542"
SPOTIFY_CLIENT_SECRET = "787194348cb544ad889c397cf4963cc8"

def get_spotify_token():
    auth_url = "https://accounts.spotify.com/api/token"
    credentials = f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}"
    headers = {
        "Authorization": f"Basic {base64.b64encode(credentials.encode()).decode()}",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {"grant_type": "client_credentials"}

    response = requests.post(auth_url, headers=headers, data=data)
    response.raise_for_status()
    return response.json().get("access_token")

# Function to get song recommendations from Spotify
def get_spotify_recommendations(mood):
    genre = "pop" if mood not in ["sad", "happy"] else mood
    access_token = get_spotify_token()

    search_url = "https://api.spotify.com/v1/search"
    headers = {"Authorization": f"Bearer {access_token}"}
    params = {
        "q": genre,
        "type": "track",
        "limit": 3
    }

    response = requests.get(search_url, headers=headers, params=params)
    response.raise_for_status()

    tracks = response.json().get("tracks", {}).get("items", [])
    return [f"{track['name']} by {track['artists'][0]['name']} - [🎡 Listen on Spotify]({track['external_urls']['spotify']})"
            for track in tracks]

# Streamlit UI
st.set_page_config(page_title="Emotion Detector & Music Finder", layout="centered")

# Display logo
st.image(logo_url, use_container_width=True)

st.title("🎭 AI Emotion Detector & Music Finder")

# Tabs for emotion detection and music finder
tab1, tab2 = st.tabs(["Emotion Detection", "Mood & Tempo Music Finder"])

# Tab 1: Emotion Detection
with tab1:
    st.subheader("Emotion Detection from Text")

    text_input = st.text_input("Enter your text here", placeholder="Type something here...")
    emoji_list = ["😊", "😒", "😑", "πŸ˜‚", "😍", "😎", "πŸ€”", "😴", "πŸ‘", "πŸŽ‰"]
    selected_emoji = st.selectbox("Choose an emoji to add", options=emoji_list)

    if st.button("Add Emoji to Text"):
        text_input = append_emoji(text_input, selected_emoji)

    if st.button("Analyze Emotion"):
        if text_input:
            detected_emotion = detect_emotion(text_input)
            st.success(f"Detected Emotion: **{detected_emotion}**")
        else:
            st.error("Please enter some text before analyzing.")

# Tab 2: Mood & Tempo Music Finder
with tab2:
    st.subheader("Find Music Based on Mood and Tempo")
    
    mood_slider = st.slider("Mood", min_value=0.0, max_value=1.0, step=0.1)
    tempo_slider = st.slider("Tempo", min_value=0.0, max_value=1.0, step=0.1)

    if st.button("Find Music"):
        youtube_embed = search_youtube_music(mood_slider, tempo_slider)
        st.markdown(youtube_embed, unsafe_allow_html=True)

    # Fetch Spotify song recommendations based on mood
        mood_description = get_mood_from_slider(mood_slider)
        spotify_recommendations = get_spotify_recommendations(mood_description)
        
        st.subheader("Spotify Song Recommendations")
        for song in spotify_recommendations:
            st.markdown(song, unsafe_allow_html=True)