File size: 6,459 Bytes
4807d4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""The `discerna` command.

    discerna serve  --model <owner>/Discerna-v1-475M [--port 8000]    # HTTP server, POST /v1/decide
    discerna ask    examples/requests/support_ticket.json             # ask a running server
    discerna decide --model <owner>/Discerna-v1-475M examples/requests/support_ticket.json   # no server

`--model` takes a Hugging Face repo id (downloaded on first use, then cached) or a local folder.

`ask` and `decide` take --image PATH (repeatable) to attach pictures, --answers KEY.json to mark each
answer right or wrong, and --raw to print the JSON response.
"""

from __future__ import annotations

import argparse
import base64
import json
import mimetypes
import sys
from pathlib import Path


def _data_url(path: Path) -> str:
    kind = mimetypes.guess_type(path.name)[0] or "image/png"
    return f"data:{kind};base64," + base64.b64encode(path.read_bytes()).decode("ascii")


def _request(args) -> dict:
    request = json.loads(sys.stdin.read() if args.request == "-" else Path(args.request).read_text())
    request["images"] = request.get("images", []) + [_data_url(Path(p)) for p in args.image]
    return request


def _key(args, request: dict) -> dict:
    if not args.answers:
        return {}
    key = json.loads(Path(args.answers).read_text()).get(Path(args.request).name, {})
    return {k: v for k, v in key.items() if k in request["questions"]}


def _picked(question: dict, answer: dict) -> str:
    """The model's answer as a key names it: yes/no, the option, or the most likely level."""
    if answer["type"] == "noul":
        return "yes" if answer["noul"] >= 0.5 else "no"
    if answer["type"] == "choice":
        return answer["choice"]
    return question["criteria"][int(max(answer["probabilities"], key=answer["probabilities"].get))]


def show(request: dict, response: dict, key: dict | None = None) -> None:
    """Print a response readably: each question, its answer, and every option's probability."""
    key, right = key or {}, 0
    for name, answer in response["answers"].items():
        question = request["questions"][name]
        print(f"\n{name} ({answer['type']}): {question.get('instructions')}")
        if answer["type"] == "noul":
            print(f"  yes {answer['noul']:.3f}   no {1 - answer['noul']:.3f}")
        else:
            names = {}
            if answer["type"] == "choice":
                top = answer["choice"]
            else:  # score: levels come back as "0", "1", ...; the score is the expected level
                names = {str(i): f"{i} {c}" for i, c in enumerate(question["criteria"])}
                likely = names[max(answer["probabilities"], key=answer["probabilities"].get)]
                top = f"{answer['score']:.2f} on 0-{len(names) - 1} (most likely: {likely})"
            confidence = f"   (confidence {answer['confidence']:.3f})" if "confidence" in answer else ""
            print(f"  answer: {top}{confidence}")
            for option, p in sorted(answer["probabilities"].items(), key=lambda kv: -kv[1]):
                print(f"  {p:6.3f}  {'#' * round(p * 30):30s} {names.get(option, option)}")
        if name in key:
            expected = key[name] if isinstance(key[name], list) else [key[name]]
            ok = _picked(question, answer) in expected
            right += ok
            print("  RIGHT" if ok else f"  WRONG - expected: {' or '.join(expected)}")
    usage = response.get("usage") or {}
    print(f"\nmodel {response.get('model')}, {usage.get('input_tokens', '?')} input tokens")
    if key:
        print(f"right: {right} of {len(key)}")


def cmd_serve(args) -> None:
    import uvicorn

    from discerna.engine import load
    from discerna.server import create_app

    model = load(args.model, device=args.device, dtype=args.dtype, revision=args.revision)
    uvicorn.run(create_app(model), host=args.host, port=args.port)


def cmd_ask(args) -> None:
    import httpx

    request = _request(args)
    reply = httpx.post(f"{args.url}/v1/decide", json=request, timeout=300)
    if reply.status_code != 200:
        raise SystemExit(f"server said {reply.status_code}: {reply.text}")
    print(json.dumps(reply.json(), indent=1)) if args.raw else show(request, reply.json(), _key(args, request))


def cmd_decide(args) -> None:
    from discerna.engine import load

    request = _request(args)
    with load(args.model, device=args.device, dtype=args.dtype, revision=args.revision) as model:
        response = model.decide(request).model_dump(mode="json", exclude_none=True)
    print(json.dumps(response, indent=1)) if args.raw else show(request, response, _key(args, request))


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(prog="discerna", description="Discerna decision model")
    sub = parser.add_subparsers(dest="command", required=True)

    def model_args(p):
        p.add_argument("--model", required=True,
                       help="a Hugging Face repo id (owner/name, downloaded once and cached) or a local folder")
        p.add_argument("--revision", help="Hugging Face branch, tag or commit to use (default: latest)")
        p.add_argument("--device", default="auto", help="auto (cuda > mps > cpu), cuda, mps or cpu")
        p.add_argument("--dtype", default="auto", help="auto (float32 on CPU, float16 on GPUs), float32, ...")

    def request_args(p):
        p.add_argument("request", help="request JSON file, or - for stdin")
        p.add_argument("--image", action="append", default=[], help="image file to attach (repeatable)")
        p.add_argument("--answers", help="answer key JSON: marks each answer right or wrong")
        p.add_argument("--raw", action="store_true", help="print the JSON response")

    p = sub.add_parser("serve", help="serve a model over HTTP at POST /v1/decide")
    model_args(p)
    p.add_argument("--host", default="127.0.0.1")
    p.add_argument("--port", type=int, default=8000)
    p.set_defaults(func=cmd_serve)

    p = sub.add_parser("ask", help="send a request to a running server and show the answers")
    request_args(p)
    p.add_argument("--url", default="http://127.0.0.1:8000", help="server address")
    p.set_defaults(func=cmd_ask)

    p = sub.add_parser("decide", help="load a model and answer one request (no server)")
    model_args(p)
    request_args(p)
    p.set_defaults(func=cmd_decide)

    args = parser.parse_args(argv)
    args.func(args)


if __name__ == "__main__":
    main()