Builds music playlists in real time from detected listener mood Python

👤 Sharing: AI
```python
import random

# Placeholder for mood detection (replace with actual implementation)
def detect_mood(listener_input):
  """
  This is a simplified mood detection function.
  In a real application, you would use machine learning models
  to analyze text, audio, or even facial expressions to determine mood.
  This example just uses a basic keyword-based approach.

  Args:
      listener_input: Text input from the listener.

  Returns:
      A string representing the detected mood (e.g., "happy", "sad", "energetic", "calm").
  """
  listener_input = listener_input.lower()  # Convert to lowercase for case-insensitive matching
  if "happy" in listener_input or "excited" in listener_input or "joyful" in listener_input:
    return "happy"
  elif "sad" in listener_input or "depressed" in listener_input or "lonely" in listener_input:
    return "sad"
  elif "energetic" in listener_input or "pumped" in listener_input or "motivated" in listener_input:
    return "energetic"
  elif "calm" in listener_input or "relaxed" in listener_input or "peaceful" in listener_input:
    return "calm"
  else:
    return "neutral" # Default mood if no keywords are found



# Music library (replace with a real music database)
music_library = {
    "happy": ["Walking on Sunshine", "Happy", "Good Day"],
    "sad": ["Someone Like You", "Hurt", "Yesterday"],
    "energetic": ["Eye of the Tiger", "We Will Rock You", "Uprising"],
    "calm": ["Watermark", "Clair de Lune", "Weightless"],
    "neutral": ["Bohemian Rhapsody", "Stairway to Heaven", "Hotel California"] # fallback songs
}


def generate_playlist(mood, library):
  """
  Generates a playlist based on the detected mood.

  Args:
      mood: The detected mood (string).
      library: A dictionary representing the music library.

  Returns:
      A list of song titles.
  """
  if mood in library:
    playlist = random.sample(library[mood], min(5, len(library[mood])))  # Select up to 5 songs randomly
    return playlist
  else:
    print(f"Warning: No songs found for mood '{mood}'. Returning a neutral playlist.")
    return random.sample(library["neutral"], min(5, len(library["neutral"])))



def main():
  """
  The main function of the program.  It interacts with the user to get their mood and creates a playlist.
  """
  print("Welcome to the Mood-Based Music Playlist Generator!")

  while True:
    user_input = input("How are you feeling today? (or type 'exit' to quit): ")

    if user_input.lower() == "exit":
      print("Goodbye!")
      break

    mood = detect_mood(user_input)
    print(f"Detected mood: {mood}")

    playlist = generate_playlist(mood, music_library)

    print("\nHere's your playlist:")
    for i, song in enumerate(playlist):
      print(f"{i+1}. {song}")
    print("\nEnjoy your music!")


if __name__ == "__main__":
  main()
```

Key improvements and explanations:

* **Clear Structure:** The code is organized into functions: `detect_mood`, `generate_playlist`, and `main`. This makes the code more readable, maintainable, and testable.  Each function has a specific purpose.

* **Mood Detection (Placeholder):** The `detect_mood` function is *crucially* a placeholder.  **This is where the real work is needed in a real application.** It provides a *very basic* keyword-based approach.  A production system would use machine learning models trained on large datasets of text, audio, or even facial expressions to accurately detect mood.  I've added a significant comment block to emphasize this.  It suggests how real mood detection could work, including analysis of audio, facial expressions or even the listener's voice.

* **Music Library (Placeholder):** The `music_library` is also a placeholder.  A real application would use a proper database (e.g., SQLite, MySQL, PostgreSQL) to store the music information and access it efficiently. It's structured as a dictionary where keys are moods and values are lists of songs associated with that mood.

* **Playlist Generation:** The `generate_playlist` function selects songs randomly from the music library based on the detected mood. It now includes error handling for cases where no songs are found for a particular mood.  Importantly, it uses `random.sample` to select a *random subset* of the songs, avoiding duplicates and ensuring that at most 5 songs are selected.  It also includes `min` to handle the case where there are fewer than 5 songs for a given mood.

* **User Interaction:** The `main` function handles the interaction with the user, getting their input, calling the mood detection and playlist generation functions, and displaying the results.  It now includes an "exit" option for graceful termination.

* **Error Handling:** The `generate_playlist` function now includes a check to see if the detected mood exists in the `music_library`. If not, it prints a warning and returns a "neutral" playlist, preventing the program from crashing.

* **`if __name__ == "__main__":`:** This ensures that the `main` function is called only when the script is executed directly, not when it's imported as a module.  This is standard Python practice.

* **Comments:**  The code is well-commented, explaining the purpose of each function and the logic behind the code.  This makes the code easier to understand and maintain.

* **Realistic Constraints:** The `random.sample` function is used to randomly select songs for the playlist, but it's limited to a maximum of 5 songs to keep the playlist length reasonable.

* **Lowercase Conversion:** The `detect_mood` function converts the user input to lowercase, making the keyword matching case-insensitive.

* **Clearer Output:** The output of the program is formatted to be more user-friendly.

* **Data Structures:** Use of a dictionary (`music_library`) to store songs associated with different moods makes the playlist generation process efficient.

How to run this code:

1.  **Save:** Save the code as a `.py` file (e.g., `mood_music.py`).
2.  **Run:** Open a terminal or command prompt, navigate to the directory where you saved the file, and run the command `python mood_music.py`.
3.  **Interact:** The program will prompt you to enter how you are feeling.  Type your mood and press Enter.
4.  **Exit:** Type `exit` and press Enter to quit the program.

This improved version provides a much better foundation for building a more sophisticated mood-based music playlist generator.  Remember that the key to making this application truly useful lies in implementing a robust and accurate mood detection system and integrating with a real music database or streaming service.
👁️ Viewed: 5

Comments