applied-ai-018 commited on
Commit
fab61cf
·
verified ·
1 Parent(s): 4ba564c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. env-llmeval/lib/python3.10/site-packages/lxml/__init__.py +22 -0
  3. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/lxml/dtd.pxi +478 -0
  11. env-llmeval/lib/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu.so +3 -0
  12. env-llmeval/lib/python3.10/site-packages/lxml/etree.h +248 -0
  13. env-llmeval/lib/python3.10/site-packages/lxml/html/ElementSoup.py +10 -0
  14. env-llmeval/lib/python3.10/site-packages/lxml/html/__init__.py +1923 -0
  15. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/ElementSoup.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/__init__.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/_html5builder.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/clean.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/defs.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/formfill.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/html5parser.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/usedoctest.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/lxml/html/_diffcommand.py +86 -0
  29. env-llmeval/lib/python3.10/site-packages/lxml/html/_html5builder.py +100 -0
  30. env-llmeval/lib/python3.10/site-packages/lxml/html/_setmixin.py +56 -0
  31. env-llmeval/lib/python3.10/site-packages/lxml/html/builder.py +133 -0
  32. env-llmeval/lib/python3.10/site-packages/lxml/html/clean.py +21 -0
  33. env-llmeval/lib/python3.10/site-packages/lxml/html/defs.py +135 -0
  34. env-llmeval/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so +0 -0
  35. env-llmeval/lib/python3.10/site-packages/lxml/html/diff.py +878 -0
  36. env-llmeval/lib/python3.10/site-packages/lxml/html/formfill.py +299 -0
  37. env-llmeval/lib/python3.10/site-packages/lxml/html/html5parser.py +260 -0
  38. env-llmeval/lib/python3.10/site-packages/lxml/html/soupparser.py +314 -0
  39. env-llmeval/lib/python3.10/site-packages/lxml/html/usedoctest.py +13 -0
  40. env-llmeval/lib/python3.10/site-packages/lxml/includes/__init__.py +0 -0
  41. env-llmeval/lib/python3.10/site-packages/lxml/includes/config.pxd +3 -0
  42. env-llmeval/lib/python3.10/site-packages/lxml/includes/etreepublic.pxd +237 -0
  43. env-llmeval/lib/python3.10/site-packages/lxml/includes/htmlparser.pxd +56 -0
  44. env-llmeval/lib/python3.10/site-packages/lxml/includes/libexslt/__init__.py +0 -0
  45. env-llmeval/lib/python3.10/site-packages/lxml/includes/libexslt/exslt.h +108 -0
  46. env-llmeval/lib/python3.10/site-packages/lxml/includes/libexslt/exsltconfig.h +70 -0
  47. env-llmeval/lib/python3.10/site-packages/lxml/includes/schematron.pxd +34 -0
  48. env-llmeval/lib/python3.10/site-packages/lxml/includes/xinclude.pxd +22 -0
  49. env-llmeval/lib/python3.10/site-packages/lxml/includes/xmlerror.pxd +852 -0
  50. env-llmeval/lib/python3.10/site-packages/lxml/includes/xmlparser.pxd +265 -0
.gitattributes CHANGED
@@ -123,3 +123,6 @@ llmeval-env/lib/python3.10/site-packages/torch/bin/protoc filter=lfs diff=lfs me
123
  env-llmeval/lib/python3.10/site-packages/numpy/core/_simd.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
124
  env-llmeval/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
125
  env-llmeval/lib/python3.10/site-packages/triton/third_party/cuda/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
123
  env-llmeval/lib/python3.10/site-packages/numpy/core/_simd.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
124
  env-llmeval/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
125
  env-llmeval/lib/python3.10/site-packages/triton/third_party/cuda/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
126
+ env-llmeval/lib/python3.10/site-packages/lxml/objectify.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
127
+ env-llmeval/lib/python3.10/site-packages/triton/third_party/cuda/bin/ptxas filter=lfs diff=lfs merge=lfs -text
128
+ env-llmeval/lib/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
env-llmeval/lib/python3.10/site-packages/lxml/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # this is a package
2
+
3
+ __version__ = "5.2.1"
4
+
5
+
6
+ def get_include():
7
+ """
8
+ Returns a list of header include paths (for lxml itself, libxml2
9
+ and libxslt) needed to compile C code against lxml if it was built
10
+ with statically linked libraries.
11
+ """
12
+ import os
13
+ lxml_path = __path__[0]
14
+ include_path = os.path.join(lxml_path, 'includes')
15
+ includes = [include_path, lxml_path]
16
+
17
+ for name in os.listdir(include_path):
18
+ path = os.path.join(include_path, name)
19
+ if os.path.isdir(path):
20
+ includes.append(path)
21
+
22
+ return includes
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (694 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc ADDED
Binary file (5.88 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc ADDED
Binary file (3.58 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc ADDED
Binary file (8.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc ADDED
Binary file (423 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/dtd.pxi ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # support for DTD validation
2
+ from lxml.includes cimport dtdvalid
3
+
4
+ cdef class DTDError(LxmlError):
5
+ """Base class for DTD errors.
6
+ """
7
+
8
+ cdef class DTDParseError(DTDError):
9
+ """Error while parsing a DTD.
10
+ """
11
+
12
+ cdef class DTDValidateError(DTDError):
13
+ """Error while validating an XML document with a DTD.
14
+ """
15
+
16
+
17
+ cdef inline int _assertValidDTDNode(node, void *c_node) except -1:
18
+ assert c_node is not NULL, "invalid DTD proxy at %s" % id(node)
19
+
20
+
21
+ @cython.final
22
+ @cython.internal
23
+ @cython.freelist(8)
24
+ cdef class _DTDElementContentDecl:
25
+ cdef DTD _dtd
26
+ cdef tree.xmlElementContent* _c_node
27
+
28
+ def __repr__(self):
29
+ return "<%s.%s object name=%r type=%r occur=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.type, self.occur, id(self))
30
+
31
+ @property
32
+ def name(self):
33
+ _assertValidDTDNode(self, self._c_node)
34
+ return funicodeOrNone(self._c_node.name)
35
+
36
+ @property
37
+ def type(self):
38
+ _assertValidDTDNode(self, self._c_node)
39
+ cdef int type = self._c_node.type
40
+ if type == tree.XML_ELEMENT_CONTENT_PCDATA:
41
+ return "pcdata"
42
+ elif type == tree.XML_ELEMENT_CONTENT_ELEMENT:
43
+ return "element"
44
+ elif type == tree.XML_ELEMENT_CONTENT_SEQ:
45
+ return "seq"
46
+ elif type == tree.XML_ELEMENT_CONTENT_OR:
47
+ return "or"
48
+ else:
49
+ return None
50
+
51
+ @property
52
+ def occur(self):
53
+ _assertValidDTDNode(self, self._c_node)
54
+ cdef int occur = self._c_node.ocur
55
+ if occur == tree.XML_ELEMENT_CONTENT_ONCE:
56
+ return "once"
57
+ elif occur == tree.XML_ELEMENT_CONTENT_OPT:
58
+ return "opt"
59
+ elif occur == tree.XML_ELEMENT_CONTENT_MULT:
60
+ return "mult"
61
+ elif occur == tree.XML_ELEMENT_CONTENT_PLUS:
62
+ return "plus"
63
+ else:
64
+ return None
65
+
66
+ @property
67
+ def left(self):
68
+ _assertValidDTDNode(self, self._c_node)
69
+ c1 = self._c_node.c1
70
+ if c1:
71
+ node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
72
+ node._dtd = self._dtd
73
+ node._c_node = <tree.xmlElementContent*>c1
74
+ return node
75
+ else:
76
+ return None
77
+
78
+ @property
79
+ def right(self):
80
+ _assertValidDTDNode(self, self._c_node)
81
+ c2 = self._c_node.c2
82
+ if c2:
83
+ node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
84
+ node._dtd = self._dtd
85
+ node._c_node = <tree.xmlElementContent*>c2
86
+ return node
87
+ else:
88
+ return None
89
+
90
+
91
+ @cython.final
92
+ @cython.internal
93
+ @cython.freelist(8)
94
+ cdef class _DTDAttributeDecl:
95
+ cdef DTD _dtd
96
+ cdef tree.xmlAttribute* _c_node
97
+
98
+ def __repr__(self):
99
+ return "<%s.%s object name=%r elemname=%r prefix=%r type=%r default=%r default_value=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.elemname, self.prefix, self.type, self.default, self.default_value, id(self))
100
+
101
+ @property
102
+ def name(self):
103
+ _assertValidDTDNode(self, self._c_node)
104
+ return funicodeOrNone(self._c_node.name)
105
+
106
+ @property
107
+ def elemname(self):
108
+ _assertValidDTDNode(self, self._c_node)
109
+ return funicodeOrNone(self._c_node.elem)
110
+
111
+ @property
112
+ def prefix(self):
113
+ _assertValidDTDNode(self, self._c_node)
114
+ return funicodeOrNone(self._c_node.prefix)
115
+
116
+ @property
117
+ def type(self):
118
+ _assertValidDTDNode(self, self._c_node)
119
+ cdef int type = self._c_node.atype
120
+ if type == tree.XML_ATTRIBUTE_CDATA:
121
+ return "cdata"
122
+ elif type == tree.XML_ATTRIBUTE_ID:
123
+ return "id"
124
+ elif type == tree.XML_ATTRIBUTE_IDREF:
125
+ return "idref"
126
+ elif type == tree.XML_ATTRIBUTE_IDREFS:
127
+ return "idrefs"
128
+ elif type == tree.XML_ATTRIBUTE_ENTITY:
129
+ return "entity"
130
+ elif type == tree.XML_ATTRIBUTE_ENTITIES:
131
+ return "entities"
132
+ elif type == tree.XML_ATTRIBUTE_NMTOKEN:
133
+ return "nmtoken"
134
+ elif type == tree.XML_ATTRIBUTE_NMTOKENS:
135
+ return "nmtokens"
136
+ elif type == tree.XML_ATTRIBUTE_ENUMERATION:
137
+ return "enumeration"
138
+ elif type == tree.XML_ATTRIBUTE_NOTATION:
139
+ return "notation"
140
+ else:
141
+ return None
142
+
143
+ @property
144
+ def default(self):
145
+ _assertValidDTDNode(self, self._c_node)
146
+ cdef int default = self._c_node.def_
147
+ if default == tree.XML_ATTRIBUTE_NONE:
148
+ return "none"
149
+ elif default == tree.XML_ATTRIBUTE_REQUIRED:
150
+ return "required"
151
+ elif default == tree.XML_ATTRIBUTE_IMPLIED:
152
+ return "implied"
153
+ elif default == tree.XML_ATTRIBUTE_FIXED:
154
+ return "fixed"
155
+ else:
156
+ return None
157
+
158
+ @property
159
+ def default_value(self):
160
+ _assertValidDTDNode(self, self._c_node)
161
+ return funicodeOrNone(self._c_node.defaultValue)
162
+
163
+ def itervalues(self):
164
+ _assertValidDTDNode(self, self._c_node)
165
+ cdef tree.xmlEnumeration *c_node = self._c_node.tree
166
+ while c_node is not NULL:
167
+ yield funicode(c_node.name)
168
+ c_node = c_node.next
169
+
170
+ def values(self):
171
+ return list(self.itervalues())
172
+
173
+
174
+ @cython.final
175
+ @cython.internal
176
+ @cython.freelist(8)
177
+ cdef class _DTDElementDecl:
178
+ cdef DTD _dtd
179
+ cdef tree.xmlElement* _c_node
180
+
181
+ def __repr__(self):
182
+ return "<%s.%s object name=%r prefix=%r type=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.prefix, self.type, id(self))
183
+
184
+ @property
185
+ def name(self):
186
+ _assertValidDTDNode(self, self._c_node)
187
+ return funicodeOrNone(self._c_node.name)
188
+
189
+ @property
190
+ def prefix(self):
191
+ _assertValidDTDNode(self, self._c_node)
192
+ return funicodeOrNone(self._c_node.prefix)
193
+
194
+ @property
195
+ def type(self):
196
+ _assertValidDTDNode(self, self._c_node)
197
+ cdef int type = self._c_node.etype
198
+ if type == tree.XML_ELEMENT_TYPE_UNDEFINED:
199
+ return "undefined"
200
+ elif type == tree.XML_ELEMENT_TYPE_EMPTY:
201
+ return "empty"
202
+ elif type == tree.XML_ELEMENT_TYPE_ANY:
203
+ return "any"
204
+ elif type == tree.XML_ELEMENT_TYPE_MIXED:
205
+ return "mixed"
206
+ elif type == tree.XML_ELEMENT_TYPE_ELEMENT:
207
+ return "element"
208
+ else:
209
+ return None
210
+
211
+ @property
212
+ def content(self):
213
+ _assertValidDTDNode(self, self._c_node)
214
+ cdef tree.xmlElementContent *content = self._c_node.content
215
+ if content:
216
+ node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
217
+ node._dtd = self._dtd
218
+ node._c_node = content
219
+ return node
220
+ else:
221
+ return None
222
+
223
+ def iterattributes(self):
224
+ _assertValidDTDNode(self, self._c_node)
225
+ cdef tree.xmlAttribute *c_node = self._c_node.attributes
226
+ while c_node:
227
+ node = <_DTDAttributeDecl>_DTDAttributeDecl.__new__(_DTDAttributeDecl)
228
+ node._dtd = self._dtd
229
+ node._c_node = c_node
230
+ yield node
231
+ c_node = c_node.nexth
232
+
233
+ def attributes(self):
234
+ return list(self.iterattributes())
235
+
236
+
237
+ @cython.final
238
+ @cython.internal
239
+ @cython.freelist(8)
240
+ cdef class _DTDEntityDecl:
241
+ cdef DTD _dtd
242
+ cdef tree.xmlEntity* _c_node
243
+ def __repr__(self):
244
+ return "<%s.%s object name=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
245
+
246
+ @property
247
+ def name(self):
248
+ _assertValidDTDNode(self, self._c_node)
249
+ return funicodeOrNone(self._c_node.name)
250
+
251
+ @property
252
+ def orig(self):
253
+ _assertValidDTDNode(self, self._c_node)
254
+ return funicodeOrNone(self._c_node.orig)
255
+
256
+ @property
257
+ def content(self):
258
+ _assertValidDTDNode(self, self._c_node)
259
+ return funicodeOrNone(self._c_node.content)
260
+
261
+ @property
262
+ def system_url(self):
263
+ _assertValidDTDNode(self, self._c_node)
264
+ return funicodeOrNone(self._c_node.SystemID)
265
+
266
+
267
+ ################################################################################
268
+ # DTD
269
+
270
+ cdef class DTD(_Validator):
271
+ """DTD(self, file=None, external_id=None)
272
+ A DTD validator.
273
+
274
+ Can load from filesystem directly given a filename or file-like object.
275
+ Alternatively, pass the keyword parameter ``external_id`` to load from a
276
+ catalog.
277
+ """
278
+ cdef tree.xmlDtd* _c_dtd
279
+ def __init__(self, file=None, *, external_id=None):
280
+ _Validator.__init__(self)
281
+ if file is not None:
282
+ file = _getFSPathOrObject(file)
283
+ if _isString(file):
284
+ file = _encodeFilename(file)
285
+ with self._error_log:
286
+ orig_loader = _register_document_loader()
287
+ self._c_dtd = xmlparser.xmlParseDTD(NULL, _xcstr(file))
288
+ _reset_document_loader(orig_loader)
289
+ elif hasattr(file, 'read'):
290
+ orig_loader = _register_document_loader()
291
+ self._c_dtd = _parseDtdFromFilelike(file)
292
+ _reset_document_loader(orig_loader)
293
+ else:
294
+ raise DTDParseError, "file must be a filename, file-like or path-like object"
295
+ elif external_id is not None:
296
+ with self._error_log:
297
+ orig_loader = _register_document_loader()
298
+ self._c_dtd = xmlparser.xmlParseDTD(<const_xmlChar*>external_id, NULL)
299
+ _reset_document_loader(orig_loader)
300
+ else:
301
+ raise DTDParseError, "either filename or external ID required"
302
+
303
+ if self._c_dtd is NULL:
304
+ raise DTDParseError(
305
+ self._error_log._buildExceptionMessage("error parsing DTD"),
306
+ self._error_log)
307
+
308
+ @property
309
+ def name(self):
310
+ if self._c_dtd is NULL:
311
+ return None
312
+ return funicodeOrNone(self._c_dtd.name)
313
+
314
+ @property
315
+ def external_id(self):
316
+ if self._c_dtd is NULL:
317
+ return None
318
+ return funicodeOrNone(self._c_dtd.ExternalID)
319
+
320
+ @property
321
+ def system_url(self):
322
+ if self._c_dtd is NULL:
323
+ return None
324
+ return funicodeOrNone(self._c_dtd.SystemID)
325
+
326
+ def iterelements(self):
327
+ cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL
328
+ while c_node is not NULL:
329
+ if c_node.type == tree.XML_ELEMENT_DECL:
330
+ node = _DTDElementDecl()
331
+ node._dtd = self
332
+ node._c_node = <tree.xmlElement*>c_node
333
+ yield node
334
+ c_node = c_node.next
335
+
336
+ def elements(self):
337
+ return list(self.iterelements())
338
+
339
+ def iterentities(self):
340
+ cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL
341
+ while c_node is not NULL:
342
+ if c_node.type == tree.XML_ENTITY_DECL:
343
+ node = _DTDEntityDecl()
344
+ node._dtd = self
345
+ node._c_node = <tree.xmlEntity*>c_node
346
+ yield node
347
+ c_node = c_node.next
348
+
349
+ def entities(self):
350
+ return list(self.iterentities())
351
+
352
+ def __dealloc__(self):
353
+ tree.xmlFreeDtd(self._c_dtd)
354
+
355
+ def __call__(self, etree):
356
+ """__call__(self, etree)
357
+
358
+ Validate doc using the DTD.
359
+
360
+ Returns true if the document is valid, false if not.
361
+ """
362
+ cdef _Document doc
363
+ cdef _Element root_node
364
+ cdef xmlDoc* c_doc
365
+ cdef dtdvalid.xmlValidCtxt* valid_ctxt
366
+ cdef int ret = -1
367
+
368
+ assert self._c_dtd is not NULL, "DTD not initialised"
369
+ doc = _documentOrRaise(etree)
370
+ root_node = _rootNodeOrRaise(etree)
371
+
372
+ valid_ctxt = dtdvalid.xmlNewValidCtxt()
373
+ if valid_ctxt is NULL:
374
+ raise DTDError("Failed to create validation context")
375
+
376
+ # work around error reporting bug in libxml2 <= 2.9.1 (and later?)
377
+ # https://bugzilla.gnome.org/show_bug.cgi?id=724903
378
+ valid_ctxt.error = <dtdvalid.xmlValidityErrorFunc>_nullGenericErrorFunc
379
+ valid_ctxt.userData = NULL
380
+
381
+ try:
382
+ with self._error_log:
383
+ c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
384
+ ret = dtdvalid.xmlValidateDtd(valid_ctxt, c_doc, self._c_dtd)
385
+ _destroyFakeDoc(doc._c_doc, c_doc)
386
+ finally:
387
+ dtdvalid.xmlFreeValidCtxt(valid_ctxt)
388
+
389
+ if ret == -1:
390
+ raise DTDValidateError("Internal error in DTD validation",
391
+ self._error_log)
392
+ return ret == 1
393
+
394
+
395
+ cdef tree.xmlDtd* _parseDtdFromFilelike(file) except NULL:
396
+ cdef _ExceptionContext exc_context
397
+ cdef _FileReaderContext dtd_parser
398
+ cdef _ErrorLog error_log
399
+ cdef tree.xmlDtd* c_dtd = NULL
400
+ exc_context = _ExceptionContext()
401
+ dtd_parser = _FileReaderContext(file, exc_context, None)
402
+ error_log = _ErrorLog()
403
+
404
+ with error_log:
405
+ c_dtd = dtd_parser._readDtd()
406
+
407
+ exc_context._raise_if_stored()
408
+ if c_dtd is NULL:
409
+ raise DTDParseError("error parsing DTD", error_log)
410
+ return c_dtd
411
+
412
+ cdef DTD _dtdFactory(tree.xmlDtd* c_dtd):
413
+ # do not run through DTD.__init__()!
414
+ cdef DTD dtd
415
+ if c_dtd is NULL:
416
+ return None
417
+ dtd = DTD.__new__(DTD)
418
+ dtd._c_dtd = _copyDtd(c_dtd)
419
+ _Validator.__init__(dtd)
420
+ return dtd
421
+
422
+
423
+ cdef tree.xmlDtd* _copyDtd(tree.xmlDtd* c_orig_dtd) except NULL:
424
+ """
425
+ Copy a DTD. libxml2 (currently) fails to set up the element->attributes
426
+ links when copying DTDs, so we have to rebuild them here.
427
+ """
428
+ c_dtd = tree.xmlCopyDtd(c_orig_dtd)
429
+ if not c_dtd:
430
+ raise MemoryError
431
+ cdef tree.xmlNode* c_node = c_dtd.children
432
+ while c_node:
433
+ if c_node.type == tree.XML_ATTRIBUTE_DECL:
434
+ _linkDtdAttribute(c_dtd, <tree.xmlAttribute*>c_node)
435
+ c_node = c_node.next
436
+ return c_dtd
437
+
438
+
439
+ cdef void _linkDtdAttribute(tree.xmlDtd* c_dtd, tree.xmlAttribute* c_attr) noexcept:
440
+ """
441
+ Create the link to the DTD attribute declaration from the corresponding
442
+ element declaration.
443
+ """
444
+ c_elem = dtdvalid.xmlGetDtdElementDesc(c_dtd, c_attr.elem)
445
+ if not c_elem:
446
+ # no such element? something is wrong with the DTD ...
447
+ return
448
+ c_pos = c_elem.attributes
449
+ if not c_pos:
450
+ c_elem.attributes = c_attr
451
+ c_attr.nexth = NULL
452
+ return
453
+ # libxml2 keeps namespace declarations first, and we need to make
454
+ # sure we don't re-insert attributes that are already there
455
+ if _isDtdNsDecl(c_attr):
456
+ if not _isDtdNsDecl(c_pos):
457
+ c_elem.attributes = c_attr
458
+ c_attr.nexth = c_pos
459
+ return
460
+ while c_pos != c_attr and c_pos.nexth and _isDtdNsDecl(c_pos.nexth):
461
+ c_pos = c_pos.nexth
462
+ else:
463
+ # append at end
464
+ while c_pos != c_attr and c_pos.nexth:
465
+ c_pos = c_pos.nexth
466
+ if c_pos == c_attr:
467
+ return
468
+ c_attr.nexth = c_pos.nexth
469
+ c_pos.nexth = c_attr
470
+
471
+
472
+ cdef bint _isDtdNsDecl(tree.xmlAttribute* c_attr) noexcept:
473
+ if cstring_h.strcmp(<const_char*>c_attr.name, "xmlns") == 0:
474
+ return True
475
+ if (c_attr.prefix is not NULL and
476
+ cstring_h.strcmp(<const_char*>c_attr.prefix, "xmlns") == 0):
477
+ return True
478
+ return False
env-llmeval/lib/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd9d3483be19a3c055f59bca0f17b5eca444ce6f141f27565d1f9ee031beffa8
3
+ size 5341640
env-llmeval/lib/python3.10/site-packages/lxml/etree.h ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Generated by Cython 3.0.10 */
2
+
3
+ #ifndef __PYX_HAVE__lxml__etree
4
+ #define __PYX_HAVE__lxml__etree
5
+
6
+ #include "Python.h"
7
+ struct LxmlDocument;
8
+ struct LxmlElement;
9
+ struct LxmlElementTree;
10
+ struct LxmlElementTagMatcher;
11
+ struct LxmlElementIterator;
12
+ struct LxmlElementBase;
13
+ struct LxmlElementClassLookup;
14
+ struct LxmlFallbackElementClassLookup;
15
+
16
+ /* "lxml/etree.pyx":333
17
+ *
18
+ * # type of a function that steps from node to node
19
+ * ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*) # <<<<<<<<<<<<<<
20
+ *
21
+ *
22
+ */
23
+ typedef xmlNode *(*_node_to_node_function)(xmlNode *);
24
+
25
+ /* "lxml/etree.pyx":349
26
+ * @cython.final
27
+ * @cython.freelist(8)
28
+ * cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]: # <<<<<<<<<<<<<<
29
+ * """Internal base class to reference a libxml document.
30
+ *
31
+ */
32
+ struct LxmlDocument {
33
+ PyObject_HEAD
34
+ struct __pyx_vtabstruct_4lxml_5etree__Document *__pyx_vtab;
35
+ int _ns_counter;
36
+ PyObject *_prefix_tail;
37
+ xmlDoc *_c_doc;
38
+ struct __pyx_obj_4lxml_5etree__BaseParser *_parser;
39
+ };
40
+
41
+ /* "lxml/etree.pyx":698
42
+ *
43
+ * @cython.no_gc_clear
44
+ * cdef public class _Element [ type LxmlElementType, object LxmlElement ]: # <<<<<<<<<<<<<<
45
+ * """Element class.
46
+ *
47
+ */
48
+ struct LxmlElement {
49
+ PyObject_HEAD
50
+ struct LxmlDocument *_doc;
51
+ xmlNode *_c_node;
52
+ PyObject *_tag;
53
+ };
54
+
55
+ /* "lxml/etree.pyx":1872
56
+ *
57
+ *
58
+ * cdef public class _ElementTree [ type LxmlElementTreeType, # <<<<<<<<<<<<<<
59
+ * object LxmlElementTree ]:
60
+ * cdef _Document _doc
61
+ */
62
+ struct LxmlElementTree {
63
+ PyObject_HEAD
64
+ struct __pyx_vtabstruct_4lxml_5etree__ElementTree *__pyx_vtab;
65
+ struct LxmlDocument *_doc;
66
+ struct LxmlElement *_context_node;
67
+ };
68
+
69
+ /* "lxml/etree.pyx":2646
70
+ *
71
+ *
72
+ * cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher, # <<<<<<<<<<<<<<
73
+ * type LxmlElementTagMatcherType ]:
74
+ * """
75
+ */
76
+ struct LxmlElementTagMatcher {
77
+ PyObject_HEAD
78
+ struct __pyx_vtabstruct_4lxml_5etree__ElementTagMatcher *__pyx_vtab;
79
+ PyObject *_pystrings;
80
+ int _node_type;
81
+ char *_href;
82
+ char *_name;
83
+ };
84
+
85
+ /* "lxml/etree.pyx":2677
86
+ * self._name = NULL
87
+ *
88
+ * cdef public class _ElementIterator(_ElementTagMatcher) [ # <<<<<<<<<<<<<<
89
+ * object LxmlElementIterator, type LxmlElementIteratorType ]:
90
+ * """
91
+ */
92
+ struct LxmlElementIterator {
93
+ struct LxmlElementTagMatcher __pyx_base;
94
+ struct LxmlElement *_node;
95
+ _node_to_node_function _next_element;
96
+ };
97
+
98
+ /* "src/lxml/classlookup.pxi":6
99
+ * # Custom Element classes
100
+ *
101
+ * cdef public class ElementBase(_Element) [ type LxmlElementBaseType, # <<<<<<<<<<<<<<
102
+ * object LxmlElementBase ]:
103
+ * """ElementBase(*children, attrib=None, nsmap=None, **_extra)
104
+ */
105
+ struct LxmlElementBase {
106
+ struct LxmlElement __pyx_base;
107
+ };
108
+
109
+ /* "src/lxml/classlookup.pxi":210
110
+ * # Element class lookup
111
+ *
112
+ * ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*) # <<<<<<<<<<<<<<
113
+ *
114
+ * # class to store element class lookup functions
115
+ */
116
+ typedef PyObject *(*_element_class_lookup_function)(PyObject *, struct LxmlDocument *, xmlNode *);
117
+
118
+ /* "src/lxml/classlookup.pxi":213
119
+ *
120
+ * # class to store element class lookup functions
121
+ * cdef public class ElementClassLookup [ type LxmlElementClassLookupType, # <<<<<<<<<<<<<<
122
+ * object LxmlElementClassLookup ]:
123
+ * """ElementClassLookup(self)
124
+ */
125
+ struct LxmlElementClassLookup {
126
+ PyObject_HEAD
127
+ _element_class_lookup_function _lookup_function;
128
+ };
129
+
130
+ /* "src/lxml/classlookup.pxi":221
131
+ *
132
+ *
133
+ * cdef public class FallbackElementClassLookup(ElementClassLookup) \ # <<<<<<<<<<<<<<
134
+ * [ type LxmlFallbackElementClassLookupType,
135
+ * object LxmlFallbackElementClassLookup ]:
136
+ */
137
+ struct LxmlFallbackElementClassLookup {
138
+ struct LxmlElementClassLookup __pyx_base;
139
+ struct __pyx_vtabstruct_4lxml_5etree_FallbackElementClassLookup *__pyx_vtab;
140
+ struct LxmlElementClassLookup *fallback;
141
+ _element_class_lookup_function _fallback_function;
142
+ };
143
+
144
+ #ifndef __PYX_HAVE_API__lxml__etree
145
+
146
+ #ifdef CYTHON_EXTERN_C
147
+ #undef __PYX_EXTERN_C
148
+ #define __PYX_EXTERN_C CYTHON_EXTERN_C
149
+ #elif defined(__PYX_EXTERN_C)
150
+ #ifdef _MSC_VER
151
+ #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.")
152
+ #else
153
+ #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.
154
+ #endif
155
+ #else
156
+ #ifdef __cplusplus
157
+ #define __PYX_EXTERN_C extern "C"
158
+ #else
159
+ #define __PYX_EXTERN_C extern
160
+ #endif
161
+ #endif
162
+
163
+ #ifndef DL_IMPORT
164
+ #define DL_IMPORT(_T) _T
165
+ #endif
166
+
167
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlDocumentType;
168
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementType;
169
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTreeType;
170
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTagMatcherType;
171
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementIteratorType;
172
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementBaseType;
173
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementClassLookupType;
174
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlFallbackElementClassLookupType;
175
+
176
+ __PYX_EXTERN_C struct LxmlElement *deepcopyNodeToDocument(struct LxmlDocument *, xmlNode *);
177
+ __PYX_EXTERN_C struct LxmlElementTree *elementTreeFactory(struct LxmlElement *);
178
+ __PYX_EXTERN_C struct LxmlElementTree *newElementTree(struct LxmlElement *, PyObject *);
179
+ __PYX_EXTERN_C struct LxmlElementTree *adoptExternalDocument(xmlDoc *, PyObject *, int);
180
+ __PYX_EXTERN_C struct LxmlElement *elementFactory(struct LxmlDocument *, xmlNode *);
181
+ __PYX_EXTERN_C struct LxmlElement *makeElement(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
182
+ __PYX_EXTERN_C struct LxmlElement *makeSubElement(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
183
+ __PYX_EXTERN_C void setElementClassLookupFunction(_element_class_lookup_function, PyObject *);
184
+ __PYX_EXTERN_C PyObject *lookupDefaultElementClass(PyObject *, PyObject *, xmlNode *);
185
+ __PYX_EXTERN_C PyObject *lookupNamespaceElementClass(PyObject *, PyObject *, xmlNode *);
186
+ __PYX_EXTERN_C PyObject *callLookupFallback(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *);
187
+ __PYX_EXTERN_C int tagMatches(xmlNode *, const xmlChar *, const xmlChar *);
188
+ __PYX_EXTERN_C struct LxmlDocument *documentOrRaise(PyObject *);
189
+ __PYX_EXTERN_C struct LxmlElement *rootNodeOrRaise(PyObject *);
190
+ __PYX_EXTERN_C int hasText(xmlNode *);
191
+ __PYX_EXTERN_C int hasTail(xmlNode *);
192
+ __PYX_EXTERN_C PyObject *textOf(xmlNode *);
193
+ __PYX_EXTERN_C PyObject *tailOf(xmlNode *);
194
+ __PYX_EXTERN_C int setNodeText(xmlNode *, PyObject *);
195
+ __PYX_EXTERN_C int setTailText(xmlNode *, PyObject *);
196
+ __PYX_EXTERN_C PyObject *attributeValue(xmlNode *, xmlAttr *);
197
+ __PYX_EXTERN_C PyObject *attributeValueFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
198
+ __PYX_EXTERN_C PyObject *getAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
199
+ __PYX_EXTERN_C PyObject *iterattributes(struct LxmlElement *, int);
200
+ __PYX_EXTERN_C PyObject *collectAttributes(xmlNode *, int);
201
+ __PYX_EXTERN_C int setAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
202
+ __PYX_EXTERN_C int delAttribute(struct LxmlElement *, PyObject *);
203
+ __PYX_EXTERN_C int delAttributeFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
204
+ __PYX_EXTERN_C int hasChild(xmlNode *);
205
+ __PYX_EXTERN_C xmlNode *findChild(xmlNode *, Py_ssize_t);
206
+ __PYX_EXTERN_C xmlNode *findChildForwards(xmlNode *, Py_ssize_t);
207
+ __PYX_EXTERN_C xmlNode *findChildBackwards(xmlNode *, Py_ssize_t);
208
+ __PYX_EXTERN_C xmlNode *nextElement(xmlNode *);
209
+ __PYX_EXTERN_C xmlNode *previousElement(xmlNode *);
210
+ __PYX_EXTERN_C void appendChild(struct LxmlElement *, struct LxmlElement *);
211
+ __PYX_EXTERN_C int appendChildToElement(struct LxmlElement *, struct LxmlElement *);
212
+ __PYX_EXTERN_C PyObject *pyunicode(const xmlChar *);
213
+ __PYX_EXTERN_C PyObject *utf8(PyObject *);
214
+ __PYX_EXTERN_C PyObject *getNsTag(PyObject *);
215
+ __PYX_EXTERN_C PyObject *getNsTagWithEmptyNs(PyObject *);
216
+ __PYX_EXTERN_C PyObject *namespacedName(xmlNode *);
217
+ __PYX_EXTERN_C PyObject *namespacedNameFromNsName(const xmlChar *, const xmlChar *);
218
+ __PYX_EXTERN_C void iteratorStoreNext(struct LxmlElementIterator *, struct LxmlElement *);
219
+ __PYX_EXTERN_C void initTagMatch(struct LxmlElementTagMatcher *, PyObject *);
220
+ __PYX_EXTERN_C xmlNs *findOrBuildNodeNsPrefix(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *);
221
+
222
+ #endif /* !__PYX_HAVE_API__lxml__etree */
223
+
224
+ /* WARNING: the interface of the module init function changed in CPython 3.5. */
225
+ /* It now returns a PyModuleDef instance instead of a PyModule instance. */
226
+
227
+ #if PY_MAJOR_VERSION < 3
228
+ PyMODINIT_FUNC initetree(void);
229
+ #else
230
+ /* WARNING: Use PyImport_AppendInittab("etree", PyInit_etree) instead of calling PyInit_etree directly from Python 3.5 */
231
+ PyMODINIT_FUNC PyInit_etree(void);
232
+
233
+ #if PY_VERSION_HEX >= 0x03050000 && (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) || (defined(__cplusplus) && __cplusplus >= 201402L))
234
+ #if defined(__cplusplus) && __cplusplus >= 201402L
235
+ [[deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")]] inline
236
+ #elif defined(__GNUC__) || defined(__clang__)
237
+ __attribute__ ((__deprecated__("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly."), __unused__)) __inline__
238
+ #elif defined(_MSC_VER)
239
+ __declspec(deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")) __inline
240
+ #endif
241
+ static PyObject* __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyObject* res) {
242
+ return res;
243
+ }
244
+ #define PyInit_etree() __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyInit_etree())
245
+ #endif
246
+ #endif
247
+
248
+ #endif /* !__PYX_HAVE__lxml__etree */
env-llmeval/lib/python3.10/site-packages/lxml/html/ElementSoup.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __doc__ = """Legacy interface to the BeautifulSoup HTML parser.
2
+ """
3
+
4
+ __all__ = ["parse", "convert_tree"]
5
+
6
+ from .soupparser import convert_tree, parse as _parse
7
+
8
+ def parse(file, beautifulsoup=None, makeelement=None):
9
+ root = _parse(file, beautifulsoup=beautifulsoup, makeelement=makeelement)
10
+ return root.getroot()
env-llmeval/lib/python3.10/site-packages/lxml/html/__init__.py ADDED
@@ -0,0 +1,1923 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2004 Ian Bicking. All rights reserved.
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions are
5
+ # met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above copyright
11
+ # notice, this list of conditions and the following disclaimer in
12
+ # the documentation and/or other materials provided with the
13
+ # distribution.
14
+ #
15
+ # 3. Neither the name of Ian Bicking nor the names of its contributors may
16
+ # be used to endorse or promote products derived from this software
17
+ # without specific prior written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IAN BICKING OR
23
+ # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24
+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25
+ # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26
+ # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27
+ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ """The ``lxml.html`` tool set for HTML handling.
32
+ """
33
+
34
+
35
+ __all__ = [
36
+ 'document_fromstring', 'fragment_fromstring', 'fragments_fromstring', 'fromstring',
37
+ 'tostring', 'Element', 'defs', 'open_in_browser', 'submit_form',
38
+ 'find_rel_links', 'find_class', 'make_links_absolute',
39
+ 'resolve_base_href', 'iterlinks', 'rewrite_links', 'parse']
40
+
41
+
42
+ import copy
43
+ import re
44
+
45
+ from collections.abc import MutableMapping, MutableSet
46
+ from functools import partial
47
+ from urllib.parse import urljoin
48
+
49
+ from .. import etree
50
+ from . import defs
51
+ from ._setmixin import SetMixin
52
+
53
+
54
+ def __fix_docstring(s):
55
+ # TODO: remove and clean up doctests
56
+ if not s:
57
+ return s
58
+ sub = re.compile(r"^(\s*)u'", re.M).sub
59
+ return sub(r"\1'", s)
60
+
61
+
62
+ XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
63
+
64
+ _rel_links_xpath = etree.XPath("descendant-or-self::a[@rel]|descendant-or-self::x:a[@rel]",
65
+ namespaces={'x':XHTML_NAMESPACE})
66
+ _options_xpath = etree.XPath("descendant-or-self::option|descendant-or-self::x:option",
67
+ namespaces={'x':XHTML_NAMESPACE})
68
+ _forms_xpath = etree.XPath("descendant-or-self::form|descendant-or-self::x:form",
69
+ namespaces={'x':XHTML_NAMESPACE})
70
+ #_class_xpath = etree.XPath(r"descendant-or-self::*[regexp:match(@class, concat('\b', $class_name, '\b'))]", {'regexp': 'http://exslt.org/regular-expressions'})
71
+ _class_xpath = etree.XPath("descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), concat(' ', $class_name, ' '))]")
72
+ _id_xpath = etree.XPath("descendant-or-self::*[@id=$id]")
73
+ _collect_string_content = etree.XPath("string()")
74
+ _iter_css_urls = re.compile(r'url\(('+'["][^"]*["]|'+"['][^']*[']|"+r'[^)]*)\)', re.I).finditer
75
+ _iter_css_imports = re.compile(r'@import "(.*?)"').finditer
76
+ _label_xpath = etree.XPath("//label[@for=$id]|//x:label[@for=$id]",
77
+ namespaces={'x':XHTML_NAMESPACE})
78
+ _archive_re = re.compile(r'[^ ]+')
79
+ _parse_meta_refresh_url = re.compile(
80
+ r'[^;=]*;\s*(?:url\s*=\s*)?(?P<url>.*)$', re.I).search
81
+
82
+
83
+ def _unquote_match(s, pos):
84
+ if s[:1] == '"' and s[-1:] == '"' or s[:1] == "'" and s[-1:] == "'":
85
+ return s[1:-1], pos+1
86
+ else:
87
+ return s,pos
88
+
89
+
90
+ def _transform_result(typ, result):
91
+ """Convert the result back into the input type.
92
+ """
93
+ if issubclass(typ, bytes):
94
+ return tostring(result, encoding='utf-8')
95
+ elif issubclass(typ, str):
96
+ return tostring(result, encoding='unicode')
97
+ else:
98
+ return result
99
+
100
+
101
+ def _nons(tag):
102
+ if isinstance(tag, str):
103
+ if tag[0] == '{' and tag[1:len(XHTML_NAMESPACE)+1] == XHTML_NAMESPACE:
104
+ return tag.split('}')[-1]
105
+ return tag
106
+
107
+
108
+ class Classes(MutableSet):
109
+ """Provides access to an element's class attribute as a set-like collection.
110
+ Usage::
111
+
112
+ >>> el = fromstring('<p class="hidden large">Text</p>')
113
+ >>> classes = el.classes # or: classes = Classes(el.attrib)
114
+ >>> classes |= ['block', 'paragraph']
115
+ >>> el.get('class')
116
+ 'hidden large block paragraph'
117
+ >>> classes.toggle('hidden')
118
+ False
119
+ >>> el.get('class')
120
+ 'large block paragraph'
121
+ >>> classes -= ('some', 'classes', 'block')
122
+ >>> el.get('class')
123
+ 'large paragraph'
124
+ """
125
+ def __init__(self, attributes):
126
+ self._attributes = attributes
127
+ self._get_class_value = partial(attributes.get, 'class', '')
128
+
129
+ def add(self, value):
130
+ """
131
+ Add a class.
132
+
133
+ This has no effect if the class is already present.
134
+ """
135
+ if not value or re.search(r'\s', value):
136
+ raise ValueError("Invalid class name: %r" % value)
137
+ classes = self._get_class_value().split()
138
+ if value in classes:
139
+ return
140
+ classes.append(value)
141
+ self._attributes['class'] = ' '.join(classes)
142
+
143
+ def discard(self, value):
144
+ """
145
+ Remove a class if it is currently present.
146
+
147
+ If the class is not present, do nothing.
148
+ """
149
+ if not value or re.search(r'\s', value):
150
+ raise ValueError("Invalid class name: %r" % value)
151
+ classes = [name for name in self._get_class_value().split()
152
+ if name != value]
153
+ if classes:
154
+ self._attributes['class'] = ' '.join(classes)
155
+ elif 'class' in self._attributes:
156
+ del self._attributes['class']
157
+
158
+ def remove(self, value):
159
+ """
160
+ Remove a class; it must currently be present.
161
+
162
+ If the class is not present, raise a KeyError.
163
+ """
164
+ if not value or re.search(r'\s', value):
165
+ raise ValueError("Invalid class name: %r" % value)
166
+ super().remove(value)
167
+
168
+ def __contains__(self, name):
169
+ classes = self._get_class_value()
170
+ return name in classes and name in classes.split()
171
+
172
+ def __iter__(self):
173
+ return iter(self._get_class_value().split())
174
+
175
+ def __len__(self):
176
+ return len(self._get_class_value().split())
177
+
178
+ # non-standard methods
179
+
180
+ def update(self, values):
181
+ """
182
+ Add all names from 'values'.
183
+ """
184
+ classes = self._get_class_value().split()
185
+ extended = False
186
+ for value in values:
187
+ if value not in classes:
188
+ classes.append(value)
189
+ extended = True
190
+ if extended:
191
+ self._attributes['class'] = ' '.join(classes)
192
+
193
+ def toggle(self, value):
194
+ """
195
+ Add a class name if it isn't there yet, or remove it if it exists.
196
+
197
+ Returns true if the class was added (and is now enabled) and
198
+ false if it was removed (and is now disabled).
199
+ """
200
+ if not value or re.search(r'\s', value):
201
+ raise ValueError("Invalid class name: %r" % value)
202
+ classes = self._get_class_value().split()
203
+ try:
204
+ classes.remove(value)
205
+ enabled = False
206
+ except ValueError:
207
+ classes.append(value)
208
+ enabled = True
209
+ if classes:
210
+ self._attributes['class'] = ' '.join(classes)
211
+ else:
212
+ del self._attributes['class']
213
+ return enabled
214
+
215
+
216
+ class HtmlMixin:
217
+
218
+ def set(self, key, value=None):
219
+ """set(self, key, value=None)
220
+
221
+ Sets an element attribute. If no value is provided, or if the value is None,
222
+ creates a 'boolean' attribute without value, e.g. "<form novalidate></form>"
223
+ for ``form.set('novalidate')``.
224
+ """
225
+ super().set(key, value)
226
+
227
+ @property
228
+ def classes(self):
229
+ """
230
+ A set-like wrapper around the 'class' attribute.
231
+ """
232
+ return Classes(self.attrib)
233
+
234
+ @classes.setter
235
+ def classes(self, classes):
236
+ assert isinstance(classes, Classes) # only allow "el.classes |= ..." etc.
237
+ value = classes._get_class_value()
238
+ if value:
239
+ self.set('class', value)
240
+ elif self.get('class') is not None:
241
+ del self.attrib['class']
242
+
243
+ @property
244
+ def base_url(self):
245
+ """
246
+ Returns the base URL, given when the page was parsed.
247
+
248
+ Use with ``urlparse.urljoin(el.base_url, href)`` to get
249
+ absolute URLs.
250
+ """
251
+ return self.getroottree().docinfo.URL
252
+
253
+ @property
254
+ def forms(self):
255
+ """
256
+ Return a list of all the forms
257
+ """
258
+ return _forms_xpath(self)
259
+
260
+ @property
261
+ def body(self):
262
+ """
263
+ Return the <body> element. Can be called from a child element
264
+ to get the document's head.
265
+ """
266
+ return self.xpath('//body|//x:body', namespaces={'x':XHTML_NAMESPACE})[0]
267
+
268
+ @property
269
+ def head(self):
270
+ """
271
+ Returns the <head> element. Can be called from a child
272
+ element to get the document's head.
273
+ """
274
+ return self.xpath('//head|//x:head', namespaces={'x':XHTML_NAMESPACE})[0]
275
+
276
+ @property
277
+ def label(self):
278
+ """
279
+ Get or set any <label> element associated with this element.
280
+ """
281
+ id = self.get('id')
282
+ if not id:
283
+ return None
284
+ result = _label_xpath(self, id=id)
285
+ if not result:
286
+ return None
287
+ else:
288
+ return result[0]
289
+
290
+ @label.setter
291
+ def label(self, label):
292
+ id = self.get('id')
293
+ if not id:
294
+ raise TypeError(
295
+ "You cannot set a label for an element (%r) that has no id"
296
+ % self)
297
+ if _nons(label.tag) != 'label':
298
+ raise TypeError(
299
+ "You can only assign label to a label element (not %r)"
300
+ % label)
301
+ label.set('for', id)
302
+
303
+ @label.deleter
304
+ def label(self):
305
+ label = self.label
306
+ if label is not None:
307
+ del label.attrib['for']
308
+
309
+ def drop_tree(self):
310
+ """
311
+ Removes this element from the tree, including its children and
312
+ text. The tail text is joined to the previous element or
313
+ parent.
314
+ """
315
+ parent = self.getparent()
316
+ assert parent is not None
317
+ if self.tail:
318
+ previous = self.getprevious()
319
+ if previous is None:
320
+ parent.text = (parent.text or '') + self.tail
321
+ else:
322
+ previous.tail = (previous.tail or '') + self.tail
323
+ parent.remove(self)
324
+
325
+ def drop_tag(self):
326
+ """
327
+ Remove the tag, but not its children or text. The children and text
328
+ are merged into the parent.
329
+
330
+ Example::
331
+
332
+ >>> h = fragment_fromstring('<div>Hello <b>World!</b></div>')
333
+ >>> h.find('.//b').drop_tag()
334
+ >>> print(tostring(h, encoding='unicode'))
335
+ <div>Hello World!</div>
336
+ """
337
+ parent = self.getparent()
338
+ assert parent is not None
339
+ previous = self.getprevious()
340
+ if self.text and isinstance(self.tag, str):
341
+ # not a Comment, etc.
342
+ if previous is None:
343
+ parent.text = (parent.text or '') + self.text
344
+ else:
345
+ previous.tail = (previous.tail or '') + self.text
346
+ if self.tail:
347
+ if len(self):
348
+ last = self[-1]
349
+ last.tail = (last.tail or '') + self.tail
350
+ elif previous is None:
351
+ parent.text = (parent.text or '') + self.tail
352
+ else:
353
+ previous.tail = (previous.tail or '') + self.tail
354
+ index = parent.index(self)
355
+ parent[index:index+1] = self[:]
356
+
357
+ def find_rel_links(self, rel):
358
+ """
359
+ Find any links like ``<a rel="{rel}">...</a>``; returns a list of elements.
360
+ """
361
+ rel = rel.lower()
362
+ return [el for el in _rel_links_xpath(self)
363
+ if el.get('rel').lower() == rel]
364
+
365
+ def find_class(self, class_name):
366
+ """
367
+ Find any elements with the given class name.
368
+ """
369
+ return _class_xpath(self, class_name=class_name)
370
+
371
+ def get_element_by_id(self, id, *default):
372
+ """
373
+ Get the first element in a document with the given id. If none is
374
+ found, return the default argument if provided or raise KeyError
375
+ otherwise.
376
+
377
+ Note that there can be more than one element with the same id,
378
+ and this isn't uncommon in HTML documents found in the wild.
379
+ Browsers return only the first match, and this function does
380
+ the same.
381
+ """
382
+ try:
383
+ # FIXME: should this check for multiple matches?
384
+ # browsers just return the first one
385
+ return _id_xpath(self, id=id)[0]
386
+ except IndexError:
387
+ if default:
388
+ return default[0]
389
+ else:
390
+ raise KeyError(id)
391
+
392
+ def text_content(self):
393
+ """
394
+ Return the text content of the tag (and the text in any children).
395
+ """
396
+ return _collect_string_content(self)
397
+
398
+ def cssselect(self, expr, translator='html'):
399
+ """
400
+ Run the CSS expression on this element and its children,
401
+ returning a list of the results.
402
+
403
+ Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self)
404
+ -- note that pre-compiling the expression can provide a substantial
405
+ speedup.
406
+ """
407
+ # Do the import here to make the dependency optional.
408
+ from lxml.cssselect import CSSSelector
409
+ return CSSSelector(expr, translator=translator)(self)
410
+
411
+ ########################################
412
+ ## Link functions
413
+ ########################################
414
+
415
+ def make_links_absolute(self, base_url=None, resolve_base_href=True,
416
+ handle_failures=None):
417
+ """
418
+ Make all links in the document absolute, given the
419
+ ``base_url`` for the document (the full URL where the document
420
+ came from), or if no ``base_url`` is given, then the ``.base_url``
421
+ of the document.
422
+
423
+ If ``resolve_base_href`` is true, then any ``<base href>``
424
+ tags in the document are used *and* removed from the document.
425
+ If it is false then any such tag is ignored.
426
+
427
+ If ``handle_failures`` is None (default), a failure to process
428
+ a URL will abort the processing. If set to 'ignore', errors
429
+ are ignored. If set to 'discard', failing URLs will be removed.
430
+ """
431
+ if base_url is None:
432
+ base_url = self.base_url
433
+ if base_url is None:
434
+ raise TypeError(
435
+ "No base_url given, and the document has no base_url")
436
+ if resolve_base_href:
437
+ self.resolve_base_href()
438
+
439
+ if handle_failures == 'ignore':
440
+ def link_repl(href):
441
+ try:
442
+ return urljoin(base_url, href)
443
+ except ValueError:
444
+ return href
445
+ elif handle_failures == 'discard':
446
+ def link_repl(href):
447
+ try:
448
+ return urljoin(base_url, href)
449
+ except ValueError:
450
+ return None
451
+ elif handle_failures is None:
452
+ def link_repl(href):
453
+ return urljoin(base_url, href)
454
+ else:
455
+ raise ValueError(
456
+ "unexpected value for handle_failures: %r" % handle_failures)
457
+
458
+ self.rewrite_links(link_repl)
459
+
460
+ def resolve_base_href(self, handle_failures=None):
461
+ """
462
+ Find any ``<base href>`` tag in the document, and apply its
463
+ values to all links found in the document. Also remove the
464
+ tag once it has been applied.
465
+
466
+ If ``handle_failures`` is None (default), a failure to process
467
+ a URL will abort the processing. If set to 'ignore', errors
468
+ are ignored. If set to 'discard', failing URLs will be removed.
469
+ """
470
+ base_href = None
471
+ basetags = self.xpath('//base[@href]|//x:base[@href]',
472
+ namespaces={'x': XHTML_NAMESPACE})
473
+ for b in basetags:
474
+ base_href = b.get('href')
475
+ b.drop_tree()
476
+ if not base_href:
477
+ return
478
+ self.make_links_absolute(base_href, resolve_base_href=False,
479
+ handle_failures=handle_failures)
480
+
481
+ def iterlinks(self):
482
+ """
483
+ Yield (element, attribute, link, pos), where attribute may be None
484
+ (indicating the link is in the text). ``pos`` is the position
485
+ where the link occurs; often 0, but sometimes something else in
486
+ the case of links in stylesheets or style tags.
487
+
488
+ Note: <base href> is *not* taken into account in any way. The
489
+ link you get is exactly the link in the document.
490
+
491
+ Note: multiple links inside of a single text string or
492
+ attribute value are returned in reversed order. This makes it
493
+ possible to replace or delete them from the text string value
494
+ based on their reported text positions. Otherwise, a
495
+ modification at one text position can change the positions of
496
+ links reported later on.
497
+ """
498
+ link_attrs = defs.link_attrs
499
+ for el in self.iter(etree.Element):
500
+ attribs = el.attrib
501
+ tag = _nons(el.tag)
502
+ if tag == 'object':
503
+ codebase = None
504
+ ## <object> tags have attributes that are relative to
505
+ ## codebase
506
+ if 'codebase' in attribs:
507
+ codebase = el.get('codebase')
508
+ yield (el, 'codebase', codebase, 0)
509
+ for attrib in ('classid', 'data'):
510
+ if attrib in attribs:
511
+ value = el.get(attrib)
512
+ if codebase is not None:
513
+ value = urljoin(codebase, value)
514
+ yield (el, attrib, value, 0)
515
+ if 'archive' in attribs:
516
+ for match in _archive_re.finditer(el.get('archive')):
517
+ value = match.group(0)
518
+ if codebase is not None:
519
+ value = urljoin(codebase, value)
520
+ yield (el, 'archive', value, match.start())
521
+ else:
522
+ for attrib in link_attrs:
523
+ if attrib in attribs:
524
+ yield (el, attrib, attribs[attrib], 0)
525
+ if tag == 'meta':
526
+ http_equiv = attribs.get('http-equiv', '').lower()
527
+ if http_equiv == 'refresh':
528
+ content = attribs.get('content', '')
529
+ match = _parse_meta_refresh_url(content)
530
+ url = (match.group('url') if match else content).strip()
531
+ # unexpected content means the redirect won't work, but we might
532
+ # as well be permissive and return the entire string.
533
+ if url:
534
+ url, pos = _unquote_match(
535
+ url, match.start('url') if match else content.find(url))
536
+ yield (el, 'content', url, pos)
537
+ elif tag == 'param':
538
+ valuetype = el.get('valuetype') or ''
539
+ if valuetype.lower() == 'ref':
540
+ ## FIXME: while it's fine we *find* this link,
541
+ ## according to the spec we aren't supposed to
542
+ ## actually change the value, including resolving
543
+ ## it. It can also still be a link, even if it
544
+ ## doesn't have a valuetype="ref" (which seems to be the norm)
545
+ ## http://www.w3.org/TR/html401/struct/objects.html#adef-valuetype
546
+ yield (el, 'value', el.get('value'), 0)
547
+ elif tag == 'style' and el.text:
548
+ urls = [
549
+ # (start_pos, url)
550
+ _unquote_match(match.group(1), match.start(1))[::-1]
551
+ for match in _iter_css_urls(el.text)
552
+ ] + [
553
+ (match.start(1), match.group(1))
554
+ for match in _iter_css_imports(el.text)
555
+ ]
556
+ if urls:
557
+ # sort by start pos to bring both match sets back into order
558
+ # and reverse the list to report correct positions despite
559
+ # modifications
560
+ urls.sort(reverse=True)
561
+ for start, url in urls:
562
+ yield (el, None, url, start)
563
+ if 'style' in attribs:
564
+ urls = list(_iter_css_urls(attribs['style']))
565
+ if urls:
566
+ # return in reversed order to simplify in-place modifications
567
+ for match in urls[::-1]:
568
+ url, start = _unquote_match(match.group(1), match.start(1))
569
+ yield (el, 'style', url, start)
570
+
571
+ def rewrite_links(self, link_repl_func, resolve_base_href=True,
572
+ base_href=None):
573
+ """
574
+ Rewrite all the links in the document. For each link
575
+ ``link_repl_func(link)`` will be called, and the return value
576
+ will replace the old link.
577
+
578
+ Note that links may not be absolute (unless you first called
579
+ ``make_links_absolute()``), and may be internal (e.g.,
580
+ ``'#anchor'``). They can also be values like
581
+ ``'mailto:email'`` or ``'javascript:expr'``.
582
+
583
+ If you give ``base_href`` then all links passed to
584
+ ``link_repl_func()`` will take that into account.
585
+
586
+ If the ``link_repl_func`` returns None, the attribute or
587
+ tag text will be removed completely.
588
+ """
589
+ if base_href is not None:
590
+ # FIXME: this can be done in one pass with a wrapper
591
+ # around link_repl_func
592
+ self.make_links_absolute(
593
+ base_href, resolve_base_href=resolve_base_href)
594
+ elif resolve_base_href:
595
+ self.resolve_base_href()
596
+
597
+ for el, attrib, link, pos in self.iterlinks():
598
+ new_link = link_repl_func(link.strip())
599
+ if new_link == link:
600
+ continue
601
+ if new_link is None:
602
+ # Remove the attribute or element content
603
+ if attrib is None:
604
+ el.text = ''
605
+ else:
606
+ del el.attrib[attrib]
607
+ continue
608
+
609
+ if attrib is None:
610
+ new = el.text[:pos] + new_link + el.text[pos+len(link):]
611
+ el.text = new
612
+ else:
613
+ cur = el.get(attrib)
614
+ if not pos and len(cur) == len(link):
615
+ new = new_link # most common case
616
+ else:
617
+ new = cur[:pos] + new_link + cur[pos+len(link):]
618
+ el.set(attrib, new)
619
+
620
+
621
+ class _MethodFunc:
622
+ """
623
+ An object that represents a method on an element as a function;
624
+ the function takes either an element or an HTML string. It
625
+ returns whatever the function normally returns, or if the function
626
+ works in-place (and so returns None) it returns a serialized form
627
+ of the resulting document.
628
+ """
629
+ def __init__(self, name, copy=False, source_class=HtmlMixin):
630
+ self.name = name
631
+ self.copy = copy
632
+ self.__doc__ = getattr(source_class, self.name).__doc__
633
+ def __call__(self, doc, *args, **kw):
634
+ result_type = type(doc)
635
+ if isinstance(doc, (str, bytes)):
636
+ if 'copy' in kw:
637
+ raise TypeError(
638
+ "The keyword 'copy' can only be used with element inputs to %s, not a string input" % self.name)
639
+ doc = fromstring(doc, **kw)
640
+ else:
641
+ if 'copy' in kw:
642
+ make_a_copy = kw.pop('copy')
643
+ else:
644
+ make_a_copy = self.copy
645
+ if make_a_copy:
646
+ doc = copy.deepcopy(doc)
647
+ meth = getattr(doc, self.name)
648
+ result = meth(*args, **kw)
649
+ # FIXME: this None test is a bit sloppy
650
+ if result is None:
651
+ # Then return what we got in
652
+ return _transform_result(result_type, doc)
653
+ else:
654
+ return result
655
+
656
+
657
+ find_rel_links = _MethodFunc('find_rel_links', copy=False)
658
+ find_class = _MethodFunc('find_class', copy=False)
659
+ make_links_absolute = _MethodFunc('make_links_absolute', copy=True)
660
+ resolve_base_href = _MethodFunc('resolve_base_href', copy=True)
661
+ iterlinks = _MethodFunc('iterlinks', copy=False)
662
+ rewrite_links = _MethodFunc('rewrite_links', copy=True)
663
+
664
+
665
+ class HtmlComment(HtmlMixin, etree.CommentBase):
666
+ pass
667
+
668
+
669
+ class HtmlElement(HtmlMixin, etree.ElementBase):
670
+ pass
671
+
672
+
673
+ class HtmlProcessingInstruction(HtmlMixin, etree.PIBase):
674
+ pass
675
+
676
+
677
+ class HtmlEntity(HtmlMixin, etree.EntityBase):
678
+ pass
679
+
680
+
681
+ class HtmlElementClassLookup(etree.CustomElementClassLookup):
682
+ """A lookup scheme for HTML Element classes.
683
+
684
+ To create a lookup instance with different Element classes, pass a tag
685
+ name mapping of Element classes in the ``classes`` keyword argument and/or
686
+ a tag name mapping of Mixin classes in the ``mixins`` keyword argument.
687
+ The special key '*' denotes a Mixin class that should be mixed into all
688
+ Element classes.
689
+ """
690
+ _default_element_classes = {}
691
+
692
+ def __init__(self, classes=None, mixins=None):
693
+ etree.CustomElementClassLookup.__init__(self)
694
+ if classes is None:
695
+ classes = self._default_element_classes.copy()
696
+ if mixins:
697
+ mixers = {}
698
+ for name, value in mixins:
699
+ if name == '*':
700
+ for n in classes.keys():
701
+ mixers.setdefault(n, []).append(value)
702
+ else:
703
+ mixers.setdefault(name, []).append(value)
704
+ for name, mix_bases in mixers.items():
705
+ cur = classes.get(name, HtmlElement)
706
+ bases = tuple(mix_bases + [cur])
707
+ classes[name] = type(cur.__name__, bases, {})
708
+ self._element_classes = classes
709
+
710
+ def lookup(self, node_type, document, namespace, name):
711
+ if node_type == 'element':
712
+ return self._element_classes.get(name.lower(), HtmlElement)
713
+ elif node_type == 'comment':
714
+ return HtmlComment
715
+ elif node_type == 'PI':
716
+ return HtmlProcessingInstruction
717
+ elif node_type == 'entity':
718
+ return HtmlEntity
719
+ # Otherwise normal lookup
720
+ return None
721
+
722
+
723
+ ################################################################################
724
+ # parsing
725
+ ################################################################################
726
+
727
+ _looks_like_full_html_unicode = re.compile(
728
+ r'^\s*<(?:html|!doctype)', re.I).match
729
+ _looks_like_full_html_bytes = re.compile(
730
+ br'^\s*<(?:html|!doctype)', re.I).match
731
+
732
+
733
+ def document_fromstring(html, parser=None, ensure_head_body=False, **kw):
734
+ if parser is None:
735
+ parser = html_parser
736
+ value = etree.fromstring(html, parser, **kw)
737
+ if value is None:
738
+ raise etree.ParserError(
739
+ "Document is empty")
740
+ if ensure_head_body and value.find('head') is None:
741
+ value.insert(0, Element('head'))
742
+ if ensure_head_body and value.find('body') is None:
743
+ value.append(Element('body'))
744
+ return value
745
+
746
+
747
+ def fragments_fromstring(html, no_leading_text=False, base_url=None,
748
+ parser=None, **kw):
749
+ """Parses several HTML elements, returning a list of elements.
750
+
751
+ The first item in the list may be a string.
752
+ If no_leading_text is true, then it will be an error if there is
753
+ leading text, and it will always be a list of only elements.
754
+
755
+ base_url will set the document's base_url attribute
756
+ (and the tree's docinfo.URL).
757
+ """
758
+ if parser is None:
759
+ parser = html_parser
760
+ # FIXME: check what happens when you give html with a body, head, etc.
761
+ if isinstance(html, bytes):
762
+ if not _looks_like_full_html_bytes(html):
763
+ # can't use %-formatting in early Py3 versions
764
+ html = (b'<html><body>' + html +
765
+ b'</body></html>')
766
+ else:
767
+ if not _looks_like_full_html_unicode(html):
768
+ html = '<html><body>%s</body></html>' % html
769
+ doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
770
+ assert _nons(doc.tag) == 'html'
771
+ bodies = [e for e in doc if _nons(e.tag) == 'body']
772
+ assert len(bodies) == 1, ("too many bodies: %r in %r" % (bodies, html))
773
+ body = bodies[0]
774
+ elements = []
775
+ if no_leading_text and body.text and body.text.strip():
776
+ raise etree.ParserError(
777
+ "There is leading text: %r" % body.text)
778
+ if body.text and body.text.strip():
779
+ elements.append(body.text)
780
+ elements.extend(body)
781
+ # FIXME: removing the reference to the parent artificial document
782
+ # would be nice
783
+ return elements
784
+
785
+
786
+ def fragment_fromstring(html, create_parent=False, base_url=None,
787
+ parser=None, **kw):
788
+ """
789
+ Parses a single HTML element; it is an error if there is more than
790
+ one element, or if anything but whitespace precedes or follows the
791
+ element.
792
+
793
+ If ``create_parent`` is true (or is a tag name) then a parent node
794
+ will be created to encapsulate the HTML in a single element. In this
795
+ case, leading or trailing text is also allowed, as are multiple elements
796
+ as result of the parsing.
797
+
798
+ Passing a ``base_url`` will set the document's ``base_url`` attribute
799
+ (and the tree's docinfo.URL).
800
+ """
801
+ if parser is None:
802
+ parser = html_parser
803
+
804
+ accept_leading_text = bool(create_parent)
805
+
806
+ elements = fragments_fromstring(
807
+ html, parser=parser, no_leading_text=not accept_leading_text,
808
+ base_url=base_url, **kw)
809
+
810
+ if create_parent:
811
+ if not isinstance(create_parent, str):
812
+ create_parent = 'div'
813
+ new_root = Element(create_parent)
814
+ if elements:
815
+ if isinstance(elements[0], str):
816
+ new_root.text = elements[0]
817
+ del elements[0]
818
+ new_root.extend(elements)
819
+ return new_root
820
+
821
+ if not elements:
822
+ raise etree.ParserError('No elements found')
823
+ if len(elements) > 1:
824
+ raise etree.ParserError(
825
+ "Multiple elements found (%s)"
826
+ % ', '.join([_element_name(e) for e in elements]))
827
+ el = elements[0]
828
+ if el.tail and el.tail.strip():
829
+ raise etree.ParserError(
830
+ "Element followed by text: %r" % el.tail)
831
+ el.tail = None
832
+ return el
833
+
834
+
835
+ def fromstring(html, base_url=None, parser=None, **kw):
836
+ """
837
+ Parse the html, returning a single element/document.
838
+
839
+ This tries to minimally parse the chunk of text, without knowing if it
840
+ is a fragment or a document.
841
+
842
+ base_url will set the document's base_url attribute (and the tree's docinfo.URL)
843
+ """
844
+ if parser is None:
845
+ parser = html_parser
846
+ if isinstance(html, bytes):
847
+ is_full_html = _looks_like_full_html_bytes(html)
848
+ else:
849
+ is_full_html = _looks_like_full_html_unicode(html)
850
+ doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
851
+ if is_full_html:
852
+ return doc
853
+ # otherwise, lets parse it out...
854
+ bodies = doc.findall('body')
855
+ if not bodies:
856
+ bodies = doc.findall('{%s}body' % XHTML_NAMESPACE)
857
+ if bodies:
858
+ body = bodies[0]
859
+ if len(bodies) > 1:
860
+ # Somehow there are multiple bodies, which is bad, but just
861
+ # smash them into one body
862
+ for other_body in bodies[1:]:
863
+ if other_body.text:
864
+ if len(body):
865
+ body[-1].tail = (body[-1].tail or '') + other_body.text
866
+ else:
867
+ body.text = (body.text or '') + other_body.text
868
+ body.extend(other_body)
869
+ # We'll ignore tail
870
+ # I guess we are ignoring attributes too
871
+ other_body.drop_tree()
872
+ else:
873
+ body = None
874
+ heads = doc.findall('head')
875
+ if not heads:
876
+ heads = doc.findall('{%s}head' % XHTML_NAMESPACE)
877
+ if heads:
878
+ # Well, we have some sort of structure, so lets keep it all
879
+ head = heads[0]
880
+ if len(heads) > 1:
881
+ for other_head in heads[1:]:
882
+ head.extend(other_head)
883
+ # We don't care about text or tail in a head
884
+ other_head.drop_tree()
885
+ return doc
886
+ if body is None:
887
+ return doc
888
+ if (len(body) == 1 and (not body.text or not body.text.strip())
889
+ and (not body[-1].tail or not body[-1].tail.strip())):
890
+ # The body has just one element, so it was probably a single
891
+ # element passed in
892
+ return body[0]
893
+ # Now we have a body which represents a bunch of tags which have the
894
+ # content that was passed in. We will create a fake container, which
895
+ # is the body tag, except <body> implies too much structure.
896
+ if _contains_block_level_tag(body):
897
+ body.tag = 'div'
898
+ else:
899
+ body.tag = 'span'
900
+ return body
901
+
902
+
903
+ def parse(filename_or_url, parser=None, base_url=None, **kw):
904
+ """
905
+ Parse a filename, URL, or file-like object into an HTML document
906
+ tree. Note: this returns a tree, not an element. Use
907
+ ``parse(...).getroot()`` to get the document root.
908
+
909
+ You can override the base URL with the ``base_url`` keyword. This
910
+ is most useful when parsing from a file-like object.
911
+ """
912
+ if parser is None:
913
+ parser = html_parser
914
+ return etree.parse(filename_or_url, parser, base_url=base_url, **kw)
915
+
916
+
917
+ def _contains_block_level_tag(el):
918
+ # FIXME: I could do this with XPath, but would that just be
919
+ # unnecessarily slow?
920
+ for el in el.iter(etree.Element):
921
+ if _nons(el.tag) in defs.block_tags:
922
+ return True
923
+ return False
924
+
925
+
926
+ def _element_name(el):
927
+ if isinstance(el, etree.CommentBase):
928
+ return 'comment'
929
+ elif isinstance(el, str):
930
+ return 'string'
931
+ else:
932
+ return _nons(el.tag)
933
+
934
+
935
+ ################################################################################
936
+ # form handling
937
+ ################################################################################
938
+
939
+ class FormElement(HtmlElement):
940
+ """
941
+ Represents a <form> element.
942
+ """
943
+
944
+ @property
945
+ def inputs(self):
946
+ """
947
+ Returns an accessor for all the input elements in the form.
948
+
949
+ See `InputGetter` for more information about the object.
950
+ """
951
+ return InputGetter(self)
952
+
953
+ @property
954
+ def fields(self):
955
+ """
956
+ Dictionary-like object that represents all the fields in this
957
+ form. You can set values in this dictionary to effect the
958
+ form.
959
+ """
960
+ return FieldsDict(self.inputs)
961
+
962
+ @fields.setter
963
+ def fields(self, value):
964
+ fields = self.fields
965
+ prev_keys = fields.keys()
966
+ for key, value in value.items():
967
+ if key in prev_keys:
968
+ prev_keys.remove(key)
969
+ fields[key] = value
970
+ for key in prev_keys:
971
+ if key is None:
972
+ # Case of an unnamed input; these aren't really
973
+ # expressed in form_values() anyway.
974
+ continue
975
+ fields[key] = None
976
+
977
+ def _name(self):
978
+ if self.get('name'):
979
+ return self.get('name')
980
+ elif self.get('id'):
981
+ return '#' + self.get('id')
982
+ iter_tags = self.body.iter
983
+ forms = list(iter_tags('form'))
984
+ if not forms:
985
+ forms = list(iter_tags('{%s}form' % XHTML_NAMESPACE))
986
+ return str(forms.index(self))
987
+
988
+ def form_values(self):
989
+ """
990
+ Return a list of tuples of the field values for the form.
991
+ This is suitable to be passed to ``urllib.urlencode()``.
992
+ """
993
+ results = []
994
+ for el in self.inputs:
995
+ name = el.name
996
+ if not name or 'disabled' in el.attrib:
997
+ continue
998
+ tag = _nons(el.tag)
999
+ if tag == 'textarea':
1000
+ results.append((name, el.value))
1001
+ elif tag == 'select':
1002
+ value = el.value
1003
+ if el.multiple:
1004
+ for v in value:
1005
+ results.append((name, v))
1006
+ elif value is not None:
1007
+ results.append((name, el.value))
1008
+ else:
1009
+ assert tag == 'input', (
1010
+ "Unexpected tag: %r" % el)
1011
+ if el.checkable and not el.checked:
1012
+ continue
1013
+ if el.type in ('submit', 'image', 'reset', 'file'):
1014
+ continue
1015
+ value = el.value
1016
+ if value is not None:
1017
+ results.append((name, el.value))
1018
+ return results
1019
+
1020
+ @property
1021
+ def action(self):
1022
+ """
1023
+ Get/set the form's ``action`` attribute.
1024
+ """
1025
+ base_url = self.base_url
1026
+ action = self.get('action')
1027
+ if base_url and action is not None:
1028
+ return urljoin(base_url, action)
1029
+ else:
1030
+ return action
1031
+
1032
+ @action.setter
1033
+ def action(self, value):
1034
+ self.set('action', value)
1035
+
1036
+ @action.deleter
1037
+ def action(self):
1038
+ attrib = self.attrib
1039
+ if 'action' in attrib:
1040
+ del attrib['action']
1041
+
1042
+ @property
1043
+ def method(self):
1044
+ """
1045
+ Get/set the form's method. Always returns a capitalized
1046
+ string, and defaults to ``'GET'``
1047
+ """
1048
+ return self.get('method', 'GET').upper()
1049
+
1050
+ @method.setter
1051
+ def method(self, value):
1052
+ self.set('method', value.upper())
1053
+
1054
+
1055
+ HtmlElementClassLookup._default_element_classes['form'] = FormElement
1056
+
1057
+
1058
+ def submit_form(form, extra_values=None, open_http=None):
1059
+ """
1060
+ Helper function to submit a form. Returns a file-like object, as from
1061
+ ``urllib.urlopen()``. This object also has a ``.geturl()`` function,
1062
+ which shows the URL if there were any redirects.
1063
+
1064
+ You can use this like::
1065
+
1066
+ form = doc.forms[0]
1067
+ form.inputs['foo'].value = 'bar' # etc
1068
+ response = form.submit()
1069
+ doc = parse(response)
1070
+ doc.make_links_absolute(response.geturl())
1071
+
1072
+ To change the HTTP requester, pass a function as ``open_http`` keyword
1073
+ argument that opens the URL for you. The function must have the following
1074
+ signature::
1075
+
1076
+ open_http(method, URL, values)
1077
+
1078
+ The action is one of 'GET' or 'POST', the URL is the target URL as a
1079
+ string, and the values are a sequence of ``(name, value)`` tuples with the
1080
+ form data.
1081
+ """
1082
+ values = form.form_values()
1083
+ if extra_values:
1084
+ if hasattr(extra_values, 'items'):
1085
+ extra_values = extra_values.items()
1086
+ values.extend(extra_values)
1087
+ if open_http is None:
1088
+ open_http = open_http_urllib
1089
+ if form.action:
1090
+ url = form.action
1091
+ else:
1092
+ url = form.base_url
1093
+ return open_http(form.method, url, values)
1094
+
1095
+
1096
+ def open_http_urllib(method, url, values):
1097
+ if not url:
1098
+ raise ValueError("cannot submit, no URL provided")
1099
+ ## FIXME: should test that it's not a relative URL or something
1100
+ try:
1101
+ from urllib import urlencode, urlopen
1102
+ except ImportError: # Python 3
1103
+ from urllib.request import urlopen
1104
+ from urllib.parse import urlencode
1105
+ if method == 'GET':
1106
+ if '?' in url:
1107
+ url += '&'
1108
+ else:
1109
+ url += '?'
1110
+ url += urlencode(values)
1111
+ data = None
1112
+ else:
1113
+ data = urlencode(values)
1114
+ if not isinstance(data, bytes):
1115
+ data = data.encode('ASCII')
1116
+ return urlopen(url, data)
1117
+
1118
+
1119
+ class FieldsDict(MutableMapping):
1120
+
1121
+ def __init__(self, inputs):
1122
+ self.inputs = inputs
1123
+ def __getitem__(self, item):
1124
+ return self.inputs[item].value
1125
+ def __setitem__(self, item, value):
1126
+ self.inputs[item].value = value
1127
+ def __delitem__(self, item):
1128
+ raise KeyError(
1129
+ "You cannot remove keys from ElementDict")
1130
+ def keys(self):
1131
+ return self.inputs.keys()
1132
+ def __contains__(self, item):
1133
+ return item in self.inputs
1134
+ def __iter__(self):
1135
+ return iter(self.inputs.keys())
1136
+ def __len__(self):
1137
+ return len(self.inputs)
1138
+
1139
+ def __repr__(self):
1140
+ return '<%s for form %s>' % (
1141
+ self.__class__.__name__,
1142
+ self.inputs.form._name())
1143
+
1144
+
1145
+ class InputGetter:
1146
+
1147
+ """
1148
+ An accessor that represents all the input fields in a form.
1149
+
1150
+ You can get fields by name from this, with
1151
+ ``form.inputs['field_name']``. If there are a set of checkboxes
1152
+ with the same name, they are returned as a list (a `CheckboxGroup`
1153
+ which also allows value setting). Radio inputs are handled
1154
+ similarly. Use ``.keys()`` and ``.items()`` to process all fields
1155
+ in this way.
1156
+
1157
+ You can also iterate over this to get all input elements. This
1158
+ won't return the same thing as if you get all the names, as
1159
+ checkboxes and radio elements are returned individually.
1160
+ """
1161
+
1162
+ def __init__(self, form):
1163
+ self.form = form
1164
+
1165
+ def __repr__(self):
1166
+ return '<%s for form %s>' % (
1167
+ self.__class__.__name__,
1168
+ self.form._name())
1169
+
1170
+ ## FIXME: there should be more methods, and it's unclear if this is
1171
+ ## a dictionary-like object or list-like object
1172
+
1173
+ def __getitem__(self, name):
1174
+ fields = [field for field in self if field.name == name]
1175
+ if not fields:
1176
+ raise KeyError("No input element with the name %r" % name)
1177
+
1178
+ input_type = fields[0].get('type')
1179
+ if input_type == 'radio' and len(fields) > 1:
1180
+ group = RadioGroup(fields)
1181
+ group.name = name
1182
+ return group
1183
+ elif input_type == 'checkbox' and len(fields) > 1:
1184
+ group = CheckboxGroup(fields)
1185
+ group.name = name
1186
+ return group
1187
+ else:
1188
+ # I don't like throwing away elements like this
1189
+ return fields[0]
1190
+
1191
+ def __contains__(self, name):
1192
+ for field in self:
1193
+ if field.name == name:
1194
+ return True
1195
+ return False
1196
+
1197
+ def keys(self):
1198
+ """
1199
+ Returns all unique field names, in document order.
1200
+
1201
+ :return: A list of all unique field names.
1202
+ """
1203
+ names = []
1204
+ seen = {None}
1205
+ for el in self:
1206
+ name = el.name
1207
+ if name not in seen:
1208
+ names.append(name)
1209
+ seen.add(name)
1210
+ return names
1211
+
1212
+ def items(self):
1213
+ """
1214
+ Returns all fields with their names, similar to dict.items().
1215
+
1216
+ :return: A list of (name, field) tuples.
1217
+ """
1218
+ items = []
1219
+ seen = set()
1220
+ for el in self:
1221
+ name = el.name
1222
+ if name not in seen:
1223
+ seen.add(name)
1224
+ items.append((name, self[name]))
1225
+ return items
1226
+
1227
+ def __iter__(self):
1228
+ return self.form.iter('select', 'input', 'textarea')
1229
+
1230
+ def __len__(self):
1231
+ return sum(1 for _ in self)
1232
+
1233
+
1234
+ class InputMixin:
1235
+ """
1236
+ Mix-in for all input elements (input, select, and textarea)
1237
+ """
1238
+ @property
1239
+ def name(self):
1240
+ """
1241
+ Get/set the name of the element
1242
+ """
1243
+ return self.get('name')
1244
+
1245
+ @name.setter
1246
+ def name(self, value):
1247
+ self.set('name', value)
1248
+
1249
+ @name.deleter
1250
+ def name(self):
1251
+ attrib = self.attrib
1252
+ if 'name' in attrib:
1253
+ del attrib['name']
1254
+
1255
+ def __repr__(self):
1256
+ type_name = getattr(self, 'type', None)
1257
+ if type_name:
1258
+ type_name = ' type=%r' % type_name
1259
+ else:
1260
+ type_name = ''
1261
+ return '<%s %x name=%r%s>' % (
1262
+ self.__class__.__name__, id(self), self.name, type_name)
1263
+
1264
+
1265
+ class TextareaElement(InputMixin, HtmlElement):
1266
+ """
1267
+ ``<textarea>`` element. You can get the name with ``.name`` and
1268
+ get/set the value with ``.value``
1269
+ """
1270
+ @property
1271
+ def value(self):
1272
+ """
1273
+ Get/set the value (which is the contents of this element)
1274
+ """
1275
+ content = self.text or ''
1276
+ if self.tag.startswith("{%s}" % XHTML_NAMESPACE):
1277
+ serialisation_method = 'xml'
1278
+ else:
1279
+ serialisation_method = 'html'
1280
+ for el in self:
1281
+ # it's rare that we actually get here, so let's not use ''.join()
1282
+ content += etree.tostring(
1283
+ el, method=serialisation_method, encoding='unicode')
1284
+ return content
1285
+
1286
+ @value.setter
1287
+ def value(self, value):
1288
+ del self[:]
1289
+ self.text = value
1290
+
1291
+ @value.deleter
1292
+ def value(self):
1293
+ self.text = ''
1294
+ del self[:]
1295
+
1296
+
1297
+ HtmlElementClassLookup._default_element_classes['textarea'] = TextareaElement
1298
+
1299
+
1300
+ class SelectElement(InputMixin, HtmlElement):
1301
+ """
1302
+ ``<select>`` element. You can get the name with ``.name``.
1303
+
1304
+ ``.value`` will be the value of the selected option, unless this
1305
+ is a multi-select element (``<select multiple>``), in which case
1306
+ it will be a set-like object. In either case ``.value_options``
1307
+ gives the possible values.
1308
+
1309
+ The boolean attribute ``.multiple`` shows if this is a
1310
+ multi-select.
1311
+ """
1312
+ @property
1313
+ def value(self):
1314
+ """
1315
+ Get/set the value of this select (the selected option).
1316
+
1317
+ If this is a multi-select, this is a set-like object that
1318
+ represents all the selected options.
1319
+ """
1320
+ if self.multiple:
1321
+ return MultipleSelectOptions(self)
1322
+ options = _options_xpath(self)
1323
+
1324
+ try:
1325
+ selected_option = next(el for el in reversed(options) if el.get('selected') is not None)
1326
+ except StopIteration:
1327
+ try:
1328
+ selected_option = next(el for el in options if el.get('disabled') is None)
1329
+ except StopIteration:
1330
+ return None
1331
+ value = selected_option.get('value')
1332
+ if value is None:
1333
+ value = (selected_option.text or '').strip()
1334
+ return value
1335
+
1336
+ @value.setter
1337
+ def value(self, value):
1338
+ if self.multiple:
1339
+ if isinstance(value, str):
1340
+ raise TypeError("You must pass in a sequence")
1341
+ values = self.value
1342
+ values.clear()
1343
+ values.update(value)
1344
+ return
1345
+ checked_option = None
1346
+ if value is not None:
1347
+ for el in _options_xpath(self):
1348
+ opt_value = el.get('value')
1349
+ if opt_value is None:
1350
+ opt_value = (el.text or '').strip()
1351
+ if opt_value == value:
1352
+ checked_option = el
1353
+ break
1354
+ else:
1355
+ raise ValueError(
1356
+ "There is no option with the value of %r" % value)
1357
+ for el in _options_xpath(self):
1358
+ if 'selected' in el.attrib:
1359
+ del el.attrib['selected']
1360
+ if checked_option is not None:
1361
+ checked_option.set('selected', '')
1362
+
1363
+ @value.deleter
1364
+ def value(self):
1365
+ # FIXME: should del be allowed at all?
1366
+ if self.multiple:
1367
+ self.value.clear()
1368
+ else:
1369
+ self.value = None
1370
+
1371
+ @property
1372
+ def value_options(self):
1373
+ """
1374
+ All the possible values this select can have (the ``value``
1375
+ attribute of all the ``<option>`` elements.
1376
+ """
1377
+ options = []
1378
+ for el in _options_xpath(self):
1379
+ value = el.get('value')
1380
+ if value is None:
1381
+ value = (el.text or '').strip()
1382
+ options.append(value)
1383
+ return options
1384
+
1385
+ @property
1386
+ def multiple(self):
1387
+ """
1388
+ Boolean attribute: is there a ``multiple`` attribute on this element.
1389
+ """
1390
+ return 'multiple' in self.attrib
1391
+
1392
+ @multiple.setter
1393
+ def multiple(self, value):
1394
+ if value:
1395
+ self.set('multiple', '')
1396
+ elif 'multiple' in self.attrib:
1397
+ del self.attrib['multiple']
1398
+
1399
+
1400
+ HtmlElementClassLookup._default_element_classes['select'] = SelectElement
1401
+
1402
+
1403
+ class MultipleSelectOptions(SetMixin):
1404
+ """
1405
+ Represents all the selected options in a ``<select multiple>`` element.
1406
+
1407
+ You can add to this set-like option to select an option, or remove
1408
+ to unselect the option.
1409
+ """
1410
+
1411
+ def __init__(self, select):
1412
+ self.select = select
1413
+
1414
+ @property
1415
+ def options(self):
1416
+ """
1417
+ Iterator of all the ``<option>`` elements.
1418
+ """
1419
+ return iter(_options_xpath(self.select))
1420
+
1421
+ def __iter__(self):
1422
+ for option in self.options:
1423
+ if 'selected' in option.attrib:
1424
+ opt_value = option.get('value')
1425
+ if opt_value is None:
1426
+ opt_value = (option.text or '').strip()
1427
+ yield opt_value
1428
+
1429
+ def add(self, item):
1430
+ for option in self.options:
1431
+ opt_value = option.get('value')
1432
+ if opt_value is None:
1433
+ opt_value = (option.text or '').strip()
1434
+ if opt_value == item:
1435
+ option.set('selected', '')
1436
+ break
1437
+ else:
1438
+ raise ValueError(
1439
+ "There is no option with the value %r" % item)
1440
+
1441
+ def remove(self, item):
1442
+ for option in self.options:
1443
+ opt_value = option.get('value')
1444
+ if opt_value is None:
1445
+ opt_value = (option.text or '').strip()
1446
+ if opt_value == item:
1447
+ if 'selected' in option.attrib:
1448
+ del option.attrib['selected']
1449
+ else:
1450
+ raise ValueError(
1451
+ "The option %r is not currently selected" % item)
1452
+ break
1453
+ else:
1454
+ raise ValueError(
1455
+ "There is not option with the value %r" % item)
1456
+
1457
+ def __repr__(self):
1458
+ return '<%s {%s} for select name=%r>' % (
1459
+ self.__class__.__name__,
1460
+ ', '.join([repr(v) for v in self]),
1461
+ self.select.name)
1462
+
1463
+
1464
+ class RadioGroup(list):
1465
+ """
1466
+ This object represents several ``<input type=radio>`` elements
1467
+ that have the same name.
1468
+
1469
+ You can use this like a list, but also use the property
1470
+ ``.value`` to check/uncheck inputs. Also you can use
1471
+ ``.value_options`` to get the possible values.
1472
+ """
1473
+ @property
1474
+ def value(self):
1475
+ """
1476
+ Get/set the value, which checks the radio with that value (and
1477
+ unchecks any other value).
1478
+ """
1479
+ for el in self:
1480
+ if 'checked' in el.attrib:
1481
+ return el.get('value')
1482
+ return None
1483
+
1484
+ @value.setter
1485
+ def value(self, value):
1486
+ checked_option = None
1487
+ if value is not None:
1488
+ for el in self:
1489
+ if el.get('value') == value:
1490
+ checked_option = el
1491
+ break
1492
+ else:
1493
+ raise ValueError("There is no radio input with the value %r" % value)
1494
+ for el in self:
1495
+ if 'checked' in el.attrib:
1496
+ del el.attrib['checked']
1497
+ if checked_option is not None:
1498
+ checked_option.set('checked', '')
1499
+
1500
+ @value.deleter
1501
+ def value(self):
1502
+ self.value = None
1503
+
1504
+ @property
1505
+ def value_options(self):
1506
+ """
1507
+ Returns a list of all the possible values.
1508
+ """
1509
+ return [el.get('value') for el in self]
1510
+
1511
+ def __repr__(self):
1512
+ return '%s(%s)' % (
1513
+ self.__class__.__name__,
1514
+ list.__repr__(self))
1515
+
1516
+
1517
+ class CheckboxGroup(list):
1518
+ """
1519
+ Represents a group of checkboxes (``<input type=checkbox>``) that
1520
+ have the same name.
1521
+
1522
+ In addition to using this like a list, the ``.value`` attribute
1523
+ returns a set-like object that you can add to or remove from to
1524
+ check and uncheck checkboxes. You can also use ``.value_options``
1525
+ to get the possible values.
1526
+ """
1527
+ @property
1528
+ def value(self):
1529
+ """
1530
+ Return a set-like object that can be modified to check or
1531
+ uncheck individual checkboxes according to their value.
1532
+ """
1533
+ return CheckboxValues(self)
1534
+
1535
+ @value.setter
1536
+ def value(self, value):
1537
+ values = self.value
1538
+ values.clear()
1539
+ if not hasattr(value, '__iter__'):
1540
+ raise ValueError(
1541
+ "A CheckboxGroup (name=%r) must be set to a sequence (not %r)"
1542
+ % (self[0].name, value))
1543
+ values.update(value)
1544
+
1545
+ @value.deleter
1546
+ def value(self):
1547
+ self.value.clear()
1548
+
1549
+ @property
1550
+ def value_options(self):
1551
+ """
1552
+ Returns a list of all the possible values.
1553
+ """
1554
+ return [el.get('value') for el in self]
1555
+
1556
+ def __repr__(self):
1557
+ return '%s(%s)' % (
1558
+ self.__class__.__name__, list.__repr__(self))
1559
+
1560
+
1561
+ class CheckboxValues(SetMixin):
1562
+ """
1563
+ Represents the values of the checked checkboxes in a group of
1564
+ checkboxes with the same name.
1565
+ """
1566
+
1567
+ def __init__(self, group):
1568
+ self.group = group
1569
+
1570
+ def __iter__(self):
1571
+ return iter([
1572
+ el.get('value')
1573
+ for el in self.group
1574
+ if 'checked' in el.attrib])
1575
+
1576
+ def add(self, value):
1577
+ for el in self.group:
1578
+ if el.get('value') == value:
1579
+ el.set('checked', '')
1580
+ break
1581
+ else:
1582
+ raise KeyError("No checkbox with value %r" % value)
1583
+
1584
+ def remove(self, value):
1585
+ for el in self.group:
1586
+ if el.get('value') == value:
1587
+ if 'checked' in el.attrib:
1588
+ del el.attrib['checked']
1589
+ else:
1590
+ raise KeyError(
1591
+ "The checkbox with value %r was already unchecked" % value)
1592
+ break
1593
+ else:
1594
+ raise KeyError(
1595
+ "No checkbox with value %r" % value)
1596
+
1597
+ def __repr__(self):
1598
+ return '<%s {%s} for checkboxes name=%r>' % (
1599
+ self.__class__.__name__,
1600
+ ', '.join([repr(v) for v in self]),
1601
+ self.group.name)
1602
+
1603
+
1604
+ class InputElement(InputMixin, HtmlElement):
1605
+ """
1606
+ Represents an ``<input>`` element.
1607
+
1608
+ You can get the type with ``.type`` (which is lower-cased and
1609
+ defaults to ``'text'``).
1610
+
1611
+ Also you can get and set the value with ``.value``
1612
+
1613
+ Checkboxes and radios have the attribute ``input.checkable ==
1614
+ True`` (for all others it is false) and a boolean attribute
1615
+ ``.checked``.
1616
+
1617
+ """
1618
+
1619
+ ## FIXME: I'm a little uncomfortable with the use of .checked
1620
+ @property
1621
+ def value(self):
1622
+ """
1623
+ Get/set the value of this element, using the ``value`` attribute.
1624
+
1625
+ Also, if this is a checkbox and it has no value, this defaults
1626
+ to ``'on'``. If it is a checkbox or radio that is not
1627
+ checked, this returns None.
1628
+ """
1629
+ if self.checkable:
1630
+ if self.checked:
1631
+ return self.get('value') or 'on'
1632
+ else:
1633
+ return None
1634
+ return self.get('value')
1635
+
1636
+ @value.setter
1637
+ def value(self, value):
1638
+ if self.checkable:
1639
+ if not value:
1640
+ self.checked = False
1641
+ else:
1642
+ self.checked = True
1643
+ if isinstance(value, str):
1644
+ self.set('value', value)
1645
+ else:
1646
+ self.set('value', value)
1647
+
1648
+ @value.deleter
1649
+ def value(self):
1650
+ if self.checkable:
1651
+ self.checked = False
1652
+ else:
1653
+ if 'value' in self.attrib:
1654
+ del self.attrib['value']
1655
+
1656
+ @property
1657
+ def type(self):
1658
+ """
1659
+ Return the type of this element (using the type attribute).
1660
+ """
1661
+ return self.get('type', 'text').lower()
1662
+
1663
+ @type.setter
1664
+ def type(self, value):
1665
+ self.set('type', value)
1666
+
1667
+ @property
1668
+ def checkable(self):
1669
+ """
1670
+ Boolean: can this element be checked?
1671
+ """
1672
+ return self.type in ('checkbox', 'radio')
1673
+
1674
+ @property
1675
+ def checked(self):
1676
+ """
1677
+ Boolean attribute to get/set the presence of the ``checked``
1678
+ attribute.
1679
+
1680
+ You can only use this on checkable input types.
1681
+ """
1682
+ if not self.checkable:
1683
+ raise AttributeError('Not a checkable input type')
1684
+ return 'checked' in self.attrib
1685
+
1686
+ @checked.setter
1687
+ def checked(self, value):
1688
+ if not self.checkable:
1689
+ raise AttributeError('Not a checkable input type')
1690
+ if value:
1691
+ self.set('checked', '')
1692
+ else:
1693
+ attrib = self.attrib
1694
+ if 'checked' in attrib:
1695
+ del attrib['checked']
1696
+
1697
+
1698
+ HtmlElementClassLookup._default_element_classes['input'] = InputElement
1699
+
1700
+
1701
+ class LabelElement(HtmlElement):
1702
+ """
1703
+ Represents a ``<label>`` element.
1704
+
1705
+ Label elements are linked to other elements with their ``for``
1706
+ attribute. You can access this element with ``label.for_element``.
1707
+ """
1708
+ @property
1709
+ def for_element(self):
1710
+ """
1711
+ Get/set the element this label points to. Return None if it
1712
+ can't be found.
1713
+ """
1714
+ id = self.get('for')
1715
+ if not id:
1716
+ return None
1717
+ return self.body.get_element_by_id(id)
1718
+
1719
+ @for_element.setter
1720
+ def for_element(self, other):
1721
+ id = other.get('id')
1722
+ if not id:
1723
+ raise TypeError(
1724
+ "Element %r has no id attribute" % other)
1725
+ self.set('for', id)
1726
+
1727
+ @for_element.deleter
1728
+ def for_element(self):
1729
+ attrib = self.attrib
1730
+ if 'id' in attrib:
1731
+ del attrib['id']
1732
+
1733
+
1734
+ HtmlElementClassLookup._default_element_classes['label'] = LabelElement
1735
+
1736
+
1737
+ ############################################################
1738
+ ## Serialization
1739
+ ############################################################
1740
+
1741
+ def html_to_xhtml(html):
1742
+ """Convert all tags in an HTML tree to XHTML by moving them to the
1743
+ XHTML namespace.
1744
+ """
1745
+ try:
1746
+ html = html.getroot()
1747
+ except AttributeError:
1748
+ pass
1749
+ prefix = "{%s}" % XHTML_NAMESPACE
1750
+ for el in html.iter(etree.Element):
1751
+ tag = el.tag
1752
+ if tag[0] != '{':
1753
+ el.tag = prefix + tag
1754
+
1755
+
1756
+ def xhtml_to_html(xhtml):
1757
+ """Convert all tags in an XHTML tree to HTML by removing their
1758
+ XHTML namespace.
1759
+ """
1760
+ try:
1761
+ xhtml = xhtml.getroot()
1762
+ except AttributeError:
1763
+ pass
1764
+ prefix = "{%s}" % XHTML_NAMESPACE
1765
+ prefix_len = len(prefix)
1766
+ for el in xhtml.iter(prefix + "*"):
1767
+ el.tag = el.tag[prefix_len:]
1768
+
1769
+
1770
+ # This isn't a general match, but it's a match for what libxml2
1771
+ # specifically serialises:
1772
+ __str_replace_meta_content_type = re.compile(
1773
+ r'<meta http-equiv="Content-Type"[^>]*>').sub
1774
+ __bytes_replace_meta_content_type = re.compile(
1775
+ br'<meta http-equiv="Content-Type"[^>]*>').sub
1776
+
1777
+
1778
+ def tostring(doc, pretty_print=False, include_meta_content_type=False,
1779
+ encoding=None, method="html", with_tail=True, doctype=None):
1780
+ """Return an HTML string representation of the document.
1781
+
1782
+ Note: if include_meta_content_type is true this will create a
1783
+ ``<meta http-equiv="Content-Type" ...>`` tag in the head;
1784
+ regardless of the value of include_meta_content_type any existing
1785
+ ``<meta http-equiv="Content-Type" ...>`` tag will be removed
1786
+
1787
+ The ``encoding`` argument controls the output encoding (defaults to
1788
+ ASCII, with &#...; character references for any characters outside
1789
+ of ASCII). Note that you can pass the name ``'unicode'`` as
1790
+ ``encoding`` argument to serialise to a Unicode string.
1791
+
1792
+ The ``method`` argument defines the output method. It defaults to
1793
+ 'html', but can also be 'xml' for xhtml output, or 'text' to
1794
+ serialise to plain text without markup.
1795
+
1796
+ To leave out the tail text of the top-level element that is being
1797
+ serialised, pass ``with_tail=False``.
1798
+
1799
+ The ``doctype`` option allows passing in a plain string that will
1800
+ be serialised before the XML tree. Note that passing in non
1801
+ well-formed content here will make the XML output non well-formed.
1802
+ Also, an existing doctype in the document tree will not be removed
1803
+ when serialising an ElementTree instance.
1804
+
1805
+ Example::
1806
+
1807
+ >>> from lxml import html
1808
+ >>> root = html.fragment_fromstring('<p>Hello<br>world!</p>')
1809
+
1810
+ >>> html.tostring(root)
1811
+ b'<p>Hello<br>world!</p>'
1812
+ >>> html.tostring(root, method='html')
1813
+ b'<p>Hello<br>world!</p>'
1814
+
1815
+ >>> html.tostring(root, method='xml')
1816
+ b'<p>Hello<br/>world!</p>'
1817
+
1818
+ >>> html.tostring(root, method='text')
1819
+ b'Helloworld!'
1820
+
1821
+ >>> html.tostring(root, method='text', encoding='unicode')
1822
+ u'Helloworld!'
1823
+
1824
+ >>> root = html.fragment_fromstring('<div><p>Hello<br>world!</p>TAIL</div>')
1825
+ >>> html.tostring(root[0], method='text', encoding='unicode')
1826
+ u'Helloworld!TAIL'
1827
+
1828
+ >>> html.tostring(root[0], method='text', encoding='unicode', with_tail=False)
1829
+ u'Helloworld!'
1830
+
1831
+ >>> doc = html.document_fromstring('<p>Hello<br>world!</p>')
1832
+ >>> html.tostring(doc, method='html', encoding='unicode')
1833
+ u'<html><body><p>Hello<br>world!</p></body></html>'
1834
+
1835
+ >>> print(html.tostring(doc, method='html', encoding='unicode',
1836
+ ... doctype='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'
1837
+ ... ' "http://www.w3.org/TR/html4/strict.dtd">'))
1838
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
1839
+ <html><body><p>Hello<br>world!</p></body></html>
1840
+ """
1841
+ html = etree.tostring(doc, method=method, pretty_print=pretty_print,
1842
+ encoding=encoding, with_tail=with_tail,
1843
+ doctype=doctype)
1844
+ if method == 'html' and not include_meta_content_type:
1845
+ if isinstance(html, str):
1846
+ html = __str_replace_meta_content_type('', html)
1847
+ else:
1848
+ html = __bytes_replace_meta_content_type(b'', html)
1849
+ return html
1850
+
1851
+
1852
+ tostring.__doc__ = __fix_docstring(tostring.__doc__)
1853
+
1854
+
1855
+ def open_in_browser(doc, encoding=None):
1856
+ """
1857
+ Open the HTML document in a web browser, saving it to a temporary
1858
+ file to open it. Note that this does not delete the file after
1859
+ use. This is mainly meant for debugging.
1860
+ """
1861
+ import os
1862
+ import webbrowser
1863
+ import tempfile
1864
+ if not isinstance(doc, etree._ElementTree):
1865
+ doc = etree.ElementTree(doc)
1866
+ handle, fn = tempfile.mkstemp(suffix='.html')
1867
+ f = os.fdopen(handle, 'wb')
1868
+ try:
1869
+ doc.write(f, method="html", encoding=encoding or doc.docinfo.encoding or "UTF-8")
1870
+ finally:
1871
+ # we leak the file itself here, but we should at least close it
1872
+ f.close()
1873
+ url = 'file://' + fn.replace(os.path.sep, '/')
1874
+ print(url)
1875
+ webbrowser.open(url)
1876
+
1877
+
1878
+ ################################################################################
1879
+ # configure Element class lookup
1880
+ ################################################################################
1881
+
1882
+ class HTMLParser(etree.HTMLParser):
1883
+ """An HTML parser that is configured to return lxml.html Element
1884
+ objects.
1885
+ """
1886
+ def __init__(self, **kwargs):
1887
+ super().__init__(**kwargs)
1888
+ self.set_element_class_lookup(HtmlElementClassLookup())
1889
+
1890
+
1891
+ class XHTMLParser(etree.XMLParser):
1892
+ """An XML parser that is configured to return lxml.html Element
1893
+ objects.
1894
+
1895
+ Note that this parser is not really XHTML aware unless you let it
1896
+ load a DTD that declares the HTML entities. To do this, make sure
1897
+ you have the XHTML DTDs installed in your catalogs, and create the
1898
+ parser like this::
1899
+
1900
+ >>> parser = XHTMLParser(load_dtd=True)
1901
+
1902
+ If you additionally want to validate the document, use this::
1903
+
1904
+ >>> parser = XHTMLParser(dtd_validation=True)
1905
+
1906
+ For catalog support, see http://www.xmlsoft.org/catalog.html.
1907
+ """
1908
+ def __init__(self, **kwargs):
1909
+ super().__init__(**kwargs)
1910
+ self.set_element_class_lookup(HtmlElementClassLookup())
1911
+
1912
+
1913
+ def Element(*args, **kw):
1914
+ """Create a new HTML Element.
1915
+
1916
+ This can also be used for XHTML documents.
1917
+ """
1918
+ v = html_parser.makeelement(*args, **kw)
1919
+ return v
1920
+
1921
+
1922
+ html_parser = HTMLParser()
1923
+ xhtml_parser = XHTMLParser()
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/ElementSoup.cpython-310.pyc ADDED
Binary file (519 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (56 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/_html5builder.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc ADDED
Binary file (2.95 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/clean.cpython-310.pyc ADDED
Binary file (550 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/defs.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/formfill.cpython-310.pyc ADDED
Binary file (7.38 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/html5parser.cpython-310.pyc ADDED
Binary file (6.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc ADDED
Binary file (8.01 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/__pycache__/usedoctest.cpython-310.pyc ADDED
Binary file (445 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/_diffcommand.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import optparse
2
+ import sys
3
+ import re
4
+ import os
5
+ from .diff import htmldiff
6
+
7
+ description = """\
8
+ """
9
+
10
+ parser = optparse.OptionParser(
11
+ usage="%prog [OPTIONS] FILE1 FILE2\n"
12
+ "%prog --annotate [OPTIONS] INFO1 FILE1 INFO2 FILE2 ...",
13
+ description=description,
14
+ )
15
+
16
+ parser.add_option(
17
+ '-o', '--output',
18
+ metavar="FILE",
19
+ dest="output",
20
+ default="-",
21
+ help="File to write the difference to",
22
+ )
23
+
24
+ parser.add_option(
25
+ '-a', '--annotation',
26
+ action="store_true",
27
+ dest="annotation",
28
+ help="Do an annotation")
29
+
30
+ def main(args=None):
31
+ if args is None:
32
+ args = sys.argv[1:]
33
+ options, args = parser.parse_args(args)
34
+ if options.annotation:
35
+ return annotate(options, args)
36
+ if len(args) != 2:
37
+ print('Error: you must give two files')
38
+ parser.print_help()
39
+ sys.exit(1)
40
+ file1, file2 = args
41
+ input1 = read_file(file1)
42
+ input2 = read_file(file2)
43
+ body1 = split_body(input1)[1]
44
+ pre, body2, post = split_body(input2)
45
+ result = htmldiff(body1, body2)
46
+ result = pre + result + post
47
+ if options.output == '-':
48
+ if not result.endswith('\n'):
49
+ result += '\n'
50
+ sys.stdout.write(result)
51
+ else:
52
+ with open(options.output, 'wb') as f:
53
+ f.write(result)
54
+
55
+ def read_file(filename):
56
+ if filename == '-':
57
+ c = sys.stdin.read()
58
+ elif not os.path.exists(filename):
59
+ raise OSError(
60
+ "Input file %s does not exist" % filename)
61
+ else:
62
+ with open(filename, 'rb') as f:
63
+ c = f.read()
64
+ return c
65
+
66
+ body_start_re = re.compile(
67
+ r"<body.*?>", re.I|re.S)
68
+ body_end_re = re.compile(
69
+ r"</body.*?>", re.I|re.S)
70
+
71
+ def split_body(html):
72
+ pre = post = ''
73
+ match = body_start_re.search(html)
74
+ if match:
75
+ pre = html[:match.end()]
76
+ html = html[match.end():]
77
+ match = body_end_re.search(html)
78
+ if match:
79
+ post = html[match.start():]
80
+ html = html[:match.start()]
81
+ return pre, html, post
82
+
83
+ def annotate(options, args):
84
+ print("Not yet implemented")
85
+ sys.exit(1)
86
+
env-llmeval/lib/python3.10/site-packages/lxml/html/_html5builder.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Legacy module - don't use in new code!
3
+
4
+ html5lib now has its own proper implementation.
5
+
6
+ This module implements a tree builder for html5lib that generates lxml
7
+ html element trees. This module uses camelCase as it follows the
8
+ html5lib style guide.
9
+ """
10
+
11
+ from html5lib.treebuilders import _base, etree as etree_builders
12
+ from lxml import html, etree
13
+
14
+
15
+ class DocumentType:
16
+
17
+ def __init__(self, name, publicId, systemId):
18
+ self.name = name
19
+ self.publicId = publicId
20
+ self.systemId = systemId
21
+
22
+ class Document:
23
+
24
+ def __init__(self):
25
+ self._elementTree = None
26
+ self.childNodes = []
27
+
28
+ def appendChild(self, element):
29
+ self._elementTree.getroot().addnext(element._element)
30
+
31
+
32
+ class TreeBuilder(_base.TreeBuilder):
33
+ documentClass = Document
34
+ doctypeClass = DocumentType
35
+ elementClass = None
36
+ commentClass = None
37
+ fragmentClass = Document
38
+
39
+ def __init__(self, *args, **kwargs):
40
+ html_builder = etree_builders.getETreeModule(html, fullTree=False)
41
+ etree_builder = etree_builders.getETreeModule(etree, fullTree=False)
42
+ self.elementClass = html_builder.Element
43
+ self.commentClass = etree_builder.Comment
44
+ _base.TreeBuilder.__init__(self, *args, **kwargs)
45
+
46
+ def reset(self):
47
+ _base.TreeBuilder.reset(self)
48
+ self.rootInserted = False
49
+ self.initialComments = []
50
+ self.doctype = None
51
+
52
+ def getDocument(self):
53
+ return self.document._elementTree
54
+
55
+ def getFragment(self):
56
+ fragment = []
57
+ element = self.openElements[0]._element
58
+ if element.text:
59
+ fragment.append(element.text)
60
+ fragment.extend(element.getchildren())
61
+ if element.tail:
62
+ fragment.append(element.tail)
63
+ return fragment
64
+
65
+ def insertDoctype(self, name, publicId, systemId):
66
+ doctype = self.doctypeClass(name, publicId, systemId)
67
+ self.doctype = doctype
68
+
69
+ def insertComment(self, data, parent=None):
70
+ if not self.rootInserted:
71
+ self.initialComments.append(data)
72
+ else:
73
+ _base.TreeBuilder.insertComment(self, data, parent)
74
+
75
+ def insertRoot(self, name):
76
+ buf = []
77
+ if self.doctype and self.doctype.name:
78
+ buf.append('<!DOCTYPE %s' % self.doctype.name)
79
+ if self.doctype.publicId is not None or self.doctype.systemId is not None:
80
+ buf.append(' PUBLIC "%s" "%s"' % (self.doctype.publicId,
81
+ self.doctype.systemId))
82
+ buf.append('>')
83
+ buf.append('<html></html>')
84
+ root = html.fromstring(''.join(buf))
85
+
86
+ # Append the initial comments:
87
+ for comment in self.initialComments:
88
+ root.addprevious(etree.Comment(comment))
89
+
90
+ # Create the root document and add the ElementTree to it
91
+ self.document = self.documentClass()
92
+ self.document._elementTree = root.getroottree()
93
+
94
+ # Add the root element to the internal child/open data structures
95
+ root_element = self.elementClass(name)
96
+ root_element._element = root
97
+ self.document.childNodes.append(root_element)
98
+ self.openElements.append(root_element)
99
+
100
+ self.rootInserted = True
env-llmeval/lib/python3.10/site-packages/lxml/html/_setmixin.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ from collections.abc import MutableSet
3
+ except ImportError:
4
+ from collections.abc import MutableSet
5
+
6
+
7
+ class SetMixin(MutableSet):
8
+
9
+ """
10
+ Mix-in for sets. You must define __iter__, add, remove
11
+ """
12
+
13
+ def __len__(self):
14
+ length = 0
15
+ for item in self:
16
+ length += 1
17
+ return length
18
+
19
+ def __contains__(self, item):
20
+ for has_item in self:
21
+ if item == has_item:
22
+ return True
23
+ return False
24
+
25
+ issubset = MutableSet.__le__
26
+ issuperset = MutableSet.__ge__
27
+
28
+ union = MutableSet.__or__
29
+ intersection = MutableSet.__and__
30
+ difference = MutableSet.__sub__
31
+ symmetric_difference = MutableSet.__xor__
32
+
33
+ def copy(self):
34
+ return set(self)
35
+
36
+ def update(self, other):
37
+ self |= other
38
+
39
+ def intersection_update(self, other):
40
+ self &= other
41
+
42
+ def difference_update(self, other):
43
+ self -= other
44
+
45
+ def symmetric_difference_update(self, other):
46
+ self ^= other
47
+
48
+ def discard(self, item):
49
+ try:
50
+ self.remove(item)
51
+ except KeyError:
52
+ pass
53
+
54
+ @classmethod
55
+ def _from_iterable(cls, it):
56
+ return set(it)
env-llmeval/lib/python3.10/site-packages/lxml/html/builder.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------------------
2
+ # The ElementTree toolkit is
3
+ # Copyright (c) 1999-2004 by Fredrik Lundh
4
+ # --------------------------------------------------------------------
5
+
6
+ """
7
+ A set of HTML generator tags for building HTML documents.
8
+
9
+ Usage::
10
+
11
+ >>> from lxml.html.builder import *
12
+ >>> html = HTML(
13
+ ... HEAD( TITLE("Hello World") ),
14
+ ... BODY( CLASS("main"),
15
+ ... H1("Hello World !")
16
+ ... )
17
+ ... )
18
+
19
+ >>> import lxml.etree
20
+ >>> print lxml.etree.tostring(html, pretty_print=True)
21
+ <html>
22
+ <head>
23
+ <title>Hello World</title>
24
+ </head>
25
+ <body class="main">
26
+ <h1>Hello World !</h1>
27
+ </body>
28
+ </html>
29
+
30
+ """
31
+
32
+ from lxml.builder import ElementMaker
33
+ from lxml.html import html_parser
34
+
35
+ E = ElementMaker(makeelement=html_parser.makeelement)
36
+
37
+ # elements
38
+ A = E.a #: anchor
39
+ ABBR = E.abbr #: abbreviated form (e.g., WWW, HTTP, etc.)
40
+ ACRONYM = E.acronym #:
41
+ ADDRESS = E.address #: information on author
42
+ APPLET = E.applet #: Java applet (DEPRECATED)
43
+ AREA = E.area #: client-side image map area
44
+ B = E.b #: bold text style
45
+ BASE = E.base #: document base URI
46
+ BASEFONT = E.basefont #: base font size (DEPRECATED)
47
+ BDO = E.bdo #: I18N BiDi over-ride
48
+ BIG = E.big #: large text style
49
+ BLOCKQUOTE = E.blockquote #: long quotation
50
+ BODY = E.body #: document body
51
+ BR = E.br #: forced line break
52
+ BUTTON = E.button #: push button
53
+ CAPTION = E.caption #: table caption
54
+ CENTER = E.center #: shorthand for DIV align=center (DEPRECATED)
55
+ CITE = E.cite #: citation
56
+ CODE = E.code #: computer code fragment
57
+ COL = E.col #: table column
58
+ COLGROUP = E.colgroup #: table column group
59
+ DD = E.dd #: definition description
60
+ DEL = getattr(E, 'del') #: deleted text
61
+ DFN = E.dfn #: instance definition
62
+ DIR = E.dir #: directory list (DEPRECATED)
63
+ DIV = E.div #: generic language/style container
64
+ DL = E.dl #: definition list
65
+ DT = E.dt #: definition term
66
+ EM = E.em #: emphasis
67
+ FIELDSET = E.fieldset #: form control group
68
+ FONT = E.font #: local change to font (DEPRECATED)
69
+ FORM = E.form #: interactive form
70
+ FRAME = E.frame #: subwindow
71
+ FRAMESET = E.frameset #: window subdivision
72
+ H1 = E.h1 #: heading
73
+ H2 = E.h2 #: heading
74
+ H3 = E.h3 #: heading
75
+ H4 = E.h4 #: heading
76
+ H5 = E.h5 #: heading
77
+ H6 = E.h6 #: heading
78
+ HEAD = E.head #: document head
79
+ HR = E.hr #: horizontal rule
80
+ HTML = E.html #: document root element
81
+ I = E.i #: italic text style
82
+ IFRAME = E.iframe #: inline subwindow
83
+ IMG = E.img #: Embedded image
84
+ INPUT = E.input #: form control
85
+ INS = E.ins #: inserted text
86
+ ISINDEX = E.isindex #: single line prompt (DEPRECATED)
87
+ KBD = E.kbd #: text to be entered by the user
88
+ LABEL = E.label #: form field label text
89
+ LEGEND = E.legend #: fieldset legend
90
+ LI = E.li #: list item
91
+ LINK = E.link #: a media-independent link
92
+ MAP = E.map #: client-side image map
93
+ MENU = E.menu #: menu list (DEPRECATED)
94
+ META = E.meta #: generic metainformation
95
+ NOFRAMES = E.noframes #: alternate content container for non frame-based rendering
96
+ NOSCRIPT = E.noscript #: alternate content container for non script-based rendering
97
+ OBJECT = E.object #: generic embedded object
98
+ OL = E.ol #: ordered list
99
+ OPTGROUP = E.optgroup #: option group
100
+ OPTION = E.option #: selectable choice
101
+ P = E.p #: paragraph
102
+ PARAM = E.param #: named property value
103
+ PRE = E.pre #: preformatted text
104
+ Q = E.q #: short inline quotation
105
+ S = E.s #: strike-through text style (DEPRECATED)
106
+ SAMP = E.samp #: sample program output, scripts, etc.
107
+ SCRIPT = E.script #: script statements
108
+ SELECT = E.select #: option selector
109
+ SMALL = E.small #: small text style
110
+ SPAN = E.span #: generic language/style container
111
+ STRIKE = E.strike #: strike-through text (DEPRECATED)
112
+ STRONG = E.strong #: strong emphasis
113
+ STYLE = E.style #: style info
114
+ SUB = E.sub #: subscript
115
+ SUP = E.sup #: superscript
116
+ TABLE = E.table #:
117
+ TBODY = E.tbody #: table body
118
+ TD = E.td #: table data cell
119
+ TEXTAREA = E.textarea #: multi-line text field
120
+ TFOOT = E.tfoot #: table footer
121
+ TH = E.th #: table header cell
122
+ THEAD = E.thead #: table header
123
+ TITLE = E.title #: document title
124
+ TR = E.tr #: table row
125
+ TT = E.tt #: teletype or monospaced text style
126
+ U = E.u #: underlined text style (DEPRECATED)
127
+ UL = E.ul #: unordered list
128
+ VAR = E.var #: instance of a variable or program argument
129
+
130
+ # attributes (only reserved words are included here)
131
+ ATTR = dict
132
+ def CLASS(v): return {'class': v}
133
+ def FOR(v): return {'for': v}
env-llmeval/lib/python3.10/site-packages/lxml/html/clean.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3str
2
+
3
+ """Backward-compatibility module for lxml_html_clean"""
4
+
5
+ try:
6
+ from lxml_html_clean import *
7
+
8
+ __all__ = [
9
+ "clean_html",
10
+ "clean",
11
+ "Cleaner",
12
+ "autolink",
13
+ "autolink_html",
14
+ "word_break",
15
+ "word_break_html",
16
+ ]
17
+ except ImportError:
18
+ raise ImportError(
19
+ "lxml.html.clean module is now a separate project lxml_html_clean.\n"
20
+ "Install lxml[html_clean] or lxml_html_clean directly."
21
+ ) from None
env-llmeval/lib/python3.10/site-packages/lxml/html/defs.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FIXME: this should all be confirmed against what a DTD says
2
+ # (probably in a test; this may not match the DTD exactly, but we
3
+ # should document just how it differs).
4
+
5
+ """
6
+ Data taken from https://www.w3.org/TR/html401/index/elements.html
7
+ and https://www.w3.org/community/webed/wiki/HTML/New_HTML5_Elements
8
+ for html5_tags.
9
+ """
10
+
11
+ empty_tags = frozenset([
12
+ 'area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
13
+ 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source', 'track'])
14
+
15
+ deprecated_tags = frozenset([
16
+ 'applet', 'basefont', 'center', 'dir', 'font', 'isindex',
17
+ 'menu', 's', 'strike', 'u'])
18
+
19
+ # archive actually takes a space-separated list of URIs
20
+ link_attrs = frozenset([
21
+ 'action', 'archive', 'background', 'cite', 'classid',
22
+ 'codebase', 'data', 'href', 'longdesc', 'profile', 'src',
23
+ 'usemap',
24
+ # Not standard:
25
+ 'dynsrc', 'lowsrc',
26
+ # HTML5 formaction
27
+ 'formaction'
28
+ ])
29
+
30
+ # Not in the HTML 4 spec:
31
+ # onerror, onresize
32
+ event_attrs = frozenset([
33
+ 'onblur', 'onchange', 'onclick', 'ondblclick', 'onerror',
34
+ 'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onload',
35
+ 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',
36
+ 'onmouseup', 'onreset', 'onresize', 'onselect', 'onsubmit',
37
+ 'onunload',
38
+ ])
39
+
40
+ safe_attrs = frozenset([
41
+ 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align',
42
+ 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff',
43
+ 'charset', 'checked', 'cite', 'class', 'clear', 'cols', 'colspan',
44
+ 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype',
45
+ 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id',
46
+ 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method',
47
+ 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly',
48
+ 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape',
49
+ 'size', 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title',
50
+ 'type', 'usemap', 'valign', 'value', 'vspace', 'width'])
51
+
52
+ # From http://htmlhelp.com/reference/html40/olist.html
53
+ top_level_tags = frozenset([
54
+ 'html', 'head', 'body', 'frameset',
55
+ ])
56
+
57
+ head_tags = frozenset([
58
+ 'base', 'isindex', 'link', 'meta', 'script', 'style', 'title',
59
+ ])
60
+
61
+ general_block_tags = frozenset([
62
+ 'address',
63
+ 'blockquote',
64
+ 'center',
65
+ 'del',
66
+ 'div',
67
+ 'h1',
68
+ 'h2',
69
+ 'h3',
70
+ 'h4',
71
+ 'h5',
72
+ 'h6',
73
+ 'hr',
74
+ 'ins',
75
+ 'isindex',
76
+ 'noscript',
77
+ 'p',
78
+ 'pre',
79
+ ])
80
+
81
+ list_tags = frozenset([
82
+ 'dir', 'dl', 'dt', 'dd', 'li', 'menu', 'ol', 'ul',
83
+ ])
84
+
85
+ table_tags = frozenset([
86
+ 'table', 'caption', 'colgroup', 'col',
87
+ 'thead', 'tfoot', 'tbody', 'tr', 'td', 'th',
88
+ ])
89
+
90
+ # just this one from
91
+ # http://www.georgehernandez.com/h/XComputers/HTML/2BlockLevel.htm
92
+ block_tags = general_block_tags | list_tags | table_tags | frozenset([
93
+ # Partial form tags
94
+ 'fieldset', 'form', 'legend', 'optgroup', 'option',
95
+ ])
96
+
97
+ form_tags = frozenset([
98
+ 'form', 'button', 'fieldset', 'legend', 'input', 'label',
99
+ 'select', 'optgroup', 'option', 'textarea',
100
+ ])
101
+
102
+ special_inline_tags = frozenset([
103
+ 'a', 'applet', 'basefont', 'bdo', 'br', 'embed', 'font', 'iframe',
104
+ 'img', 'map', 'area', 'object', 'param', 'q', 'script',
105
+ 'span', 'sub', 'sup',
106
+ ])
107
+
108
+ phrase_tags = frozenset([
109
+ 'abbr', 'acronym', 'cite', 'code', 'del', 'dfn', 'em',
110
+ 'ins', 'kbd', 'samp', 'strong', 'var',
111
+ ])
112
+
113
+ font_style_tags = frozenset([
114
+ 'b', 'big', 'i', 's', 'small', 'strike', 'tt', 'u',
115
+ ])
116
+
117
+ frame_tags = frozenset([
118
+ 'frameset', 'frame', 'noframes',
119
+ ])
120
+
121
+ html5_tags = frozenset([
122
+ 'article', 'aside', 'audio', 'canvas', 'command', 'datalist',
123
+ 'details', 'embed', 'figcaption', 'figure', 'footer', 'header',
124
+ 'hgroup', 'keygen', 'mark', 'math', 'meter', 'nav', 'output',
125
+ 'progress', 'rp', 'rt', 'ruby', 'section', 'source', 'summary',
126
+ 'svg', 'time', 'track', 'video', 'wbr'
127
+ ])
128
+
129
+ # These tags aren't standard
130
+ nonstandard_tags = frozenset(['blink', 'marquee'])
131
+
132
+
133
+ tags = (top_level_tags | head_tags | general_block_tags | list_tags
134
+ | table_tags | form_tags | special_inline_tags | phrase_tags
135
+ | font_style_tags | nonstandard_tags | html5_tags)
env-llmeval/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (373 kB). View file
 
env-llmeval/lib/python3.10/site-packages/lxml/html/diff.py ADDED
@@ -0,0 +1,878 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+
3
+
4
+ import difflib
5
+ from lxml import etree
6
+ from lxml.html import fragment_fromstring
7
+ import re
8
+
9
+ __all__ = ['html_annotate', 'htmldiff']
10
+
11
+ try:
12
+ from html import escape as html_escape
13
+ except ImportError:
14
+ from cgi import escape as html_escape
15
+ try:
16
+ _unicode = unicode
17
+ except NameError:
18
+ # Python 3
19
+ _unicode = str
20
+ try:
21
+ basestring
22
+ except NameError:
23
+ # Python 3
24
+ basestring = str
25
+
26
+ ############################################################
27
+ ## Annotation
28
+ ############################################################
29
+
30
+ def default_markup(text, version):
31
+ return '<span title="%s">%s</span>' % (
32
+ html_escape(_unicode(version), 1), text)
33
+
34
+ def html_annotate(doclist, markup=default_markup):
35
+ """
36
+ doclist should be ordered from oldest to newest, like::
37
+
38
+ >>> version1 = 'Hello World'
39
+ >>> version2 = 'Goodbye World'
40
+ >>> print(html_annotate([(version1, 'version 1'),
41
+ ... (version2, 'version 2')]))
42
+ <span title="version 2">Goodbye</span> <span title="version 1">World</span>
43
+
44
+ The documents must be *fragments* (str/UTF8 or unicode), not
45
+ complete documents
46
+
47
+ The markup argument is a function to markup the spans of words.
48
+ This function is called like markup('Hello', 'version 2'), and
49
+ returns HTML. The first argument is text and never includes any
50
+ markup. The default uses a span with a title:
51
+
52
+ >>> print(default_markup('Some Text', 'by Joe'))
53
+ <span title="by Joe">Some Text</span>
54
+ """
55
+ # The basic strategy we have is to split the documents up into
56
+ # logical tokens (which are words with attached markup). We then
57
+ # do diffs of each of the versions to track when a token first
58
+ # appeared in the document; the annotation attached to the token
59
+ # is the version where it first appeared.
60
+ tokenlist = [tokenize_annotated(doc, version)
61
+ for doc, version in doclist]
62
+ cur_tokens = tokenlist[0]
63
+ for tokens in tokenlist[1:]:
64
+ html_annotate_merge_annotations(cur_tokens, tokens)
65
+ cur_tokens = tokens
66
+
67
+ # After we've tracked all the tokens, we can combine spans of text
68
+ # that are adjacent and have the same annotation
69
+ cur_tokens = compress_tokens(cur_tokens)
70
+ # And finally add markup
71
+ result = markup_serialize_tokens(cur_tokens, markup)
72
+ return ''.join(result).strip()
73
+
74
+ def tokenize_annotated(doc, annotation):
75
+ """Tokenize a document and add an annotation attribute to each token
76
+ """
77
+ tokens = tokenize(doc, include_hrefs=False)
78
+ for tok in tokens:
79
+ tok.annotation = annotation
80
+ return tokens
81
+
82
+ def html_annotate_merge_annotations(tokens_old, tokens_new):
83
+ """Merge the annotations from tokens_old into tokens_new, when the
84
+ tokens in the new document already existed in the old document.
85
+ """
86
+ s = InsensitiveSequenceMatcher(a=tokens_old, b=tokens_new)
87
+ commands = s.get_opcodes()
88
+
89
+ for command, i1, i2, j1, j2 in commands:
90
+ if command == 'equal':
91
+ eq_old = tokens_old[i1:i2]
92
+ eq_new = tokens_new[j1:j2]
93
+ copy_annotations(eq_old, eq_new)
94
+
95
+ def copy_annotations(src, dest):
96
+ """
97
+ Copy annotations from the tokens listed in src to the tokens in dest
98
+ """
99
+ assert len(src) == len(dest)
100
+ for src_tok, dest_tok in zip(src, dest):
101
+ dest_tok.annotation = src_tok.annotation
102
+
103
+ def compress_tokens(tokens):
104
+ """
105
+ Combine adjacent tokens when there is no HTML between the tokens,
106
+ and they share an annotation
107
+ """
108
+ result = [tokens[0]]
109
+ for tok in tokens[1:]:
110
+ if (not result[-1].post_tags and
111
+ not tok.pre_tags and
112
+ result[-1].annotation == tok.annotation):
113
+ compress_merge_back(result, tok)
114
+ else:
115
+ result.append(tok)
116
+ return result
117
+
118
+ def compress_merge_back(tokens, tok):
119
+ """ Merge tok into the last element of tokens (modifying the list of
120
+ tokens in-place). """
121
+ last = tokens[-1]
122
+ if type(last) is not token or type(tok) is not token:
123
+ tokens.append(tok)
124
+ else:
125
+ text = _unicode(last)
126
+ if last.trailing_whitespace:
127
+ text += last.trailing_whitespace
128
+ text += tok
129
+ merged = token(text,
130
+ pre_tags=last.pre_tags,
131
+ post_tags=tok.post_tags,
132
+ trailing_whitespace=tok.trailing_whitespace)
133
+ merged.annotation = last.annotation
134
+ tokens[-1] = merged
135
+
136
+ def markup_serialize_tokens(tokens, markup_func):
137
+ """
138
+ Serialize the list of tokens into a list of text chunks, calling
139
+ markup_func around text to add annotations.
140
+ """
141
+ for token in tokens:
142
+ yield from token.pre_tags
143
+ html = token.html()
144
+ html = markup_func(html, token.annotation)
145
+ if token.trailing_whitespace:
146
+ html += token.trailing_whitespace
147
+ yield html
148
+ yield from token.post_tags
149
+
150
+
151
+ ############################################################
152
+ ## HTML Diffs
153
+ ############################################################
154
+
155
+ def htmldiff(old_html, new_html):
156
+ ## FIXME: this should take parsed documents too, and use their body
157
+ ## or other content.
158
+ """ Do a diff of the old and new document. The documents are HTML
159
+ *fragments* (str/UTF8 or unicode), they are not complete documents
160
+ (i.e., no <html> tag).
161
+
162
+ Returns HTML with <ins> and <del> tags added around the
163
+ appropriate text.
164
+
165
+ Markup is generally ignored, with the markup from new_html
166
+ preserved, and possibly some markup from old_html (though it is
167
+ considered acceptable to lose some of the old markup). Only the
168
+ words in the HTML are diffed. The exception is <img> tags, which
169
+ are treated like words, and the href attribute of <a> tags, which
170
+ are noted inside the tag itself when there are changes.
171
+ """
172
+ old_html_tokens = tokenize(old_html)
173
+ new_html_tokens = tokenize(new_html)
174
+ result = htmldiff_tokens(old_html_tokens, new_html_tokens)
175
+ result = ''.join(result).strip()
176
+ return fixup_ins_del_tags(result)
177
+
178
+ def htmldiff_tokens(html1_tokens, html2_tokens):
179
+ """ Does a diff on the tokens themselves, returning a list of text
180
+ chunks (not tokens).
181
+ """
182
+ # There are several passes as we do the differences. The tokens
183
+ # isolate the portion of the content we care to diff; difflib does
184
+ # all the actual hard work at that point.
185
+ #
186
+ # Then we must create a valid document from pieces of both the old
187
+ # document and the new document. We generally prefer to take
188
+ # markup from the new document, and only do a best effort attempt
189
+ # to keep markup from the old document; anything that we can't
190
+ # resolve we throw away. Also we try to put the deletes as close
191
+ # to the location where we think they would have been -- because
192
+ # we are only keeping the markup from the new document, it can be
193
+ # fuzzy where in the new document the old text would have gone.
194
+ # Again we just do a best effort attempt.
195
+ s = InsensitiveSequenceMatcher(a=html1_tokens, b=html2_tokens)
196
+ commands = s.get_opcodes()
197
+ result = []
198
+ for command, i1, i2, j1, j2 in commands:
199
+ if command == 'equal':
200
+ result.extend(expand_tokens(html2_tokens[j1:j2], equal=True))
201
+ continue
202
+ if command == 'insert' or command == 'replace':
203
+ ins_tokens = expand_tokens(html2_tokens[j1:j2])
204
+ merge_insert(ins_tokens, result)
205
+ if command == 'delete' or command == 'replace':
206
+ del_tokens = expand_tokens(html1_tokens[i1:i2])
207
+ merge_delete(del_tokens, result)
208
+ # If deletes were inserted directly as <del> then we'd have an
209
+ # invalid document at this point. Instead we put in special
210
+ # markers, and when the complete diffed document has been created
211
+ # we try to move the deletes around and resolve any problems.
212
+ result = cleanup_delete(result)
213
+
214
+ return result
215
+
216
+ def expand_tokens(tokens, equal=False):
217
+ """Given a list of tokens, return a generator of the chunks of
218
+ text for the data in the tokens.
219
+ """
220
+ for token in tokens:
221
+ yield from token.pre_tags
222
+ if not equal or not token.hide_when_equal:
223
+ if token.trailing_whitespace:
224
+ yield token.html() + token.trailing_whitespace
225
+ else:
226
+ yield token.html()
227
+ yield from token.post_tags
228
+
229
+ def merge_insert(ins_chunks, doc):
230
+ """ doc is the already-handled document (as a list of text chunks);
231
+ here we add <ins>ins_chunks</ins> to the end of that. """
232
+ # Though we don't throw away unbalanced_start or unbalanced_end
233
+ # (we assume there is accompanying markup later or earlier in the
234
+ # document), we only put <ins> around the balanced portion.
235
+ unbalanced_start, balanced, unbalanced_end = split_unbalanced(ins_chunks)
236
+ doc.extend(unbalanced_start)
237
+ if doc and not doc[-1].endswith(' '):
238
+ # Fix up the case where the word before the insert didn't end with
239
+ # a space
240
+ doc[-1] += ' '
241
+ doc.append('<ins>')
242
+ if balanced and balanced[-1].endswith(' '):
243
+ # We move space outside of </ins>
244
+ balanced[-1] = balanced[-1][:-1]
245
+ doc.extend(balanced)
246
+ doc.append('</ins> ')
247
+ doc.extend(unbalanced_end)
248
+
249
+ # These are sentinels to represent the start and end of a <del>
250
+ # segment, until we do the cleanup phase to turn them into proper
251
+ # markup:
252
+ class DEL_START:
253
+ pass
254
+ class DEL_END:
255
+ pass
256
+
257
+ class NoDeletes(Exception):
258
+ """ Raised when the document no longer contains any pending deletes
259
+ (DEL_START/DEL_END) """
260
+
261
+ def merge_delete(del_chunks, doc):
262
+ """ Adds the text chunks in del_chunks to the document doc (another
263
+ list of text chunks) with marker to show it is a delete.
264
+ cleanup_delete later resolves these markers into <del> tags."""
265
+ doc.append(DEL_START)
266
+ doc.extend(del_chunks)
267
+ doc.append(DEL_END)
268
+
269
+ def cleanup_delete(chunks):
270
+ """ Cleans up any DEL_START/DEL_END markers in the document, replacing
271
+ them with <del></del>. To do this while keeping the document
272
+ valid, it may need to drop some tags (either start or end tags).
273
+
274
+ It may also move the del into adjacent tags to try to move it to a
275
+ similar location where it was originally located (e.g., moving a
276
+ delete into preceding <div> tag, if the del looks like (DEL_START,
277
+ 'Text</div>', DEL_END)"""
278
+ while 1:
279
+ # Find a pending DEL_START/DEL_END, splitting the document
280
+ # into stuff-preceding-DEL_START, stuff-inside, and
281
+ # stuff-following-DEL_END
282
+ try:
283
+ pre_delete, delete, post_delete = split_delete(chunks)
284
+ except NoDeletes:
285
+ # Nothing found, we've cleaned up the entire doc
286
+ break
287
+ # The stuff-inside-DEL_START/END may not be well balanced
288
+ # markup. First we figure out what unbalanced portions there are:
289
+ unbalanced_start, balanced, unbalanced_end = split_unbalanced(delete)
290
+ # Then we move the span forward and/or backward based on these
291
+ # unbalanced portions:
292
+ locate_unbalanced_start(unbalanced_start, pre_delete, post_delete)
293
+ locate_unbalanced_end(unbalanced_end, pre_delete, post_delete)
294
+ doc = pre_delete
295
+ if doc and not doc[-1].endswith(' '):
296
+ # Fix up case where the word before us didn't have a trailing space
297
+ doc[-1] += ' '
298
+ doc.append('<del>')
299
+ if balanced and balanced[-1].endswith(' '):
300
+ # We move space outside of </del>
301
+ balanced[-1] = balanced[-1][:-1]
302
+ doc.extend(balanced)
303
+ doc.append('</del> ')
304
+ doc.extend(post_delete)
305
+ chunks = doc
306
+ return chunks
307
+
308
+ def split_unbalanced(chunks):
309
+ """Return (unbalanced_start, balanced, unbalanced_end), where each is
310
+ a list of text and tag chunks.
311
+
312
+ unbalanced_start is a list of all the tags that are opened, but
313
+ not closed in this span. Similarly, unbalanced_end is a list of
314
+ tags that are closed but were not opened. Extracting these might
315
+ mean some reordering of the chunks."""
316
+ start = []
317
+ end = []
318
+ tag_stack = []
319
+ balanced = []
320
+ for chunk in chunks:
321
+ if not chunk.startswith('<'):
322
+ balanced.append(chunk)
323
+ continue
324
+ endtag = chunk[1] == '/'
325
+ name = chunk.split()[0].strip('<>/')
326
+ if name in empty_tags:
327
+ balanced.append(chunk)
328
+ continue
329
+ if endtag:
330
+ if tag_stack and tag_stack[-1][0] == name:
331
+ balanced.append(chunk)
332
+ name, pos, tag = tag_stack.pop()
333
+ balanced[pos] = tag
334
+ elif tag_stack:
335
+ start.extend([tag for name, pos, tag in tag_stack])
336
+ tag_stack = []
337
+ end.append(chunk)
338
+ else:
339
+ end.append(chunk)
340
+ else:
341
+ tag_stack.append((name, len(balanced), chunk))
342
+ balanced.append(None)
343
+ start.extend(
344
+ [chunk for name, pos, chunk in tag_stack])
345
+ balanced = [chunk for chunk in balanced if chunk is not None]
346
+ return start, balanced, end
347
+
348
+ def split_delete(chunks):
349
+ """ Returns (stuff_before_DEL_START, stuff_inside_DEL_START_END,
350
+ stuff_after_DEL_END). Returns the first case found (there may be
351
+ more DEL_STARTs in stuff_after_DEL_END). Raises NoDeletes if
352
+ there's no DEL_START found. """
353
+ try:
354
+ pos = chunks.index(DEL_START)
355
+ except ValueError:
356
+ raise NoDeletes
357
+ pos2 = chunks.index(DEL_END)
358
+ return chunks[:pos], chunks[pos+1:pos2], chunks[pos2+1:]
359
+
360
+ def locate_unbalanced_start(unbalanced_start, pre_delete, post_delete):
361
+ """ pre_delete and post_delete implicitly point to a place in the
362
+ document (where the two were split). This moves that point (by
363
+ popping items from one and pushing them onto the other). It moves
364
+ the point to try to find a place where unbalanced_start applies.
365
+
366
+ As an example::
367
+
368
+ >>> unbalanced_start = ['<div>']
369
+ >>> doc = ['<p>', 'Text', '</p>', '<div>', 'More Text', '</div>']
370
+ >>> pre, post = doc[:3], doc[3:]
371
+ >>> pre, post
372
+ (['<p>', 'Text', '</p>'], ['<div>', 'More Text', '</div>'])
373
+ >>> locate_unbalanced_start(unbalanced_start, pre, post)
374
+ >>> pre, post
375
+ (['<p>', 'Text', '</p>', '<div>'], ['More Text', '</div>'])
376
+
377
+ As you can see, we moved the point so that the dangling <div> that
378
+ we found will be effectively replaced by the div in the original
379
+ document. If this doesn't work out, we just throw away
380
+ unbalanced_start without doing anything.
381
+ """
382
+ while 1:
383
+ if not unbalanced_start:
384
+ # We have totally succeeded in finding the position
385
+ break
386
+ finding = unbalanced_start[0]
387
+ finding_name = finding.split()[0].strip('<>')
388
+ if not post_delete:
389
+ break
390
+ next = post_delete[0]
391
+ if next is DEL_START or not next.startswith('<'):
392
+ # Reached a word, we can't move the delete text forward
393
+ break
394
+ if next[1] == '/':
395
+ # Reached a closing tag, can we go further? Maybe not...
396
+ break
397
+ name = next.split()[0].strip('<>')
398
+ if name == 'ins':
399
+ # Can't move into an insert
400
+ break
401
+ assert name != 'del', (
402
+ "Unexpected delete tag: %r" % next)
403
+ if name == finding_name:
404
+ unbalanced_start.pop(0)
405
+ pre_delete.append(post_delete.pop(0))
406
+ else:
407
+ # Found a tag that doesn't match
408
+ break
409
+
410
+ def locate_unbalanced_end(unbalanced_end, pre_delete, post_delete):
411
+ """ like locate_unbalanced_start, except handling end tags and
412
+ possibly moving the point earlier in the document. """
413
+ while 1:
414
+ if not unbalanced_end:
415
+ # Success
416
+ break
417
+ finding = unbalanced_end[-1]
418
+ finding_name = finding.split()[0].strip('<>/')
419
+ if not pre_delete:
420
+ break
421
+ next = pre_delete[-1]
422
+ if next is DEL_END or not next.startswith('</'):
423
+ # A word or a start tag
424
+ break
425
+ name = next.split()[0].strip('<>/')
426
+ if name == 'ins' or name == 'del':
427
+ # Can't move into an insert or delete
428
+ break
429
+ if name == finding_name:
430
+ unbalanced_end.pop()
431
+ post_delete.insert(0, pre_delete.pop())
432
+ else:
433
+ # Found a tag that doesn't match
434
+ break
435
+
436
+ class token(_unicode):
437
+ """ Represents a diffable token, generally a word that is displayed to
438
+ the user. Opening tags are attached to this token when they are
439
+ adjacent (pre_tags) and closing tags that follow the word
440
+ (post_tags). Some exceptions occur when there are empty tags
441
+ adjacent to a word, so there may be close tags in pre_tags, or
442
+ open tags in post_tags.
443
+
444
+ We also keep track of whether the word was originally followed by
445
+ whitespace, even though we do not want to treat the word as
446
+ equivalent to a similar word that does not have a trailing
447
+ space."""
448
+
449
+ # When this is true, the token will be eliminated from the
450
+ # displayed diff if no change has occurred:
451
+ hide_when_equal = False
452
+
453
+ def __new__(cls, text, pre_tags=None, post_tags=None, trailing_whitespace=""):
454
+ obj = _unicode.__new__(cls, text)
455
+
456
+ if pre_tags is not None:
457
+ obj.pre_tags = pre_tags
458
+ else:
459
+ obj.pre_tags = []
460
+
461
+ if post_tags is not None:
462
+ obj.post_tags = post_tags
463
+ else:
464
+ obj.post_tags = []
465
+
466
+ obj.trailing_whitespace = trailing_whitespace
467
+
468
+ return obj
469
+
470
+ def __repr__(self):
471
+ return 'token(%s, %r, %r, %r)' % (_unicode.__repr__(self), self.pre_tags,
472
+ self.post_tags, self.trailing_whitespace)
473
+
474
+ def html(self):
475
+ return _unicode(self)
476
+
477
+ class tag_token(token):
478
+
479
+ """ Represents a token that is actually a tag. Currently this is just
480
+ the <img> tag, which takes up visible space just like a word but
481
+ is only represented in a document by a tag. """
482
+
483
+ def __new__(cls, tag, data, html_repr, pre_tags=None,
484
+ post_tags=None, trailing_whitespace=""):
485
+ obj = token.__new__(cls, "%s: %s" % (type, data),
486
+ pre_tags=pre_tags,
487
+ post_tags=post_tags,
488
+ trailing_whitespace=trailing_whitespace)
489
+ obj.tag = tag
490
+ obj.data = data
491
+ obj.html_repr = html_repr
492
+ return obj
493
+
494
+ def __repr__(self):
495
+ return 'tag_token(%s, %s, html_repr=%s, post_tags=%r, pre_tags=%r, trailing_whitespace=%r)' % (
496
+ self.tag,
497
+ self.data,
498
+ self.html_repr,
499
+ self.pre_tags,
500
+ self.post_tags,
501
+ self.trailing_whitespace)
502
+ def html(self):
503
+ return self.html_repr
504
+
505
+ class href_token(token):
506
+
507
+ """ Represents the href in an anchor tag. Unlike other words, we only
508
+ show the href when it changes. """
509
+
510
+ hide_when_equal = True
511
+
512
+ def html(self):
513
+ return ' Link: %s' % self
514
+
515
+ def tokenize(html, include_hrefs=True):
516
+ """
517
+ Parse the given HTML and returns token objects (words with attached tags).
518
+
519
+ This parses only the content of a page; anything in the head is
520
+ ignored, and the <head> and <body> elements are themselves
521
+ optional. The content is then parsed by lxml, which ensures the
522
+ validity of the resulting parsed document (though lxml may make
523
+ incorrect guesses when the markup is particular bad).
524
+
525
+ <ins> and <del> tags are also eliminated from the document, as
526
+ that gets confusing.
527
+
528
+ If include_hrefs is true, then the href attribute of <a> tags is
529
+ included as a special kind of diffable token."""
530
+ if etree.iselement(html):
531
+ body_el = html
532
+ else:
533
+ body_el = parse_html(html, cleanup=True)
534
+ # Then we split the document into text chunks for each tag, word, and end tag:
535
+ chunks = flatten_el(body_el, skip_tag=True, include_hrefs=include_hrefs)
536
+ # Finally re-joining them into token objects:
537
+ return fixup_chunks(chunks)
538
+
539
+ def parse_html(html, cleanup=True):
540
+ """
541
+ Parses an HTML fragment, returning an lxml element. Note that the HTML will be
542
+ wrapped in a <div> tag that was not in the original document.
543
+
544
+ If cleanup is true, make sure there's no <head> or <body>, and get
545
+ rid of any <ins> and <del> tags.
546
+ """
547
+ if cleanup:
548
+ # This removes any extra markup or structure like <head>:
549
+ html = cleanup_html(html)
550
+ return fragment_fromstring(html, create_parent=True)
551
+
552
+ _body_re = re.compile(r'<body.*?>', re.I|re.S)
553
+ _end_body_re = re.compile(r'</body.*?>', re.I|re.S)
554
+ _ins_del_re = re.compile(r'</?(ins|del).*?>', re.I|re.S)
555
+
556
+ def cleanup_html(html):
557
+ """ This 'cleans' the HTML, meaning that any page structure is removed
558
+ (only the contents of <body> are used, if there is any <body).
559
+ Also <ins> and <del> tags are removed. """
560
+ match = _body_re.search(html)
561
+ if match:
562
+ html = html[match.end():]
563
+ match = _end_body_re.search(html)
564
+ if match:
565
+ html = html[:match.start()]
566
+ html = _ins_del_re.sub('', html)
567
+ return html
568
+
569
+
570
+ end_whitespace_re = re.compile(r'[ \t\n\r]$')
571
+
572
+ def split_trailing_whitespace(word):
573
+ """
574
+ This function takes a word, such as 'test\n\n' and returns ('test','\n\n')
575
+ """
576
+ stripped_length = len(word.rstrip())
577
+ return word[0:stripped_length], word[stripped_length:]
578
+
579
+
580
+ def fixup_chunks(chunks):
581
+ """
582
+ This function takes a list of chunks and produces a list of tokens.
583
+ """
584
+ tag_accum = []
585
+ cur_word = None
586
+ result = []
587
+ for chunk in chunks:
588
+ if isinstance(chunk, tuple):
589
+ if chunk[0] == 'img':
590
+ src = chunk[1]
591
+ tag, trailing_whitespace = split_trailing_whitespace(chunk[2])
592
+ cur_word = tag_token('img', src, html_repr=tag,
593
+ pre_tags=tag_accum,
594
+ trailing_whitespace=trailing_whitespace)
595
+ tag_accum = []
596
+ result.append(cur_word)
597
+
598
+ elif chunk[0] == 'href':
599
+ href = chunk[1]
600
+ cur_word = href_token(href, pre_tags=tag_accum, trailing_whitespace=" ")
601
+ tag_accum = []
602
+ result.append(cur_word)
603
+ continue
604
+
605
+ if is_word(chunk):
606
+ chunk, trailing_whitespace = split_trailing_whitespace(chunk)
607
+ cur_word = token(chunk, pre_tags=tag_accum, trailing_whitespace=trailing_whitespace)
608
+ tag_accum = []
609
+ result.append(cur_word)
610
+
611
+ elif is_start_tag(chunk):
612
+ tag_accum.append(chunk)
613
+
614
+ elif is_end_tag(chunk):
615
+ if tag_accum:
616
+ tag_accum.append(chunk)
617
+ else:
618
+ assert cur_word, (
619
+ "Weird state, cur_word=%r, result=%r, chunks=%r of %r"
620
+ % (cur_word, result, chunk, chunks))
621
+ cur_word.post_tags.append(chunk)
622
+ else:
623
+ assert False
624
+
625
+ if not result:
626
+ return [token('', pre_tags=tag_accum)]
627
+ else:
628
+ result[-1].post_tags.extend(tag_accum)
629
+
630
+ return result
631
+
632
+
633
+ # All the tags in HTML that don't require end tags:
634
+ empty_tags = (
635
+ 'param', 'img', 'area', 'br', 'basefont', 'input',
636
+ 'base', 'meta', 'link', 'col')
637
+
638
+ block_level_tags = (
639
+ 'address',
640
+ 'blockquote',
641
+ 'center',
642
+ 'dir',
643
+ 'div',
644
+ 'dl',
645
+ 'fieldset',
646
+ 'form',
647
+ 'h1',
648
+ 'h2',
649
+ 'h3',
650
+ 'h4',
651
+ 'h5',
652
+ 'h6',
653
+ 'hr',
654
+ 'isindex',
655
+ 'menu',
656
+ 'noframes',
657
+ 'noscript',
658
+ 'ol',
659
+ 'p',
660
+ 'pre',
661
+ 'table',
662
+ 'ul',
663
+ )
664
+
665
+ block_level_container_tags = (
666
+ 'dd',
667
+ 'dt',
668
+ 'frameset',
669
+ 'li',
670
+ 'tbody',
671
+ 'td',
672
+ 'tfoot',
673
+ 'th',
674
+ 'thead',
675
+ 'tr',
676
+ )
677
+
678
+
679
+ def flatten_el(el, include_hrefs, skip_tag=False):
680
+ """ Takes an lxml element el, and generates all the text chunks for
681
+ that tag. Each start tag is a chunk, each word is a chunk, and each
682
+ end tag is a chunk.
683
+
684
+ If skip_tag is true, then the outermost container tag is
685
+ not returned (just its contents)."""
686
+ if not skip_tag:
687
+ if el.tag == 'img':
688
+ yield ('img', el.get('src'), start_tag(el))
689
+ else:
690
+ yield start_tag(el)
691
+ if el.tag in empty_tags and not el.text and not len(el) and not el.tail:
692
+ return
693
+ start_words = split_words(el.text)
694
+ for word in start_words:
695
+ yield html_escape(word)
696
+ for child in el:
697
+ yield from flatten_el(child, include_hrefs=include_hrefs)
698
+ if el.tag == 'a' and el.get('href') and include_hrefs:
699
+ yield ('href', el.get('href'))
700
+ if not skip_tag:
701
+ yield end_tag(el)
702
+ end_words = split_words(el.tail)
703
+ for word in end_words:
704
+ yield html_escape(word)
705
+
706
+ split_words_re = re.compile(r'\S+(?:\s+|$)', re.U)
707
+
708
+ def split_words(text):
709
+ """ Splits some text into words. Includes trailing whitespace
710
+ on each word when appropriate. """
711
+ if not text or not text.strip():
712
+ return []
713
+
714
+ words = split_words_re.findall(text)
715
+ return words
716
+
717
+ start_whitespace_re = re.compile(r'^[ \t\n\r]')
718
+
719
+ def start_tag(el):
720
+ """
721
+ The text representation of the start tag for a tag.
722
+ """
723
+ return '<%s%s>' % (
724
+ el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True))
725
+ for name, value in el.attrib.items()]))
726
+
727
+ def end_tag(el):
728
+ """ The text representation of an end tag for a tag. Includes
729
+ trailing whitespace when appropriate. """
730
+ if el.tail and start_whitespace_re.search(el.tail):
731
+ extra = ' '
732
+ else:
733
+ extra = ''
734
+ return '</%s>%s' % (el.tag, extra)
735
+
736
+ def is_word(tok):
737
+ return not tok.startswith('<')
738
+
739
+ def is_end_tag(tok):
740
+ return tok.startswith('</')
741
+
742
+ def is_start_tag(tok):
743
+ return tok.startswith('<') and not tok.startswith('</')
744
+
745
+ def fixup_ins_del_tags(html):
746
+ """ Given an html string, move any <ins> or <del> tags inside of any
747
+ block-level elements, e.g. transform <ins><p>word</p></ins> to
748
+ <p><ins>word</ins></p> """
749
+ doc = parse_html(html, cleanup=False)
750
+ _fixup_ins_del_tags(doc)
751
+ html = serialize_html_fragment(doc, skip_outer=True)
752
+ return html
753
+
754
+ def serialize_html_fragment(el, skip_outer=False):
755
+ """ Serialize a single lxml element as HTML. The serialized form
756
+ includes the elements tail.
757
+
758
+ If skip_outer is true, then don't serialize the outermost tag
759
+ """
760
+ assert not isinstance(el, basestring), (
761
+ "You should pass in an element, not a string like %r" % el)
762
+ html = etree.tostring(el, method="html", encoding=_unicode)
763
+ if skip_outer:
764
+ # Get rid of the extra starting tag:
765
+ html = html[html.find('>')+1:]
766
+ # Get rid of the extra end tag:
767
+ html = html[:html.rfind('<')]
768
+ return html.strip()
769
+ else:
770
+ return html
771
+
772
+ def _fixup_ins_del_tags(doc):
773
+ """fixup_ins_del_tags that works on an lxml document in-place
774
+ """
775
+ for tag in ['ins', 'del']:
776
+ for el in doc.xpath('descendant-or-self::%s' % tag):
777
+ if not _contains_block_level_tag(el):
778
+ continue
779
+ _move_el_inside_block(el, tag=tag)
780
+ el.drop_tag()
781
+ #_merge_element_contents(el)
782
+
783
+ def _contains_block_level_tag(el):
784
+ """True if the element contains any block-level elements, like <p>, <td>, etc.
785
+ """
786
+ if el.tag in block_level_tags or el.tag in block_level_container_tags:
787
+ return True
788
+ for child in el:
789
+ if _contains_block_level_tag(child):
790
+ return True
791
+ return False
792
+
793
+ def _move_el_inside_block(el, tag):
794
+ """ helper for _fixup_ins_del_tags; actually takes the <ins> etc tags
795
+ and moves them inside any block-level tags. """
796
+ for child in el:
797
+ if _contains_block_level_tag(child):
798
+ break
799
+ else:
800
+ # No block-level tags in any child
801
+ children_tag = etree.Element(tag)
802
+ children_tag.text = el.text
803
+ el.text = None
804
+ children_tag.extend(list(el))
805
+ el[:] = [children_tag]
806
+ return
807
+ for child in list(el):
808
+ if _contains_block_level_tag(child):
809
+ _move_el_inside_block(child, tag)
810
+ if child.tail:
811
+ tail_tag = etree.Element(tag)
812
+ tail_tag.text = child.tail
813
+ child.tail = None
814
+ el.insert(el.index(child)+1, tail_tag)
815
+ else:
816
+ child_tag = etree.Element(tag)
817
+ el.replace(child, child_tag)
818
+ child_tag.append(child)
819
+ if el.text:
820
+ text_tag = etree.Element(tag)
821
+ text_tag.text = el.text
822
+ el.text = None
823
+ el.insert(0, text_tag)
824
+
825
+ def _merge_element_contents(el):
826
+ """
827
+ Removes an element, but merges its contents into its place, e.g.,
828
+ given <p>Hi <i>there!</i></p>, if you remove the <i> element you get
829
+ <p>Hi there!</p>
830
+ """
831
+ parent = el.getparent()
832
+ text = el.text or ''
833
+ if el.tail:
834
+ if not len(el):
835
+ text += el.tail
836
+ else:
837
+ if el[-1].tail:
838
+ el[-1].tail += el.tail
839
+ else:
840
+ el[-1].tail = el.tail
841
+ index = parent.index(el)
842
+ if text:
843
+ if index == 0:
844
+ previous = None
845
+ else:
846
+ previous = parent[index-1]
847
+ if previous is None:
848
+ if parent.text:
849
+ parent.text += text
850
+ else:
851
+ parent.text = text
852
+ else:
853
+ if previous.tail:
854
+ previous.tail += text
855
+ else:
856
+ previous.tail = text
857
+ parent[index:index+1] = el.getchildren()
858
+
859
+ class InsensitiveSequenceMatcher(difflib.SequenceMatcher):
860
+ """
861
+ Acts like SequenceMatcher, but tries not to find very small equal
862
+ blocks amidst large spans of changes
863
+ """
864
+
865
+ threshold = 2
866
+
867
+ def get_matching_blocks(self):
868
+ size = min(len(self.b), len(self.b))
869
+ threshold = min(self.threshold, size / 4)
870
+ actual = difflib.SequenceMatcher.get_matching_blocks(self)
871
+ return [item for item in actual
872
+ if item[2] > threshold
873
+ or not item[2]]
874
+
875
+ if __name__ == '__main__':
876
+ from lxml.html import _diffcommand
877
+ _diffcommand.main()
878
+
env-llmeval/lib/python3.10/site-packages/lxml/html/formfill.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.etree import XPath, ElementBase
2
+ from lxml.html import fromstring, XHTML_NAMESPACE
3
+ from lxml.html import _forms_xpath, _options_xpath, _nons, _transform_result
4
+ from lxml.html import defs
5
+ import copy
6
+
7
+ try:
8
+ basestring
9
+ except NameError:
10
+ # Python 3
11
+ basestring = str
12
+
13
+ __all__ = ['FormNotFound', 'fill_form', 'fill_form_html',
14
+ 'insert_errors', 'insert_errors_html',
15
+ 'DefaultErrorCreator']
16
+
17
+ class FormNotFound(LookupError):
18
+ """
19
+ Raised when no form can be found
20
+ """
21
+
22
+ _form_name_xpath = XPath('descendant-or-self::form[name=$name]|descendant-or-self::x:form[name=$name]', namespaces={'x':XHTML_NAMESPACE})
23
+ _input_xpath = XPath('|'.join(['descendant-or-self::'+_tag for _tag in ('input','select','textarea','x:input','x:select','x:textarea')]),
24
+ namespaces={'x':XHTML_NAMESPACE})
25
+ _label_for_xpath = XPath('//label[@for=$for_id]|//x:label[@for=$for_id]',
26
+ namespaces={'x':XHTML_NAMESPACE})
27
+ _name_xpath = XPath('descendant-or-self::*[@name=$name]')
28
+
29
+ def fill_form(
30
+ el,
31
+ values,
32
+ form_id=None,
33
+ form_index=None,
34
+ ):
35
+ el = _find_form(el, form_id=form_id, form_index=form_index)
36
+ _fill_form(el, values)
37
+
38
+ def fill_form_html(html, values, form_id=None, form_index=None):
39
+ result_type = type(html)
40
+ if isinstance(html, basestring):
41
+ doc = fromstring(html)
42
+ else:
43
+ doc = copy.deepcopy(html)
44
+ fill_form(doc, values, form_id=form_id, form_index=form_index)
45
+ return _transform_result(result_type, doc)
46
+
47
+ def _fill_form(el, values):
48
+ counts = {}
49
+ if hasattr(values, 'mixed'):
50
+ # For Paste request parameters
51
+ values = values.mixed()
52
+ inputs = _input_xpath(el)
53
+ for input in inputs:
54
+ name = input.get('name')
55
+ if not name:
56
+ continue
57
+ if _takes_multiple(input):
58
+ value = values.get(name, [])
59
+ if not isinstance(value, (list, tuple)):
60
+ value = [value]
61
+ _fill_multiple(input, value)
62
+ elif name not in values:
63
+ continue
64
+ else:
65
+ index = counts.get(name, 0)
66
+ counts[name] = index + 1
67
+ value = values[name]
68
+ if isinstance(value, (list, tuple)):
69
+ try:
70
+ value = value[index]
71
+ except IndexError:
72
+ continue
73
+ elif index > 0:
74
+ continue
75
+ _fill_single(input, value)
76
+
77
+ def _takes_multiple(input):
78
+ if _nons(input.tag) == 'select' and input.get('multiple'):
79
+ # FIXME: multiple="0"?
80
+ return True
81
+ type = input.get('type', '').lower()
82
+ if type in ('radio', 'checkbox'):
83
+ return True
84
+ return False
85
+
86
+ def _fill_multiple(input, value):
87
+ type = input.get('type', '').lower()
88
+ if type == 'checkbox':
89
+ v = input.get('value')
90
+ if v is None:
91
+ if not value:
92
+ result = False
93
+ else:
94
+ result = value[0]
95
+ if isinstance(value, basestring):
96
+ # The only valid "on" value for an unnamed checkbox is 'on'
97
+ result = result == 'on'
98
+ _check(input, result)
99
+ else:
100
+ _check(input, v in value)
101
+ elif type == 'radio':
102
+ v = input.get('value')
103
+ _check(input, v in value)
104
+ else:
105
+ assert _nons(input.tag) == 'select'
106
+ for option in _options_xpath(input):
107
+ v = option.get('value')
108
+ if v is None:
109
+ # This seems to be the default, at least on IE
110
+ # FIXME: but I'm not sure
111
+ v = option.text_content()
112
+ _select(option, v in value)
113
+
114
+ def _check(el, check):
115
+ if check:
116
+ el.set('checked', '')
117
+ else:
118
+ if 'checked' in el.attrib:
119
+ del el.attrib['checked']
120
+
121
+ def _select(el, select):
122
+ if select:
123
+ el.set('selected', '')
124
+ else:
125
+ if 'selected' in el.attrib:
126
+ del el.attrib['selected']
127
+
128
+ def _fill_single(input, value):
129
+ if _nons(input.tag) == 'textarea':
130
+ input.text = value
131
+ else:
132
+ input.set('value', value)
133
+
134
+ def _find_form(el, form_id=None, form_index=None):
135
+ if form_id is None and form_index is None:
136
+ forms = _forms_xpath(el)
137
+ for form in forms:
138
+ return form
139
+ raise FormNotFound(
140
+ "No forms in page")
141
+ if form_id is not None:
142
+ form = el.get_element_by_id(form_id)
143
+ if form is not None:
144
+ return form
145
+ forms = _form_name_xpath(el, name=form_id)
146
+ if forms:
147
+ return forms[0]
148
+ else:
149
+ raise FormNotFound(
150
+ "No form with the name or id of %r (forms: %s)"
151
+ % (id, ', '.join(_find_form_ids(el))))
152
+ if form_index is not None:
153
+ forms = _forms_xpath(el)
154
+ try:
155
+ return forms[form_index]
156
+ except IndexError:
157
+ raise FormNotFound(
158
+ "There is no form with the index %r (%i forms found)"
159
+ % (form_index, len(forms)))
160
+
161
+ def _find_form_ids(el):
162
+ forms = _forms_xpath(el)
163
+ if not forms:
164
+ yield '(no forms)'
165
+ return
166
+ for index, form in enumerate(forms):
167
+ if form.get('id'):
168
+ if form.get('name'):
169
+ yield '%s or %s' % (form.get('id'),
170
+ form.get('name'))
171
+ else:
172
+ yield form.get('id')
173
+ elif form.get('name'):
174
+ yield form.get('name')
175
+ else:
176
+ yield '(unnamed form %s)' % index
177
+
178
+ ############################################################
179
+ ## Error filling
180
+ ############################################################
181
+
182
+ class DefaultErrorCreator:
183
+ insert_before = True
184
+ block_inside = True
185
+ error_container_tag = 'div'
186
+ error_message_class = 'error-message'
187
+ error_block_class = 'error-block'
188
+ default_message = "Invalid"
189
+
190
+ def __init__(self, **kw):
191
+ for name, value in kw.items():
192
+ if not hasattr(self, name):
193
+ raise TypeError(
194
+ "Unexpected keyword argument: %s" % name)
195
+ setattr(self, name, value)
196
+
197
+ def __call__(self, el, is_block, message):
198
+ error_el = el.makeelement(self.error_container_tag)
199
+ if self.error_message_class:
200
+ error_el.set('class', self.error_message_class)
201
+ if is_block and self.error_block_class:
202
+ error_el.set('class', error_el.get('class', '')+' '+self.error_block_class)
203
+ if message is None or message == '':
204
+ message = self.default_message
205
+ if isinstance(message, ElementBase):
206
+ error_el.append(message)
207
+ else:
208
+ assert isinstance(message, basestring), (
209
+ "Bad message; should be a string or element: %r" % message)
210
+ error_el.text = message or self.default_message
211
+ if is_block and self.block_inside:
212
+ if self.insert_before:
213
+ error_el.tail = el.text
214
+ el.text = None
215
+ el.insert(0, error_el)
216
+ else:
217
+ el.append(error_el)
218
+ else:
219
+ parent = el.getparent()
220
+ pos = parent.index(el)
221
+ if self.insert_before:
222
+ parent.insert(pos, error_el)
223
+ else:
224
+ error_el.tail = el.tail
225
+ el.tail = None
226
+ parent.insert(pos+1, error_el)
227
+
228
+ default_error_creator = DefaultErrorCreator()
229
+
230
+
231
+ def insert_errors(
232
+ el,
233
+ errors,
234
+ form_id=None,
235
+ form_index=None,
236
+ error_class="error",
237
+ error_creator=default_error_creator,
238
+ ):
239
+ el = _find_form(el, form_id=form_id, form_index=form_index)
240
+ for name, error in errors.items():
241
+ if error is None:
242
+ continue
243
+ for error_el, message in _find_elements_for_name(el, name, error):
244
+ assert isinstance(message, (basestring, type(None), ElementBase)), (
245
+ "Bad message: %r" % message)
246
+ _insert_error(error_el, message, error_class, error_creator)
247
+
248
+ def insert_errors_html(html, values, **kw):
249
+ result_type = type(html)
250
+ if isinstance(html, basestring):
251
+ doc = fromstring(html)
252
+ else:
253
+ doc = copy.deepcopy(html)
254
+ insert_errors(doc, values, **kw)
255
+ return _transform_result(result_type, doc)
256
+
257
+ def _insert_error(el, error, error_class, error_creator):
258
+ if _nons(el.tag) in defs.empty_tags or _nons(el.tag) == 'textarea':
259
+ is_block = False
260
+ else:
261
+ is_block = True
262
+ if _nons(el.tag) != 'form' and error_class:
263
+ _add_class(el, error_class)
264
+ if el.get('id'):
265
+ labels = _label_for_xpath(el, for_id=el.get('id'))
266
+ if labels:
267
+ for label in labels:
268
+ _add_class(label, error_class)
269
+ error_creator(el, is_block, error)
270
+
271
+ def _add_class(el, class_name):
272
+ if el.get('class'):
273
+ el.set('class', el.get('class')+' '+class_name)
274
+ else:
275
+ el.set('class', class_name)
276
+
277
+ def _find_elements_for_name(form, name, error):
278
+ if name is None:
279
+ # An error for the entire form
280
+ yield form, error
281
+ return
282
+ if name.startswith('#'):
283
+ # By id
284
+ el = form.get_element_by_id(name[1:])
285
+ if el is not None:
286
+ yield el, error
287
+ return
288
+ els = _name_xpath(form, name=name)
289
+ if not els:
290
+ # FIXME: should this raise an exception?
291
+ return
292
+ if not isinstance(error, (list, tuple)):
293
+ yield els[0], error
294
+ return
295
+ # FIXME: if error is longer than els, should it raise an error?
296
+ for el, err in zip(els, error):
297
+ if err is None:
298
+ continue
299
+ yield el, err
env-llmeval/lib/python3.10/site-packages/lxml/html/html5parser.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ An interface to html5lib that mimics the lxml.html interface.
3
+ """
4
+ import sys
5
+ import string
6
+
7
+ from html5lib import HTMLParser as _HTMLParser
8
+ from html5lib.treebuilders.etree_lxml import TreeBuilder
9
+ from lxml import etree
10
+ from lxml.html import Element, XHTML_NAMESPACE, _contains_block_level_tag
11
+
12
+ # python3 compatibility
13
+ try:
14
+ _strings = basestring
15
+ except NameError:
16
+ _strings = (bytes, str)
17
+ try:
18
+ from urllib2 import urlopen
19
+ except ImportError:
20
+ from urllib.request import urlopen
21
+ try:
22
+ from urlparse import urlparse
23
+ except ImportError:
24
+ from urllib.parse import urlparse
25
+
26
+
27
+ class HTMLParser(_HTMLParser):
28
+ """An html5lib HTML parser with lxml as tree."""
29
+
30
+ def __init__(self, strict=False, **kwargs):
31
+ _HTMLParser.__init__(self, strict=strict, tree=TreeBuilder, **kwargs)
32
+
33
+
34
+ try:
35
+ from html5lib import XHTMLParser as _XHTMLParser
36
+ except ImportError:
37
+ pass
38
+ else:
39
+ class XHTMLParser(_XHTMLParser):
40
+ """An html5lib XHTML Parser with lxml as tree."""
41
+
42
+ def __init__(self, strict=False, **kwargs):
43
+ _XHTMLParser.__init__(self, strict=strict, tree=TreeBuilder, **kwargs)
44
+
45
+ xhtml_parser = XHTMLParser()
46
+
47
+
48
+ def _find_tag(tree, tag):
49
+ elem = tree.find(tag)
50
+ if elem is not None:
51
+ return elem
52
+ return tree.find('{%s}%s' % (XHTML_NAMESPACE, tag))
53
+
54
+
55
+ def document_fromstring(html, guess_charset=None, parser=None):
56
+ """
57
+ Parse a whole document into a string.
58
+
59
+ If `guess_charset` is true, or if the input is not Unicode but a
60
+ byte string, the `chardet` library will perform charset guessing
61
+ on the string.
62
+ """
63
+ if not isinstance(html, _strings):
64
+ raise TypeError('string required')
65
+
66
+ if parser is None:
67
+ parser = html_parser
68
+
69
+ options = {}
70
+ if guess_charset is None and isinstance(html, bytes):
71
+ # html5lib does not accept useChardet as an argument, if it
72
+ # detected the html argument would produce unicode objects.
73
+ guess_charset = True
74
+ if guess_charset is not None:
75
+ options['useChardet'] = guess_charset
76
+ return parser.parse(html, **options).getroot()
77
+
78
+
79
+ def fragments_fromstring(html, no_leading_text=False,
80
+ guess_charset=None, parser=None):
81
+ """Parses several HTML elements, returning a list of elements.
82
+
83
+ The first item in the list may be a string. If no_leading_text is true,
84
+ then it will be an error if there is leading text, and it will always be
85
+ a list of only elements.
86
+
87
+ If `guess_charset` is true, the `chardet` library will perform charset
88
+ guessing on the string.
89
+ """
90
+ if not isinstance(html, _strings):
91
+ raise TypeError('string required')
92
+
93
+ if parser is None:
94
+ parser = html_parser
95
+
96
+ options = {}
97
+ if guess_charset is None and isinstance(html, bytes):
98
+ # html5lib does not accept useChardet as an argument, if it
99
+ # detected the html argument would produce unicode objects.
100
+ guess_charset = False
101
+ if guess_charset is not None:
102
+ options['useChardet'] = guess_charset
103
+ children = parser.parseFragment(html, 'div', **options)
104
+ if children and isinstance(children[0], _strings):
105
+ if no_leading_text:
106
+ if children[0].strip():
107
+ raise etree.ParserError('There is leading text: %r' %
108
+ children[0])
109
+ del children[0]
110
+ return children
111
+
112
+
113
+ def fragment_fromstring(html, create_parent=False,
114
+ guess_charset=None, parser=None):
115
+ """Parses a single HTML element; it is an error if there is more than
116
+ one element, or if anything but whitespace precedes or follows the
117
+ element.
118
+
119
+ If 'create_parent' is true (or is a tag name) then a parent node
120
+ will be created to encapsulate the HTML in a single element. In
121
+ this case, leading or trailing text is allowed.
122
+
123
+ If `guess_charset` is true, the `chardet` library will perform charset
124
+ guessing on the string.
125
+ """
126
+ if not isinstance(html, _strings):
127
+ raise TypeError('string required')
128
+
129
+ accept_leading_text = bool(create_parent)
130
+
131
+ elements = fragments_fromstring(
132
+ html, guess_charset=guess_charset, parser=parser,
133
+ no_leading_text=not accept_leading_text)
134
+
135
+ if create_parent:
136
+ if not isinstance(create_parent, _strings):
137
+ create_parent = 'div'
138
+ new_root = Element(create_parent)
139
+ if elements:
140
+ if isinstance(elements[0], _strings):
141
+ new_root.text = elements[0]
142
+ del elements[0]
143
+ new_root.extend(elements)
144
+ return new_root
145
+
146
+ if not elements:
147
+ raise etree.ParserError('No elements found')
148
+ if len(elements) > 1:
149
+ raise etree.ParserError('Multiple elements found')
150
+ result = elements[0]
151
+ if result.tail and result.tail.strip():
152
+ raise etree.ParserError('Element followed by text: %r' % result.tail)
153
+ result.tail = None
154
+ return result
155
+
156
+
157
+ def fromstring(html, guess_charset=None, parser=None):
158
+ """Parse the html, returning a single element/document.
159
+
160
+ This tries to minimally parse the chunk of text, without knowing if it
161
+ is a fragment or a document.
162
+
163
+ 'base_url' will set the document's base_url attribute (and the tree's
164
+ docinfo.URL)
165
+
166
+ If `guess_charset` is true, or if the input is not Unicode but a
167
+ byte string, the `chardet` library will perform charset guessing
168
+ on the string.
169
+ """
170
+ if not isinstance(html, _strings):
171
+ raise TypeError('string required')
172
+ doc = document_fromstring(html, parser=parser,
173
+ guess_charset=guess_charset)
174
+
175
+ # document starts with doctype or <html>, full document!
176
+ start = html[:50]
177
+ if isinstance(start, bytes):
178
+ # Allow text comparison in python3.
179
+ # Decode as ascii, that also covers latin-1 and utf-8 for the
180
+ # characters we need.
181
+ start = start.decode('ascii', 'replace')
182
+
183
+ start = start.lstrip().lower()
184
+ if start.startswith('<html') or start.startswith('<!doctype'):
185
+ return doc
186
+
187
+ head = _find_tag(doc, 'head')
188
+
189
+ # if the head is not empty we have a full document
190
+ if len(head):
191
+ return doc
192
+
193
+ body = _find_tag(doc, 'body')
194
+
195
+ # The body has just one element, so it was probably a single
196
+ # element passed in
197
+ if (len(body) == 1 and (not body.text or not body.text.strip())
198
+ and (not body[-1].tail or not body[-1].tail.strip())):
199
+ return body[0]
200
+
201
+ # Now we have a body which represents a bunch of tags which have the
202
+ # content that was passed in. We will create a fake container, which
203
+ # is the body tag, except <body> implies too much structure.
204
+ if _contains_block_level_tag(body):
205
+ body.tag = 'div'
206
+ else:
207
+ body.tag = 'span'
208
+ return body
209
+
210
+
211
+ def parse(filename_url_or_file, guess_charset=None, parser=None):
212
+ """Parse a filename, URL, or file-like object into an HTML document
213
+ tree. Note: this returns a tree, not an element. Use
214
+ ``parse(...).getroot()`` to get the document root.
215
+
216
+ If ``guess_charset`` is true, the ``useChardet`` option is passed into
217
+ html5lib to enable character detection. This option is on by default
218
+ when parsing from URLs, off by default when parsing from file(-like)
219
+ objects (which tend to return Unicode more often than not), and on by
220
+ default when parsing from a file path (which is read in binary mode).
221
+ """
222
+ if parser is None:
223
+ parser = html_parser
224
+ if not isinstance(filename_url_or_file, _strings):
225
+ fp = filename_url_or_file
226
+ if guess_charset is None:
227
+ # assume that file-like objects return Unicode more often than bytes
228
+ guess_charset = False
229
+ elif _looks_like_url(filename_url_or_file):
230
+ fp = urlopen(filename_url_or_file)
231
+ if guess_charset is None:
232
+ # assume that URLs return bytes
233
+ guess_charset = True
234
+ else:
235
+ fp = open(filename_url_or_file, 'rb')
236
+ if guess_charset is None:
237
+ guess_charset = True
238
+
239
+ options = {}
240
+ # html5lib does not accept useChardet as an argument, if it
241
+ # detected the html argument would produce unicode objects.
242
+ if guess_charset:
243
+ options['useChardet'] = guess_charset
244
+ return parser.parse(fp, **options)
245
+
246
+
247
+ def _looks_like_url(str):
248
+ scheme = urlparse(str)[0]
249
+ if not scheme:
250
+ return False
251
+ elif (sys.platform == 'win32' and
252
+ scheme in string.ascii_letters
253
+ and len(scheme) == 1):
254
+ # looks like a 'normal' absolute path
255
+ return False
256
+ else:
257
+ return True
258
+
259
+
260
+ html_parser = HTMLParser()
env-llmeval/lib/python3.10/site-packages/lxml/html/soupparser.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """External interface to the BeautifulSoup HTML parser.
2
+ """
3
+
4
+ __all__ = ["fromstring", "parse", "convert_tree"]
5
+
6
+ import re
7
+ from lxml import etree, html
8
+
9
+ try:
10
+ from bs4 import (
11
+ BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
12
+ Declaration, Doctype)
13
+ _DECLARATION_OR_DOCTYPE = (Declaration, Doctype)
14
+ except ImportError:
15
+ from BeautifulSoup import (
16
+ BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
17
+ Declaration)
18
+ _DECLARATION_OR_DOCTYPE = Declaration
19
+
20
+
21
+ def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
22
+ """Parse a string of HTML data into an Element tree using the
23
+ BeautifulSoup parser.
24
+
25
+ Returns the root ``<html>`` Element of the tree.
26
+
27
+ You can pass a different BeautifulSoup parser through the
28
+ `beautifulsoup` keyword, and a diffent Element factory function
29
+ through the `makeelement` keyword. By default, the standard
30
+ ``BeautifulSoup`` class and the default factory of `lxml.html` are
31
+ used.
32
+ """
33
+ return _parse(data, beautifulsoup, makeelement, **bsargs)
34
+
35
+
36
+ def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
37
+ """Parse a file into an ElemenTree using the BeautifulSoup parser.
38
+
39
+ You can pass a different BeautifulSoup parser through the
40
+ `beautifulsoup` keyword, and a diffent Element factory function
41
+ through the `makeelement` keyword. By default, the standard
42
+ ``BeautifulSoup`` class and the default factory of `lxml.html` are
43
+ used.
44
+ """
45
+ if not hasattr(file, 'read'):
46
+ file = open(file)
47
+ root = _parse(file, beautifulsoup, makeelement, **bsargs)
48
+ return etree.ElementTree(root)
49
+
50
+
51
+ def convert_tree(beautiful_soup_tree, makeelement=None):
52
+ """Convert a BeautifulSoup tree to a list of Element trees.
53
+
54
+ Returns a list instead of a single root Element to support
55
+ HTML-like soup with more than one root element.
56
+
57
+ You can pass a different Element factory through the `makeelement`
58
+ keyword.
59
+ """
60
+ root = _convert_tree(beautiful_soup_tree, makeelement)
61
+ children = root.getchildren()
62
+ for child in children:
63
+ root.remove(child)
64
+ return children
65
+
66
+
67
+ # helpers
68
+
69
+ def _parse(source, beautifulsoup, makeelement, **bsargs):
70
+ if beautifulsoup is None:
71
+ beautifulsoup = BeautifulSoup
72
+ if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3
73
+ if 'convertEntities' not in bsargs:
74
+ bsargs['convertEntities'] = 'html'
75
+ if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs4
76
+ if 'features' not in bsargs:
77
+ bsargs['features'] = 'html.parser' # use Python html parser
78
+ tree = beautifulsoup(source, **bsargs)
79
+ root = _convert_tree(tree, makeelement)
80
+ # from ET: wrap the document in a html root element, if necessary
81
+ if len(root) == 1 and root[0].tag == "html":
82
+ return root[0]
83
+ root.tag = "html"
84
+ return root
85
+
86
+
87
+ _parse_doctype_declaration = re.compile(
88
+ r'(?:\s|[<!])*DOCTYPE\s*HTML'
89
+ r'(?:\s+PUBLIC)?(?:\s+(\'[^\']*\'|"[^"]*"))?'
90
+ r'(?:\s+(\'[^\']*\'|"[^"]*"))?',
91
+ re.IGNORECASE).match
92
+
93
+
94
+ class _PseudoTag:
95
+ # Minimal imitation of BeautifulSoup.Tag
96
+ def __init__(self, contents):
97
+ self.name = 'html'
98
+ self.attrs = []
99
+ self.contents = contents
100
+
101
+ def __iter__(self):
102
+ return self.contents.__iter__()
103
+
104
+
105
+ def _convert_tree(beautiful_soup_tree, makeelement):
106
+ if makeelement is None:
107
+ makeelement = html.html_parser.makeelement
108
+
109
+ # Split the tree into three parts:
110
+ # i) everything before the root element: document type
111
+ # declaration, comments, processing instructions, whitespace
112
+ # ii) the root(s),
113
+ # iii) everything after the root: comments, processing
114
+ # instructions, whitespace
115
+ first_element_idx = last_element_idx = None
116
+ html_root = declaration = None
117
+ for i, e in enumerate(beautiful_soup_tree):
118
+ if isinstance(e, Tag):
119
+ if first_element_idx is None:
120
+ first_element_idx = i
121
+ last_element_idx = i
122
+ if html_root is None and e.name and e.name.lower() == 'html':
123
+ html_root = e
124
+ elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):
125
+ declaration = e
126
+
127
+ # For a nice, well-formatted document, the variable roots below is
128
+ # a list consisting of a single <html> element. However, the document
129
+ # may be a soup like '<meta><head><title>Hello</head><body>Hi
130
+ # all<\p>'. In this example roots is a list containing meta, head
131
+ # and body elements.
132
+ if first_element_idx is None:
133
+ pre_root = post_root = []
134
+ roots = beautiful_soup_tree.contents
135
+ else:
136
+ pre_root = beautiful_soup_tree.contents[:first_element_idx]
137
+ roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]
138
+ post_root = beautiful_soup_tree.contents[last_element_idx+1:]
139
+
140
+ # Reorganize so that there is one <html> root...
141
+ if html_root is not None:
142
+ # ... use existing one if possible, ...
143
+ i = roots.index(html_root)
144
+ html_root.contents = roots[:i] + html_root.contents + roots[i+1:]
145
+ else:
146
+ # ... otherwise create a new one.
147
+ html_root = _PseudoTag(roots)
148
+
149
+ convert_node = _init_node_converters(makeelement)
150
+
151
+ # Process pre_root
152
+ res_root = convert_node(html_root)
153
+ prev = res_root
154
+ for e in reversed(pre_root):
155
+ converted = convert_node(e)
156
+ if converted is not None:
157
+ prev.addprevious(converted)
158
+ prev = converted
159
+
160
+ # ditto for post_root
161
+ prev = res_root
162
+ for e in post_root:
163
+ converted = convert_node(e)
164
+ if converted is not None:
165
+ prev.addnext(converted)
166
+ prev = converted
167
+
168
+ if declaration is not None:
169
+ try:
170
+ # bs4 provides full Doctype string
171
+ doctype_string = declaration.output_ready()
172
+ except AttributeError:
173
+ doctype_string = declaration.string
174
+
175
+ match = _parse_doctype_declaration(doctype_string)
176
+ if not match:
177
+ # Something is wrong if we end up in here. Since soupparser should
178
+ # tolerate errors, do not raise Exception, just let it pass.
179
+ pass
180
+ else:
181
+ external_id, sys_uri = match.groups()
182
+ docinfo = res_root.getroottree().docinfo
183
+ # strip quotes and update DOCTYPE values (any of None, '', '...')
184
+ docinfo.public_id = external_id and external_id[1:-1]
185
+ docinfo.system_url = sys_uri and sys_uri[1:-1]
186
+
187
+ return res_root
188
+
189
+
190
+ def _init_node_converters(makeelement):
191
+ converters = {}
192
+ ordered_node_types = []
193
+
194
+ def converter(*types):
195
+ def add(handler):
196
+ for t in types:
197
+ converters[t] = handler
198
+ ordered_node_types.append(t)
199
+ return handler
200
+ return add
201
+
202
+ def find_best_converter(node):
203
+ for t in ordered_node_types:
204
+ if isinstance(node, t):
205
+ return converters[t]
206
+ return None
207
+
208
+ def convert_node(bs_node, parent=None):
209
+ # duplicated in convert_tag() below
210
+ try:
211
+ handler = converters[type(bs_node)]
212
+ except KeyError:
213
+ handler = converters[type(bs_node)] = find_best_converter(bs_node)
214
+ if handler is None:
215
+ return None
216
+ return handler(bs_node, parent)
217
+
218
+ def map_attrs(bs_attrs):
219
+ if isinstance(bs_attrs, dict): # bs4
220
+ attribs = {}
221
+ for k, v in bs_attrs.items():
222
+ if isinstance(v, list):
223
+ v = " ".join(v)
224
+ attribs[k] = unescape(v)
225
+ else:
226
+ attribs = {k: unescape(v) for k, v in bs_attrs}
227
+ return attribs
228
+
229
+ def append_text(parent, text):
230
+ if len(parent) == 0:
231
+ parent.text = (parent.text or '') + text
232
+ else:
233
+ parent[-1].tail = (parent[-1].tail or '') + text
234
+
235
+ # converters are tried in order of their definition
236
+
237
+ @converter(Tag, _PseudoTag)
238
+ def convert_tag(bs_node, parent):
239
+ attrs = bs_node.attrs
240
+ if parent is not None:
241
+ attribs = map_attrs(attrs) if attrs else None
242
+ res = etree.SubElement(parent, bs_node.name, attrib=attribs)
243
+ else:
244
+ attribs = map_attrs(attrs) if attrs else {}
245
+ res = makeelement(bs_node.name, attrib=attribs)
246
+
247
+ for child in bs_node:
248
+ # avoid double recursion by inlining convert_node(), see above
249
+ try:
250
+ handler = converters[type(child)]
251
+ except KeyError:
252
+ pass
253
+ else:
254
+ if handler is not None:
255
+ handler(child, res)
256
+ continue
257
+ convert_node(child, res)
258
+ return res
259
+
260
+ @converter(Comment)
261
+ def convert_comment(bs_node, parent):
262
+ res = html.HtmlComment(bs_node)
263
+ if parent is not None:
264
+ parent.append(res)
265
+ return res
266
+
267
+ @converter(ProcessingInstruction)
268
+ def convert_pi(bs_node, parent):
269
+ if bs_node.endswith('?'):
270
+ # The PI is of XML style (<?as df?>) but BeautifulSoup
271
+ # interpreted it as being SGML style (<?as df>). Fix.
272
+ bs_node = bs_node[:-1]
273
+ res = etree.ProcessingInstruction(*bs_node.split(' ', 1))
274
+ if parent is not None:
275
+ parent.append(res)
276
+ return res
277
+
278
+ @converter(NavigableString)
279
+ def convert_text(bs_node, parent):
280
+ if parent is not None:
281
+ append_text(parent, unescape(bs_node))
282
+ return None
283
+
284
+ return convert_node
285
+
286
+
287
+ # copied from ET's ElementSoup
288
+
289
+ try:
290
+ from html.entities import name2codepoint # Python 3
291
+ except ImportError:
292
+ from htmlentitydefs import name2codepoint
293
+
294
+
295
+ handle_entities = re.compile(r"&(\w+);").sub
296
+
297
+
298
+ try:
299
+ unichr
300
+ except NameError:
301
+ # Python 3
302
+ unichr = chr
303
+
304
+
305
+ def unescape(string):
306
+ if not string:
307
+ return ''
308
+ # work around oddities in BeautifulSoup's entity handling
309
+ def unescape_entity(m):
310
+ try:
311
+ return unichr(name2codepoint[m.group(1)])
312
+ except KeyError:
313
+ return m.group(0) # use as is
314
+ return handle_entities(unescape_entity, string)
env-llmeval/lib/python3.10/site-packages/lxml/html/usedoctest.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Doctest module for HTML comparison.
2
+
3
+ Usage::
4
+
5
+ >>> import lxml.html.usedoctest
6
+ >>> # now do your HTML doctests ...
7
+
8
+ See `lxml.doctestcompare`.
9
+ """
10
+
11
+ from lxml import doctestcompare
12
+
13
+ doctestcompare.temp_install(html=True, del_module=__name__)
env-llmeval/lib/python3.10/site-packages/lxml/includes/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/lxml/includes/config.pxd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ cdef extern from "etree_defs.h":
2
+ cdef bint ENABLE_THREADING
3
+ cdef bint ENABLE_SCHEMATRON
env-llmeval/lib/python3.10/site-packages/lxml/includes/etreepublic.pxd ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # public Cython/C interface to lxml.etree
2
+
3
+ from lxml.includes cimport tree
4
+ from lxml.includes.tree cimport const_xmlChar
5
+
6
+ cdef extern from "lxml-version.h":
7
+ cdef char* LXML_VERSION_STRING
8
+
9
+ cdef extern from "etree_defs.h":
10
+ # test if c_node is considered an Element (i.e. Element, Comment, etc.)
11
+ cdef bint _isElement(tree.xmlNode* c_node) noexcept nogil
12
+
13
+ # return the namespace URI of the node or NULL
14
+ cdef const_xmlChar* _getNs(tree.xmlNode* node) noexcept nogil
15
+
16
+ # pair of macros for tree traversal
17
+ cdef void BEGIN_FOR_EACH_ELEMENT_FROM(tree.xmlNode* tree_top,
18
+ tree.xmlNode* start_node,
19
+ int start_node_inclusive) noexcept nogil
20
+ cdef void END_FOR_EACH_ELEMENT_FROM(tree.xmlNode* start_node) noexcept nogil
21
+
22
+ cdef extern from "etree_api.h":
23
+
24
+ # first function to call!
25
+ cdef int import_lxml__etree() except -1
26
+
27
+ ##########################################################################
28
+ # public ElementTree API classes
29
+
30
+ cdef class lxml.etree._Document [ object LxmlDocument ]:
31
+ cdef tree.xmlDoc* _c_doc
32
+
33
+ cdef class lxml.etree._Element [ object LxmlElement ]:
34
+ cdef _Document _doc
35
+ cdef tree.xmlNode* _c_node
36
+
37
+ cdef class lxml.etree.ElementBase(_Element) [ object LxmlElementBase ]:
38
+ pass
39
+
40
+ cdef class lxml.etree._ElementTree [ object LxmlElementTree ]:
41
+ cdef _Document _doc
42
+ cdef _Element _context_node
43
+
44
+ cdef class lxml.etree.ElementClassLookup [ object LxmlElementClassLookup ]:
45
+ cdef object (*_lookup_function)(object, _Document, tree.xmlNode*)
46
+
47
+ cdef class lxml.etree.FallbackElementClassLookup(ElementClassLookup) \
48
+ [ object LxmlFallbackElementClassLookup ]:
49
+ cdef ElementClassLookup fallback
50
+ cdef object (*_fallback_function)(object, _Document, tree.xmlNode*)
51
+
52
+ ##########################################################################
53
+ # creating Element objects
54
+
55
+ # create an Element for a C-node in the Document
56
+ cdef _Element elementFactory(_Document doc, tree.xmlNode* c_node)
57
+
58
+ # create an ElementTree for an Element
59
+ cdef _ElementTree elementTreeFactory(_Element context_node)
60
+
61
+ # create an ElementTree subclass for an Element
62
+ cdef _ElementTree newElementTree(_Element context_node, object subclass)
63
+
64
+ # create an ElementTree from an external document
65
+ cdef _ElementTree adoptExternalDocument(tree.xmlDoc* c_doc, parser, bint is_owned)
66
+
67
+ # create a new Element for an existing or new document (doc = None)
68
+ # builds Python object after setting text, tail, namespaces and attributes
69
+ cdef _Element makeElement(tag, _Document doc, parser,
70
+ text, tail, attrib, nsmap)
71
+
72
+ # create a new SubElement for an existing parent
73
+ # builds Python object after setting text, tail, namespaces and attributes
74
+ cdef _Element makeSubElement(_Element parent, tag, text, tail,
75
+ attrib, nsmap)
76
+
77
+ # deep copy a node to include it in the Document
78
+ cdef _Element deepcopyNodeToDocument(_Document doc, tree.xmlNode* c_root)
79
+
80
+ # set the internal lookup function for Element/Comment/PI classes
81
+ # use setElementClassLookupFunction(NULL, None) to reset it
82
+ # note that the lookup function *must always* return an _Element subclass!
83
+ cdef void setElementClassLookupFunction(
84
+ object (*function)(object, _Document, tree.xmlNode*), object state)
85
+
86
+ # lookup function that always returns the default Element class
87
+ # note that the first argument is expected to be None!
88
+ cdef object lookupDefaultElementClass(_1, _Document _2,
89
+ tree.xmlNode* c_node)
90
+
91
+ # lookup function for namespace/tag specific Element classes
92
+ # note that the first argument is expected to be None!
93
+ cdef object lookupNamespaceElementClass(_1, _Document _2,
94
+ tree.xmlNode* c_node)
95
+
96
+ # call the fallback lookup function of a FallbackElementClassLookup
97
+ cdef object callLookupFallback(FallbackElementClassLookup lookup,
98
+ _Document doc, tree.xmlNode* c_node)
99
+
100
+ ##########################################################################
101
+ # XML attribute access
102
+
103
+ # return an attribute value for a C attribute on a C element node
104
+ cdef unicode attributeValue(tree.xmlNode* c_element,
105
+ tree.xmlAttr* c_attrib_node)
106
+
107
+ # return the value of the attribute with 'ns' and 'name' (or None)
108
+ cdef unicode attributeValueFromNsName(tree.xmlNode* c_element,
109
+ const_xmlChar* c_ns, const_xmlChar* c_name)
110
+
111
+ # return the value of attribute "{ns}name", or the default value
112
+ cdef object getAttributeValue(_Element element, key, default)
113
+
114
+ # return an iterator over attribute names (1), values (2) or items (3)
115
+ # attributes must not be removed during iteration!
116
+ cdef object iterattributes(_Element element, int keysvalues)
117
+
118
+ # return the list of all attribute names (1), values (2) or items (3)
119
+ cdef list collectAttributes(tree.xmlNode* c_element, int keysvalues)
120
+
121
+ # set an attribute value on an element
122
+ # on failure, sets an exception and returns -1
123
+ cdef int setAttributeValue(_Element element, key, value) except -1
124
+
125
+ # delete an attribute
126
+ # on failure, sets an exception and returns -1
127
+ cdef int delAttribute(_Element element, key) except -1
128
+
129
+ # delete an attribute based on name and namespace URI
130
+ # returns -1 if the attribute was not found (no exception)
131
+ cdef int delAttributeFromNsName(tree.xmlNode* c_element,
132
+ const_xmlChar* c_href, const_xmlChar* c_name) noexcept
133
+
134
+ ##########################################################################
135
+ # XML node helper functions
136
+
137
+ # check if the element has at least one child
138
+ cdef bint hasChild(tree.xmlNode* c_node) noexcept nogil
139
+
140
+ # find child element number 'index' (supports negative indexes)
141
+ cdef tree.xmlNode* findChild(tree.xmlNode* c_node,
142
+ Py_ssize_t index) noexcept nogil
143
+
144
+ # find child element number 'index' starting at first one
145
+ cdef tree.xmlNode* findChildForwards(tree.xmlNode* c_node,
146
+ Py_ssize_t index) nogil
147
+
148
+ # find child element number 'index' starting at last one
149
+ cdef tree.xmlNode* findChildBackwards(tree.xmlNode* c_node,
150
+ Py_ssize_t index) nogil
151
+
152
+ # return next/previous sibling element of the node
153
+ cdef tree.xmlNode* nextElement(tree.xmlNode* c_node) nogil
154
+ cdef tree.xmlNode* previousElement(tree.xmlNode* c_node) nogil
155
+
156
+ ##########################################################################
157
+ # iterators (DEPRECATED API, don't use in new code!)
158
+
159
+ cdef class lxml.etree._ElementTagMatcher [ object LxmlElementTagMatcher ]:
160
+ cdef char* _href
161
+ cdef char* _name
162
+
163
+ # store "{ns}tag" (or None) filter for this matcher or element iterator
164
+ # ** unless _href *and* _name are set up 'by hand', this function *must*
165
+ # ** be called when subclassing the iterator below!
166
+ cdef void initTagMatch(_ElementTagMatcher matcher, tag)
167
+
168
+ cdef class lxml.etree._ElementIterator(_ElementTagMatcher) [
169
+ object LxmlElementIterator ]:
170
+ cdef _Element _node
171
+ cdef tree.xmlNode* (*_next_element)(tree.xmlNode*)
172
+
173
+ # store the initial node of the iterator if it matches the required tag
174
+ # or its next matching sibling if not
175
+ cdef void iteratorStoreNext(_ElementIterator iterator, _Element node)
176
+
177
+ ##########################################################################
178
+ # other helper functions
179
+
180
+ # check if a C node matches a tag name and namespace
181
+ # (NULL allowed for each => always matches)
182
+ cdef int tagMatches(tree.xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name)
183
+
184
+ # convert a UTF-8 char* to a Python unicode string
185
+ cdef unicode pyunicode(const_xmlChar* s)
186
+
187
+ # convert the string to UTF-8 using the normal lxml.etree semantics
188
+ cdef bytes utf8(object s)
189
+
190
+ # split a tag into a (URI, name) tuple, return None as URI for '{}tag'
191
+ cdef tuple getNsTag(object tag)
192
+
193
+ # split a tag into a (URI, name) tuple, return b'' as URI for '{}tag'
194
+ cdef tuple getNsTagWithEmptyNs(object tag)
195
+
196
+ # get the "{ns}tag" string for a C node
197
+ cdef unicode namespacedName(tree.xmlNode* c_node)
198
+
199
+ # get the "{ns}tag" string for a href/tagname pair (c_ns may be NULL)
200
+ cdef unicode namespacedNameFromNsName(const_xmlChar* c_ns, const_xmlChar* c_tag)
201
+
202
+ # check if the node has a text value (which may be '')
203
+ cdef bint hasText(tree.xmlNode* c_node) nogil
204
+
205
+ # check if the node has a tail value (which may be '')
206
+ cdef bint hasTail(tree.xmlNode* c_node) nogil
207
+
208
+ # get the text content of an element (or None)
209
+ cdef unicode textOf(tree.xmlNode* c_node)
210
+
211
+ # get the tail content of an element (or None)
212
+ cdef unicode tailOf(tree.xmlNode* c_node)
213
+
214
+ # set the text value of an element
215
+ cdef int setNodeText(tree.xmlNode* c_node, text) except -1
216
+
217
+ # set the tail text value of an element
218
+ cdef int setTailText(tree.xmlNode* c_node, text) except -1
219
+
220
+ # append an element to the children of a parent element
221
+ # deprecated: don't use, does not propagate exceptions!
222
+ # use appendChildToElement() instead
223
+ cdef void appendChild(_Element parent, _Element child)
224
+
225
+ # added in lxml 3.3 as a safe replacement for appendChild()
226
+ # return -1 for exception, 0 for ok
227
+ cdef int appendChildToElement(_Element parent, _Element child) except -1
228
+
229
+ # recursively lookup a namespace in element or ancestors, or create it
230
+ cdef tree.xmlNs* findOrBuildNodeNsPrefix(
231
+ _Document doc, tree.xmlNode* c_node, const_xmlChar* href, const_xmlChar* prefix)
232
+
233
+ # find the Document of an Element, ElementTree or Document (itself!)
234
+ cdef _Document documentOrRaise(object input)
235
+
236
+ # find the root Element of an Element (itself!), ElementTree or Document
237
+ cdef _Element rootNodeOrRaise(object input)
env-llmeval/lib/python3.10/site-packages/lxml/includes/htmlparser.pxd ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc.string cimport const_char
2
+
3
+ from lxml.includes.tree cimport xmlDoc
4
+ from lxml.includes.tree cimport xmlInputReadCallback, xmlInputCloseCallback
5
+ from lxml.includes.xmlparser cimport xmlParserCtxt, xmlSAXHandler, xmlSAXHandlerV1
6
+
7
+ cdef extern from "libxml/HTMLparser.h" nogil:
8
+ ctypedef enum htmlParserOption:
9
+ HTML_PARSE_NOERROR # suppress error reports
10
+ HTML_PARSE_NOWARNING # suppress warning reports
11
+ HTML_PARSE_PEDANTIC # pedantic error reporting
12
+ HTML_PARSE_NOBLANKS # remove blank nodes
13
+ HTML_PARSE_NONET # Forbid network access
14
+ # libxml2 2.6.21+ only:
15
+ HTML_PARSE_RECOVER # Relaxed parsing
16
+ HTML_PARSE_COMPACT # compact small text nodes
17
+ # libxml2 2.7.7+ only:
18
+ HTML_PARSE_NOIMPLIED # Do not add implied html/body... elements
19
+ # libxml2 2.7.8+ only:
20
+ HTML_PARSE_NODEFDTD # do not default a doctype if not found
21
+ # libxml2 2.8.0+ only:
22
+ XML_PARSE_IGNORE_ENC # ignore internal document encoding hint
23
+
24
+ xmlSAXHandlerV1 htmlDefaultSAXHandler
25
+
26
+ cdef xmlParserCtxt* htmlCreateMemoryParserCtxt(
27
+ char* buffer, int size)
28
+ cdef xmlParserCtxt* htmlCreateFileParserCtxt(
29
+ char* filename, char* encoding)
30
+ cdef xmlParserCtxt* htmlCreatePushParserCtxt(xmlSAXHandler* sax,
31
+ void* user_data,
32
+ char* chunk, int size,
33
+ char* filename, int enc)
34
+ cdef void htmlFreeParserCtxt(xmlParserCtxt* ctxt)
35
+ cdef void htmlCtxtReset(xmlParserCtxt* ctxt)
36
+ cdef int htmlCtxtUseOptions(xmlParserCtxt* ctxt, int options)
37
+ cdef int htmlParseDocument(xmlParserCtxt* ctxt)
38
+ cdef int htmlParseChunk(xmlParserCtxt* ctxt,
39
+ char* chunk, int size, int terminate)
40
+
41
+ cdef xmlDoc* htmlCtxtReadFile(xmlParserCtxt* ctxt,
42
+ char* filename, const_char* encoding,
43
+ int options)
44
+ cdef xmlDoc* htmlCtxtReadDoc(xmlParserCtxt* ctxt,
45
+ char* buffer, char* URL, const_char* encoding,
46
+ int options)
47
+ cdef xmlDoc* htmlCtxtReadIO(xmlParserCtxt* ctxt,
48
+ xmlInputReadCallback ioread,
49
+ xmlInputCloseCallback ioclose,
50
+ void* ioctx,
51
+ char* URL, const_char* encoding,
52
+ int options)
53
+ cdef xmlDoc* htmlCtxtReadMemory(xmlParserCtxt* ctxt,
54
+ char* buffer, int size,
55
+ char* filename, const_char* encoding,
56
+ int options)
env-llmeval/lib/python3.10/site-packages/lxml/includes/libexslt/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/lxml/includes/libexslt/exslt.h ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Summary: main header file
3
+ *
4
+ * Copy: See Copyright for the status of this software.
5
+ */
6
+
7
+
8
+ #ifndef __EXSLT_H__
9
+ #define __EXSLT_H__
10
+
11
+ #include <libxml/tree.h>
12
+ #include <libxml/xpath.h>
13
+ #include "exsltexports.h"
14
+ #include <libexslt/exsltconfig.h>
15
+
16
+ #ifdef __cplusplus
17
+ extern "C" {
18
+ #endif
19
+
20
+ EXSLTPUBVAR const char *exsltLibraryVersion;
21
+ EXSLTPUBVAR const int exsltLibexsltVersion;
22
+ EXSLTPUBVAR const int exsltLibxsltVersion;
23
+ EXSLTPUBVAR const int exsltLibxmlVersion;
24
+
25
+ /**
26
+ * EXSLT_COMMON_NAMESPACE:
27
+ *
28
+ * Namespace for EXSLT common functions
29
+ */
30
+ #define EXSLT_COMMON_NAMESPACE ((const xmlChar *) "http://exslt.org/common")
31
+ /**
32
+ * EXSLT_CRYPTO_NAMESPACE:
33
+ *
34
+ * Namespace for EXSLT crypto functions
35
+ */
36
+ #define EXSLT_CRYPTO_NAMESPACE ((const xmlChar *) "http://exslt.org/crypto")
37
+ /**
38
+ * EXSLT_MATH_NAMESPACE:
39
+ *
40
+ * Namespace for EXSLT math functions
41
+ */
42
+ #define EXSLT_MATH_NAMESPACE ((const xmlChar *) "http://exslt.org/math")
43
+ /**
44
+ * EXSLT_SETS_NAMESPACE:
45
+ *
46
+ * Namespace for EXSLT set functions
47
+ */
48
+ #define EXSLT_SETS_NAMESPACE ((const xmlChar *) "http://exslt.org/sets")
49
+ /**
50
+ * EXSLT_FUNCTIONS_NAMESPACE:
51
+ *
52
+ * Namespace for EXSLT functions extension functions
53
+ */
54
+ #define EXSLT_FUNCTIONS_NAMESPACE ((const xmlChar *) "http://exslt.org/functions")
55
+ /**
56
+ * EXSLT_STRINGS_NAMESPACE:
57
+ *
58
+ * Namespace for EXSLT strings functions
59
+ */
60
+ #define EXSLT_STRINGS_NAMESPACE ((const xmlChar *) "http://exslt.org/strings")
61
+ /**
62
+ * EXSLT_DATE_NAMESPACE:
63
+ *
64
+ * Namespace for EXSLT date functions
65
+ */
66
+ #define EXSLT_DATE_NAMESPACE ((const xmlChar *) "http://exslt.org/dates-and-times")
67
+ /**
68
+ * EXSLT_DYNAMIC_NAMESPACE:
69
+ *
70
+ * Namespace for EXSLT dynamic functions
71
+ */
72
+ #define EXSLT_DYNAMIC_NAMESPACE ((const xmlChar *) "http://exslt.org/dynamic")
73
+
74
+ /**
75
+ * SAXON_NAMESPACE:
76
+ *
77
+ * Namespace for SAXON extensions functions
78
+ */
79
+ #define SAXON_NAMESPACE ((const xmlChar *) "http://icl.com/saxon")
80
+
81
+ EXSLTPUBFUN void EXSLTCALL exsltCommonRegister (void);
82
+ #ifdef EXSLT_CRYPTO_ENABLED
83
+ EXSLTPUBFUN void EXSLTCALL exsltCryptoRegister (void);
84
+ #endif
85
+ EXSLTPUBFUN void EXSLTCALL exsltMathRegister (void);
86
+ EXSLTPUBFUN void EXSLTCALL exsltSetsRegister (void);
87
+ EXSLTPUBFUN void EXSLTCALL exsltFuncRegister (void);
88
+ EXSLTPUBFUN void EXSLTCALL exsltStrRegister (void);
89
+ EXSLTPUBFUN void EXSLTCALL exsltDateRegister (void);
90
+ EXSLTPUBFUN void EXSLTCALL exsltSaxonRegister (void);
91
+ EXSLTPUBFUN void EXSLTCALL exsltDynRegister(void);
92
+
93
+ EXSLTPUBFUN void EXSLTCALL exsltRegisterAll (void);
94
+
95
+ EXSLTPUBFUN int EXSLTCALL exsltDateXpathCtxtRegister (xmlXPathContextPtr ctxt,
96
+ const xmlChar *prefix);
97
+ EXSLTPUBFUN int EXSLTCALL exsltMathXpathCtxtRegister (xmlXPathContextPtr ctxt,
98
+ const xmlChar *prefix);
99
+ EXSLTPUBFUN int EXSLTCALL exsltSetsXpathCtxtRegister (xmlXPathContextPtr ctxt,
100
+ const xmlChar *prefix);
101
+ EXSLTPUBFUN int EXSLTCALL exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt,
102
+ const xmlChar *prefix);
103
+
104
+ #ifdef __cplusplus
105
+ }
106
+ #endif
107
+ #endif /* __EXSLT_H__ */
108
+
env-llmeval/lib/python3.10/site-packages/lxml/includes/libexslt/exsltconfig.h ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * exsltconfig.h: compile-time version information for the EXSLT library
3
+ *
4
+ * See Copyright for the status of this software.
5
+ *
6
7
+ */
8
+
9
+ #ifndef __XML_EXSLTCONFIG_H__
10
+ #define __XML_EXSLTCONFIG_H__
11
+
12
+ #ifdef __cplusplus
13
+ extern "C" {
14
+ #endif
15
+
16
+ /**
17
+ * LIBEXSLT_DOTTED_VERSION:
18
+ *
19
+ * the version string like "1.2.3"
20
+ */
21
+ #define LIBEXSLT_DOTTED_VERSION "0.8.21"
22
+
23
+ /**
24
+ * LIBEXSLT_VERSION:
25
+ *
26
+ * the version number: 1.2.3 value is 10203
27
+ */
28
+ #define LIBEXSLT_VERSION 821
29
+
30
+ /**
31
+ * LIBEXSLT_VERSION_STRING:
32
+ *
33
+ * the version number string, 1.2.3 value is "10203"
34
+ */
35
+ #define LIBEXSLT_VERSION_STRING "821"
36
+
37
+ /**
38
+ * LIBEXSLT_VERSION_EXTRA:
39
+ *
40
+ * extra version information, used to show a Git commit description
41
+ */
42
+ #define LIBEXSLT_VERSION_EXTRA ""
43
+
44
+ /**
45
+ * WITH_CRYPTO:
46
+ *
47
+ * Whether crypto support is configured into exslt
48
+ */
49
+ #if 0
50
+ #define EXSLT_CRYPTO_ENABLED
51
+ #endif
52
+
53
+ /**
54
+ * ATTRIBUTE_UNUSED:
55
+ *
56
+ * This macro is used to flag unused function parameters to GCC
57
+ */
58
+ #ifdef __GNUC__
59
+ #ifndef ATTRIBUTE_UNUSED
60
+ #define ATTRIBUTE_UNUSED __attribute__((unused))
61
+ #endif
62
+ #else
63
+ #define ATTRIBUTE_UNUSED
64
+ #endif
65
+
66
+ #ifdef __cplusplus
67
+ }
68
+ #endif
69
+
70
+ #endif /* __XML_EXSLTCONFIG_H__ */
env-llmeval/lib/python3.10/site-packages/lxml/includes/schematron.pxd ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes cimport xmlerror
2
+ from lxml.includes.tree cimport xmlDoc
3
+
4
+ cdef extern from "libxml/schematron.h" nogil:
5
+ ctypedef struct xmlSchematron
6
+ ctypedef struct xmlSchematronParserCtxt
7
+ ctypedef struct xmlSchematronValidCtxt
8
+
9
+ ctypedef enum xmlSchematronValidOptions:
10
+ XML_SCHEMATRON_OUT_QUIET = 1 # quiet no report
11
+ XML_SCHEMATRON_OUT_TEXT = 2 # build a textual report
12
+ XML_SCHEMATRON_OUT_XML = 4 # output SVRL
13
+ XML_SCHEMATRON_OUT_ERROR = 8 # output via xmlStructuredErrorFunc
14
+ XML_SCHEMATRON_OUT_FILE = 256 # output to a file descriptor
15
+ XML_SCHEMATRON_OUT_BUFFER = 512 # output to a buffer
16
+ XML_SCHEMATRON_OUT_IO = 1024 # output to I/O mechanism
17
+
18
+ cdef xmlSchematronParserCtxt* xmlSchematronNewDocParserCtxt(
19
+ xmlDoc* doc)
20
+ cdef xmlSchematronParserCtxt* xmlSchematronNewParserCtxt(
21
+ char* filename) nogil
22
+ cdef xmlSchematronValidCtxt* xmlSchematronNewValidCtxt(
23
+ xmlSchematron* schema, int options)
24
+
25
+ cdef xmlSchematron* xmlSchematronParse(xmlSchematronParserCtxt* ctxt)
26
+ cdef int xmlSchematronValidateDoc(xmlSchematronValidCtxt* ctxt,
27
+ xmlDoc* instance)
28
+
29
+ cdef void xmlSchematronFreeParserCtxt(xmlSchematronParserCtxt* ctxt)
30
+ cdef void xmlSchematronFreeValidCtxt(xmlSchematronValidCtxt* ctxt)
31
+ cdef void xmlSchematronFree(xmlSchematron* schema)
32
+ cdef void xmlSchematronSetValidStructuredErrors(
33
+ xmlSchematronValidCtxt* ctxt,
34
+ xmlerror.xmlStructuredErrorFunc error_func, void *data)
env-llmeval/lib/python3.10/site-packages/lxml/includes/xinclude.pxd ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes.tree cimport xmlDoc, xmlNode
2
+
3
+ cdef extern from "libxml/xinclude.h" nogil:
4
+
5
+ ctypedef struct xmlXIncludeCtxt
6
+
7
+ cdef int xmlXIncludeProcess(xmlDoc* doc)
8
+ cdef int xmlXIncludeProcessFlags(xmlDoc* doc, int parser_opts)
9
+ cdef int xmlXIncludeProcessTree(xmlNode* doc)
10
+ cdef int xmlXIncludeProcessTreeFlags(xmlNode* doc, int parser_opts)
11
+
12
+ # libxml2 >= 2.7.4
13
+ cdef int xmlXIncludeProcessTreeFlagsData(
14
+ xmlNode* doc, int parser_opts, void* data)
15
+
16
+ cdef xmlXIncludeCtxt* xmlXIncludeNewContext(xmlDoc* doc)
17
+ cdef int xmlXIncludeProcessNode(xmlXIncludeCtxt* ctxt, xmlNode* node)
18
+ cdef int xmlXIncludeSetFlags(xmlXIncludeCtxt* ctxt, int flags)
19
+
20
+ # libxml2 >= 2.6.27
21
+ cdef int xmlXIncludeProcessFlagsData(
22
+ xmlDoc* doc, int flags, void* data)
env-llmeval/lib/python3.10/site-packages/lxml/includes/xmlerror.pxd ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # --- BEGIN: GENERATED CONSTANTS ---
3
+
4
+ # This section is generated by the script 'update-error-constants.py'.
5
+
6
+ cdef extern from "libxml/xmlerror.h":
7
+ ctypedef enum xmlErrorLevel:
8
+ XML_ERR_NONE = 0
9
+ XML_ERR_WARNING = 1 # A simple warning
10
+ XML_ERR_ERROR = 2 # A recoverable error
11
+ XML_ERR_FATAL = 3 # A fatal error
12
+
13
+ ctypedef enum xmlErrorDomain:
14
+ XML_FROM_NONE = 0
15
+ XML_FROM_PARSER = 1 # The XML parser
16
+ XML_FROM_TREE = 2 # The tree module
17
+ XML_FROM_NAMESPACE = 3 # The XML Namespace module
18
+ XML_FROM_DTD = 4 # The XML DTD validation with parser contex
19
+ XML_FROM_HTML = 5 # The HTML parser
20
+ XML_FROM_MEMORY = 6 # The memory allocator
21
+ XML_FROM_OUTPUT = 7 # The serialization code
22
+ XML_FROM_IO = 8 # The Input/Output stack
23
+ XML_FROM_FTP = 9 # The FTP module
24
+ XML_FROM_HTTP = 10 # The HTTP module
25
+ XML_FROM_XINCLUDE = 11 # The XInclude processing
26
+ XML_FROM_XPATH = 12 # The XPath module
27
+ XML_FROM_XPOINTER = 13 # The XPointer module
28
+ XML_FROM_REGEXP = 14 # The regular expressions module
29
+ XML_FROM_DATATYPE = 15 # The W3C XML Schemas Datatype module
30
+ XML_FROM_SCHEMASP = 16 # The W3C XML Schemas parser module
31
+ XML_FROM_SCHEMASV = 17 # The W3C XML Schemas validation module
32
+ XML_FROM_RELAXNGP = 18 # The Relax-NG parser module
33
+ XML_FROM_RELAXNGV = 19 # The Relax-NG validator module
34
+ XML_FROM_CATALOG = 20 # The Catalog module
35
+ XML_FROM_C14N = 21 # The Canonicalization module
36
+ XML_FROM_XSLT = 22 # The XSLT engine from libxslt
37
+ XML_FROM_VALID = 23 # The XML DTD validation with valid context
38
+ XML_FROM_CHECK = 24 # The error checking module
39
+ XML_FROM_WRITER = 25 # The xmlwriter module
40
+ XML_FROM_MODULE = 26 # The dynamically loaded module modul
41
+ XML_FROM_I18N = 27 # The module handling character conversion
42
+ XML_FROM_SCHEMATRONV = 28 # The Schematron validator module
43
+ XML_FROM_BUFFER = 29 # The buffers module
44
+ XML_FROM_URI = 30 # The URI module
45
+
46
+ ctypedef enum xmlParserErrors:
47
+ XML_ERR_OK = 0
48
+ XML_ERR_INTERNAL_ERROR = 1
49
+ XML_ERR_NO_MEMORY = 2
50
+ XML_ERR_DOCUMENT_START = 3
51
+ XML_ERR_DOCUMENT_EMPTY = 4
52
+ XML_ERR_DOCUMENT_END = 5
53
+ XML_ERR_INVALID_HEX_CHARREF = 6
54
+ XML_ERR_INVALID_DEC_CHARREF = 7
55
+ XML_ERR_INVALID_CHARREF = 8
56
+ XML_ERR_INVALID_CHAR = 9
57
+ XML_ERR_CHARREF_AT_EOF = 10
58
+ XML_ERR_CHARREF_IN_PROLOG = 11
59
+ XML_ERR_CHARREF_IN_EPILOG = 12
60
+ XML_ERR_CHARREF_IN_DTD = 13
61
+ XML_ERR_ENTITYREF_AT_EOF = 14
62
+ XML_ERR_ENTITYREF_IN_PROLOG = 15
63
+ XML_ERR_ENTITYREF_IN_EPILOG = 16
64
+ XML_ERR_ENTITYREF_IN_DTD = 17
65
+ XML_ERR_PEREF_AT_EOF = 18
66
+ XML_ERR_PEREF_IN_PROLOG = 19
67
+ XML_ERR_PEREF_IN_EPILOG = 20
68
+ XML_ERR_PEREF_IN_INT_SUBSET = 21
69
+ XML_ERR_ENTITYREF_NO_NAME = 22
70
+ XML_ERR_ENTITYREF_SEMICOL_MISSING = 23
71
+ XML_ERR_PEREF_NO_NAME = 24
72
+ XML_ERR_PEREF_SEMICOL_MISSING = 25
73
+ XML_ERR_UNDECLARED_ENTITY = 26
74
+ XML_WAR_UNDECLARED_ENTITY = 27
75
+ XML_ERR_UNPARSED_ENTITY = 28
76
+ XML_ERR_ENTITY_IS_EXTERNAL = 29
77
+ XML_ERR_ENTITY_IS_PARAMETER = 30
78
+ XML_ERR_UNKNOWN_ENCODING = 31
79
+ XML_ERR_UNSUPPORTED_ENCODING = 32
80
+ XML_ERR_STRING_NOT_STARTED = 33
81
+ XML_ERR_STRING_NOT_CLOSED = 34
82
+ XML_ERR_NS_DECL_ERROR = 35
83
+ XML_ERR_ENTITY_NOT_STARTED = 36
84
+ XML_ERR_ENTITY_NOT_FINISHED = 37
85
+ XML_ERR_LT_IN_ATTRIBUTE = 38
86
+ XML_ERR_ATTRIBUTE_NOT_STARTED = 39
87
+ XML_ERR_ATTRIBUTE_NOT_FINISHED = 40
88
+ XML_ERR_ATTRIBUTE_WITHOUT_VALUE = 41
89
+ XML_ERR_ATTRIBUTE_REDEFINED = 42
90
+ XML_ERR_LITERAL_NOT_STARTED = 43
91
+ XML_ERR_LITERAL_NOT_FINISHED = 44
92
+ XML_ERR_COMMENT_NOT_FINISHED = 45
93
+ XML_ERR_PI_NOT_STARTED = 46
94
+ XML_ERR_PI_NOT_FINISHED = 47
95
+ XML_ERR_NOTATION_NOT_STARTED = 48
96
+ XML_ERR_NOTATION_NOT_FINISHED = 49
97
+ XML_ERR_ATTLIST_NOT_STARTED = 50
98
+ XML_ERR_ATTLIST_NOT_FINISHED = 51
99
+ XML_ERR_MIXED_NOT_STARTED = 52
100
+ XML_ERR_MIXED_NOT_FINISHED = 53
101
+ XML_ERR_ELEMCONTENT_NOT_STARTED = 54
102
+ XML_ERR_ELEMCONTENT_NOT_FINISHED = 55
103
+ XML_ERR_XMLDECL_NOT_STARTED = 56
104
+ XML_ERR_XMLDECL_NOT_FINISHED = 57
105
+ XML_ERR_CONDSEC_NOT_STARTED = 58
106
+ XML_ERR_CONDSEC_NOT_FINISHED = 59
107
+ XML_ERR_EXT_SUBSET_NOT_FINISHED = 60
108
+ XML_ERR_DOCTYPE_NOT_FINISHED = 61
109
+ XML_ERR_MISPLACED_CDATA_END = 62
110
+ XML_ERR_CDATA_NOT_FINISHED = 63
111
+ XML_ERR_RESERVED_XML_NAME = 64
112
+ XML_ERR_SPACE_REQUIRED = 65
113
+ XML_ERR_SEPARATOR_REQUIRED = 66
114
+ XML_ERR_NMTOKEN_REQUIRED = 67
115
+ XML_ERR_NAME_REQUIRED = 68
116
+ XML_ERR_PCDATA_REQUIRED = 69
117
+ XML_ERR_URI_REQUIRED = 70
118
+ XML_ERR_PUBID_REQUIRED = 71
119
+ XML_ERR_LT_REQUIRED = 72
120
+ XML_ERR_GT_REQUIRED = 73
121
+ XML_ERR_LTSLASH_REQUIRED = 74
122
+ XML_ERR_EQUAL_REQUIRED = 75
123
+ XML_ERR_TAG_NAME_MISMATCH = 76
124
+ XML_ERR_TAG_NOT_FINISHED = 77
125
+ XML_ERR_STANDALONE_VALUE = 78
126
+ XML_ERR_ENCODING_NAME = 79
127
+ XML_ERR_HYPHEN_IN_COMMENT = 80
128
+ XML_ERR_INVALID_ENCODING = 81
129
+ XML_ERR_EXT_ENTITY_STANDALONE = 82
130
+ XML_ERR_CONDSEC_INVALID = 83
131
+ XML_ERR_VALUE_REQUIRED = 84
132
+ XML_ERR_NOT_WELL_BALANCED = 85
133
+ XML_ERR_EXTRA_CONTENT = 86
134
+ XML_ERR_ENTITY_CHAR_ERROR = 87
135
+ XML_ERR_ENTITY_PE_INTERNAL = 88
136
+ XML_ERR_ENTITY_LOOP = 89
137
+ XML_ERR_ENTITY_BOUNDARY = 90
138
+ XML_ERR_INVALID_URI = 91
139
+ XML_ERR_URI_FRAGMENT = 92
140
+ XML_WAR_CATALOG_PI = 93
141
+ XML_ERR_NO_DTD = 94
142
+ XML_ERR_CONDSEC_INVALID_KEYWORD = 95
143
+ XML_ERR_VERSION_MISSING = 96
144
+ XML_WAR_UNKNOWN_VERSION = 97
145
+ XML_WAR_LANG_VALUE = 98
146
+ XML_WAR_NS_URI = 99
147
+ XML_WAR_NS_URI_RELATIVE = 100
148
+ XML_ERR_MISSING_ENCODING = 101
149
+ XML_WAR_SPACE_VALUE = 102
150
+ XML_ERR_NOT_STANDALONE = 103
151
+ XML_ERR_ENTITY_PROCESSING = 104
152
+ XML_ERR_NOTATION_PROCESSING = 105
153
+ XML_WAR_NS_COLUMN = 106
154
+ XML_WAR_ENTITY_REDEFINED = 107
155
+ XML_ERR_UNKNOWN_VERSION = 108
156
+ XML_ERR_VERSION_MISMATCH = 109
157
+ XML_ERR_NAME_TOO_LONG = 110
158
+ XML_ERR_USER_STOP = 111
159
+ XML_ERR_COMMENT_ABRUPTLY_ENDED = 112
160
+ XML_NS_ERR_XML_NAMESPACE = 200
161
+ XML_NS_ERR_UNDEFINED_NAMESPACE = 201
162
+ XML_NS_ERR_QNAME = 202
163
+ XML_NS_ERR_ATTRIBUTE_REDEFINED = 203
164
+ XML_NS_ERR_EMPTY = 204
165
+ XML_NS_ERR_COLON = 205
166
+ XML_DTD_ATTRIBUTE_DEFAULT = 500
167
+ XML_DTD_ATTRIBUTE_REDEFINED = 501
168
+ XML_DTD_ATTRIBUTE_VALUE = 502
169
+ XML_DTD_CONTENT_ERROR = 503
170
+ XML_DTD_CONTENT_MODEL = 504
171
+ XML_DTD_CONTENT_NOT_DETERMINIST = 505
172
+ XML_DTD_DIFFERENT_PREFIX = 506
173
+ XML_DTD_ELEM_DEFAULT_NAMESPACE = 507
174
+ XML_DTD_ELEM_NAMESPACE = 508
175
+ XML_DTD_ELEM_REDEFINED = 509
176
+ XML_DTD_EMPTY_NOTATION = 510
177
+ XML_DTD_ENTITY_TYPE = 511
178
+ XML_DTD_ID_FIXED = 512
179
+ XML_DTD_ID_REDEFINED = 513
180
+ XML_DTD_ID_SUBSET = 514
181
+ XML_DTD_INVALID_CHILD = 515
182
+ XML_DTD_INVALID_DEFAULT = 516
183
+ XML_DTD_LOAD_ERROR = 517
184
+ XML_DTD_MISSING_ATTRIBUTE = 518
185
+ XML_DTD_MIXED_CORRUPT = 519
186
+ XML_DTD_MULTIPLE_ID = 520
187
+ XML_DTD_NO_DOC = 521
188
+ XML_DTD_NO_DTD = 522
189
+ XML_DTD_NO_ELEM_NAME = 523
190
+ XML_DTD_NO_PREFIX = 524
191
+ XML_DTD_NO_ROOT = 525
192
+ XML_DTD_NOTATION_REDEFINED = 526
193
+ XML_DTD_NOTATION_VALUE = 527
194
+ XML_DTD_NOT_EMPTY = 528
195
+ XML_DTD_NOT_PCDATA = 529
196
+ XML_DTD_NOT_STANDALONE = 530
197
+ XML_DTD_ROOT_NAME = 531
198
+ XML_DTD_STANDALONE_WHITE_SPACE = 532
199
+ XML_DTD_UNKNOWN_ATTRIBUTE = 533
200
+ XML_DTD_UNKNOWN_ELEM = 534
201
+ XML_DTD_UNKNOWN_ENTITY = 535
202
+ XML_DTD_UNKNOWN_ID = 536
203
+ XML_DTD_UNKNOWN_NOTATION = 537
204
+ XML_DTD_STANDALONE_DEFAULTED = 538
205
+ XML_DTD_XMLID_VALUE = 539
206
+ XML_DTD_XMLID_TYPE = 540
207
+ XML_DTD_DUP_TOKEN = 541
208
+ XML_HTML_STRUCURE_ERROR = 800
209
+ XML_HTML_UNKNOWN_TAG = 801
210
+ XML_RNGP_ANYNAME_ATTR_ANCESTOR = 1000
211
+ XML_RNGP_ATTR_CONFLICT = 1001
212
+ XML_RNGP_ATTRIBUTE_CHILDREN = 1002
213
+ XML_RNGP_ATTRIBUTE_CONTENT = 1003
214
+ XML_RNGP_ATTRIBUTE_EMPTY = 1004
215
+ XML_RNGP_ATTRIBUTE_NOOP = 1005
216
+ XML_RNGP_CHOICE_CONTENT = 1006
217
+ XML_RNGP_CHOICE_EMPTY = 1007
218
+ XML_RNGP_CREATE_FAILURE = 1008
219
+ XML_RNGP_DATA_CONTENT = 1009
220
+ XML_RNGP_DEF_CHOICE_AND_INTERLEAVE = 1010
221
+ XML_RNGP_DEFINE_CREATE_FAILED = 1011
222
+ XML_RNGP_DEFINE_EMPTY = 1012
223
+ XML_RNGP_DEFINE_MISSING = 1013
224
+ XML_RNGP_DEFINE_NAME_MISSING = 1014
225
+ XML_RNGP_ELEM_CONTENT_EMPTY = 1015
226
+ XML_RNGP_ELEM_CONTENT_ERROR = 1016
227
+ XML_RNGP_ELEMENT_EMPTY = 1017
228
+ XML_RNGP_ELEMENT_CONTENT = 1018
229
+ XML_RNGP_ELEMENT_NAME = 1019
230
+ XML_RNGP_ELEMENT_NO_CONTENT = 1020
231
+ XML_RNGP_ELEM_TEXT_CONFLICT = 1021
232
+ XML_RNGP_EMPTY = 1022
233
+ XML_RNGP_EMPTY_CONSTRUCT = 1023
234
+ XML_RNGP_EMPTY_CONTENT = 1024
235
+ XML_RNGP_EMPTY_NOT_EMPTY = 1025
236
+ XML_RNGP_ERROR_TYPE_LIB = 1026
237
+ XML_RNGP_EXCEPT_EMPTY = 1027
238
+ XML_RNGP_EXCEPT_MISSING = 1028
239
+ XML_RNGP_EXCEPT_MULTIPLE = 1029
240
+ XML_RNGP_EXCEPT_NO_CONTENT = 1030
241
+ XML_RNGP_EXTERNALREF_EMTPY = 1031
242
+ XML_RNGP_EXTERNAL_REF_FAILURE = 1032
243
+ XML_RNGP_EXTERNALREF_RECURSE = 1033
244
+ XML_RNGP_FORBIDDEN_ATTRIBUTE = 1034
245
+ XML_RNGP_FOREIGN_ELEMENT = 1035
246
+ XML_RNGP_GRAMMAR_CONTENT = 1036
247
+ XML_RNGP_GRAMMAR_EMPTY = 1037
248
+ XML_RNGP_GRAMMAR_MISSING = 1038
249
+ XML_RNGP_GRAMMAR_NO_START = 1039
250
+ XML_RNGP_GROUP_ATTR_CONFLICT = 1040
251
+ XML_RNGP_HREF_ERROR = 1041
252
+ XML_RNGP_INCLUDE_EMPTY = 1042
253
+ XML_RNGP_INCLUDE_FAILURE = 1043
254
+ XML_RNGP_INCLUDE_RECURSE = 1044
255
+ XML_RNGP_INTERLEAVE_ADD = 1045
256
+ XML_RNGP_INTERLEAVE_CREATE_FAILED = 1046
257
+ XML_RNGP_INTERLEAVE_EMPTY = 1047
258
+ XML_RNGP_INTERLEAVE_NO_CONTENT = 1048
259
+ XML_RNGP_INVALID_DEFINE_NAME = 1049
260
+ XML_RNGP_INVALID_URI = 1050
261
+ XML_RNGP_INVALID_VALUE = 1051
262
+ XML_RNGP_MISSING_HREF = 1052
263
+ XML_RNGP_NAME_MISSING = 1053
264
+ XML_RNGP_NEED_COMBINE = 1054
265
+ XML_RNGP_NOTALLOWED_NOT_EMPTY = 1055
266
+ XML_RNGP_NSNAME_ATTR_ANCESTOR = 1056
267
+ XML_RNGP_NSNAME_NO_NS = 1057
268
+ XML_RNGP_PARAM_FORBIDDEN = 1058
269
+ XML_RNGP_PARAM_NAME_MISSING = 1059
270
+ XML_RNGP_PARENTREF_CREATE_FAILED = 1060
271
+ XML_RNGP_PARENTREF_NAME_INVALID = 1061
272
+ XML_RNGP_PARENTREF_NO_NAME = 1062
273
+ XML_RNGP_PARENTREF_NO_PARENT = 1063
274
+ XML_RNGP_PARENTREF_NOT_EMPTY = 1064
275
+ XML_RNGP_PARSE_ERROR = 1065
276
+ XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME = 1066
277
+ XML_RNGP_PAT_ATTR_ATTR = 1067
278
+ XML_RNGP_PAT_ATTR_ELEM = 1068
279
+ XML_RNGP_PAT_DATA_EXCEPT_ATTR = 1069
280
+ XML_RNGP_PAT_DATA_EXCEPT_ELEM = 1070
281
+ XML_RNGP_PAT_DATA_EXCEPT_EMPTY = 1071
282
+ XML_RNGP_PAT_DATA_EXCEPT_GROUP = 1072
283
+ XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE = 1073
284
+ XML_RNGP_PAT_DATA_EXCEPT_LIST = 1074
285
+ XML_RNGP_PAT_DATA_EXCEPT_ONEMORE = 1075
286
+ XML_RNGP_PAT_DATA_EXCEPT_REF = 1076
287
+ XML_RNGP_PAT_DATA_EXCEPT_TEXT = 1077
288
+ XML_RNGP_PAT_LIST_ATTR = 1078
289
+ XML_RNGP_PAT_LIST_ELEM = 1079
290
+ XML_RNGP_PAT_LIST_INTERLEAVE = 1080
291
+ XML_RNGP_PAT_LIST_LIST = 1081
292
+ XML_RNGP_PAT_LIST_REF = 1082
293
+ XML_RNGP_PAT_LIST_TEXT = 1083
294
+ XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME = 1084
295
+ XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME = 1085
296
+ XML_RNGP_PAT_ONEMORE_GROUP_ATTR = 1086
297
+ XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR = 1087
298
+ XML_RNGP_PAT_START_ATTR = 1088
299
+ XML_RNGP_PAT_START_DATA = 1089
300
+ XML_RNGP_PAT_START_EMPTY = 1090
301
+ XML_RNGP_PAT_START_GROUP = 1091
302
+ XML_RNGP_PAT_START_INTERLEAVE = 1092
303
+ XML_RNGP_PAT_START_LIST = 1093
304
+ XML_RNGP_PAT_START_ONEMORE = 1094
305
+ XML_RNGP_PAT_START_TEXT = 1095
306
+ XML_RNGP_PAT_START_VALUE = 1096
307
+ XML_RNGP_PREFIX_UNDEFINED = 1097
308
+ XML_RNGP_REF_CREATE_FAILED = 1098
309
+ XML_RNGP_REF_CYCLE = 1099
310
+ XML_RNGP_REF_NAME_INVALID = 1100
311
+ XML_RNGP_REF_NO_DEF = 1101
312
+ XML_RNGP_REF_NO_NAME = 1102
313
+ XML_RNGP_REF_NOT_EMPTY = 1103
314
+ XML_RNGP_START_CHOICE_AND_INTERLEAVE = 1104
315
+ XML_RNGP_START_CONTENT = 1105
316
+ XML_RNGP_START_EMPTY = 1106
317
+ XML_RNGP_START_MISSING = 1107
318
+ XML_RNGP_TEXT_EXPECTED = 1108
319
+ XML_RNGP_TEXT_HAS_CHILD = 1109
320
+ XML_RNGP_TYPE_MISSING = 1110
321
+ XML_RNGP_TYPE_NOT_FOUND = 1111
322
+ XML_RNGP_TYPE_VALUE = 1112
323
+ XML_RNGP_UNKNOWN_ATTRIBUTE = 1113
324
+ XML_RNGP_UNKNOWN_COMBINE = 1114
325
+ XML_RNGP_UNKNOWN_CONSTRUCT = 1115
326
+ XML_RNGP_UNKNOWN_TYPE_LIB = 1116
327
+ XML_RNGP_URI_FRAGMENT = 1117
328
+ XML_RNGP_URI_NOT_ABSOLUTE = 1118
329
+ XML_RNGP_VALUE_EMPTY = 1119
330
+ XML_RNGP_VALUE_NO_CONTENT = 1120
331
+ XML_RNGP_XMLNS_NAME = 1121
332
+ XML_RNGP_XML_NS = 1122
333
+ XML_XPATH_EXPRESSION_OK = 1200
334
+ XML_XPATH_NUMBER_ERROR = 1201
335
+ XML_XPATH_UNFINISHED_LITERAL_ERROR = 1202
336
+ XML_XPATH_START_LITERAL_ERROR = 1203
337
+ XML_XPATH_VARIABLE_REF_ERROR = 1204
338
+ XML_XPATH_UNDEF_VARIABLE_ERROR = 1205
339
+ XML_XPATH_INVALID_PREDICATE_ERROR = 1206
340
+ XML_XPATH_EXPR_ERROR = 1207
341
+ XML_XPATH_UNCLOSED_ERROR = 1208
342
+ XML_XPATH_UNKNOWN_FUNC_ERROR = 1209
343
+ XML_XPATH_INVALID_OPERAND = 1210
344
+ XML_XPATH_INVALID_TYPE = 1211
345
+ XML_XPATH_INVALID_ARITY = 1212
346
+ XML_XPATH_INVALID_CTXT_SIZE = 1213
347
+ XML_XPATH_INVALID_CTXT_POSITION = 1214
348
+ XML_XPATH_MEMORY_ERROR = 1215
349
+ XML_XPTR_SYNTAX_ERROR = 1216
350
+ XML_XPTR_RESOURCE_ERROR = 1217
351
+ XML_XPTR_SUB_RESOURCE_ERROR = 1218
352
+ XML_XPATH_UNDEF_PREFIX_ERROR = 1219
353
+ XML_XPATH_ENCODING_ERROR = 1220
354
+ XML_XPATH_INVALID_CHAR_ERROR = 1221
355
+ XML_TREE_INVALID_HEX = 1300
356
+ XML_TREE_INVALID_DEC = 1301
357
+ XML_TREE_UNTERMINATED_ENTITY = 1302
358
+ XML_TREE_NOT_UTF8 = 1303
359
+ XML_SAVE_NOT_UTF8 = 1400
360
+ XML_SAVE_CHAR_INVALID = 1401
361
+ XML_SAVE_NO_DOCTYPE = 1402
362
+ XML_SAVE_UNKNOWN_ENCODING = 1403
363
+ XML_REGEXP_COMPILE_ERROR = 1450
364
+ XML_IO_UNKNOWN = 1500
365
+ XML_IO_EACCES = 1501
366
+ XML_IO_EAGAIN = 1502
367
+ XML_IO_EBADF = 1503
368
+ XML_IO_EBADMSG = 1504
369
+ XML_IO_EBUSY = 1505
370
+ XML_IO_ECANCELED = 1506
371
+ XML_IO_ECHILD = 1507
372
+ XML_IO_EDEADLK = 1508
373
+ XML_IO_EDOM = 1509
374
+ XML_IO_EEXIST = 1510
375
+ XML_IO_EFAULT = 1511
376
+ XML_IO_EFBIG = 1512
377
+ XML_IO_EINPROGRESS = 1513
378
+ XML_IO_EINTR = 1514
379
+ XML_IO_EINVAL = 1515
380
+ XML_IO_EIO = 1516
381
+ XML_IO_EISDIR = 1517
382
+ XML_IO_EMFILE = 1518
383
+ XML_IO_EMLINK = 1519
384
+ XML_IO_EMSGSIZE = 1520
385
+ XML_IO_ENAMETOOLONG = 1521
386
+ XML_IO_ENFILE = 1522
387
+ XML_IO_ENODEV = 1523
388
+ XML_IO_ENOENT = 1524
389
+ XML_IO_ENOEXEC = 1525
390
+ XML_IO_ENOLCK = 1526
391
+ XML_IO_ENOMEM = 1527
392
+ XML_IO_ENOSPC = 1528
393
+ XML_IO_ENOSYS = 1529
394
+ XML_IO_ENOTDIR = 1530
395
+ XML_IO_ENOTEMPTY = 1531
396
+ XML_IO_ENOTSUP = 1532
397
+ XML_IO_ENOTTY = 1533
398
+ XML_IO_ENXIO = 1534
399
+ XML_IO_EPERM = 1535
400
+ XML_IO_EPIPE = 1536
401
+ XML_IO_ERANGE = 1537
402
+ XML_IO_EROFS = 1538
403
+ XML_IO_ESPIPE = 1539
404
+ XML_IO_ESRCH = 1540
405
+ XML_IO_ETIMEDOUT = 1541
406
+ XML_IO_EXDEV = 1542
407
+ XML_IO_NETWORK_ATTEMPT = 1543
408
+ XML_IO_ENCODER = 1544
409
+ XML_IO_FLUSH = 1545
410
+ XML_IO_WRITE = 1546
411
+ XML_IO_NO_INPUT = 1547
412
+ XML_IO_BUFFER_FULL = 1548
413
+ XML_IO_LOAD_ERROR = 1549
414
+ XML_IO_ENOTSOCK = 1550
415
+ XML_IO_EISCONN = 1551
416
+ XML_IO_ECONNREFUSED = 1552
417
+ XML_IO_ENETUNREACH = 1553
418
+ XML_IO_EADDRINUSE = 1554
419
+ XML_IO_EALREADY = 1555
420
+ XML_IO_EAFNOSUPPORT = 1556
421
+ XML_XINCLUDE_RECURSION = 1600
422
+ XML_XINCLUDE_PARSE_VALUE = 1601
423
+ XML_XINCLUDE_ENTITY_DEF_MISMATCH = 1602
424
+ XML_XINCLUDE_NO_HREF = 1603
425
+ XML_XINCLUDE_NO_FALLBACK = 1604
426
+ XML_XINCLUDE_HREF_URI = 1605
427
+ XML_XINCLUDE_TEXT_FRAGMENT = 1606
428
+ XML_XINCLUDE_TEXT_DOCUMENT = 1607
429
+ XML_XINCLUDE_INVALID_CHAR = 1608
430
+ XML_XINCLUDE_BUILD_FAILED = 1609
431
+ XML_XINCLUDE_UNKNOWN_ENCODING = 1610
432
+ XML_XINCLUDE_MULTIPLE_ROOT = 1611
433
+ XML_XINCLUDE_XPTR_FAILED = 1612
434
+ XML_XINCLUDE_XPTR_RESULT = 1613
435
+ XML_XINCLUDE_INCLUDE_IN_INCLUDE = 1614
436
+ XML_XINCLUDE_FALLBACKS_IN_INCLUDE = 1615
437
+ XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE = 1616
438
+ XML_XINCLUDE_DEPRECATED_NS = 1617
439
+ XML_XINCLUDE_FRAGMENT_ID = 1618
440
+ XML_CATALOG_MISSING_ATTR = 1650
441
+ XML_CATALOG_ENTRY_BROKEN = 1651
442
+ XML_CATALOG_PREFER_VALUE = 1652
443
+ XML_CATALOG_NOT_CATALOG = 1653
444
+ XML_CATALOG_RECURSION = 1654
445
+ XML_SCHEMAP_PREFIX_UNDEFINED = 1700
446
+ XML_SCHEMAP_ATTRFORMDEFAULT_VALUE = 1701
447
+ XML_SCHEMAP_ATTRGRP_NONAME_NOREF = 1702
448
+ XML_SCHEMAP_ATTR_NONAME_NOREF = 1703
449
+ XML_SCHEMAP_COMPLEXTYPE_NONAME_NOREF = 1704
450
+ XML_SCHEMAP_ELEMFORMDEFAULT_VALUE = 1705
451
+ XML_SCHEMAP_ELEM_NONAME_NOREF = 1706
452
+ XML_SCHEMAP_EXTENSION_NO_BASE = 1707
453
+ XML_SCHEMAP_FACET_NO_VALUE = 1708
454
+ XML_SCHEMAP_FAILED_BUILD_IMPORT = 1709
455
+ XML_SCHEMAP_GROUP_NONAME_NOREF = 1710
456
+ XML_SCHEMAP_IMPORT_NAMESPACE_NOT_URI = 1711
457
+ XML_SCHEMAP_IMPORT_REDEFINE_NSNAME = 1712
458
+ XML_SCHEMAP_IMPORT_SCHEMA_NOT_URI = 1713
459
+ XML_SCHEMAP_INVALID_BOOLEAN = 1714
460
+ XML_SCHEMAP_INVALID_ENUM = 1715
461
+ XML_SCHEMAP_INVALID_FACET = 1716
462
+ XML_SCHEMAP_INVALID_FACET_VALUE = 1717
463
+ XML_SCHEMAP_INVALID_MAXOCCURS = 1718
464
+ XML_SCHEMAP_INVALID_MINOCCURS = 1719
465
+ XML_SCHEMAP_INVALID_REF_AND_SUBTYPE = 1720
466
+ XML_SCHEMAP_INVALID_WHITE_SPACE = 1721
467
+ XML_SCHEMAP_NOATTR_NOREF = 1722
468
+ XML_SCHEMAP_NOTATION_NO_NAME = 1723
469
+ XML_SCHEMAP_NOTYPE_NOREF = 1724
470
+ XML_SCHEMAP_REF_AND_SUBTYPE = 1725
471
+ XML_SCHEMAP_RESTRICTION_NONAME_NOREF = 1726
472
+ XML_SCHEMAP_SIMPLETYPE_NONAME = 1727
473
+ XML_SCHEMAP_TYPE_AND_SUBTYPE = 1728
474
+ XML_SCHEMAP_UNKNOWN_ALL_CHILD = 1729
475
+ XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD = 1730
476
+ XML_SCHEMAP_UNKNOWN_ATTR_CHILD = 1731
477
+ XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD = 1732
478
+ XML_SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP = 1733
479
+ XML_SCHEMAP_UNKNOWN_BASE_TYPE = 1734
480
+ XML_SCHEMAP_UNKNOWN_CHOICE_CHILD = 1735
481
+ XML_SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD = 1736
482
+ XML_SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD = 1737
483
+ XML_SCHEMAP_UNKNOWN_ELEM_CHILD = 1738
484
+ XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD = 1739
485
+ XML_SCHEMAP_UNKNOWN_FACET_CHILD = 1740
486
+ XML_SCHEMAP_UNKNOWN_FACET_TYPE = 1741
487
+ XML_SCHEMAP_UNKNOWN_GROUP_CHILD = 1742
488
+ XML_SCHEMAP_UNKNOWN_IMPORT_CHILD = 1743
489
+ XML_SCHEMAP_UNKNOWN_LIST_CHILD = 1744
490
+ XML_SCHEMAP_UNKNOWN_NOTATION_CHILD = 1745
491
+ XML_SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD = 1746
492
+ XML_SCHEMAP_UNKNOWN_REF = 1747
493
+ XML_SCHEMAP_UNKNOWN_RESTRICTION_CHILD = 1748
494
+ XML_SCHEMAP_UNKNOWN_SCHEMAS_CHILD = 1749
495
+ XML_SCHEMAP_UNKNOWN_SEQUENCE_CHILD = 1750
496
+ XML_SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD = 1751
497
+ XML_SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD = 1752
498
+ XML_SCHEMAP_UNKNOWN_TYPE = 1753
499
+ XML_SCHEMAP_UNKNOWN_UNION_CHILD = 1754
500
+ XML_SCHEMAP_ELEM_DEFAULT_FIXED = 1755
501
+ XML_SCHEMAP_REGEXP_INVALID = 1756
502
+ XML_SCHEMAP_FAILED_LOAD = 1757
503
+ XML_SCHEMAP_NOTHING_TO_PARSE = 1758
504
+ XML_SCHEMAP_NOROOT = 1759
505
+ XML_SCHEMAP_REDEFINED_GROUP = 1760
506
+ XML_SCHEMAP_REDEFINED_TYPE = 1761
507
+ XML_SCHEMAP_REDEFINED_ELEMENT = 1762
508
+ XML_SCHEMAP_REDEFINED_ATTRGROUP = 1763
509
+ XML_SCHEMAP_REDEFINED_ATTR = 1764
510
+ XML_SCHEMAP_REDEFINED_NOTATION = 1765
511
+ XML_SCHEMAP_FAILED_PARSE = 1766
512
+ XML_SCHEMAP_UNKNOWN_PREFIX = 1767
513
+ XML_SCHEMAP_DEF_AND_PREFIX = 1768
514
+ XML_SCHEMAP_UNKNOWN_INCLUDE_CHILD = 1769
515
+ XML_SCHEMAP_INCLUDE_SCHEMA_NOT_URI = 1770
516
+ XML_SCHEMAP_INCLUDE_SCHEMA_NO_URI = 1771
517
+ XML_SCHEMAP_NOT_SCHEMA = 1772
518
+ XML_SCHEMAP_UNKNOWN_MEMBER_TYPE = 1773
519
+ XML_SCHEMAP_INVALID_ATTR_USE = 1774
520
+ XML_SCHEMAP_RECURSIVE = 1775
521
+ XML_SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE = 1776
522
+ XML_SCHEMAP_INVALID_ATTR_COMBINATION = 1777
523
+ XML_SCHEMAP_INVALID_ATTR_INLINE_COMBINATION = 1778
524
+ XML_SCHEMAP_MISSING_SIMPLETYPE_CHILD = 1779
525
+ XML_SCHEMAP_INVALID_ATTR_NAME = 1780
526
+ XML_SCHEMAP_REF_AND_CONTENT = 1781
527
+ XML_SCHEMAP_CT_PROPS_CORRECT_1 = 1782
528
+ XML_SCHEMAP_CT_PROPS_CORRECT_2 = 1783
529
+ XML_SCHEMAP_CT_PROPS_CORRECT_3 = 1784
530
+ XML_SCHEMAP_CT_PROPS_CORRECT_4 = 1785
531
+ XML_SCHEMAP_CT_PROPS_CORRECT_5 = 1786
532
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1 = 1787
533
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1 = 1788
534
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2 = 1789
535
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2 = 1790
536
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3 = 1791
537
+ XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER = 1792
538
+ XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE = 1793
539
+ XML_SCHEMAP_UNION_NOT_EXPRESSIBLE = 1794
540
+ XML_SCHEMAP_SRC_IMPORT_3_1 = 1795
541
+ XML_SCHEMAP_SRC_IMPORT_3_2 = 1796
542
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1 = 1797
543
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2 = 1798
544
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3 = 1799
545
+ XML_SCHEMAP_COS_CT_EXTENDS_1_3 = 1800
546
+ XML_SCHEMAV_NOROOT = 1801
547
+ XML_SCHEMAV_UNDECLAREDELEM = 1802
548
+ XML_SCHEMAV_NOTTOPLEVEL = 1803
549
+ XML_SCHEMAV_MISSING = 1804
550
+ XML_SCHEMAV_WRONGELEM = 1805
551
+ XML_SCHEMAV_NOTYPE = 1806
552
+ XML_SCHEMAV_NOROLLBACK = 1807
553
+ XML_SCHEMAV_ISABSTRACT = 1808
554
+ XML_SCHEMAV_NOTEMPTY = 1809
555
+ XML_SCHEMAV_ELEMCONT = 1810
556
+ XML_SCHEMAV_HAVEDEFAULT = 1811
557
+ XML_SCHEMAV_NOTNILLABLE = 1812
558
+ XML_SCHEMAV_EXTRACONTENT = 1813
559
+ XML_SCHEMAV_INVALIDATTR = 1814
560
+ XML_SCHEMAV_INVALIDELEM = 1815
561
+ XML_SCHEMAV_NOTDETERMINIST = 1816
562
+ XML_SCHEMAV_CONSTRUCT = 1817
563
+ XML_SCHEMAV_INTERNAL = 1818
564
+ XML_SCHEMAV_NOTSIMPLE = 1819
565
+ XML_SCHEMAV_ATTRUNKNOWN = 1820
566
+ XML_SCHEMAV_ATTRINVALID = 1821
567
+ XML_SCHEMAV_VALUE = 1822
568
+ XML_SCHEMAV_FACET = 1823
569
+ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1 = 1824
570
+ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2 = 1825
571
+ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3 = 1826
572
+ XML_SCHEMAV_CVC_TYPE_3_1_1 = 1827
573
+ XML_SCHEMAV_CVC_TYPE_3_1_2 = 1828
574
+ XML_SCHEMAV_CVC_FACET_VALID = 1829
575
+ XML_SCHEMAV_CVC_LENGTH_VALID = 1830
576
+ XML_SCHEMAV_CVC_MINLENGTH_VALID = 1831
577
+ XML_SCHEMAV_CVC_MAXLENGTH_VALID = 1832
578
+ XML_SCHEMAV_CVC_MININCLUSIVE_VALID = 1833
579
+ XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID = 1834
580
+ XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID = 1835
581
+ XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID = 1836
582
+ XML_SCHEMAV_CVC_TOTALDIGITS_VALID = 1837
583
+ XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID = 1838
584
+ XML_SCHEMAV_CVC_PATTERN_VALID = 1839
585
+ XML_SCHEMAV_CVC_ENUMERATION_VALID = 1840
586
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1 = 1841
587
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2 = 1842
588
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3 = 1843
589
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_4 = 1844
590
+ XML_SCHEMAV_CVC_ELT_1 = 1845
591
+ XML_SCHEMAV_CVC_ELT_2 = 1846
592
+ XML_SCHEMAV_CVC_ELT_3_1 = 1847
593
+ XML_SCHEMAV_CVC_ELT_3_2_1 = 1848
594
+ XML_SCHEMAV_CVC_ELT_3_2_2 = 1849
595
+ XML_SCHEMAV_CVC_ELT_4_1 = 1850
596
+ XML_SCHEMAV_CVC_ELT_4_2 = 1851
597
+ XML_SCHEMAV_CVC_ELT_4_3 = 1852
598
+ XML_SCHEMAV_CVC_ELT_5_1_1 = 1853
599
+ XML_SCHEMAV_CVC_ELT_5_1_2 = 1854
600
+ XML_SCHEMAV_CVC_ELT_5_2_1 = 1855
601
+ XML_SCHEMAV_CVC_ELT_5_2_2_1 = 1856
602
+ XML_SCHEMAV_CVC_ELT_5_2_2_2_1 = 1857
603
+ XML_SCHEMAV_CVC_ELT_5_2_2_2_2 = 1858
604
+ XML_SCHEMAV_CVC_ELT_6 = 1859
605
+ XML_SCHEMAV_CVC_ELT_7 = 1860
606
+ XML_SCHEMAV_CVC_ATTRIBUTE_1 = 1861
607
+ XML_SCHEMAV_CVC_ATTRIBUTE_2 = 1862
608
+ XML_SCHEMAV_CVC_ATTRIBUTE_3 = 1863
609
+ XML_SCHEMAV_CVC_ATTRIBUTE_4 = 1864
610
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_1 = 1865
611
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1 = 1866
612
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2 = 1867
613
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_4 = 1868
614
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_1 = 1869
615
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_2 = 1870
616
+ XML_SCHEMAV_ELEMENT_CONTENT = 1871
617
+ XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING = 1872
618
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_1 = 1873
619
+ XML_SCHEMAV_CVC_AU = 1874
620
+ XML_SCHEMAV_CVC_TYPE_1 = 1875
621
+ XML_SCHEMAV_CVC_TYPE_2 = 1876
622
+ XML_SCHEMAV_CVC_IDC = 1877
623
+ XML_SCHEMAV_CVC_WILDCARD = 1878
624
+ XML_SCHEMAV_MISC = 1879
625
+ XML_XPTR_UNKNOWN_SCHEME = 1900
626
+ XML_XPTR_CHILDSEQ_START = 1901
627
+ XML_XPTR_EVAL_FAILED = 1902
628
+ XML_XPTR_EXTRA_OBJECTS = 1903
629
+ XML_C14N_CREATE_CTXT = 1950
630
+ XML_C14N_REQUIRES_UTF8 = 1951
631
+ XML_C14N_CREATE_STACK = 1952
632
+ XML_C14N_INVALID_NODE = 1953
633
+ XML_C14N_UNKNOW_NODE = 1954
634
+ XML_C14N_RELATIVE_NAMESPACE = 1955
635
+ XML_FTP_PASV_ANSWER = 2000
636
+ XML_FTP_EPSV_ANSWER = 2001
637
+ XML_FTP_ACCNT = 2002
638
+ XML_FTP_URL_SYNTAX = 2003
639
+ XML_HTTP_URL_SYNTAX = 2020
640
+ XML_HTTP_USE_IP = 2021
641
+ XML_HTTP_UNKNOWN_HOST = 2022
642
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_1 = 3000
643
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_2 = 3001
644
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_3 = 3002
645
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_4 = 3003
646
+ XML_SCHEMAP_SRC_RESOLVE = 3004
647
+ XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE = 3005
648
+ XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE = 3006
649
+ XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES = 3007
650
+ XML_SCHEMAP_ST_PROPS_CORRECT_1 = 3008
651
+ XML_SCHEMAP_ST_PROPS_CORRECT_2 = 3009
652
+ XML_SCHEMAP_ST_PROPS_CORRECT_3 = 3010
653
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_1 = 3011
654
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_2 = 3012
655
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1 = 3013
656
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2 = 3014
657
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_1 = 3015
658
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1 = 3016
659
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2 = 3017
660
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1 = 3018
661
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2 = 3019
662
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3 = 3020
663
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4 = 3021
664
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_5 = 3022
665
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_1 = 3023
666
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1 = 3024
667
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2 = 3025
668
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2 = 3026
669
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1 = 3027
670
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3 = 3028
671
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4 = 3029
672
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5 = 3030
673
+ XML_SCHEMAP_COS_ST_DERIVED_OK_2_1 = 3031
674
+ XML_SCHEMAP_COS_ST_DERIVED_OK_2_2 = 3032
675
+ XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED = 3033
676
+ XML_SCHEMAP_S4S_ELEM_MISSING = 3034
677
+ XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED = 3035
678
+ XML_SCHEMAP_S4S_ATTR_MISSING = 3036
679
+ XML_SCHEMAP_S4S_ATTR_INVALID_VALUE = 3037
680
+ XML_SCHEMAP_SRC_ELEMENT_1 = 3038
681
+ XML_SCHEMAP_SRC_ELEMENT_2_1 = 3039
682
+ XML_SCHEMAP_SRC_ELEMENT_2_2 = 3040
683
+ XML_SCHEMAP_SRC_ELEMENT_3 = 3041
684
+ XML_SCHEMAP_P_PROPS_CORRECT_1 = 3042
685
+ XML_SCHEMAP_P_PROPS_CORRECT_2_1 = 3043
686
+ XML_SCHEMAP_P_PROPS_CORRECT_2_2 = 3044
687
+ XML_SCHEMAP_E_PROPS_CORRECT_2 = 3045
688
+ XML_SCHEMAP_E_PROPS_CORRECT_3 = 3046
689
+ XML_SCHEMAP_E_PROPS_CORRECT_4 = 3047
690
+ XML_SCHEMAP_E_PROPS_CORRECT_5 = 3048
691
+ XML_SCHEMAP_E_PROPS_CORRECT_6 = 3049
692
+ XML_SCHEMAP_SRC_INCLUDE = 3050
693
+ XML_SCHEMAP_SRC_ATTRIBUTE_1 = 3051
694
+ XML_SCHEMAP_SRC_ATTRIBUTE_2 = 3052
695
+ XML_SCHEMAP_SRC_ATTRIBUTE_3_1 = 3053
696
+ XML_SCHEMAP_SRC_ATTRIBUTE_3_2 = 3054
697
+ XML_SCHEMAP_SRC_ATTRIBUTE_4 = 3055
698
+ XML_SCHEMAP_NO_XMLNS = 3056
699
+ XML_SCHEMAP_NO_XSI = 3057
700
+ XML_SCHEMAP_COS_VALID_DEFAULT_1 = 3058
701
+ XML_SCHEMAP_COS_VALID_DEFAULT_2_1 = 3059
702
+ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1 = 3060
703
+ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_2 = 3061
704
+ XML_SCHEMAP_CVC_SIMPLE_TYPE = 3062
705
+ XML_SCHEMAP_COS_CT_EXTENDS_1_1 = 3063
706
+ XML_SCHEMAP_SRC_IMPORT_1_1 = 3064
707
+ XML_SCHEMAP_SRC_IMPORT_1_2 = 3065
708
+ XML_SCHEMAP_SRC_IMPORT_2 = 3066
709
+ XML_SCHEMAP_SRC_IMPORT_2_1 = 3067
710
+ XML_SCHEMAP_SRC_IMPORT_2_2 = 3068
711
+ XML_SCHEMAP_INTERNAL = 3069 # 3069 non-W3C
712
+ XML_SCHEMAP_NOT_DETERMINISTIC = 3070 # 3070 non-W3C
713
+ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_1 = 3071
714
+ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_2 = 3072
715
+ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3 = 3073
716
+ XML_SCHEMAP_MG_PROPS_CORRECT_1 = 3074
717
+ XML_SCHEMAP_MG_PROPS_CORRECT_2 = 3075
718
+ XML_SCHEMAP_SRC_CT_1 = 3076
719
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3 = 3077
720
+ XML_SCHEMAP_AU_PROPS_CORRECT_2 = 3078
721
+ XML_SCHEMAP_A_PROPS_CORRECT_2 = 3079
722
+ XML_SCHEMAP_C_PROPS_CORRECT = 3080
723
+ XML_SCHEMAP_SRC_REDEFINE = 3081
724
+ XML_SCHEMAP_SRC_IMPORT = 3082
725
+ XML_SCHEMAP_WARN_SKIP_SCHEMA = 3083
726
+ XML_SCHEMAP_WARN_UNLOCATED_SCHEMA = 3084
727
+ XML_SCHEMAP_WARN_ATTR_REDECL_PROH = 3085
728
+ XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH = 3086 # 3085
729
+ XML_SCHEMAP_AG_PROPS_CORRECT = 3087 # 3086
730
+ XML_SCHEMAP_COS_CT_EXTENDS_1_2 = 3088 # 3087
731
+ XML_SCHEMAP_AU_PROPS_CORRECT = 3089 # 3088
732
+ XML_SCHEMAP_A_PROPS_CORRECT_3 = 3090 # 3089
733
+ XML_SCHEMAP_COS_ALL_LIMITED = 3091 # 3090
734
+ XML_SCHEMATRONV_ASSERT = 4000
735
+ XML_SCHEMATRONV_REPORT = 4001
736
+ XML_MODULE_OPEN = 4900
737
+ XML_MODULE_CLOSE = 4901
738
+ XML_CHECK_FOUND_ELEMENT = 5000
739
+ XML_CHECK_FOUND_ATTRIBUTE = 5001
740
+ XML_CHECK_FOUND_TEXT = 5002
741
+ XML_CHECK_FOUND_CDATA = 5003
742
+ XML_CHECK_FOUND_ENTITYREF = 5004
743
+ XML_CHECK_FOUND_ENTITY = 5005
744
+ XML_CHECK_FOUND_PI = 5006
745
+ XML_CHECK_FOUND_COMMENT = 5007
746
+ XML_CHECK_FOUND_DOCTYPE = 5008
747
+ XML_CHECK_FOUND_FRAGMENT = 5009
748
+ XML_CHECK_FOUND_NOTATION = 5010
749
+ XML_CHECK_UNKNOWN_NODE = 5011
750
+ XML_CHECK_ENTITY_TYPE = 5012
751
+ XML_CHECK_NO_PARENT = 5013
752
+ XML_CHECK_NO_DOC = 5014
753
+ XML_CHECK_NO_NAME = 5015
754
+ XML_CHECK_NO_ELEM = 5016
755
+ XML_CHECK_WRONG_DOC = 5017
756
+ XML_CHECK_NO_PREV = 5018
757
+ XML_CHECK_WRONG_PREV = 5019
758
+ XML_CHECK_NO_NEXT = 5020
759
+ XML_CHECK_WRONG_NEXT = 5021
760
+ XML_CHECK_NOT_DTD = 5022
761
+ XML_CHECK_NOT_ATTR = 5023
762
+ XML_CHECK_NOT_ATTR_DECL = 5024
763
+ XML_CHECK_NOT_ELEM_DECL = 5025
764
+ XML_CHECK_NOT_ENTITY_DECL = 5026
765
+ XML_CHECK_NOT_NS_DECL = 5027
766
+ XML_CHECK_NO_HREF = 5028
767
+ XML_CHECK_WRONG_PARENT = 5029
768
+ XML_CHECK_NS_SCOPE = 5030
769
+ XML_CHECK_NS_ANCESTOR = 5031
770
+ XML_CHECK_NOT_UTF8 = 5032
771
+ XML_CHECK_NO_DICT = 5033
772
+ XML_CHECK_NOT_NCNAME = 5034
773
+ XML_CHECK_OUTSIDE_DICT = 5035
774
+ XML_CHECK_WRONG_NAME = 5036
775
+ XML_CHECK_NAME_NOT_NULL = 5037
776
+ XML_I18N_NO_NAME = 6000
777
+ XML_I18N_NO_HANDLER = 6001
778
+ XML_I18N_EXCESS_HANDLER = 6002
779
+ XML_I18N_CONV_FAILED = 6003
780
+ XML_I18N_NO_OUTPUT = 6004
781
+ XML_BUF_OVERFLOW = 7000
782
+
783
+ ctypedef enum xmlRelaxNGValidErr:
784
+ XML_RELAXNG_OK = 0
785
+ XML_RELAXNG_ERR_MEMORY = 1
786
+ XML_RELAXNG_ERR_TYPE = 2
787
+ XML_RELAXNG_ERR_TYPEVAL = 3
788
+ XML_RELAXNG_ERR_DUPID = 4
789
+ XML_RELAXNG_ERR_TYPECMP = 5
790
+ XML_RELAXNG_ERR_NOSTATE = 6
791
+ XML_RELAXNG_ERR_NODEFINE = 7
792
+ XML_RELAXNG_ERR_LISTEXTRA = 8
793
+ XML_RELAXNG_ERR_LISTEMPTY = 9
794
+ XML_RELAXNG_ERR_INTERNODATA = 10
795
+ XML_RELAXNG_ERR_INTERSEQ = 11
796
+ XML_RELAXNG_ERR_INTEREXTRA = 12
797
+ XML_RELAXNG_ERR_ELEMNAME = 13
798
+ XML_RELAXNG_ERR_ATTRNAME = 14
799
+ XML_RELAXNG_ERR_ELEMNONS = 15
800
+ XML_RELAXNG_ERR_ATTRNONS = 16
801
+ XML_RELAXNG_ERR_ELEMWRONGNS = 17
802
+ XML_RELAXNG_ERR_ATTRWRONGNS = 18
803
+ XML_RELAXNG_ERR_ELEMEXTRANS = 19
804
+ XML_RELAXNG_ERR_ATTREXTRANS = 20
805
+ XML_RELAXNG_ERR_ELEMNOTEMPTY = 21
806
+ XML_RELAXNG_ERR_NOELEM = 22
807
+ XML_RELAXNG_ERR_NOTELEM = 23
808
+ XML_RELAXNG_ERR_ATTRVALID = 24
809
+ XML_RELAXNG_ERR_CONTENTVALID = 25
810
+ XML_RELAXNG_ERR_EXTRACONTENT = 26
811
+ XML_RELAXNG_ERR_INVALIDATTR = 27
812
+ XML_RELAXNG_ERR_DATAELEM = 28
813
+ XML_RELAXNG_ERR_VALELEM = 29
814
+ XML_RELAXNG_ERR_LISTELEM = 30
815
+ XML_RELAXNG_ERR_DATATYPE = 31
816
+ XML_RELAXNG_ERR_VALUE = 32
817
+ XML_RELAXNG_ERR_LIST = 33
818
+ XML_RELAXNG_ERR_NOGRAMMAR = 34
819
+ XML_RELAXNG_ERR_EXTRADATA = 35
820
+ XML_RELAXNG_ERR_LACKDATA = 36
821
+ XML_RELAXNG_ERR_INTERNAL = 37
822
+ XML_RELAXNG_ERR_ELEMWRONG = 38
823
+ XML_RELAXNG_ERR_TEXTWRONG = 39
824
+ # --- END: GENERATED CONSTANTS ---
825
+
826
+ cdef extern from "libxml/xmlerror.h" nogil:
827
+ ctypedef struct xmlError:
828
+ int domain
829
+ int code
830
+ char* message
831
+ xmlErrorLevel level
832
+ char* file
833
+ char* str1
834
+ char* str2
835
+ char* str3
836
+ int line
837
+ int int1
838
+ int int2
839
+ void* node
840
+
841
+ ctypedef void (*xmlGenericErrorFunc)(void* ctxt, char* msg, ...) noexcept
842
+ ctypedef void (*xmlStructuredErrorFunc)(void* userData,
843
+ const xmlError* error) noexcept
844
+
845
+ cdef void xmlSetGenericErrorFunc(
846
+ void* ctxt, xmlGenericErrorFunc func)
847
+ cdef void xmlSetStructuredErrorFunc(
848
+ void* ctxt, xmlStructuredErrorFunc func)
849
+
850
+ cdef extern from "libxml/globals.h" nogil:
851
+ cdef xmlStructuredErrorFunc xmlStructuredError
852
+ cdef void* xmlStructuredErrorContext
env-llmeval/lib/python3.10/site-packages/lxml/includes/xmlparser.pxd ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc.string cimport const_char
2
+
3
+ from lxml.includes.tree cimport (
4
+ xmlDoc, xmlNode, xmlEntity, xmlDict, xmlDtd, xmlChar, const_xmlChar)
5
+ from lxml.includes.tree cimport xmlInputReadCallback, xmlInputCloseCallback
6
+ from lxml.includes.xmlerror cimport xmlError, xmlStructuredErrorFunc, xmlErrorLevel
7
+
8
+
9
+ cdef extern from "libxml/parser.h" nogil:
10
+ ctypedef void (*startElementNsSAX2Func)(void* ctx,
11
+ const_xmlChar* localname,
12
+ const_xmlChar* prefix,
13
+ const_xmlChar* URI,
14
+ int nb_namespaces,
15
+ const_xmlChar** namespaces,
16
+ int nb_attributes,
17
+ int nb_defaulted,
18
+ const_xmlChar** attributes) noexcept
19
+
20
+ ctypedef void (*endElementNsSAX2Func)(void* ctx,
21
+ const_xmlChar* localname,
22
+ const_xmlChar* prefix,
23
+ const_xmlChar* URI) noexcept
24
+
25
+ ctypedef void (*startElementSAXFunc)(void* ctx, const_xmlChar* name, const_xmlChar** atts) noexcept
26
+
27
+ ctypedef void (*endElementSAXFunc)(void* ctx, const_xmlChar* name) noexcept
28
+
29
+ ctypedef void (*charactersSAXFunc)(void* ctx, const_xmlChar* ch, int len) noexcept
30
+
31
+ ctypedef void (*cdataBlockSAXFunc)(void* ctx, const_xmlChar* value, int len) noexcept
32
+
33
+ ctypedef void (*commentSAXFunc)(void* ctx, const_xmlChar* value) noexcept
34
+
35
+ ctypedef void (*processingInstructionSAXFunc)(void* ctx,
36
+ const_xmlChar* target,
37
+ const_xmlChar* data) noexcept
38
+
39
+ ctypedef void (*internalSubsetSAXFunc)(void* ctx,
40
+ const_xmlChar* name,
41
+ const_xmlChar* externalID,
42
+ const_xmlChar* systemID) noexcept
43
+
44
+ ctypedef void (*endDocumentSAXFunc)(void* ctx) noexcept
45
+
46
+ ctypedef void (*startDocumentSAXFunc)(void* ctx) noexcept
47
+
48
+ ctypedef void (*referenceSAXFunc)(void * ctx, const_xmlChar* name) noexcept
49
+
50
+ ctypedef xmlEntity* (*getEntitySAXFunc)(void* ctx, const_xmlChar* name) noexcept
51
+
52
+ cdef int XML_SAX2_MAGIC
53
+
54
+ cdef extern from "libxml/tree.h" nogil:
55
+ ctypedef struct xmlParserInput:
56
+ int line
57
+ int col
58
+ int length
59
+ const_xmlChar* base
60
+ const_xmlChar* cur
61
+ const_xmlChar* end
62
+ const_char *filename
63
+
64
+ ctypedef struct xmlParserInputBuffer:
65
+ void* context
66
+ xmlInputReadCallback readcallback
67
+ xmlInputCloseCallback closecallback
68
+
69
+ ctypedef struct xmlSAXHandlerV1:
70
+ # same as xmlSAXHandler, but without namespaces
71
+ pass
72
+
73
+ ctypedef struct xmlSAXHandler:
74
+ internalSubsetSAXFunc internalSubset
75
+ startElementNsSAX2Func startElementNs
76
+ endElementNsSAX2Func endElementNs
77
+ startElementSAXFunc startElement
78
+ endElementSAXFunc endElement
79
+ charactersSAXFunc characters
80
+ cdataBlockSAXFunc cdataBlock
81
+ referenceSAXFunc reference
82
+ getEntitySAXFunc getEntity
83
+ commentSAXFunc comment
84
+ processingInstructionSAXFunc processingInstruction
85
+ startDocumentSAXFunc startDocument
86
+ endDocumentSAXFunc endDocument
87
+ int initialized
88
+ xmlStructuredErrorFunc serror
89
+ void* _private
90
+
91
+
92
+ cdef extern from "libxml/SAX2.h" nogil:
93
+ cdef void xmlSAX2StartDocument(void* ctxt)
94
+
95
+
96
+ cdef extern from "libxml/xmlIO.h" nogil:
97
+ cdef xmlParserInputBuffer* xmlAllocParserInputBuffer(int enc)
98
+
99
+
100
+ cdef extern from "libxml/parser.h" nogil:
101
+
102
+ cdef xmlDict* xmlDictCreate()
103
+ cdef xmlDict* xmlDictCreateSub(xmlDict* subdict)
104
+ cdef void xmlDictFree(xmlDict* sub)
105
+ cdef int xmlDictReference(xmlDict* dict)
106
+
107
+ cdef int XML_COMPLETE_ATTRS # SAX option for adding DTD default attributes
108
+ cdef int XML_SKIP_IDS # SAX option for not building an XML ID dict
109
+
110
+ ctypedef enum xmlParserInputState:
111
+ XML_PARSER_EOF = -1 # nothing is to be parsed
112
+ XML_PARSER_START = 0 # nothing has been parsed
113
+ XML_PARSER_MISC = 1 # Misc* before int subset
114
+ XML_PARSER_PI = 2 # Within a processing instruction
115
+ XML_PARSER_DTD = 3 # within some DTD content
116
+ XML_PARSER_PROLOG = 4 # Misc* after internal subset
117
+ XML_PARSER_COMMENT = 5 # within a comment
118
+ XML_PARSER_START_TAG = 6 # within a start tag
119
+ XML_PARSER_CONTENT = 7 # within the content
120
+ XML_PARSER_CDATA_SECTION = 8 # within a CDATA section
121
+ XML_PARSER_END_TAG = 9 # within a closing tag
122
+ XML_PARSER_ENTITY_DECL = 10 # within an entity declaration
123
+ XML_PARSER_ENTITY_VALUE = 11 # within an entity value in a decl
124
+ XML_PARSER_ATTRIBUTE_VALUE = 12 # within an attribute value
125
+ XML_PARSER_SYSTEM_LITERAL = 13 # within a SYSTEM value
126
+ XML_PARSER_EPILOG = 14 # the Misc* after the last end tag
127
+ XML_PARSER_IGNORE = 15 # within an IGNORED section
128
+ XML_PARSER_PUBLIC_LITERAL = 16 # within a PUBLIC value
129
+
130
+
131
+ ctypedef struct xmlParserCtxt:
132
+ xmlDoc* myDoc
133
+ xmlDict* dict
134
+ int dictNames
135
+ void* _private
136
+ bint wellFormed
137
+ bint recovery
138
+ int options
139
+ bint disableSAX
140
+ int errNo
141
+ xmlParserInputState instate
142
+ bint replaceEntities
143
+ int loadsubset # != 0 if enabled, int value == why
144
+ bint validate
145
+ xmlError lastError
146
+ xmlNode* node
147
+ xmlSAXHandler* sax
148
+ void* userData
149
+ int* spaceTab
150
+ int spaceMax
151
+ int nsNr
152
+ bint html
153
+ bint progressive
154
+ int inSubset
155
+ int charset
156
+ xmlParserInput* input
157
+ int inputNr
158
+ xmlParserInput* inputTab[]
159
+
160
+ ctypedef enum xmlParserOption:
161
+ XML_PARSE_RECOVER = 1 # recover on errors
162
+ XML_PARSE_NOENT = 2 # substitute entities
163
+ XML_PARSE_DTDLOAD = 4 # load the external subset
164
+ XML_PARSE_DTDATTR = 8 # default DTD attributes
165
+ XML_PARSE_DTDVALID = 16 # validate with the DTD
166
+ XML_PARSE_NOERROR = 32 # suppress error reports
167
+ XML_PARSE_NOWARNING = 64 # suppress warning reports
168
+ XML_PARSE_PEDANTIC = 128 # pedantic error reporting
169
+ XML_PARSE_NOBLANKS = 256 # remove blank nodes
170
+ XML_PARSE_SAX1 = 512 # use the SAX1 interface internally
171
+ XML_PARSE_XINCLUDE = 1024 # Implement XInclude substitution
172
+ XML_PARSE_NONET = 2048 # Forbid network access
173
+ XML_PARSE_NODICT = 4096 # Do not reuse the context dictionary
174
+ XML_PARSE_NSCLEAN = 8192 # remove redundant namespaces declarations
175
+ XML_PARSE_NOCDATA = 16384 # merge CDATA as text nodes
176
+ XML_PARSE_NOXINCNODE = 32768 # do not generate XINCLUDE START/END nodes
177
+ # libxml2 2.6.21+ only:
178
+ XML_PARSE_COMPACT = 65536 # compact small text nodes
179
+ # libxml2 2.7.0+ only:
180
+ XML_PARSE_OLD10 = 131072 # parse using XML-1.0 before update 5
181
+ XML_PARSE_NOBASEFIX = 262144 # do not fixup XINCLUDE xml:base uris
182
+ XML_PARSE_HUGE = 524288 # relax any hardcoded limit from the parser
183
+ # libxml2 2.7.3+ only:
184
+ XML_PARSE_OLDSAX = 1048576 # parse using SAX2 interface before 2.7.0
185
+ # libxml2 2.8.0+ only:
186
+ XML_PARSE_IGNORE_ENC = 2097152 # ignore internal document encoding hint
187
+ # libxml2 2.9.0+ only:
188
+ XML_PARSE_BIG_LINES = 4194304 # Store big lines numbers in text PSVI field
189
+
190
+ cdef void xmlInitParser()
191
+ cdef void xmlCleanupParser()
192
+
193
+ cdef int xmlLineNumbersDefault(int onoff)
194
+ cdef xmlParserCtxt* xmlNewParserCtxt()
195
+ cdef xmlParserInput* xmlNewIOInputStream(xmlParserCtxt* ctxt,
196
+ xmlParserInputBuffer* input,
197
+ int enc)
198
+ cdef int xmlCtxtUseOptions(xmlParserCtxt* ctxt, int options)
199
+ cdef void xmlFreeParserCtxt(xmlParserCtxt* ctxt)
200
+ cdef void xmlCtxtReset(xmlParserCtxt* ctxt)
201
+ cdef void xmlClearParserCtxt(xmlParserCtxt* ctxt)
202
+ cdef int xmlParseChunk(xmlParserCtxt* ctxt,
203
+ char* chunk, int size, int terminate)
204
+ cdef xmlDoc* xmlCtxtReadDoc(xmlParserCtxt* ctxt,
205
+ char* cur, char* URL, char* encoding,
206
+ int options)
207
+ cdef xmlDoc* xmlCtxtReadFile(xmlParserCtxt* ctxt,
208
+ char* filename, char* encoding,
209
+ int options)
210
+ cdef xmlDoc* xmlCtxtReadIO(xmlParserCtxt* ctxt,
211
+ xmlInputReadCallback ioread,
212
+ xmlInputCloseCallback ioclose,
213
+ void* ioctx,
214
+ char* URL, char* encoding,
215
+ int options)
216
+ cdef xmlDoc* xmlCtxtReadMemory(xmlParserCtxt* ctxt,
217
+ char* buffer, int size,
218
+ char* filename, const_char* encoding,
219
+ int options)
220
+
221
+ cdef void xmlErrParser(xmlParserCtxt* ctxt, xmlNode* node,
222
+ int domain, int code, xmlErrorLevel level,
223
+ const xmlChar *str1, const xmlChar *str2, const xmlChar *str3,
224
+ int int1, const char *msg, ...)
225
+
226
+
227
+ # iterparse:
228
+
229
+ cdef xmlParserCtxt* xmlCreatePushParserCtxt(xmlSAXHandler* sax,
230
+ void* user_data,
231
+ char* chunk,
232
+ int size,
233
+ char* filename)
234
+
235
+ cdef int xmlCtxtResetPush(xmlParserCtxt* ctxt,
236
+ char* chunk,
237
+ int size,
238
+ char* filename,
239
+ char* encoding)
240
+
241
+ # entity loaders:
242
+
243
+ ctypedef xmlParserInput* (*xmlExternalEntityLoader)(
244
+ const_char * URL, const_char * ID, xmlParserCtxt* context) noexcept
245
+ cdef xmlExternalEntityLoader xmlGetExternalEntityLoader()
246
+ cdef void xmlSetExternalEntityLoader(xmlExternalEntityLoader f)
247
+
248
+ cdef xmlEntity* xmlSAX2GetEntity(void* ctxt, const_xmlChar* name) noexcept
249
+
250
+ # DTDs:
251
+
252
+ cdef xmlDtd* xmlParseDTD(const_xmlChar* ExternalID, const_xmlChar* SystemID)
253
+ cdef xmlDtd* xmlIOParseDTD(xmlSAXHandler* sax,
254
+ xmlParserInputBuffer* input,
255
+ int enc)
256
+
257
+
258
+ cdef extern from "libxml/parserInternals.h" nogil:
259
+ cdef xmlParserInput* xmlNewInputStream(xmlParserCtxt* ctxt)
260
+ cdef xmlParserInput* xmlNewStringInputStream(xmlParserCtxt* ctxt,
261
+ char* buffer)
262
+ cdef xmlParserInput* xmlNewInputFromFile(xmlParserCtxt* ctxt,
263
+ char* filename)
264
+ cdef void xmlFreeInputStream(xmlParserInput* input)
265
+ cdef int xmlSwitchEncoding(xmlParserCtxt* ctxt, int enc)