photoprism-fix/save-albums.py
2024-11-05 14:20:22 -08:00

100 lines
2.8 KiB
Python
Executable File

#!/usr/bin/env python
"""Script to save and restore favorite photos in PhotoPrism."""
import json
import sys
import os
from pathlib import Path
import requests
# PhotoPrism API configuration
PHOTOPRISM_API_URL = (
os.getenv("PHOTOPRISM_URL", "https://example.com").removesuffix("/") + "/api/v1"
)
PHOTOPRISM_API_TOKEN = os.getenv("PHOTOPRISM_API_TOKEN")
# Headers for authorization
headers = {
"X-Auth-Token": f"{PHOTOPRISM_API_TOKEN}",
"Content-Type": "application/json",
}
def fetch_favorites():
"""Fetches favorite photos and maps their primary hashes to 'favorite' status."""
response = requests.get(
f"{PHOTOPRISM_API_URL}/photos",
headers=headers,
params={"count": 1000000, "favorite": True, "quality": 0},
)
print(response.text)
response.raise_for_status()
return {photo["Hash"]: "favorite" for photo in response.json()}
def save_mapping(favorites, filepath: Path):
"""Saves the favorites and album mapping to a JSON file."""
with filepath.open("w") as file:
json.dump({"favorites": favorites}, file)
print(f"Mapping saved to {filepath}")
def load_mapping(filepath: Path):
"""Loads the mapping from a JSON file."""
with filepath.open("r") as file:
return json.load(file)
def fetch_photo_uid(photo_hash):
"""Fetches the photo UID based on the provided hash."""
response = requests.get(
f"{PHOTOPRISM_API_URL}/files/{photo_hash}",
headers=headers,
)
response.raise_for_status()
return response.json()["PhotoUID"] if response.json() else None
def re_add_favorites(mapping):
"""Re-adds photos as favorites based on the provided mapping."""
for photo_hash in mapping["favorites"]:
photo_uid = fetch_photo_uid(photo_hash)
if photo_uid is None:
print(f"Photo with hash {photo_hash} not found.")
continue
response = requests.post(
f"{PHOTOPRISM_API_URL}/photos/{photo_uid}/like",
headers=headers,
)
response.raise_for_status()
print("Favorites re-added successfully")
if __name__ == "__main__":
# Fetch and save the mappings before deletion
if len(sys.argv) > 2:
filepath = Path(sys.argv[2])
else:
filepath = Path("photo_mapping.json")
if sys.argv[1] == "save":
if filepath.exists():
print(f"File {filepath} already exists. Please provide a new file path.")
sys.exit(1)
if not filepath.parent.exists():
print(f"Parent directory {filepath.parent} does not exist.")
sys.exit(1)
favorites = fetch_favorites()
save_mapping(favorites, filepath)
elif sys.argv[1] == "restore":
mapping = load_mapping(filepath)
re_add_favorites(mapping)
else:
print("Invalid command. Please use 'save' or 'restore'.")
sys.exit(1)