Spaces:
Sleeping
Sleeping
File size: 1,029 Bytes
ff912cd | 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 | 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
@spaces.GPU
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() |