alarm.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import datetime
  2. import os
  3. import re
  4. import subprocess
  5. def rename_files_with_whitespaces(cd, files, extra_path=""):
  6. for file in files:
  7. if " " in file:
  8. renamed_file = file.replace(" ", "_")
  9. os.rename(os.path.join(cd, extra_path, file), os.path.join(cd, extra_path, renamed_file))
  10. def clean_filename(file):
  11. return ' '.join(map(str.capitalize, file[:-4].split('_')))
  12. def set_alarm():
  13. stop = False
  14. error = True
  15. while error:
  16. user_set_time = ":".join(map(lambda x: str(x).zfill(2), input("\nSet the alarm time (e.g. 01:10): ").split(":")))
  17. if re.match(r"^[0-9]{2}:[0-9]{2}$", user_set_time):
  18. playback_time = f"{user_set_time}:00.000000"
  19. error = False
  20. else:
  21. print(">>> Error: Time format invalid! Please try again!\n")
  22. cd = os.path.dirname(os.path.realpath(__file__))
  23. musics_path = os.path.join(cd, "musics")
  24. rename_files_with_whitespaces(cd, os.listdir(musics_path), "musics")
  25. musics = os.listdir(musics_path)
  26. if len(musics) < 1:
  27. print(">>> Error: No music in the musics folder! Please add music first!\n")
  28. exit()
  29. elif len(musics) == 1:
  30. print(">> Alarm music has been set default --> " + clean_filename(musics[0]))
  31. selected_music = musics[0]
  32. else:
  33. error = True
  34. while error:
  35. try:
  36. print("\nSelect any alarm music:\n")
  37. for i in range(1, len(musics) + 1):
  38. print(f"{i}. {clean_filename(musics[i - 1])}")
  39. user_input = int(input("\nEnter the index of the listed musics (e.g. 1): "))
  40. selected_music = musics[user_input - 1]
  41. print(">> Alarm music has been set --> "+ clean_filename(selected_music))
  42. error = False
  43. except:
  44. print(">>> Error: Invalid Index! Please try again!\n")
  45. print(f"\n>>> Alarm has been set successfully for {user_set_time}! Please dont close the program! <<<")
  46. while stop == False:
  47. current_time = str(datetime.datetime.now().time())
  48. if current_time >= playback_time:
  49. stop = True
  50. subprocess.run(('cmd', '/C', 'start', f"{cd}\\musics\\{selected_music}"))
  51. print(">>> Alarm ringing! Closing the program!! Bye Bye!!! <<<")
  52. def display_header(header):
  53. print("")
  54. print("###########################".center(os.get_terminal_size().columns))
  55. print(f"###### {header} ######".center(os.get_terminal_size().columns))
  56. print("###########################".center(os.get_terminal_size().columns))
  57. if __name__ == "__main__":
  58. display_header("Alarm Program")
  59. set_alarm()