Guest User

Untitled

a guest
Dec 4th, 2024
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.57 KB | None | 0 0
  1. import os
  2. import random
  3. import time
  4. import logging
  5. import subprocess
  6. import json
  7. import re
  8.  
  9. # Logging setup
  10. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  11.  
  12. # Constants
  13. VIDEO_DIRS = {
  14. 'daytime': '/home/minipc/Videos/daytime/',
  15. 'primetime': '/home/minipc/Videos/primetime/',
  16. 'adultswim': '/home/minipc/Videos/adultswim/'
  17. }
  18.  
  19. COMMERCIAL_DIRS = {
  20. 'daytime': '/home/minipc/Videos/daytime_commercials/',
  21. 'primetime': '/home/minipc/Videos/primetime_commercials/',
  22. 'adultswim': '/home/minipc/Videos/commercialsbumps/'
  23. }
  24.  
  25. SUPPORTED_FORMATS = ('.mp4', '.mkv', '.avi', '.webm', '.mov')
  26. PLAYED_VIDEOS_LOG = 'played_videos.json'
  27. COMMERCIAL_COUNT = 4
  28. MID_EPISODE_BREAK_RATIO = 0.5
  29.  
  30. def load_played_videos():
  31. if os.path.exists(PLAYED_VIDEOS_LOG):
  32. with open(PLAYED_VIDEOS_LOG, 'r') as f:
  33. return json.load(f)
  34. return {slot: {'show_progress': {}, 'round_tracker': []} for slot in VIDEO_DIRS}
  35.  
  36. def save_played_videos(data):
  37. with open(PLAYED_VIDEOS_LOG, 'w') as f:
  38. json.dump(data, f)
  39.  
  40. def get_current_time_slot():
  41. hour = time.localtime().tm_hour
  42. if 8 <= hour < 16:
  43. return 'daytime'
  44. elif 16 <= hour < 21:
  45. return 'primetime'
  46. else:
  47. return 'adultswim'
  48.  
  49. def get_video_duration(video_file):
  50. try:
  51. result = subprocess.run(
  52. ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
  53. '-of', 'default=noprint_wrappers=1:nokey=1', video_file],
  54. capture_output=True, text=True, check=True
  55. )
  56. return float(result.stdout)
  57. except subprocess.CalledProcessError:
  58. return 1800 # Default 30 minutes
  59.  
  60. def play_video(video_file, start_time=None):
  61. cmd = ['mpv', '--fullscreen', '--no-terminal']
  62. if start_time:
  63. cmd.extend(['--start=' + str(start_time)])
  64. cmd.append(video_file)
  65. return subprocess.Popen(cmd)
  66.  
  67. def play_commercials(time_slot):
  68. commercial_dir = COMMERCIAL_DIRS[time_slot]
  69. commercials = [f for f in os.listdir(commercial_dir) if f.lower().endswith(SUPPORTED_FORMATS)]
  70. for commercial in random.sample(commercials, min(COMMERCIAL_COUNT, len(commercials))):
  71. process = play_video(os.path.join(commercial_dir, commercial))
  72. process.wait()
  73. time.sleep(0.5)
  74.  
  75. def get_episode_info(filename):
  76. name = os.path.splitext(filename)[0]
  77. match = re.match(r'^(.*?)\s*S(\d+)E(\d+)', name, re.IGNORECASE)
  78. if match:
  79. return match.group(1).strip(), int(match.group(2)), int(match.group(3))
  80. match = re.match(r'^(.*?)(?:[_\-\s]\d+)?$', name)
  81. return match.group(1).strip(), 1, 1
  82.  
  83. def get_next_episode(time_slot, played_videos):
  84. video_dir = VIDEO_DIRS[time_slot]
  85. shows = {}
  86.  
  87. # Group episodes by show
  88. for file in os.listdir(video_dir):
  89. if file.lower().endswith(SUPPORTED_FORMATS):
  90. show_name, season, episode = get_episode_info(file)
  91. if show_name not in shows:
  92. shows[show_name] = []
  93. shows[show_name].append((file, season, episode))
  94.  
  95. if not shows:
  96. return None, None
  97.  
  98. # Initialize round tracker if not present
  99. round_tracker = played_videos[time_slot].get('round_tracker', [])
  100. if not round_tracker:
  101. round_tracker = list(shows.keys())
  102. random.shuffle(round_tracker)
  103. played_videos[time_slot]['round_tracker'] = round_tracker
  104.  
  105. # Find the next show to play
  106. for show_name in round_tracker[:]:
  107. episodes = sorted(shows[show_name], key=lambda x: (x[1], x[2]))
  108. progress = played_videos[time_slot]['show_progress'].get(show_name, (1, 0))
  109.  
  110. # Find next episode
  111. for file, season, episode in episodes:
  112. if season > progress[0] or (season == progress[0] and episode > progress[1]):
  113. played_videos[time_slot]['show_progress'][show_name] = (season, episode)
  114. round_tracker.remove(show_name)
  115. if not round_tracker: # Reset the round tracker if empty
  116. played_videos[time_slot]['round_tracker'] = list(shows.keys())
  117. return os.path.join(video_dir, file), f"{show_name} S{season}E{episode}"
  118.  
  119. # Reset progress for this show if all episodes are played
  120. played_videos[time_slot]['show_progress'][show_name] = (1, 0)
  121.  
  122. # Reset round tracker and retry
  123. played_videos[time_slot]['round_tracker'] = list(shows.keys())
  124. return get_next_episode(time_slot, played_videos)
  125.  
  126. def play_content():
  127. played_videos = load_played_videos()
  128.  
  129. while True:
  130. time_slot = get_current_time_slot()
  131. video_path, episode_info = get_next_episode(time_slot, played_videos)
  132.  
  133. if not video_path:
  134. logging.error(f"No videos found in {time_slot} directory")
  135. time.sleep(60)
  136. continue
  137.  
  138. logging.info(f"Now playing: {episode_info}")
  139. duration = get_video_duration(video_path)
  140.  
  141. # Play first half
  142. video_process = play_video(video_path)
  143. time.sleep(duration * MID_EPISODE_BREAK_RATIO)
  144.  
  145. # Mid-episode commercials
  146. video_process.terminate()
  147. play_commercials(time_slot)
  148.  
  149. # Play second half
  150. video_process = play_video(video_path, start_time=duration * MID_EPISODE_BREAK_RATIO)
  151. video_process.wait()
  152.  
  153. # Post-episode commercials
  154. play_commercials(time_slot)
  155. save_played_videos(played_videos)
  156.  
  157. if __name__ == "__main__":
  158. play_content()
  159.  
  160.  
  161.  
Add Comment
Please, Sign In to add comment