Spaces:
Sleeping
Sleeping
Download app.py from shao001/test-embedding-api: direct link, hf CLI and curl.
- Browser
- Download file 1.03 kB
-
https://huggingface.co/spaces/shao001/test-embedding-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/shao001/test-embedding-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/shao001/test-embedding-api/resolve/main/app.py
1.03 kB
| import json | |
| import gradio as gr | |
| import spaces | |
| from sentence_transformers import SentenceTransformer | |
| MODEL_NAME = "intfloat/multilingual-e5-small" | |
| model = SentenceTransformer(MODEL_NAME) | |
| model.to("cuda") # ZeroGPU gives the GPU only while a @spaces.GPU function runs | |
| def embed(texts_json: str, kind: str = "query"): | |
| """texts_json: a JSON list of strings, e.g. '["hello", "world"]'.""" | |
| texts = json.loads(texts_json) | |
| if not isinstance(texts, list) or len(texts) > 64: | |
| raise gr.Error("Send a JSON list of at most 64 strings.") | |
| prefix = "passage: " if kind == "passage" else "query: " | |
| vectors = model.encode([prefix + t for t in texts], normalize_embeddings=True) | |
| return {"model": MODEL_NAME, "dim": int(vectors.shape[1]), "vectors": vectors.tolist()} | |
| demo = gr.Interface( | |
| fn=embed, | |
| inputs=[ | |
| gr.Textbox(label="texts (JSON list)"), | |
| gr.Radio(["query", "passage"], value="query", label="kind"), | |
| ], | |
| outputs=gr.JSON(), | |
| api_name="embed", | |
| ) | |
| demo.launch() |