MCS12 commited on
Commit
9017320
·
verified ·
1 Parent(s): efaa530

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +77 -4
handler.py CHANGED
@@ -1,5 +1,7 @@
1
  from typing import Dict, List, Any
2
  import torch
 
 
3
  from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training, PeftConfig, PeftModel
4
  from transformers import (
5
  AutoModelForCausalLM,
@@ -11,6 +13,7 @@ from transformers import (
11
 
12
  class EndpointHandler:
13
  def __init__(self, path=""):
 
14
 
15
  peft_config = PeftConfig.from_pretrained(path)
16
 
@@ -70,12 +73,29 @@ class EndpointHandler:
70
  do_sample=True,
71
  repetition_penalty=1.15,
72
  )
73
-
 
74
  prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
75
- start_indices = positions = [i for i in range(len(prediction)) if prediction.startswith("<presentation>", i)]
 
 
 
 
 
 
76
  start_index = start_indices[-1]
77
  end_index = prediction.find("</presentation>") + 15
78
  prediction = prediction[start_index:end_index]
 
 
 
 
 
 
 
 
 
 
79
 
80
  return [{"generated_text": prediction}]
81
 
@@ -84,7 +104,7 @@ class EndpointHandler:
84
 
85
  # Create messages following Llama 3's chat format
86
  messages = [
87
- {"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"},
88
  {"role": "user", "content": content}
89
  ]
90
 
@@ -95,4 +115,57 @@ class EndpointHandler:
95
  add_generation_prompt=True # Adds the assistant prefix for generation
96
  )
97
 
98
- return prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from typing import Dict, List, Any
2
  import torch
3
+ import re
4
+ from typing import List, Tuple, Dict
5
  from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training, PeftConfig, PeftModel
6
  from transformers import (
7
  AutoModelForCausalLM,
 
13
 
14
  class EndpointHandler:
15
  def __init__(self, path=""):
16
+ pass
17
 
18
  peft_config = PeftConfig.from_pretrained(path)
19
 
 
73
  do_sample=True,
74
  repetition_penalty=1.15,
75
  )
76
+ available_tags = ["presentation", "slide", "ul", "ol", "li", "h1", "h2", "h3", "p"]
77
+ available_stylings = ["bold", "italic", "underline", "color", "align", "fontSize"]
78
  prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
79
+
80
+ start_indices = []
81
+ tag_start_indices = []
82
+ for i in range(len(prediction)):
83
+ if (prediction.startswith("<presentation>", i)):
84
+ start_indices.append(i)
85
+
86
  start_index = start_indices[-1]
87
  end_index = prediction.find("</presentation>") + 15
88
  prediction = prediction[start_index:end_index]
89
+
90
+ # correct any syntax error
91
+ brackets_indices = find_matching_brackets(prediction)
92
+ offset = 0
93
+ for start_end in brackets_indices:
94
+ close_index = start_end[1] - offset
95
+ char_before = prediction[close_index - 1]
96
+ if (not (ord(char_before) <= 122 and ord(char_before) >= 97) and not(ord(char_before) == 34 or ord(char_before) == 39 or ord(char_before) == 32)):
97
+ prediction = prediction[:close_index - 1] + prediction[close_index:]
98
+ offset += 1
99
 
100
  return [{"generated_text": prediction}]
101
 
 
104
 
105
  # Create messages following Llama 3's chat format
106
  messages = [
107
+ {"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"},
108
  {"role": "user", "content": content}
109
  ]
110
 
 
115
  add_generation_prompt=True # Adds the assistant prefix for generation
116
  )
117
 
118
+ return prompt
119
+
120
+ def find_matching_brackets(text: str) -> List[Tuple[int, int]]:
121
+ """
122
+ Find all matching '<' and '>' pairs (including nested).
123
+ Returns list of tuples (open_index, close_index).
124
+ """
125
+ stack = []
126
+ matches = []
127
+
128
+ for i, char in enumerate(text):
129
+ if char == '<' and (start_with_valid_tag(text, i + 1)):
130
+ stack.append(i)
131
+ elif char == '>' and stack:
132
+ open_index = stack.pop()
133
+ matches.append((open_index, i))
134
+
135
+ return matches
136
+
137
+ def start_with_valid_tag(text, index):
138
+ available_tags = ["presentation", "slide", "ul", "ol", "li", "h1", "h2", "h3", "p"]
139
+ for tag in available_tags:
140
+ if text.startswith(tag, index):
141
+ return True
142
+
143
+ return False
144
+
145
+ # if __name__ == "__main__":
146
+ # sample_xml = """<presentation]>
147
+ # <slide id="1" class="intro">
148
+ # <h1>Main Title</h1>
149
+ # <p style="color:blue">Some text</p>
150
+ # <img src="test.jpg"/>
151
+ # <ul>
152
+ # <li>Item 1</li>
153
+ # <li>Item 2</li>
154
+ # </ul>
155
+ # </slide>
156
+ # <slide id="2"[>
157
+ # <h2>Second Slide</h2>
158
+ # </slide>
159
+ # </presentation>"""
160
+
161
+ # # # correct any syntax error
162
+ # brackets_indices = find_matching_brackets(sample_xml)
163
+ # offset = 0
164
+ # for start_end in brackets_indices:
165
+ # close_index = start_end[1] - offset
166
+ # char_before = sample_xml[close_index - 1]
167
+ # if (not (ord(char_before) <= 122 and ord(char_before) >= 97) and not(ord(char_before) == 34 or ord(char_before) == 39 or ord(char_before) == 32)):
168
+ # sample_xml = sample_xml[:close_index - 1] + sample_xml[close_index:]
169
+ # offset += 1
170
+
171
+ # print(sample_xml)