Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import random
- import time
- import logging
- import subprocess
- import json
- import re
- # Logging setup
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
- # Constants
- VIDEO_DIRS = {
- 'daytime': '/home/minipc/Videos/daytime/',
- 'primetime': '/home/minipc/Videos/primetime/',
- 'adultswim': '/home/minipc/Videos/adultswim/'
- }
- COMMERCIAL_DIRS = {
- 'daytime': '/home/minipc/Videos/daytime_commercials/',
- 'primetime': '/home/minipc/Videos/primetime_commercials/',
- 'adultswim': '/home/minipc/Videos/commercialsbumps/'
- }
- SUPPORTED_FORMATS = ('.mp4', '.mkv', '.avi', '.webm', '.mov')
- PLAYED_VIDEOS_LOG = 'played_videos.json'
- COMMERCIAL_COUNT = 4
- MID_EPISODE_BREAK_RATIO = 0.5
- def load_played_videos():
- if os.path.exists(PLAYED_VIDEOS_LOG):
- with open(PLAYED_VIDEOS_LOG, 'r') as f:
- return json.load(f)
- return {slot: {'show_progress': {}, 'round_tracker': []} for slot in VIDEO_DIRS}
- def save_played_videos(data):
- with open(PLAYED_VIDEOS_LOG, 'w') as f:
- json.dump(data, f)
- def get_current_time_slot():
- hour = time.localtime().tm_hour
- if 8 <= hour < 16:
- return 'daytime'
- elif 16 <= hour < 21:
- return 'primetime'
- else:
- return 'adultswim'
- def get_video_duration(video_file):
- try:
- result = subprocess.run(
- ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
- '-of', 'default=noprint_wrappers=1:nokey=1', video_file],
- capture_output=True, text=True, check=True
- )
- return float(result.stdout)
- except subprocess.CalledProcessError:
- return 1800 # Default 30 minutes
- def play_video(video_file, start_time=None):
- cmd = ['mpv', '--fullscreen', '--no-terminal']
- if start_time:
- cmd.extend(['--start=' + str(start_time)])
- cmd.append(video_file)
- return subprocess.Popen(cmd)
- def play_commercials(time_slot):
- commercial_dir = COMMERCIAL_DIRS[time_slot]
- commercials = [f for f in os.listdir(commercial_dir) if f.lower().endswith(SUPPORTED_FORMATS)]
- for commercial in random.sample(commercials, min(COMMERCIAL_COUNT, len(commercials))):
- process = play_video(os.path.join(commercial_dir, commercial))
- process.wait()
- time.sleep(0.5)
- def get_episode_info(filename):
- name = os.path.splitext(filename)[0]
- match = re.match(r'^(.*?)\s*S(\d+)E(\d+)', name, re.IGNORECASE)
- if match:
- return match.group(1).strip(), int(match.group(2)), int(match.group(3))
- match = re.match(r'^(.*?)(?:[_\-\s]\d+)?$', name)
- return match.group(1).strip(), 1, 1
- def get_next_episode(time_slot, played_videos):
- video_dir = VIDEO_DIRS[time_slot]
- shows = {}
- # Group episodes by show
- for file in os.listdir(video_dir):
- if file.lower().endswith(SUPPORTED_FORMATS):
- show_name, season, episode = get_episode_info(file)
- if show_name not in shows:
- shows[show_name] = []
- shows[show_name].append((file, season, episode))
- if not shows:
- return None, None
- # Initialize round tracker if not present
- round_tracker = played_videos[time_slot].get('round_tracker', [])
- if not round_tracker:
- round_tracker = list(shows.keys())
- random.shuffle(round_tracker)
- played_videos[time_slot]['round_tracker'] = round_tracker
- # Find the next show to play
- for show_name in round_tracker[:]:
- episodes = sorted(shows[show_name], key=lambda x: (x[1], x[2]))
- progress = played_videos[time_slot]['show_progress'].get(show_name, (1, 0))
- # Find next episode
- for file, season, episode in episodes:
- if season > progress[0] or (season == progress[0] and episode > progress[1]):
- played_videos[time_slot]['show_progress'][show_name] = (season, episode)
- round_tracker.remove(show_name)
- if not round_tracker: # Reset the round tracker if empty
- played_videos[time_slot]['round_tracker'] = list(shows.keys())
- return os.path.join(video_dir, file), f"{show_name} S{season}E{episode}"
- # Reset progress for this show if all episodes are played
- played_videos[time_slot]['show_progress'][show_name] = (1, 0)
- # Reset round tracker and retry
- played_videos[time_slot]['round_tracker'] = list(shows.keys())
- return get_next_episode(time_slot, played_videos)
- def play_content():
- played_videos = load_played_videos()
- while True:
- time_slot = get_current_time_slot()
- video_path, episode_info = get_next_episode(time_slot, played_videos)
- if not video_path:
- logging.error(f"No videos found in {time_slot} directory")
- time.sleep(60)
- continue
- logging.info(f"Now playing: {episode_info}")
- duration = get_video_duration(video_path)
- # Play first half
- video_process = play_video(video_path)
- time.sleep(duration * MID_EPISODE_BREAK_RATIO)
- # Mid-episode commercials
- video_process.terminate()
- play_commercials(time_slot)
- # Play second half
- video_process = play_video(video_path, start_time=duration * MID_EPISODE_BREAK_RATIO)
- video_process.wait()
- # Post-episode commercials
- play_commercials(time_slot)
- save_played_videos(played_videos)
- if __name__ == "__main__":
- play_content()
Add Comment
Please, Sign In to add comment