Spaces:
Sleeping
Sleeping
| 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) | |