Britania commited on
Commit
0782331
路
verified 路
1 Parent(s): fb2a5f9

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +13 -26
handler.py CHANGED
@@ -5,18 +5,6 @@ import jsonschema
5
  import torch
6
  import json
7
 
8
- schema = {
9
- "type": "object",
10
- "properties": {
11
- "objetivoDistancia": {"type": "string"},
12
- "calentamiento": {"type": "string"},
13
- "drills": {"type": "array", "items": {"type": "object"}},
14
- "sprints": {"type": "array", "items": {"type": "object"}},
15
- "enfriamiento": {"type": "string"}
16
- },
17
- "required": ["objetivoDistancia", "calentamiento", "drills", "sprints", "enfriamiento"]
18
- }
19
-
20
  class EndpointHandler():
21
  def __init__(self, path=""):
22
  self.model = AutoModelForCausalLM.from_pretrained(
@@ -25,9 +13,9 @@ class EndpointHandler():
25
  torch_dtype=torch.bfloat16,
26
  device_map="auto"
27
  )
28
- self.my_tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
29
 
30
- def parse_and_validate_json(output):
31
  output = output.replace("\n\n", "\n").strip()
32
  outputs = output.split("\n")
33
 
@@ -39,10 +27,9 @@ class EndpointHandler():
39
  return True, corrected_json
40
  except (json.JSONDecodeError, ValidationError):
41
  continue
42
-
43
  return False, "No se encontr贸 ning煤n JSON v谩lido seg煤n el esquema requerido."
44
 
45
- def model_inference(model, tokenizer, text, **parameters):
46
  default_parameters = {
47
  "max_new_tokens": 300,
48
  "temperature": 0.5,
@@ -51,20 +38,22 @@ class EndpointHandler():
51
  "repetition_penalty": 1.2
52
  }
53
  default_parameters.update(parameters)
54
- inputs = tokenizer(text, return_tensors="pt").to("cuda:0")
55
  inputs_length = len(inputs["input_ids"][0])
56
  with torch.inference_mode():
57
- outputs = model.generate(**inputs, **default_parameters)
58
- return tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
59
 
60
- def model_inference_with_validation(filled_template, **parameters):
61
  while True:
62
- result = self.model_inference(self.model, self.my_tokenizer, filled_template, **parameters)
63
  is_valid, response_or_error = self.parse_and_validate_json(result)
64
  if is_valid:
65
- return {'generated_text': [result]}
 
 
66
 
67
- def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
68
  input_data = data.pop("inputs", data)
69
  parameters = data.pop("parameters", {})
70
 
@@ -78,6 +67,4 @@ class EndpointHandler():
78
  data_text = json.dumps(input_data, indent=4)
79
  filled_template = template.replace("{data}", data_text)
80
 
81
- return self.model_inference_with_validation(filled_template, **parameters)
82
-
83
-
 
5
  import torch
6
  import json
7
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  class EndpointHandler():
9
  def __init__(self, path=""):
10
  self.model = AutoModelForCausalLM.from_pretrained(
 
13
  torch_dtype=torch.bfloat16,
14
  device_map="auto"
15
  )
16
+ self.tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
17
 
18
+ def parse_and_validate_json(self, output):
19
  output = output.replace("\n\n", "\n").strip()
20
  outputs = output.split("\n")
21
 
 
27
  return True, corrected_json
28
  except (json.JSONDecodeError, ValidationError):
29
  continue
 
30
  return False, "No se encontr贸 ning煤n JSON v谩lido seg煤n el esquema requerido."
31
 
32
+ def model_inference(self, text, **parameters):
33
  default_parameters = {
34
  "max_new_tokens": 300,
35
  "temperature": 0.5,
 
38
  "repetition_penalty": 1.2
39
  }
40
  default_parameters.update(parameters)
41
+ inputs = self.tokenizer(text, return_tensors="pt").to("cuda:0")
42
  inputs_length = len(inputs["input_ids"][0])
43
  with torch.inference_mode():
44
+ outputs = self.model.generate(**inputs, **default_parameters)
45
+ return self.tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
46
 
47
+ def model_inference_with_validation(self, filled_template, **parameters):
48
  while True:
49
+ result = self.model_inference(filled_template, **parameters)
50
  is_valid, response_or_error = self.parse_and_validate_json(result)
51
  if is_valid:
52
+ return {'generated_text': [response_or_error]}
53
+ else:
54
+ continue
55
 
56
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
57
  input_data = data.pop("inputs", data)
58
  parameters = data.pop("parameters", {})
59
 
 
67
  data_text = json.dumps(input_data, indent=4)
68
  filled_template = template.replace("{data}", data_text)
69
 
70
+ return self.model_inference_with_validation(filled_template, **parameters)