def annotate_event(ev, key, ts=None, namespace=None, **kwargs):
    """Add an annotation to an event."""
    ann = {}
    if ts is None:
        ts = time.time()
    ann["ts"] = ts
    ann["key"] = key
    if namespace is None and "HUMILIS_ENVIRONMENT" in os.environ:
        namespace = "{}:{}:{}".format(
            os.environ.get("HUMILIS_ENVIRONMENT"),
            os.environ.get("HUMILIS_LAYER"),
            os.environ.get("HUMILIS_STAGE"))

    if namespace is not None:
        ann["namespace"] = namespace
    ann.update(kwargs)
    _humilis = ev.get("_humilis", {})
    if not _humilis:
        ev["_humilis"] = {"annotation": [ann]}
    else:
        ev["_humilis"]["annotation"] = _humilis.get("annotation", [])
        # Clean up previous annotations with the same key
        delete_annotations(ev, key)
        ev["_humilis"]["annotation"].append(ann)

    return ev
Add an annotation to an event.