Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import yaml
- from plexapi.server import PlexServer
- from plexapi.exceptions import NotFound
- # --- CONFIGURATION ---
- # Replace with your Plex server URL and token
- PLEX_URL = 'http://YOUR_PLEX_IP:32400'
- PLEX_TOKEN = 'YOUR_PLEX_TOKEN'
- # The name of the library you want to export (e.g., 'Movies', 'TV Shows')
- LIBRARY_NAME = 'Movies'
- # The name for the output YAML file
- OUTPUT_FILE = 'plex_library_metadata.yml'
- # --- SCRIPT ---
- def get_imdb_id(plex_item):
- """
- Parses the Plex item's GUID to find and return the IMDb ID (ttXXXXXXX).
- Returns None if no IMDb ID is found.
- """
- for guid in plex_item.guids:
- if guid.id.startswith('imdb://'):
- # The format is 'imdb://tt1234567'
- return guid.id.split('//')[-1]
- return None
- def generate_yaml_from_plex():
- """
- Connects to a Plex server, retrieves library items, and
- generates a YAML file in the specified format.
- """
- try:
- # Connect to your Plex server
- plex = PlexServer(PLEX_URL, PLEX_TOKEN)
- print(f"Successfully connected to Plex server at {PLEX_URL}")
- # Get the specified library
- library = plex.library.section(LIBRARY_NAME)
- print(f"Found library: '{library.title}'")
- # The final dictionary to hold all the data
- all_metadata = {}
- # Loop through each item in the library
- for item in library.all():
- imdb_id = get_imdb_id(item)
- # Skip items without an IMDb ID, as it's required for the format
- if not imdb_id:
- print(f"Skipping '{item.title}' - no IMDb ID found.")
- continue
- # Get the list of genres
- genre = item.genres[0].tag
- # Create the nested dictionary for this item
- item_data = {
- 'match': {
- 'mapping_id': imdb_id
- },
- 'genre.sync': genre
- }
- # Add the item's data to the main dictionary, using the title as the key
- all_metadata[item.title] = item_data
- # Wrap the entire dictionary in the 'metadata' key
- final_yaml_data = {'metadata': all_metadata}
- # Write the data to a YAML file
- with open(OUTPUT_FILE, 'w', encoding='utf-8') as file:
- # Use yaml.dump to write to the file. We can add a custom flow_style for better readability.
- yaml.dump(final_yaml_data, file, allow_unicode=True, sort_keys=False)
- print(f"Successfully generated '{OUTPUT_FILE}' with {len(all_metadata)} items!")
- except NotFound:
- print(f"Library '{LIBRARY_NAME}' not found. Please check the library name and try again.")
- except Exception as e:
- print(f"An error occurred: {e}")
- if __name__ == '__main__':
- generate_yaml_from_plex()
Advertisement