#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Minimal client of the all-MiniLM-L6-v2 server (standard library only). python3 client.py "A man is playing a guitar." "Someone plays an instrument." # embeddings + cosine matrix python3 client.py --url http://127.0.0.1:20000 --native --pooling cls "some text" """ from __future__ import annotations import argparse import json import math import sys import urllib.error import urllib.request def post(url: str, payload: dict, timeout: float = 120.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 embed(base: str, texts, **native): """Embeddings (lists of floats) of ``texts``: /v1/embeddings, or /embed when native options are given.""" if native: code, body = post(base.rstrip("/") + "/embed", {"texts": list(texts), **native}) if code != 200: raise RuntimeError(f"HTTP {code}: {body}") return body["embeddings"] code, body = post(base.rstrip("/") + "/v1/embeddings", {"input": list(texts)}) if code != 200: raise RuntimeError(f"HTTP {code}: {body}") return [d["embedding"] for d in sorted(body["data"], key=lambda d: d["index"])] 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("--native", action="store_true", help="use /embed") ap.add_argument("--pooling", default="mean") ap.add_argument("--no-normalize", action="store_true") a = ap.parse_args() if a.native: e = embed(a.url, a.texts, pooling=a.pooling, normalize=not a.no_normalize) else: e = embed(a.url, a.texts) if a.native and a.pooling == "none": print(json.dumps({"n_tokens": [len(t) for t in e]})) return 0 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())