updated
Browse files- handler.py +23 -38
handler.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
from typing import Dict, List, Any
|
| 2 |
-
from transformers import
|
| 3 |
import torch
|
| 4 |
import base64
|
| 5 |
from io import BytesIO
|
|
@@ -9,9 +9,8 @@ import requests
|
|
| 9 |
|
| 10 |
class EndpointHandler:
|
| 11 |
def __init__(self, path=""):
|
| 12 |
-
self.
|
| 13 |
-
|
| 14 |
-
trust_remote_code=True
|
| 15 |
)
|
| 16 |
self.model = AutoModel.from_pretrained(
|
| 17 |
path,
|
|
@@ -26,40 +25,26 @@ class EndpointHandler:
|
|
| 26 |
if not isinstance(inputs_data, list):
|
| 27 |
inputs_data = [inputs_data]
|
| 28 |
|
| 29 |
-
|
|
|
|
| 30 |
for item in inputs_data:
|
| 31 |
if isinstance(item, str):
|
| 32 |
-
|
| 33 |
-
image = None
|
| 34 |
elif isinstance(item, dict):
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
text=text,
|
| 53 |
-
return_tensors="pt"
|
| 54 |
-
).to(self.model.device)
|
| 55 |
-
|
| 56 |
-
with torch.no_grad():
|
| 57 |
-
outputs = self.model(**inputs, output_hidden_states=True)
|
| 58 |
-
# Last token pooling (correct for Qwen embedding models)
|
| 59 |
-
hidden = outputs.last_hidden_state
|
| 60 |
-
embedding = hidden[:, -1, :]
|
| 61 |
-
embedding = torch.nn.functional.normalize(embedding, p=2, dim=1)
|
| 62 |
-
|
| 63 |
-
results.append({"embedding": embedding[0].cpu().tolist()})
|
| 64 |
-
|
| 65 |
-
return results
|
|
|
|
| 1 |
from typing import Dict, List, Any
|
| 2 |
+
from transformers import AutoTokenizer, AutoModel
|
| 3 |
import torch
|
| 4 |
import base64
|
| 5 |
from io import BytesIO
|
|
|
|
| 9 |
|
| 10 |
class EndpointHandler:
|
| 11 |
def __init__(self, path=""):
|
| 12 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 13 |
+
path, trust_remote_code=True
|
|
|
|
| 14 |
)
|
| 15 |
self.model = AutoModel.from_pretrained(
|
| 16 |
path,
|
|
|
|
| 25 |
if not isinstance(inputs_data, list):
|
| 26 |
inputs_data = [inputs_data]
|
| 27 |
|
| 28 |
+
# For now handle text only
|
| 29 |
+
texts = []
|
| 30 |
for item in inputs_data:
|
| 31 |
if isinstance(item, str):
|
| 32 |
+
texts.append(item)
|
|
|
|
| 33 |
elif isinstance(item, dict):
|
| 34 |
+
texts.append(item.get("text", ""))
|
| 35 |
+
|
| 36 |
+
encoded = self.tokenizer(
|
| 37 |
+
texts,
|
| 38 |
+
padding=True,
|
| 39 |
+
truncation=True,
|
| 40 |
+
max_length=512,
|
| 41 |
+
return_tensors="pt"
|
| 42 |
+
).to(self.model.device)
|
| 43 |
+
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
outputs = self.model(**encoded, output_hidden_states=True)
|
| 46 |
+
# Last token pooling
|
| 47 |
+
embeddings = outputs.last_hidden_state[:, -1, :]
|
| 48 |
+
embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
|
| 49 |
+
|
| 50 |
+
return [{"embedding": emb.cpu().tolist()} for emb in embeddings]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|