Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

style_extract.py 8.6 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
  1. from html.parser import HTMLParser
  2. from html import unescape
  3. from collections import namedtuple, deque
  4. import re
  5. import json
  6. Clause = namedtuple('Clause', ('title', 'body'))
  7. taggedData = namedtuple('taggedData', ('data', 'tag', 'index'))
  8. predefined_tokens = {'number': "{num}", 'enum': "{enum}", 'pad': "{pad}", 'unknown': "{unk}"}
  9. not_alpha_pattern = re.compile(r'[^A-Za-z\s#]+')
  10. not_alpha_pattern_punct = re.compile(r'[^A-Za-z\s#\,\.\!\?\(\)]+')
  11. numeric_pattern = re.compile('\d[\d\.,]+')
  12. enum_pattern = re.compile('^(?:\d+\.\s)|^(?:\(\d+\)\s)|^(?:[a-zA-Z]+\.\s)|^(?:\([a-zA-Z]+\)\s)')
  13. upper_pattern = re.compile(r"[A-Z]+[\s\.,:';\(\)A-Z]+[\n\s]]")
  14. def tokenizer(txt, lower=True, enum=False, numeric=True, split=True):
  15. # preprocessing
  16. if lower:
  17. txt = txt.lower()
  18. if enum:
  19. txt = enum_pattern.sub(predefined_tokens["enum"], txt)
  20. if numeric:
  21. txt = numeric_pattern.sub(predefined_tokens["number"], txt)
  22. # splitting
  23. if not split:
  24. return txt
  25. for c in '()[]./,;:"':
  26. txt = txt.replace(c, " "+c+" ")
  27. return [w for w in txt.split() if any(w)]
  28. def to_float(s):
  29. """Forces a conversion to float"""
  30. try:
  31. return float("".join([c for c in s if s.isdigit() or c == '.']))
  32. except:
  33. return 0.0
  34. class MLStripper(HTMLParser):
  35. def __init__(self):
  36. super().__init__()
  37. self.reset()
  38. self.strict = False
  39. self.convert_charrefs = True
  40. self.fed = []
  41. def handle_data(self, d):
  42. self.fed.append(d)
  43. def get_data(self):
  44. return ''.join(self.fed)
  45. class StyleExtrater(HTMLParser):
  46. def __init__(self):
  47. super().__init__()
  48. self.reset()
  49. self.strict = False
  50. self.convert_charrefs = True
  51. self.stack = deque()
  52. self.indices = deque()
  53. self.indices.append(0)
  54. self.tagged = []
  55. def starttag_of_interest(self, tag, styles):
  56. tag = tag.lower()
  57. if tag in ['t']:
  58. return 't'
  59. if tag in ['b', 'strong']:
  60. return 'b'
  61. if tag in ['i', 'em']:
  62. return 'i'
  63. if tag in ['u']:
  64. return 'u'
  65. if tag in ['h1', 'h2']: # ,'h3','h4','h5','h6']:
  66. return 'h'
  67. if 'font-size' in styles:
  68. font_size = 10.0
  69. if styles['font-size'].find('%') > -1:
  70. font_size *= to_float(styles['font-size'])
  71. elif styles['font-size'].replace('pt', 'px').find('px') > -1:
  72. font_size = to_float(styles['font-size'])
  73. if styles['font-size'].find("pt") >= 0:
  74. font_size /= 0.75 # pt to px conversion
  75. if font_size >= 200:
  76. return ('h', tag)
  77. if styles.get('text-decoration') == 'underline':
  78. return ('u', tag)
  79. if styles.get('font-style') == 'italic':
  80. return ('i', tag)
  81. if styles.get('font-weight') == 'bold' or (
  82. type(styles.get('font-weight', 0)) == int and (styles.get('font-weight', 0) >= 500)):
  83. return ('b', tag)
  84. return None
  85. def endtag_of_interest(self, tag):
  86. if not any(self.stack):
  87. return False
  88. tag = tag.lower()
  89. if type(self.stack[-1]) == tuple: # complex tag
  90. if tag == self.stack[-1][1]:
  91. return True
  92. else:
  93. if tag == 't' and self.stack[-1] == 't':
  94. return True
  95. if tag in ['b', 'strong'] and self.stack[-1] == 'b':
  96. return True
  97. if tag in ['i', 'em'] and self.stack[-1] == 'i':
  98. return True
  99. if tag in ['u'] and self.stack[-1] == 'u':
  100. return True
  101. if self.stack[-1] == 'h' and tag in ['h1', 'h2']: # ,'h3','h4','h5','h6']:
  102. return True
  103. return False
  104. def parse_style_tag(self, style_tag):
  105. """Returns an array of tuples defining the style"""
  106. return [tuple(map(lambda s: s.strip(), styl.split(':', 1))) for styl in style_tag.split(';')]
  107. def parse_class_tag(self, class_tag):
  108. """Should get a class tag and return the derived styles"""
  109. classes = class_tag.split()
  110. # Not implemented
  111. return []
  112. def handle_starttag(self, tag, attrs):
  113. attrs = dict([(k.lower(), v.lower()) for k, v in attrs if type(k) == type(v) == str])
  114. styles = []
  115. if 'style' in attrs:
  116. styles.extend(self.parse_style_tag(attrs['style']))
  117. if 'class' in attrs:
  118. styles.extend(self.parse_class_tag(attrs['class']))
  119. if 'align' in attrs:
  120. styles.append(("text-align", attrs["align"]))
  121. if tag.lower() in ['div', 'p', 'tr', 'li']:
  122. self.indices.append(0)
  123. elif tag.lower() in ['br', 'hr']:
  124. self.indices[-1] = 0
  125. styles = dict(filter(lambda t: len(t) == 2, styles))
  126. tag = self.starttag_of_interest(tag, styles)
  127. if tag is None:
  128. return
  129. self.stack.append(tag)
  130. def handle_endtag(self, tag):
  131. if self.endtag_of_interest(tag):
  132. self.stack.pop()
  133. elif tag.lower() in ['div', 'p', 'tr', 'li']:
  134. if len(self.indices) > 1:
  135. self.indices.pop()
  136. else:
  137. self.indices[-1] = 0
  138. def handle_data(self, d):
  139. if not any(self.stack):
  140. tag = 'n'
  141. elif type(self.stack[-1]) == tuple: # complex tag
  142. tag = self.stack[-1][0]
  143. else: # Simple tag
  144. tag = self.stack[-1]
  145. d = d.strip()
  146. if any(d):
  147. self.tagged.append(taggedData(d, tag, self.indices[-1]))
  148. self.indices[-1] += 1
  149. def get_data(self):
  150. return self.tagged
  151. def get_lines(self):
  152. arr = []
  153. for t in self.tagged:
  154. if t.index == 0:
  155. if any(arr):
  156. arr[0] = taggedData(enum_pattern.sub(predefined_tokens["enum"] + ' ', arr[0].data + ' '),
  157. arr[0].tag, 0)
  158. yield arr
  159. arr = []
  160. arr.append(t)
  161. if any(arr):
  162. arr[0] = taggedData(enum_pattern.sub(predefined_tokens["enum"] + ' ', arr[0].data + ' '),
  163. arr[0].tag, 0)
  164. yield arr
  165. def uppercase2Ttag(txt):
  166. return upper_pattern.sub(
  167. lambda x: "<t>" + x.group(0).title() + "</t>" if len(x.group(0).strip().split()) > 1 else x.group(0), txt)
  168. def strip_tags(fname):
  169. with open(fname, 'r') as f:
  170. html = f.read()
  171. s = MLStripper()
  172. s.feed(html)
  173. return s.get_data()
  174. def parse_lines(fname, tokenize=True):
  175. styler = StyleExtrater()
  176. if fname.find("<") >= 0:
  177. html = fname
  178. else:
  179. char_dict = {
  180. ord('*'): None,
  181. ord('\\'): None,
  182. ord('['): None,
  183. ord(']'): None,
  184. ord('`'): ord("'"),
  185. ord('’'): ord("'"),
  186. 8220: ord('"'),
  187. 8221: ord('"'),
  188. 160: ord(' '),
  189. }
  190. with open(fname, 'rb') as f:
  191. html = f.read().decode('utf8', errors='ignore')
  192. html = uppercase2Ttag(unescape(html).translate(char_dict))
  193. styler.feed(html)
  194. if not tokenize:
  195. return list(styler.get_lines())
  196. ret = []
  197. for line in styler.get_lines():
  198. new_line = []
  199. i = 0
  200. for td in line:
  201. for token in tokenizer(td.data):
  202. new_line.append(taggedData(token, td.tag, i))
  203. i += 1
  204. ret.append(new_line)
  205. return ret
  206. def main(params):
  207. if params.out_json:
  208. with open(params.out_json, "w") as f:
  209. json.dump(parse_lines(params.in_html), f)
  210. elif params.out_text:
  211. with open(params.out_text, 'w') as f:
  212. for line in parse_lines(params.in_html):
  213. for td in line:
  214. f.write(td.data + " ")
  215. f.write('\n')
  216. if params.out_labels:
  217. with open(params.out_labels, 'w') as f:
  218. for line in parse_lines(params.in_html):
  219. for td in line:
  220. f.write(td.tag + " ")
  221. f.write('\n')
  222. else:
  223. sys.stderr.write("either `out_text` or `out_json` parameter is required\n")
  224. if __name__ == "__main__":
  225. import sys
  226. from argparse import ArgumentParser
  227. argparse = ArgumentParser()
  228. argparse.add_argument('--in_html', default="", type=str, help='window size')
  229. argparse.add_argument('--out_json', default="", type=str, help='vector size')
  230. argparse.add_argument('--out_text', default="", type=str, help='number of processes')
  231. argparse.add_argument('--out_labels', default="", type=str, help='number of processes')
  232. sys.exit(main(argparse.parse_args()))
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...