shao001's picture
Create app.py
ff912cd verified
Raw History Blame Contribute Delete
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
@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()