Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import spaces
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
|
| 6 |
+
MODEL_NAME = "intfloat/multilingual-e5-small"
|
| 7 |
+
model = SentenceTransformer(MODEL_NAME)
|
| 8 |
+
model.to("cuda") # ZeroGPU gives the GPU only while a @spaces.GPU function runs
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@spaces.GPU
|
| 12 |
+
def embed(texts_json: str, kind: str = "query"):
|
| 13 |
+
"""texts_json: a JSON list of strings, e.g. '["hello", "world"]'."""
|
| 14 |
+
texts = json.loads(texts_json)
|
| 15 |
+
if not isinstance(texts, list) or len(texts) > 64:
|
| 16 |
+
raise gr.Error("Send a JSON list of at most 64 strings.")
|
| 17 |
+
prefix = "passage: " if kind == "passage" else "query: "
|
| 18 |
+
vectors = model.encode([prefix + t for t in texts], normalize_embeddings=True)
|
| 19 |
+
return {"model": MODEL_NAME, "dim": int(vectors.shape[1]), "vectors": vectors.tolist()}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
demo = gr.Interface(
|
| 23 |
+
fn=embed,
|
| 24 |
+
inputs=[
|
| 25 |
+
gr.Textbox(label="texts (JSON list)"),
|
| 26 |
+
gr.Radio(["query", "passage"], value="query", label="kind"),
|
| 27 |
+
],
|
| 28 |
+
outputs=gr.JSON(),
|
| 29 |
+
api_name="embed",
|
| 30 |
+
)
|
| 31 |
+
demo.launch()
|