File size: 3,230 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Minimal client of the EmbeddingGemma 2 server (standard library only).

    python3 client.py "What causes the northern lights?" "Charged solar particles hit the atmosphere."
    python3 client.py --prompt-name SearchQuery --dimensions 256 "northern lights"
    python3 client.py --image photo.jpg --audio clip.wav "a dog barking in a park"     # one embedding per input
"""
from __future__ import annotations

import argparse
import base64
import json
import math
import sys
import urllib.error
import urllib.request


def post(url: str, payload: dict, timeout: float = 300.0):
    req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read() or b"{}")
        except Exception:  # noqa: BLE001
            return e.code, {}


def get_json(url: str, timeout: float = 10.0):
    with urllib.request.urlopen(url, timeout=timeout) as r:
        return json.loads(r.read())


def b64file(path: str) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("ascii")


def embed(base: str, inputs, **opts):
    """Embeddings (lists of floats): /v1/embeddings for plain texts without options, /embed otherwise."""
    if all(isinstance(x, str) for x in inputs) and set(opts) <= {"prompt_name", "dimensions"}:
        code, body = post(base.rstrip("/") + "/v1/embeddings", {"input": list(inputs), **opts})
        if code != 200:
            raise RuntimeError(f"HTTP {code}: {body}")
        return [d["embedding"] for d in sorted(body["data"], key=lambda d: d["index"])]
    code, body = post(base.rstrip("/") + "/embed", {"inputs": list(inputs), **opts})
    if code != 200:
        raise RuntimeError(f"HTTP {code}: {body}")
    return body["embeddings"]


def cosine(a, b) -> float:
    num = sum(x * y for x, y in zip(a, b))
    return num / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)) + 1e-30)


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("texts", nargs="*")
    ap.add_argument("--url", default="http://127.0.0.1:20000")
    ap.add_argument("--image", action="append", default=[])
    ap.add_argument("--audio", action="append", default=[])
    ap.add_argument("--prompt-name", default=None)
    ap.add_argument("--dimensions", type=int, default=None)
    a = ap.parse_args()
    inputs = list(a.texts) + [{"image": b64file(p)} for p in a.image] + [{"audio": b64file(p)} for p in a.audio]
    if not inputs:
        ap.error("give texts, --image or --audio")
    opts = {}
    if a.prompt_name:
        opts["prompt_name"] = a.prompt_name
    if a.dimensions:
        opts["dimensions"] = a.dimensions
    e = embed(a.url, inputs, **opts)
    print(json.dumps({"dim": len(e[0]), "first": [round(v, 6) for v in e[0][:8]]}))
    for i in range(len(e)):
        print(" ".join(f"{cosine(e[i], e[j]):7.4f}" for j in range(len(e))))
    return 0


if __name__ == "__main__":
    sys.exit(main())