from typing import Union
from typing import IO
from typing import Optional


def extract_format(fp: Union[IO, str]) -> str:
    """Extract the altair_saver output format from a file or filename."""
    filename: Optional[str]
    if isinstance(fp, str):
        filename = fp
    else:
        filename = getattr(fp, "name", None)
    if filename is None:
        raise ValueError(f"Cannot infer format from {fp}")
    if filename.endswith(".vg.json"):
        return "vega"
    elif filename.endswith(".vl.json"):
        return "vega-lite"
    else:
        return filename.split(".")[-1]