Alexandre-Numind commited on
Commit
c04a9f0
1 Parent(s): caedcd0

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +37 -0
handler.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
+ import os
5
+
6
+
7
+ MAX_INPUT_SIZE = 10_000
8
+ MAX_NEW_TOKENS = 4_000
9
+
10
+ def clean_json_text(text):
11
+ """
12
+ Cleans JSON text by removing leading/trailing whitespace and escaping special characters.
13
+ """
14
+ text = text.strip()
15
+ text = text.replace("\#", "#").replace("\&", "&")
16
+ return text
17
+
18
+ class EndpointHandler:
19
+ def __init__(self, path=""):
20
+ # load model and processor from path
21
+ self.model = AutoModelForCausalLM.from_pretrained(path,
22
+ trust_remote_code=True,
23
+ torch_dtype=torch.bfloat16,
24
+ device_map="auto")
25
+ self.model.eval()
26
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
27
+
28
+ def __call__(self, data: Dict[str, Any]) -> str:
29
+ data = data.pop("inputs")
30
+ template = data.pop("template")
31
+ text = data.pop("text")
32
+ input_llm = f"<|input|>\n### Template:\n{template}\n### Text:\n{text}\n\n<|output|>" + "{"
33
+
34
+ input_ids = self.tokenizer(input_llm, return_tensors="pt", truncation=True, max_length=MAX_INPUT_SIZE).to("cuda")
35
+ output = self.tokenizer.decode(self.model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS)[0], skip_special_tokens=True)
36
+
37
+ return clean_json_text(output.split("<|output|>")[1])