MCS12 commited on
Commit
5646b48
·
verified ·
1 Parent(s): 3ff4379

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +55 -0
handler.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
+
4
+ class EndpointHandler:
5
+ def __init__(self, path=""):
6
+
7
+ self.model = AutoModelForCausalLM.from_pretrained(path, device_map="auto")
8
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
9
+
10
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
11
+ """
12
+ data args:
13
+ inputs (:obj: `str`)
14
+ date (:obj: `str`)
15
+ Return:
16
+ A :obj:`list` | `dict`: will be serialized and returned
17
+ """
18
+ # get inputs
19
+ inputs = data.pop("inputs", data)
20
+ tone = data.pop("tone")
21
+ length = data.pop("length")
22
+
23
+ prompt = self.apply_chat_template_for_presentation(self.tokenizer, inputs, tone, length)
24
+ input_ids = self.tokenizer(prompt, return_tensors="pt")
25
+
26
+ outputs = self.model.generate(
27
+ **input_ids,
28
+ max_new_tokens=8192,
29
+ temperature=0.7,
30
+ top_p=0.95,
31
+ do_sample=True,
32
+ repetition_penalty=1.15,
33
+ )
34
+
35
+ prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
36
+
37
+ return [{"generated_text": prediction}]
38
+
39
+ def apply_chat_template_for_presentation(tokenizer, content, tone="professional", length="medium"):
40
+ """Format input using the model's chat template"""
41
+
42
+ # Create messages following Llama 3's chat format
43
+ messages = [
44
+ {"role": "system", "content": f"Summarize the content into presentation slides in XML syntax with following parameters:\n Tone: {tone}\n Length: {length}\n Strictly use only the tags: <presentation>, <slide>, <h1>, <h2>, <p>, <ul>, <ol>, <li> only\n Strictly use only the available formatting: bold=True/False, italic=True/False, underline=True/False, color='red'/'green'/'yellow'/'blue', alight='left'/'center'/'right', fontSize=integer"},
45
+ {"role": "user", "content": content}
46
+ ]
47
+
48
+ # Apply the chat template
49
+ prompt = tokenizer.apply_chat_template(
50
+ messages,
51
+ tokenize=False,
52
+ add_generation_prompt=True # Adds the assistant prefix for generation
53
+ )
54
+
55
+ return prompt