PsychoStatic

Code I use to easily rate albums

Apr 26th, 2023 (edited)
1,620
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.13 KB | Music | 0 0
  1. import os
  2. import time
  3. import configparser
  4. import json
  5.  
  6.  
  7. class Config:
  8.     def __init__(self):
  9.         self.settings = {}
  10.  
  11.     def load_from_config_file(self, file_path):
  12.         config = configparser.ConfigParser()
  13.         config.read(file_path)
  14.  
  15.         for section in config.sections():
  16.             for option in config.options(section):
  17.                 value = config.get(section, option)
  18.                 self.settings[(section, option)] = value
  19.  
  20.     def get_setting(self, section, option):
  21.         return self.settings.get((section, option))
  22.  
  23.     def set_setting(self, section, option, value):
  24.         self.settings[(section, option)] = value
  25.  
  26.  
  27. def read_config(file_path):
  28.     config = configparser.ConfigParser()
  29.     config.read(file_path)
  30.     return config
  31.  
  32.  
  33. def choose_settings(config):
  34.     settings = {}
  35.  
  36.     for section in config.sections():
  37.         print(f"\n[{section}]")
  38.         for option in config.options(section):
  39.             value = config.get(section, option)
  40.             print(f"{option}: {value}")
  41.             choice = input(f"Enter new value for {option} (press Enter to keep the current value): \n")
  42.             if choice.strip():
  43.                 settings[(section, option)] = choice.strip()
  44.  
  45.     return settings
  46.  
  47.  
  48. def read_album_info(json_data):
  49.     keyword = input("Enter a keyword to search for albums: ")
  50.     matched_albums = []
  51.  
  52.     for index, album_data in json_data.items():
  53.         if keyword.lower() in album_data["Album_Title"].lower() or keyword.lower() in album_data["Artist_Title"].lower():
  54.             matched_albums.append((index, album_data))
  55.  
  56.     if len(matched_albums) == 0:
  57.         print("No matching albums found.")
  58.         return
  59.  
  60.     for index, album_data in matched_albums:
  61.         print(f"\nAlbum {index}:")
  62.         print("Artist: " + album_data["Artist_Title"])
  63.         print("Album: " + album_data["Album_Title"])
  64.         print("Average Score: " + str(album_data["Average_Score"]))
  65.         option = input("Is this the album you were looking for? (y/n): ")
  66.         if option.lower() == 'y':
  67.             display_album_details(album_data)
  68.  
  69.     choice = input("Do you want to see another album or go back to the main menu? (a/m): ")
  70.     if choice.lower() == 'a':
  71.         read_album_info(json_data)
  72.     else:
  73.         main_menu()
  74.  
  75.  
  76. def display_album_details(album_data):
  77.     print("Artist: " + album_data["Artist_Title"])
  78.     print("Album: " + album_data["Album_Title"])
  79.     print("Average Score: " + str(album_data["Average_Score"]))
  80.     print("Scores:")
  81.     for i, score in enumerate(album_data["Scores"], start=1):
  82.         print(f"  Song {i}: {score}")
  83.  
  84.  
  85. def update_config(file_path, settings):
  86.     config = configparser.ConfigParser()
  87.     config.read(file_path)
  88.  
  89.     for (section, option), value in settings.items():
  90.         config.set(section, option, value)
  91.  
  92.     with open(file_path, "w") as config_file:
  93.         config.write(config_file)
  94.     print("Configuration file updated.")
  95.  
  96.  
  97. def export_to_json(scores, avg_score, artist_title, album_title):
  98.     # Specify the directory path where the JSON files are located
  99.     directory = os.getcwd()
  100.  
  101.     # Specify the file path for the JSON file
  102.     json_file_path = os.path.join(directory, "album_data.json")
  103.  
  104.     # Check if the JSON file already exists
  105.     if os.path.exists(json_file_path):
  106.         # Load the existing data from the JSON file
  107.         with open(json_file_path, "r") as json_file:
  108.             existing_data = json.load(json_file)
  109.     else:
  110.         # If the JSON file doesn't exist, initialize with an empty dictionary
  111.         existing_data = {}
  112.  
  113.     # Create a dictionary for the new data
  114.     new_data = {
  115.         "Artist_Title": artist_title,
  116.         "Album_Title": album_title,
  117.         "Scores": scores,
  118.         "Average_Score": avg_score
  119.     }
  120.  
  121.     # Update the existing data with the new data
  122.     existing_data[str(len(existing_data) + 1)] = new_data
  123.  
  124.     # Write the updated data to the JSON file
  125.     with open(json_file_path, "w") as json_file:
  126.         json.dump(existing_data, json_file, indent=4)
  127.  
  128.     print(f"Song list exported to {json_file_path}")
  129.  
  130.  
  131. def main_menu():
  132.     print("Welcome to EARS (Easy Album Rating System)!")
  133.     print("1 - Start program")
  134.     print("2 - Change Settings")
  135.     print("3 - Search Database")
  136.     print("4 - Exit Program")
  137.  
  138.     option = input("Please select an option: ")
  139.  
  140.     if option == '1':
  141.         print("Happy Listening!")
  142.         rate_album()
  143.     elif option == '2':
  144.         config_file = "config.ini"
  145.         config = read_config(config_file)
  146.         selected_settings = choose_settings(config)
  147.         update_config(config_file, selected_settings)
  148.         main_menu()
  149.     elif option == '3':
  150.         # Specify the directory path where the JSON file is located
  151.         directory = os.getcwd()
  152.  
  153.         # Specify the file path for the JSON file
  154.         json_file_path = os.path.join(directory, "album_data.json")
  155.  
  156.         # Check if the JSON file exists
  157.         if os.path.exists(json_file_path):
  158.             # Load the existing data from the JSON file
  159.             with open(json_file_path, "r") as json_file:
  160.                 existing_data = json.load(json_file)
  161.  
  162.             # Display the limited selection of information for each album
  163.             read_album_info(existing_data)
  164.         else:
  165.             print("No data found in the database.")
  166.  
  167.         main_menu()
  168.     elif option == '4':
  169.         exit_program()
  170.  
  171.  
  172. def rate_album():
  173.     # Initialize a Config instance
  174.     config = Config()
  175.     config.load_from_config_file("config.ini")
  176.  
  177.     scale_type = config.get_setting("Defaults", "scale_type")
  178.     true_average = config.get_setting("Defaults", "true_average")
  179.  
  180.     if scale_type == '0':
  181.         max_rating = 100
  182.     elif scale_type == '1':
  183.         max_rating = 10
  184.     elif scale_type == '2':
  185.         max_rating = 5
  186.  
  187.     while True:
  188.         # Initialize a list to store the interlude positions
  189.         interlude_positions = []
  190.  
  191.         # Initialize a list to store the scores
  192.         scores = []
  193.  
  194.         # Ask the user for basic info on the album.
  195.         artist_title = input("What is the artist's name? ")
  196.         album_title = input("What is the album name? ")
  197.         num_songs = int(input("How many songs are on the album? "))
  198.         interlude_amount = input("Are there any interludes? (y/n) ")
  199.  
  200.         while interlude_amount.lower() == 'y':
  201.             interlude = int(input("Which position is the interlude in? (Enter the track number) "))
  202.  
  203.             if interlude < 0 or interlude > num_songs or interlude in interlude_positions:
  204.                 print(f"Invalid index. You have either chosen a position that already has an interlude or haven't "
  205.                       f"entered a number between 1 and {num_songs}.")
  206.             else:
  207.                 interlude_positions.append(interlude)
  208.                 interlude_amount = input("Are there any more interludes? (y/n) ")
  209.  
  210.         # Loop through each song and ask for its score
  211.         for i in range(num_songs):
  212.             if i + 1 in interlude_positions:
  213.                 scores.append("NR")
  214.             else:
  215.                 score = float(input(f"What is the score for song {i + 1}? "))
  216.  
  217.                 # Check if the score is valid (between 0 and max_rating)
  218.                 while score < 0 or score > max_rating:
  219.                     print(f"Invalid score. Score must be between 0 and {max_rating}.")
  220.                     score = float(input(f"What is the score for song {i + 1}? "))
  221.  
  222.                 # Add the score to the list
  223.                 scores.append(score)
  224.  
  225.         # Ask the user if they want to change a score
  226.         change_score = input("Do you want to change a score? (y/n) ")
  227.  
  228.         while change_score.lower() == 'y':
  229.             # Ask for the index of the score to change
  230.             index = int(input("Which score do you want to change? (Enter the index number) ")) - 1
  231.  
  232.             # Check if the index is valid
  233.             if index < 0 or index >= num_songs:
  234.                 print(f"Invalid index. Please enter a number between 1 and {num_songs}.")
  235.             else:
  236.                 # Ask for the new score
  237.                 new_score = float(input(f"What is the new score for song {index + 1}? "))
  238.  
  239.                 # Check if the new score is valid
  240.                 while new_score < 0 or new_score > max_rating:
  241.                     print(f"Invalid score. Score must be between 0 and {max_rating}.")
  242.                     new_score = float(input(f"What is the new score for song {index + 1}? "))
  243.  
  244.                 # Update the score in the list
  245.                 scores[index] = new_score
  246.  
  247.             # Ask if the user wants to change another score
  248.             change_score = input("Do you want to change another score? (y/n) ")
  249.  
  250.         # Calculate the average score
  251.         num_valid_scores = len([score for score in scores if score != "NR"])
  252.         if num_valid_scores > 0:
  253.             sum_score = sum([score for score in scores if score != "NR"])
  254.             if true_average == '0':
  255.                 avg_score = (((sum_score) + (num_valid_scores ** 2)) / (
  256.                         (num_valid_scores * max_rating) + (num_valid_scores ** 2)))
  257.                 avg_score = avg_score * 100
  258.             else:
  259.                 avg_score = sum_score / num_valid_scores
  260.         else:
  261.             avg_score = "NR"
  262.  
  263.         # Print the average score
  264.         print(f"The average score for the album is {avg_score:.2f}")
  265.  
  266.         # Ask the user if they want to export the song list to a file
  267.         export_file = input("Do you want to export the song list to a file? (y/n) ")
  268.  
  269.         if export_file.lower() == 'y':
  270.             export_to_json(scores, avg_score, artist_title, album_title)
  271.         else:
  272.             print("Song list not exported.")
  273.  
  274.         restart = input("Do you want to go to the main menu? (y/n) ")
  275.  
  276.         if restart.lower() == 'y':
  277.             main_menu()
  278.         else:
  279.             exit_program()
  280.  
  281.  
  282. def exit_program():
  283.     input("Press enter to close the program")
  284.     time.sleep(1)
  285.     print("4")
  286.     time.sleep(1)
  287.     print("3")
  288.     time.sleep(1)
  289.     print("2")
  290.     time.sleep(1)
  291.     print("1")
  292.     sys.exit()
  293.  
  294.  
  295. main_menu()
  296.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment