Here's a Python script that connects to Radarr, checks the hard link count for each movie file, and tags movies accordingly:
import requests
import subprocess
import os
import sys
from time import sleep
# Configuration - EDIT THESE VALUES
RADARR_URL = "http://localhost:7878" # Radarr base URL
RADARR_API_KEY = "your_api_key_here" # Radarr API key
VERBOSE_LOGGING = True # Set to False to reduce output
def get_movies():
"""Fetch all movies from Radarr"""
url = f"{RADARR_URL}/api/v3/movie"
params = {'apiKey': RADARR_API_KEY}
try:
response = requests.get(url, params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching movies: {e}")
sys.exit(1)
def get_tags():
"""Fetch existing tags from Radarr"""
url = f"{RADARR_URL}/api/v3/tag"
params = {'apiKey': RADARR_API_KEY}
try:
response = requests.get(url, params=params)
response.raise_for_status()
return {tag['label']: tag['id'] for tag in response.json()}
except requests.exceptions.RequestException as e:
print(f"Error fetching tags: {e}")
return {}
def create_tag(tag_name):
"""Create a new tag in Radarr"""
url = f"{RADARR_URL}/api/v3/tag"
params = {'apiKey': RADARR_API_KEY}
payload = {'label': tag_name}
try:
response = requests.post(url, json=payload, params=params)
if response.status_code == 201:
return response.json()['id']
elif response.status_code == 400 and "already exists" in response.text:
return None # Tag already exists
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error creating tag '{tag_name}': {e}")
return None
def update_movie_tags(movie, new_tag_id, existing_tags):
"""Update movie tags preserving existing non-hl tags"""
# Remove existing _hl tags
current_tags = movie.get('tags', [])
hl_tags_removed = [tag for tag in current_tags if existing_tags.get(tag, '').endswith('_hl') is False]
# Add new tag if not already present
if new_tag_id not in hl_tags_removed:
hl_tags_removed.append(new_tag_id)
# Prepare update payload
payload = movie.copy()
payload['tags'] = hl_tags_removed
# Send update request
url = f"{RADARR_URL}/api/v3/movie/{movie['id']}"
params = {'apiKey': RADARR_API_KEY}
try:
response = requests.put(url, json=payload, params=params)
response.raise_for_status()
return True
except requests.exceptions.RequestException as e:
print(f"Error updating movie {movie['title']}: {e}")
return False
def main():
# Get existing tags
existing_tags = {v: k for k, v in get_tags().items()} # ID -> Label mapping
tag_label_to_id = {k: v for v, k in existing_tags.items()} # Label -> ID mapping
# Get all movies
movies = get_movies()
print(f"Found {len(movies)} movies in Radarr")
processed = 0
for movie in movies:
movie_file = movie.get('movieFile', {})
file_path = movie_file.get('path', '')
# Skip movies without files
if not file_path or not os.path.exists(file_path):
if VERBOSE_LOGGING:
print(f"Skipping {movie['title']} - no file available")
continue
# Get hard link count
try:
result = subprocess.run(
['stat', '-c', '%h', file_path],
capture_output=True,
text=True,
check=True
)
hardlinks = result.stdout.strip()
tag_name = f"{hardlinks}_hl"
if VERBOSE_LOGGING:
print(f"{movie['title']}: {hardlinks} hardlinks")
except (subprocess.CalledProcessError, FileNotFoundError) as e:
print(f"Error processing {movie['title']}: {e}")
continue
# Create tag if needed
if tag_name not in tag_label_to_id:
new_tag_id = create_tag(tag_name)
if new_tag_id:
tag_label_to_id[tag_name] = new_tag_id
existing_tags[new_tag_id] = tag_name
print(f"Created new tag: {tag_name} (ID: {new_tag_id})")
else:
# Try to find existing tag if creation failed
tag_label_to_id = {k: v for v, k in existing_tags.items()}
if tag_name not in tag_label_to_id:
print(f"Could not create/find tag for {tag_name}, skipping")
continue
# Update movie tags
tag_id = tag_label_to_id[tag_name]
if update_movie_tags(movie, tag_id, existing_tags):
processed += 1
if VERBOSE_LOGGING:
print(f"Tagged {movie['title']} with {tag_name}")
# Be gentle with the API
sleep(0.5)
print(f"\nProcessed {processed} movies successfully")
if __name__ == "__main__":
main()
Features:
- Connects to Radarr's API to fetch all movies
- Checks hard link count using
stat -c %h for each movie file
- Creates new tags in the format
<count>_hl (e.g., "2_hl")
- Updates movie tags while preserving existing non-hl tags
- Handles API errors and missing files gracefully
- Includes rate limiting to avoid API flooding
Requirements:
- Python 3.6+
requests library (pip install requests)
- Access to Radarr instance
- File system access to movie files
- Linux/Unix OS (for
stat command)
Setup:
- Replace
RADARR_URL with your Radarr base URL
- Replace
RADARR_API_KEY with your actual API key (found in Radarr: Settings > General)
- Install required dependency:
pip install requests
- Run the script:
python3 radarr_hardlink_tagger.py
What it does:
- For each movie with an existing file:
- Runs
stat -c %h on the video file
- Creates a tag named
<hardlink_count>_hl if it doesn't exist
- Updates the movie's tags:
- Removes any existing
_hl tags
- Adds the new hardlink count tag
- Preserves existing non-hl tags
- Skips movies without files or with inaccessible paths
Notes:
- The script may take several minutes to run if you have a large library
- Verify Radarr's API key has write permissions
- Test with a few movies first by temporarily modifying the movies list
- Movies without files will be skipped and noted in the output
- Existing non-hl tags will be preserved during updates
To find your API key in Radarr:
- Go to Settings > General
- Copy the "API Key" value
- Paste it in the script's
RADARR_API_KEY variable