Skip to content

sources

Class info

Classes

Name Children Inherits
Source
framesheet.sources
A resolved input.

    🛈 DocStrings

    Input handling: files, stdin snippets and URLs.

    VIDEO_ORIGIN module-attribute

    VIDEO_ORIGIN = 'https://framesheet.invalid'
    

    Video wrapper pages and media are served from this virtual (secure) origin.

    Source dataclass

    A resolved input.

    Source code in src/framesheet/sources.py
    @dataclass
    class Source:
        """A resolved input."""
    
        label: str
        """What the user passed (path, ``-`` or URL)."""
        kind: SourceKind
        url: str
        """What the browser navigates to."""
        text: str | None
        """Source text if available locally (used for static checks and size detection)."""
        media: bytes | None = None
        """Video/animated image bytes (``kind == "video"``), served to the wrapper page."""
        container: str | None = None
        """Video container (``mp4``, ``webm``, ``gif``, ...) for video sources."""
    

    container class-attribute instance-attribute

    container: str | None = None
    

    Video container (mp4, webm, gif, ...) for video sources.

    label instance-attribute

    label: str
    

    What the user passed (path, - or URL).

    media class-attribute instance-attribute

    media: bytes | None = None
    

    Video/animated image bytes (kind == "video"), served to the wrapper page.

    text instance-attribute

    text: str | None
    

    Source text if available locally (used for static checks and size detection).

    url instance-attribute

    url: str
    

    What the browser navigates to.

    fetch_bytes

    fetch_bytes(url: str, timeout: float = 60.0) -> bytes
    

    Download a video URL (errors are raised: there is nothing to inspect without it).

    Source code in src/framesheet/sources.py
    def fetch_bytes(url: str, timeout: float = 60.0) -> bytes:
        """Download a video URL (errors are raised: there is nothing to inspect without it)."""
        request = urllib.request.Request(url, headers={"User-Agent": "framesheet"})
        try:
            with urllib.request.urlopen(request, timeout=timeout) as response:
                return response.read()
        except (OSError, ValueError) as exc:
            msg = f"Cannot download {url}: {exc}"
            raise FileNotFoundError(msg) from None
    

    fetch_text

    fetch_text(url: str, timeout: float = 15.0) -> str | None
    

    Best-effort download of a URL's body (for static checks and SVG size detection).

    Source code in src/framesheet/sources.py
    def fetch_text(url: str, timeout: float = 15.0) -> str | None:
        """Best-effort download of a URL's body (for static checks and SVG size detection)."""
        request = urllib.request.Request(url, headers={"User-Agent": "framesheet"})
        try:
            with urllib.request.urlopen(request, timeout=timeout) as response:
                return response.read().decode("utf-8", errors="replace")
        except OSError, ValueError:
            return None
    

    parse_size

    parse_size(value: str) -> tuple[int, int]
    

    Parse WxH (e.g. 1280x720).

    Source code in src/framesheet/sources.py
    def parse_size(value: str) -> tuple[int, int]:
        """Parse ``WxH`` (e.g. ``1280x720``)."""
        match = re.fullmatch(r"\s*(\d+)\s*[xX*]\s*(\d+)\s*", value)
        if not match:
            msg = f"Invalid size {value!r}; expected WIDTHxHEIGHT, e.g. 1280x720"
            raise ValueError(msg)
        return int(match.group(1)), int(match.group(2))
    

    resolve

    resolve(source: str | Path, workdir: Path) -> Source
    

    Turn a path, - (stdin) or URL into a :class:Source.

    Stdin snippets are written to workdir so they load as real documents.

    Source code in src/framesheet/sources.py
    def resolve(source: str | Path, workdir: Path) -> Source:
        """Turn a path, ``-`` (stdin) or URL into a :class:`Source`.
    
        Stdin snippets are written to ``workdir`` so they load as real documents.
        """
        if isinstance(source, str) and source == "-":
            text = sys.stdin.read()
            return snippet(text, workdir, label="-")
        if isinstance(source, str) and re.match(r"^https?://", source):
            if container := _video_ext(source):
                return video_source(source, fetch_bytes(source), container)
            text = fetch_text(source)
            by_name = source.split("?")[0].lower().endswith(".svg")
            is_svg = by_name or bool(text and looks_like_svg(text))
            kind: SourceKind = "svg" if is_svg else "html"
            return Source(label=source, kind=kind, url=source, text=text)
        path = Path(source).expanduser().resolve()
        if not path.is_file():
            msg = f"Input not found: {source}"
            raise FileNotFoundError(msg)
        with path.open("rb") as fh:
            head = fh.read(64)
        if (container := _video_ext(path.name)) or media.sniff(head):
            return video_source(str(source), path.read_bytes(), container)
        text = path.read_text(encoding="utf-8", errors="replace")
        if path.suffix.lower() == ".svg":
            kind = "svg"
        elif path.suffix.lower() in {".html", ".htm", ".xhtml"}:
            kind = "html"
        else:
            kind = "svg" if looks_like_svg(text) else "html"
        return Source(label=str(source), kind=kind, url=path.as_uri(), text=text)
    

    snippet

    snippet(text: str, workdir: Path, *, label: str = '<snippet>') -> Source
    

    Wrap an in-memory SVG/HTML snippet as a source (written to workdir).

    Source code in src/framesheet/sources.py
    def snippet(text: str, workdir: Path, *, label: str = "<snippet>") -> Source:
        """Wrap an in-memory SVG/HTML snippet as a source (written to ``workdir``)."""
        kind: SourceKind = "svg" if looks_like_svg(text) else "html"
        if kind == "html" and "<html" not in text.lower():
            text = (
                f"<!DOCTYPE html>\n<html><head><meta charset='utf-8'></head><body>{text}</body></html>"
            )
        workdir.mkdir(parents=True, exist_ok=True)
        path = workdir / f"input.{kind}"
        path.write_text(text, encoding="utf-8")
        return Source(label=label, kind=kind, url=path.as_uri(), text=text)
    

    svg_size

    svg_size(text: str) -> tuple[int, int] | None
    

    Intrinsic size of an SVG: absolute width/height attributes, else the viewBox.

    Source code in src/framesheet/sources.py
    def svg_size(text: str) -> tuple[int, int] | None:
        """Intrinsic size of an SVG: absolute width/height attributes, else the viewBox."""
        try:
            root = ET.fromstring(text)
        except ET.ParseError:
            return None
        width, height = _length(root.get("width")), _length(root.get("height"))
        box = [float(v) for v in re.split(r"[\s,]+", root.get("viewBox", "").strip()) if v]
        if len(box) == 4 and box[2] > 0 and box[3] > 0:  # noqa: PLR2004
            vb_w, vb_h = box[2], box[3]
            if width and not height:
                height = width * vb_h / vb_w
            elif height and not width:
                width = height * vb_w / vb_h
            width, height = width or vb_w, height or vb_h
        if width and height:
            return max(1, round(width)), max(1, round(height))
        return None
    

    video_source

    video_source(label: str, data: bytes, container: str | None = None) -> Source
    

    A video/animated image, played in a wrapper page on :data:VIDEO_ORIGIN.

    Source code in src/framesheet/sources.py
    def video_source(label: str, data: bytes, container: str | None = None) -> Source:
        """A video/animated image, played in a wrapper page on :data:`VIDEO_ORIGIN`."""
        kind = media.sniff(data) or container
        if kind is None:
            msg = f"Not a supported video or animated image: {label}"
            raise ValueError(msg)
        return Source(
            label=label, kind="video", url=f"{VIDEO_ORIGIN}/video.html", text=None, media=data,
            container=kind,
        )  # fmt: skip