Commit ·
7d3bb28
1
Parent(s): 888adce
get all films bug fix
Browse filesFiles changed (2)
- LoadBalancer.py+76-75
- TODO.md+2-4
29 unmodified lines3031323334353637383940414 unmodified lines464748495051525354555628 unmodified lines8586878889909168 unmodified lines16016116216316416516616716816917017117217317417517617717817918018114 unmodified lines1961971981992002012022032042052061 unmodified line20820921021121221321421521621721821922022122222322422514 unmodified lines2402412422432442452462472482492502 unmodified lines2532542552562572582592602612622632642652662672682692702712722732742752762772782792802812 unmodified lines28428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431529 unmodified linesself.file_structure = Noneself.previous_file_structure = None # To keep track of previous content# Ensure CACHE_DIR existsif not os.path.exists(self.CACHE_DIR):os.makedirs(self.CACHE_DIR)# Initialize file structure and start prefetchingself.file_structure = indexer()self.start_prefetching()# Start polling and file checking in separate threads4 unmodified lines# Start periodic tasksasyncio.create_task(self.run_periodic_tasks())async def run_periodic_tasks(self):"""Run indexer and prefetch functions every 5 minutes."""while not self.stop_event.is_set():self.file_structure = indexer() # Re-run indexerawait self.start_prefetching() # Start prefetchingawait asyncio.sleep(300) # Sleep for 5 minutesdef start_prefetching(self):28 unmodified linesjson_cache_path = os.path.join(self.CACHE_DIR, f"{urllib.parse.quote(original_title)}.json")if not os.path.exists(json_cache_path):tasks.append(fetch_and_cache_json(original_title, title, media_type, year))logging.info(f"Skipping.. {original_title} metadata already cached")# Run all tasks concurrentlyawait asyncio.gather(*tasks)68 unmodified lineslogging.info(f"Instance {instance_url} not found for removal.")def update_instances_health(self, instance, cache_size):self.instances_health[instance] = {"used":cache_size["cache_size"],"total": "50 GB"}logging.info(f"Updated instance {instance} with cache size {cache_size}")def download_film_to_best_instance(self, title):"""Downloads a film to the first instance that has more free space on the self.instance_health list variable.The instance_health looks like this:{"https://unicone-studio-instance1.hf.space": {"total": "50 GB","used": "3.33 GB"}}Args:title (str): The title of the film."""best_instance = Nonemax_free_space = -114 unmodified linesstatus = result["status"]progress_url = f'{best_instance}/api/get/progress/{film_id}'response = {"film_id":film_id,"status":status,"progress_url":progress_url}return responseelse:logging.error("No suitable instance found for downloading the film.")1 unmodified linedef download_episode_to_best_instance(self, title, season, episode):"""Downloads a episode to the first instance that has more free space on the self.instance_health list variable.The instance_health looks like this:{"https://unicone-studio-instance1.hf.space": {"total": "50 GB","used": "3.33 GB"}}Args:title (str): The title of the Tv show.season (str): The season of the Tv show.episode (str): The title of the Tv show."""best_instance = Nonemax_free_space = -114 unmodified linesstatus = result["status"]progress_url = f'{best_instance}/api/get/progress/{episode_id}'response = {"episode_id":episode_id,"status":status,"progress_url":progress_url}return responseelse:logging.error("No suitable instance found for downloading the film.")2 unmodified linesdef find_movie_path(self, title):"""Find the path of the movie in the JSON data based on the title."""for directory in self.file_structure:if directory['type'] == 'directory' and directory['path'] == 'films':for sub_directory in directory['contents']:if sub_directory['type'] == 'directory':for item in sub_directory['contents']:if item['type'] == 'file' and title.lower() in item['path'].lower():return item['path']return Nonedef find_tv_path(self, title):"""Find the path of the TV show in the JSON data based on the title."""for directory in self.file_structure:if directory['type'] == 'directory' and directory['path'] == 'tv':for sub_directory in directory['contents']:if sub_directory['type'] == 'directory' and title.lower() in sub_directory['path'].lower():return sub_directory['path']return Nonedef get_tv_structure(self, title):"""Find the path of the TV show in the JSON data based on the title."""for directory in self.file_structure:if directory['type'] == 'directory' and directory['path'] == 'tv':for sub_directory in directory['contents']:if sub_directory['type'] == 'directory' and title.lower() in sub_directory['path'].lower():return sub_directoryreturn None2 unmodified linesreturn title.replace(" ", "_").lower()def get_all_tv_shows(self):"""Get all TV shows from the indexed cache structure JSON file."""tv_shows = {}for directory in self.file_structure:if directory['type'] == 'directory' and directory['path'] == 'tv':for sub_directory in directory['contents']:if sub_directory['type'] == 'directory':show_title = sub_directory['path'].split('/')[-1]tv_shows[show_title] = []for season_directory in sub_directory['contents']:if season_directory['type'] == 'directory':season = season_directory['path'].split('/')[-1]for episode in season_directory['contents']:if episode['type'] == 'file':tv_shows[show_title].append({"season": season,"episode": episode['path'].split('/')[-1],"path": episode['path']})return tv_showsdef get_all_films(self):"""Get all films from the indexed cache structure JSON file."""films = []for directory in self.file_structure:if directory['type'] == 'directory' and directory['path'] == 'films':for sub_directory in directory['contents']:if sub_directory['type'] == 'directory':films.append(sub_directory['path'])return films29 unmodified lines30313233343536373839404142434445464 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010128 unmodified lines13013113213313413513613768 unmodified lines20620720820921021121221321421521621721814 unmodified lines2332342352362372382392402412421 unmodified line24424524624724824925014 unmodified lines2652662672682692702712722732742 unmodified lines2772782792802812822832842852862872882892902912922932942952962972982993003013023033043052 unmodified lines30830931031131231331431531629 unmodified linesself.file_structure = Noneself.previous_file_structure = None # To keep track of previous content# Caches for films and TV shows to avoid returning empty lists in case of errorsself.cached_films = []self.cached_tv_shows = {}# Ensure CACHE_DIR existsif not os.path.exists(self.CACHE_DIR):os.makedirs(self.CACHE_DIR)# Initialize file structure, update caches, and start prefetchingself.file_structure = indexer()self.update_media_cache()self.start_prefetching()# Start polling and file checking in separate threads4 unmodified lines# Start periodic tasksasyncio.create_task(self.run_periodic_tasks())def update_media_cache(self):"""Update the cached films and TV shows from the current file_structure.Only update if the new data is non-empty, preserving the last valid cache."""new_films = []new_tv_shows = {}for directory in self.file_structure:if directory.get('type') == 'directory':if directory.get('path') == 'films':for sub_directory in directory.get('contents', []):if sub_directory.get('type') == 'directory':new_films.append(sub_directory.get('path'))elif directory.get('path') == 'tv':for sub_directory in directory.get('contents', []):if sub_directory.get('type') == 'directory':show_title = sub_directory.get('path').split('/')[-1]episodes_list = []for season_directory in sub_directory.get('contents', []):if season_directory.get('type') == 'directory':season = season_directory.get('path').split('/')[-1]for episode in season_directory.get('contents', []):if episode.get('type') == 'file':episodes_list.append({"season": season,"episode": episode.get('path').split('/')[-1],"path": episode.get('path')})if episodes_list:new_tv_shows[show_title] = episodes_listif new_films:self.cached_films = new_filmsif new_tv_shows:self.cached_tv_shows = new_tv_showsasync def run_periodic_tasks(self):"""Run indexer and prefetch functions every 5 minutes."""while not self.stop_event.is_set():new_file_structure = indexer() # Re-run indexer# Only update if the new file_structure is non-emptyif new_file_structure:self.file_structure = new_file_structureself.update_media_cache()await self.start_prefetching() # Start prefetching metadataawait asyncio.sleep(300) # Sleep for 5 minutesdef start_prefetching(self):28 unmodified linesjson_cache_path = os.path.join(self.CACHE_DIR, f"{urllib.parse.quote(original_title)}.json")if not os.path.exists(json_cache_path):tasks.append(fetch_and_cache_json(original_title, title, media_type, year))else:logging.info(f"Skipping.. {original_title} metadata already cached")# Run all tasks concurrentlyawait asyncio.gather(*tasks)68 unmodified lineslogging.info(f"Instance {instance_url} not found for removal.")def update_instances_health(self, instance, cache_size):self.instances_health[instance] = {"used": cache_size["cache_size"],"total": "50 GB"}logging.info(f"Updated instance {instance} with cache size {cache_size}")def download_film_to_best_instance(self, title):"""Downloads a film to the first instance that has more free space on the self.instances_health list."""best_instance = Nonemax_free_space = -114 unmodified linesstatus = result["status"]progress_url = f'{best_instance}/api/get/progress/{film_id}'response = {"film_id": film_id,"status": status,"progress_url": progress_url}return responseelse:logging.error("No suitable instance found for downloading the film.")1 unmodified linedef download_episode_to_best_instance(self, title, season, episode):"""Downloads an episode to the first instance that has more free space on the self.instances_health list."""best_instance = Nonemax_free_space = -114 unmodified linesstatus = result["status"]progress_url = f'{best_instance}/api/get/progress/{episode_id}'response = {"episode_id": episode_id,"status": status,"progress_url": progress_url}return responseelse:logging.error("No suitable instance found for downloading the film.")2 unmodified linesdef find_movie_path(self, title):"""Find the path of the movie in the JSON data based on the title."""for directory in self.file_structure:if directory.get('type') == 'directory' and directory.get('path') == 'films':for sub_directory in directory.get('contents', []):if sub_directory.get('type') == 'directory':for item in sub_directory.get('contents', []):if item.get('type') == 'file' and title.lower() in item.get('path').lower():return item.get('path')return Nonedef find_tv_path(self, title):"""Find the path of the TV show in the JSON data based on the title."""for directory in self.file_structure:if directory.get('type') == 'directory' and directory.get('path') == 'tv':for sub_directory in directory.get('contents', []):if sub_directory.get('type') == 'directory' and title.lower() in sub_directory.get('path').lower():return sub_directory.get('path')return Nonedef get_tv_structure(self, title):"""Find the path of the TV show in the JSON data based on the title."""for directory in self.file_structure:if directory.get('type') == 'directory' and directory.get('path') == 'tv':for sub_directory in directory.get('contents', []):if sub_directory.get('type') == 'directory' and title.lower() in sub_directory.get('path').lower():return sub_directoryreturn None2 unmodified linesreturn title.replace(" ", "_").lower()def get_all_tv_shows(self):"""Return the cached TV shows."""return self.cached_tv_showsdef get_all_films(self):"""Return the cached films."""return self.cached_films
1234create endpoints for* /api/get/film/{title} `Endpoint to get the movie by title.`* /api/get/tv/{title}/{season}/{episode} `Endpoint to get the episode by title, season and episode.`12Fix BUGS* /api/get/film/all `After some times the list becomes empty`
LoadBalancer.py+76-75
TODO.md+2-4