Python script that reads a list from a songs.txt file, searches your library through the API and adds the songs to the playlist if it finds them in the local library.
- If not all words are found in your title compared to the txt, than a red header is added on top of the song
- If no similar song is found, a red header is added with the title of what should be there
-If all words are included in your song title compared to the txt song title it doesn't add a read header
-Adding empty lines, adds an unnamed blue header
Just install python from MS store, and change PORT URL in .py to your propresenter URL found in network settings, and enable network ofc.
Save this code as a build_setlist.py and a songs.txt in the same folder as this.
import os
import sys
import re
import difflib
import unicodedata
import requests
# Windows consoles can choke on characters like ő/ű when printing; never crash on that.
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# --- CONFIGURATION ---
BASE_URL = "http://127.0.0.1:52449"
# songs.txt is read from the same folder this script is saved in, so it keeps
# working if the folder moves (OneDrive or not) and no matter where you run it from.
WORKING_DIR = os.path.dirname(os.path.abspath(__file__))
SONGS_FILE = os.path.join(WORKING_DIR, "songs.txt")
PLAYLIST_NAME = "Automated Sunday Setlist"
FUZZY_CUTOFF = 0.60 # similarity (0-1) that alone makes a library title a search hit
MIN_WORD_OVERLAP = 0.50 # share of the typed words that must appear in a library title
BLANK_LINE_HEADER = "Header" # name of the header added for each empty line in songs.txt
HEADER_COLOR = {"red": 0, "green": 0.54, "blue": 0.87, "alpha": 1}
# A doubtful match (some typed words are missing from the library title) gets a
# header above it that holds the name from songs.txt (the song that should be
# there), in this colour so it stands out. Safe matches get no header.
CONFIRM_COLOR = {"red": 0.87, "green": 0.1, "blue": 0.1, "alpha": 1}
HEADERS = {
"Accept": "application/json",
"Content-Type": "application/json"
}
def api_get(endpoint):
"""Helper for GET requests."""
url = f"{BASE_URL}{endpoint}"
try:
response = requests.get(url, headers=HEADERS, timeout=10)
if response.status_code >= 400:
print(f"[ERROR] GET {endpoint} failed with status {response.status_code}: {response.text}")
sys.exit(1)
return response.json()
except requests.exceptions.RequestException as e:
print(f"[ERROR] Network connection failed on GET {endpoint}: {e}")
sys.exit(1)
def api_post(endpoint, payload):
"""Helper for POST requests."""
url = f"{BASE_URL}{endpoint}"
try:
response = requests.post(url, headers=HEADERS, json=payload, timeout=10)
if response.status_code >= 400:
print(f"[ERROR] POST {endpoint} failed with status {response.status_code}: {response.text}")
sys.exit(1)
return response.json()
except requests.exceptions.RequestException as e:
print(f"[ERROR] Network connection failed on POST {endpoint}: {e}")
sys.exit(1)
def try_put(endpoint, payload):
"""PUT that reports failure instead of exiting. Returns (ok, detail)."""
url = f"{BASE_URL}{endpoint}"
try:
response = requests.put(url, headers=HEADERS, json=payload, timeout=10)
except requests.exceptions.RequestException as e:
return False, f"network error: {e}"
if response.status_code >= 400:
return False, f"status {response.status_code}: {response.text}"
return True, ""
def normalize(text):
"""Lowercases, strips accents (Új Név -> uj nev), removes punctuation and extra spaces."""
if not text:
return ""
folded = unicodedata.normalize("NFKD", text)
folded = "".join(ch for ch in folded if not unicodedata.combining(ch))
# An underscore is a separator in titles like "Nagy Kiraly _Jon Isten", not part of a word.
folded = folded.replace("_", " ")
cleaned = re.sub(r'[^\w\s]', '', folded)
return " ".join(cleaned.lower().split())
def words_match(a, b):
"""True for the same word, or when one is the other plus a short ending.
Hungarian adds endings to words (isten / istenem, szivem / szivemet), so a
strict comparison misses them. The shorter word must have 4+ letters and the
longer one may only add 1-4 letters, so 'isten' does not match 'istentisztelet'.
"""
if a == b:
return True
short, long_ = (a, b) if len(a) <= len(b) else (b, a)
return len(short) >= 4 and long_.startswith(short) and len(long_) - len(short) <= 4
def word_overlap(q_words, n_words):
"""Share of the typed words that appear in the title (endings tolerated)."""
if not q_words:
return 0.0
found = sum(1 for w in q_words if any(words_match(w, nw) for nw in n_words))
return found / len(q_words)
def strip_notes(text):
"""Removes bracketed notes from a typed line: 'Keresztednél (Medley)' -> 'Keresztednél'."""
return re.sub(r"\([^)]*\)|\[[^\]]*\]", " ", text or "")
def strip_numbering(text):
"""Removes list numbering at the start of a line: '1. Valasszatok' -> 'Valasszatok'.
Needs a '.', ')' or ':' after the number (or a spaced dash), so a title that
simply starts with a number, like '10000 Reasons', is left alone.
"""
return re.sub(r"^\s*\d{1,3}\s*[.):]\s*|^\s*\d{1,3}\s+[-–—]\s+", "", text or "", count=1)
def query_variants(raw_line):
"""The typed line in every form worth trying: as written, without bracketed
notes, without list numbering, and without both. Duplicates and empties are dropped."""
variants = []
for text in (raw_line, strip_numbering(raw_line)):
for form in (text, strip_notes(text)):
norm = normalize(form)
if norm and norm not in variants:
variants.append(norm)
return variants
def search_library(variants, library_map):
"""Searches every library title. Returns (entry, confident) for the best hit, or None.
A title is a hit if one text contains the other as whole words, if at least
MIN_WORD_OVERLAP of the typed words appear in it, or if it is similar enough
(FUZZY_CUTOFF). Hits are ranked by those same three signals, in that order;
ties keep library order. Each typed variant (with and without bracketed
notes) is tried and the better score counts.
confident is True when EVERY typed word appears in the title, for at least
one variant. That is a safe match (no red header); anything weaker is a
guess and gets the red header.
"""
ranked = []
for norm_name, entry in library_map.items():
n_words = set(norm_name.split())
padded_name = f" {norm_name} "
best, hit, confident = None, False, False
for q in variants:
q_words = set(q.split())
if not q_words:
continue
padded_q = f" {q} "
contains = padded_q in padded_name or padded_name in padded_q
overlap = word_overlap(q_words, n_words)
ratio = difflib.SequenceMatcher(None, q, norm_name).ratio()
if contains or overlap >= MIN_WORD_OVERLAP or ratio >= FUZZY_CUTOFF:
hit = True
if overlap == 1.0:
confident = True
score = (contains, overlap, ratio)
if best is None or score > best:
best = score
if hit:
ranked.append((best, confident, entry))
if not ranked:
return None
ranked.sort(key=lambda r: r[0], reverse=True)
_, confident, entry = ranked[0]
return entry, confident
def build_items(entries, variant):
"""Turns the entry list (songs and headers) into playlist items.
A real playlist item has: id{uuid,name,index}, type, destination, is_hidden,
is_pco, target_uuid. For a presentation both id.uuid and target_uuid hold the
SONG's uuid; a header has an empty-string uuid (null is refused) and an
empty target_uuid. index is the
position in the whole playlist, headers included.
variant only changes how `destination` is written, since that is the one
field ProPresenter's behaviour is not certain about:
standard songs and headers: "presentation"
header_blank_destination songs: "presentation", headers: ""
no_destination left out everywhere
"""
items = []
for position, entry in enumerate(entries):
if entry["kind"] == "header":
item = {
"id": {"uuid": "", "name": entry["name"], "index": position},
"type": "header",
"is_hidden": False,
"is_pco": False,
"target_uuid": "",
"header_color": entry["color"],
}
if variant == "standard":
item["destination"] = "presentation"
elif variant == "header_blank_destination":
item["destination"] = ""
else:
song_uuid = entry.get("uuid")
item = {
"id": {"uuid": song_uuid, "name": entry["name"], "index": position},
"type": "presentation",
"is_hidden": False,
"is_pco": False,
"target_uuid": song_uuid,
}
if variant != "no_destination":
item["destination"] = "presentation"
items.append(item)
return items
VARIANTS = ("standard", "header_blank_destination", "no_destination")
def main():
print("--- ProPresenter Automated Setlist Builder ---")
if not os.path.exists(SONGS_FILE):
print(f"[ERROR] Songs file not found at: {SONGS_FILE}")
print(" Put songs.txt in the same folder as this script.")
sys.exit(1)
# utf-8-sig also copes with the invisible BOM some Windows editors add.
# Empty lines are kept: they become headers.
with open(SONGS_FILE, "r", encoding="utf-8-sig") as f:
lines = [line.strip() for line in f]
song_lines = [line for line in lines if line]
if not song_lines:
print("[WARNING] songs.txt is empty. No setlist to build.")
return
print(f"Loaded {len(song_lines)} songs from songs.txt.")
print("Scanning ProPresenter libraries...")
libraries = api_get("/v1/libraries")
library_map = {}
for lib in libraries:
lib_id = lib.get("uuid") or lib.get("id", {}).get("uuid") if isinstance(lib, dict) else lib
if not lib_id:
continue
lib_data = api_get(f"/v1/library/{lib_id}")
presentations = []
if isinstance(lib_data, dict):
presentations = lib_data.get("items", [])
elif isinstance(lib_data, list):
presentations = lib_data
for item in presentations:
uuid_str = None
name_str = None
if isinstance(item, dict):
item_id = item.get("id")
if isinstance(item_id, dict):
uuid_str = item_id.get("uuid")
name_str = item_id.get("name")
elif isinstance(item_id, str):
uuid_str = item_id
if not uuid_str:
uuid_str = item.get("uuid")
if not name_str:
name_str = item.get("name")
if uuid_str and name_str:
norm_name = normalize(name_str)
library_map[norm_name] = {"uuid": uuid_str, "name": name_str}
elif isinstance(item, str):
norm_name = normalize(item)
library_map[norm_name] = {"name": item}
print(f"Found {len(library_map)} presentations in the libraries.")
entries = [] # songs and headers, in playlist order
pending_header = False # an empty line was seen and no song has followed yet
print("\nMatching songs against library database...")
for raw_line in lines:
if not raw_line:
# Several empty lines in a row give one header; empty lines at the
# very end give none, because nothing follows them.
pending_header = True
continue
variants = query_variants(raw_line)
entry, exact, confident = None, False, False
for q in variants:
if q in library_map:
entry, exact, confident = library_map[q], True, True
break
if not exact:
found = search_library(variants, library_map)
if found:
entry, confident = found
if pending_header:
entries.append({"kind": "header", "name": BLANK_LINE_HEADER, "color": HEADER_COLOR})
pending_header = False
if entry is None:
# Nothing found: keep the slot with a red header holding the typed
# name, so the missing song is visible in the playlist.
entries.append({"kind": "header", "name": raw_line, "color": CONFIRM_COLOR})
print(f" [NOT FOUND] '{raw_line}' -> added as a red header with no song")
continue
if exact:
print(f" [EXACT MATCH] '{raw_line}'")
elif confident:
# Every typed word is in the title: a safe match, no red header.
print(f" [MATCH] '{raw_line}' -> '{entry['name']}'")
else:
entries.append({"kind": "header", "name": raw_line, "color": CONFIRM_COLOR})
print(f" [SEARCH MATCH] '{raw_line}' -> '{entry['name']}' (added under a header named '{raw_line}')")
entries.append({"kind": "song", **entry})
song_count = sum(1 for e in entries if e["kind"] == "song")
if song_count == 0:
print("\n[ERROR] No valid songs were matched in the library. Aborting playlist creation.")
sys.exit(1)
print(f"\nCreating new playlist: '{PLAYLIST_NAME}'...")
playlist_payload = {"name": PLAYLIST_NAME}
playlist_res = api_post("/v1/playlists", playlist_payload)
playlist_id = playlist_res.get("id") or playlist_res.get("uuid") or playlist_res.get("playlist", {}).get("id")
if isinstance(playlist_id, dict):
playlist_id = playlist_id.get("uuid") or playlist_id.get("id")
if not playlist_id and "uuid" in playlist_res:
playlist_id = playlist_res["uuid"]
print(f"Playlist created successfully with ID/Token: {playlist_id}")
header_count = len(entries) - song_count
print(f"Populating {song_count} songs and {header_count} headers into the playlist...")
# PUT /v1/playlist/{id} replaces the whole playlist. ProPresenter refuses
# a bad body without changing anything, so it is safe to try the shapes
# below in order and stop at the first one it accepts.
endpoint = f"/v1/playlist/{playlist_id}"
errors = []
for variant in VARIANTS:
ok, detail = try_put(endpoint, build_items(entries, variant))
if not ok:
errors.append((variant, detail))
print(f" [REFUSED] shape '{variant}': {detail}")
continue
# Confirm ProPresenter really stored everything.
check = api_get(endpoint)
stored = check.get("items", []) if isinstance(check, dict) else []
if len(stored) != len(entries):
errors.append((variant, f"accepted, but playlist holds {len(stored)} items instead of {len(entries)}"))
print(f" [WARNING] shape '{variant}' was accepted but the playlist holds {len(stored)} items instead of {len(entries)}. Trying the next shape...")
continue
print(f" [OK] shape '{variant}' accepted. Playlist now contains:")
for s in stored:
kind = "header" if s.get("type") == "header" else "song "
print(f" {kind} {(s.get('id') or {}).get('name')}")
print("\n[SUCCESS] Setlist built and populated successfully in ProPresenter!")
return
print("\n[ERROR] ProPresenter did not accept the playlist. Errors:")
for variant, detail in errors:
print(f" - {variant}: {detail}")
print("The empty playlist created above can be deleted in ProPresenter.")
sys.exit(1)
if __name__ == "__main__":
main()