Python script: trim an XMLTV guide to a few days and to the channels you actually have

What it does: takes a large XMLTV file and writes a smaller one that contains only the next N days and, optionally, only the channels listed in your M3U playlist. Reads and writes plain or gzip files.

Requirements: Python 3.8 or newer. No extra packages.

Licence: free to use and change.

Why

Players download and parse the whole guide. A file with a week of data for thousands of channels is slow on a phone and can fail on a set-top box. Most of that data is for channels the user does not have.

The script

#!/usr/bin/env python3
"""Trim an XMLTV file by time window and, optionally, by playlist channels."""
import argparse
import gzip
import re
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone

TVG_ID = re.compile(r'tvg-id="([^"]+)"')


def open_any(path, mode):
    return gzip.open(path, mode) if path.endswith(".gz") else open(path, mode)


def parse_time(value):
    """'20261128180000 +0100' -> aware datetime in UTC."""
    stamp, _, offset = value.strip().partition(" ")
    moment = datetime.strptime(stamp[:14], "%Y%m%d%H%M%S")
    if len(offset) >= 5 and offset[0] in "+-":
        delta = timedelta(hours=int(offset[1:3]), minutes=int(offset[3:5]))
        moment = moment - delta if offset[0] == "+" else moment + delta
    return moment.replace(tzinfo=timezone.utc)


def playlist_ids(path):
    with open(path, encoding="utf-8-sig", errors="replace") as fh:
        return set(TVG_ID.findall(fh.read()))


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("source")
    ap.add_argument("target")
    ap.add_argument("--days", type=int, default=3)
    ap.add_argument("--playlist", help="keep only channels whose id is a tvg-id in this M3U")
    args = ap.parse_args()

    wanted = playlist_ids(args.playlist) if args.playlist else None
    now = datetime.now(timezone.utc)
    until = now + timedelta(days=args.days)

    with open_any(args.source, "rb") as fh:
        root = ET.parse(fh).getroot()

    kept_channels = dropped_channels = kept_prog = dropped_prog = 0
    for node in list(root):
        if node.tag == "channel":
            if wanted is not None and node.get("id") not in wanted:
                root.remove(node)
                dropped_channels += 1
            else:
                kept_channels += 1
        elif node.tag == "programme":
            keep = wanted is None or node.get("channel") in wanted
            if keep:
                try:
                    start = parse_time(node.get("start", ""))
                    stop = parse_time(node.get("stop", "") or node.get("start", ""))
                    keep = stop > now and start < until
                except ValueError:
                    keep = False
            if keep:
                kept_prog += 1
            else:
                root.remove(node)
                dropped_prog += 1

    with open_any(args.target, "wb") as out:
        ET.ElementTree(root).write(out, encoding="utf-8", xml_declaration=True)

    print(f"channels kept {kept_channels}, removed {dropped_channels}")
    print(f"programmes kept {kept_prog}, removed {dropped_prog}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

How to use it

python3 trim_epg.py guide.xml.gz small.xml.gz --days 3 --playlist playlist.m3u

Example output:

channels kept 180, removed 2410
programmes kept 12960, removed 402117

Notes on how it works

  • Time zones are respected. Each time is converted to UTC using its own offset before it is compared, so a guide that mixes offsets is still cut correctly. A time without an offset is read as UTC.
  • Programmes that already ended are removed, and so is everything that starts after the window.
  • A programme with an unreadable time is dropped instead of stopping the whole run.
  • Channel matching is exact, the same way players do it. If a channel disappears from the result, its tvg-id in the playlist does not equal its id in the guide.
  • Memory. The whole file is loaded. For a guide of a few hundred megabytes that needs a few gigabytes of RAM. Run it on the server, not on the player device.

Run it after every guide update

30 4 * * * /usr/bin/python3 /opt/scripts/trim_epg.py /srv/epg/full.xml.gz /srv/www/guide.xml.gz --days 3 --playlist /srv/www/playlist.m3u

Write to a temporary name and rename it afterwards if players may download the file while it is being written.