Views
No views yet
<|sys|>...system category...</|sys|> for system classification<|top|>...topic summary...</|top|> for topic summarizationOutputParser class to extract the system category and topic summary.1# Example prediction
2title = "Windows Stuck"
3description = "I cannot start my computer because Windows keeps getting stuck on a blue screen."
4
5prediction = predict_ticket_summary(model, title, description)
6system, topic = OutputParser.parse_prediction(prediction)
7
8print(f"System: {system}")
9print(f"Topic: {topic}")pip install torch transformers sentencepiecetorch - Used for the PyTorch model and tensor operationstransformers - For the T5 model and tokenizer classessentencepiece - Required by the T5 tokenizer for text tokenizationThe requirements are based on:torch - Used for the PyTorch model and tensor operationstransformers - For the T5 model and tokenizer classessentencepiece - Required by the T51from transformers import T5ForConditionalGeneration, T5Tokenizer
2import torch
3import re
4
5
6model_path = "KameronB/sitcc-t5-large-v4"
7
8# Load the model
9model = T5ForConditionalGeneration.from_pretrained(model_path, use_safetensors=True)
10
11# Load the tokenizer (if applicable)
12tokenizer = T5Tokenizer.from_pretrained(model_path)
13
14model.half()
15
16def create_model_input(short_description:str, description:str, max_chars = 1024) -> str:
17 # Convert the newlines to sentences
18 lines = description.split("\n")
19
20 for line in lines:
21 if line[-1] in [".", "!", "?"]:
22 line += " "
23 else:
24 line += ". "
25 description = "".join(lines)
26
27 # constrain the description to the specified length
28 total_chars = 0
29 sentences = []
30 for s in sent_tokenize(description):
31 total_chars += len(s)
32 if total_chars < max_chars:
33 sentences.append(s)
34 else:
35 break
36
37 description = " ".join(sentences)
38
39 return "<|title|>" + short_description + "</|title|><|desc|>" + description + "</|desc|>"
40
41def predict_ticket_summary(model:T5ForConditionalGeneration, title, description, max_length=128):
42 """
43 Generate system and topic predictions for a ticket using quantized model
44 """
45 # Format input text as used during training
46 input_text = create_model_input(title, description, max_length)
47
48 # Clear any previous tokenizer state and create fresh inputs
49 tokenizer.pad_token = tokenizer.eos_token # Ensure pad token is set
50
51 # Tokenize input with explicit parameters to avoid caching issues
52 inputs = tokenizer(
53 input_text,
54 return_tensors="pt",
55 max_length=512,
56 truncation=True,
57 padding=True,
58 add_special_tokens=False # Explicitly add special tokens
59 )
60
61 with torch.no_grad():
62 outputs = model.generate(
63 **inputs,
64 max_length=max_length,
65 do_sample=False,
66 )
67
68 # Decode prediction
69 prediction = tokenizer.decode(outputs[0], skip_special_tokens=False)
70
71 return prediction1class OutputParser:
2 SYS_TOKEN = "<|sys|>"
3 SYS_END_TOKEN = "</|sys|>"
4 TOP_TOKEN = "<|top|>"
5 TOP_END_TOKEN = "</|top|>"
6
7 LINE_RE = re.compile(r"(</\|(?:sys|top)\|>|<\|(?:sys|top)\|>|(?:<(?!/?\|(?:sys|top)\|>)|[^<])+)")
8
9 @classmethod
10 def parse_prediction(cls, prediction: str) -> tuple[str, str]:
11 # remove other special tokens
12 prediction = prediction.replace("<pad>", "").replace("</s>", "").strip()
13 mode = None
14 sys_content, top_content = [], []
15
16 for m in cls.LINE_RE.finditer(prediction):
17 token = m.group(0).strip()
18
19 if mode == None:
20 if token == cls.SYS_TOKEN or token == cls.SYS_END_TOKEN:
21 mode = cls.SYS_TOKEN
22 continue
23 elif token == cls.TOP_TOKEN or token == cls.TOP_END_TOKEN:
24 mode = cls.TOP_TOKEN
25 continue
26 else:
27 mode = cls.SYS_TOKEN
28 sys_content.append(token)
29 continue
30
31 elif mode == cls.SYS_TOKEN:
32 if token == cls.SYS_END_TOKEN or token == cls.SYS_TOKEN:
33 mode = cls.SYS_END_TOKEN
34 continue
35
36 elif token == cls.TOP_TOKEN:
37 mode = cls.TOP_TOKEN
38 continue
39 else:
40 sys_content.append(token)
41
42 elif mode == cls.SYS_END_TOKEN:
43 if token == cls.TOP_TOKEN or token == cls.TOP_END_TOKEN:
44 mode = cls.TOP_TOKEN
45 continue
46 else:
47 continue
48
49 elif mode == cls.TOP_TOKEN:
50 if token == cls.TOP_TOKEN:
51 continue
52 elif token == cls.TOP_END_TOKEN:
53 break
54 else:
55 top_content.append(token)
56
57 return " ".join(sys_content).strip(), " ".join(top_content).strip()OutputParser.parse_prediction(predict_ticket_summary(model, "Windows Stuck", "I cannot start my computer because Windows keeps getting stuck on a blue screen."))