dejanseo commited on
Commit
65c7bf6
1 Parent(s): f0c6f33

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +41 -47
handler.py CHANGED
@@ -1,48 +1,42 @@
 
1
  import torch
2
- from transformers import BertTokenizer, BertForTokenClassification
3
-
4
- # Initialize the model and tokenizer
5
- model_name = "dejanseo/LinkBERT"
6
- tokenizer = BertTokenizer.from_pretrained(model_name)
7
- model = BertForTokenClassification.from_pretrained(model_name)
8
-
9
- def model_init(path, device='cpu'):
10
- """Initialize model."""
11
- model.to(device)
12
- model.eval()
13
- return model
14
-
15
- # This function will be called to load the model
16
- def init():
17
- # If your model requires any specific initialization, handle it here
18
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
19
- model_init(model, device=device)
20
-
21
- # This function will be called to process requests
22
- def process(inputs):
23
- # Preprocess input data
24
- input_data = inputs["inputs"]
25
- inputs_tensor = tokenizer(input_data, return_tensors="pt", add_special_tokens=True)
26
- input_ids = inputs_tensor["input_ids"]
27
-
28
- # Run model
29
- with torch.no_grad():
30
- outputs = model(input_ids)
31
- predictions = torch.argmax(outputs.logits, dim=-1)
32
-
33
- # Postprocess model outputs
34
- tokens = tokenizer.convert_ids_to_tokens(input_ids[0])[1:-1] # Exclude CLS and SEP tokens
35
- predictions = predictions[0][1:-1]
36
- result = []
37
- for token, pred in zip(tokens, predictions):
38
- if pred.item() == 1:
39
- result.append(f"<u>{token}</u>")
40
- else:
41
- result.append(token)
42
-
43
- # Join tokens back into a string
44
- reconstructed_text = " ".join(result).replace(" ##", "")
45
-
46
- return {"result": reconstructed_text}
47
-
48
- # Note: The actual function signatures for init() and process() might need to be adapted based on Hugging Face's requirements.
 
1
+ from transformers import AutoModelForTokenClassification, AutoTokenizer
2
  import torch
3
+ from typing import Dict, List, Any
4
+
5
+ class EndpointHandler:
6
+ def __init__(self, path: str = "dejanseo/LinkBERT"):
7
+ # Initialize tokenizer and model with the specified path
8
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
9
+ self.model = AutoModelForTokenClassification.from_pretrained(path)
10
+ self.model.eval() # Set model to evaluation mode
11
+
12
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
13
+ # Extract input text from the request
14
+ inputs = data.get("inputs", "")
15
+
16
+ # Tokenize the inputs
17
+ inputs_tensor = self.tokenizer(inputs, return_tensors="pt", add_special_tokens=True)
18
+ input_ids = inputs_tensor["input_ids"]
19
+
20
+ # Run the model
21
+ with torch.no_grad():
22
+ outputs = self.model(input_ids)
23
+ predictions = torch.argmax(outputs.logits, dim=-1)
24
+
25
+ # Process the predictions to generate readable output
26
+ tokens = self.tokenizer.convert_ids_to_tokens(input_ids[0])[1:-1] # Exclude CLS and SEP tokens
27
+ predictions = predictions[0][1:-1].tolist()
28
+
29
+ # Reconstruct the text with annotations for token classification
30
+ result = []
31
+ for token, pred in zip(tokens, predictions):
32
+ if pred == 1: # Assuming '1' is the label for the class of interest
33
+ result.append(f"<u>{token}</u>")
34
+ else:
35
+ result.append(token)
36
+
37
+ reconstructed_text = " ".join(result).replace(" ##", "")
38
+
39
+ # Return the processed text in a structured format
40
+ return [{"text": reconstructed_text}]
41
+
42
+ # Note: You'll need to replace 'path' with the actual path or identifier of your model when initializing the EndpointHandler.