import json
from typing import Dict
from typing import Any
from typing import cast


def tx_dict_from_text(text: str) -> Dict[str, Any]:
    """
    Takes json or hexadecimal, returns a dictionary.

    Raises `ValueError` if the text is not valid.
    """
    text = text.strip()
    if not text:
        raise ValueError("empty string")

    try:
        bytes.fromhex(text)
    except ValueError:
        pass
    else:
        return { "hex": text }

    tx_dict = cast(Dict[str, Any], json.loads(text))
    if "hex" not in tx_dict:
        raise ValueError("invalid transaction format")
    return tx_dict