{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); ')\n \n\n \"\"\"\n tb = treebuilders.getTreeBuilder(treebuilder)\n p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)\n return p.parse(doc, **kwargs)\n\n\ndef parseFragment(doc, container=\"div\", treebuilder=\"etree\", namespaceHTMLElements=True, **kwargs):\n \"\"\"Parse an HTML fragment as a string or file-like object into a tree\n\n :arg doc: the fragment to parse as a string or file-like object\n\n :arg container: the container context to parse the fragment in\n\n :arg treebuilder: the treebuilder to use when parsing\n\n :arg namespaceHTMLElements: whether or not to namespace HTML elements\n\n :returns: parsed tree\n\n Example:\n\n >>> from html5lib.html5libparser import parseFragment\n >>> parseFragment('this is a fragment')\n \n\n \"\"\"\n tb = treebuilders.getTreeBuilder(treebuilder)\n p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements)\n return p.parseFragment(doc, container=container, **kwargs)\n\n\ndef method_decorator_metaclass(function):\n class Decorated(type):\n def __new__(meta, classname, bases, classDict):\n for attributeName, attribute in classDict.items():\n if isinstance(attribute, types.FunctionType):\n attribute = function(attribute)\n\n classDict[attributeName] = attribute\n return type.__new__(meta, classname, bases, classDict)\n return Decorated\n\n\nclass HTMLParser(object):\n \"\"\"HTML parser\n\n Generates a tree structure from a stream of (possibly malformed) HTML.\n\n \"\"\"\n\n def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False):\n \"\"\"\n :arg tree: a treebuilder class controlling the type of tree that will be\n returned. Built in treebuilders can be accessed through\n html5lib.treebuilders.getTreeBuilder(treeType)\n\n :arg strict: raise an exception when a parse error is encountered\n\n :arg namespaceHTMLElements: whether or not to namespace HTML elements\n\n :arg debug: whether or not to enable debug mode which logs things\n\n Example:\n\n >>> from html5lib.html5parser import HTMLParser\n >>> parser = HTMLParser() # generates parser with etree builder\n >>> parser = HTMLParser('lxml', strict=True) # generates parser with lxml builder which is strict\n\n \"\"\"\n\n # Raise an exception on the first error encountered\n self.strict = strict\n\n if tree is None:\n tree = treebuilders.getTreeBuilder(\"etree\")\n self.tree = tree(namespaceHTMLElements)\n self.errors = []\n\n self.phases = dict([(name, cls(self, self.tree)) for name, cls in\n getPhases(debug).items()])\n\n def _parse(self, stream, innerHTML=False, container=\"div\", scripting=False, **kwargs):\n\n self.innerHTMLMode = innerHTML\n self.container = container\n self.scripting = scripting\n self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs)\n self.reset()\n\n try:\n self.mainLoop()\n except _ReparseException:\n self.reset()\n self.mainLoop()\n\n def reset(self):\n self.tree.reset()\n self.firstStartTag = False\n self.errors = []\n self.log = [] # only used with debug mode\n # \"quirks\" / \"limited quirks\" / \"no quirks\"\n self.compatMode = \"no quirks\"\n\n if self.innerHTMLMode:\n self.innerHTML = self.container.lower()\n\n if self.innerHTML in cdataElements:\n self.tokenizer.state = self.tokenizer.rcdataState\n elif self.innerHTML in rcdataElements:\n self.tokenizer.state = self.tokenizer.rawtextState\n elif self.innerHTML == 'plaintext':\n self.tokenizer.state = self.tokenizer.plaintextState\n else:\n # state already is data state\n # self.tokenizer.state = self.tokenizer.dataState\n pass\n self.phase = self.phases[\"beforeHtml\"]\n self.phase.insertHtmlElement()\n self.resetInsertionMode()\n else:\n self.innerHTML = False # pylint:disable=redefined-variable-type\n self.phase = self.phases[\"initial\"]\n\n self.lastPhase = None\n\n self.beforeRCDataPhase = None\n\n self.framesetOK = True\n\n @property\n def documentEncoding(self):\n \"\"\"Name of the character encoding that was used to decode the input stream, or\n :obj:`None` if that is not determined yet\n\n \"\"\"\n if not hasattr(self, 'tokenizer'):\n return None\n return self.tokenizer.stream.charEncoding[0].name\n\n def isHTMLIntegrationPoint(self, element):\n if (element.name == \"annotation-xml\" and\n element.namespace == namespaces[\"mathml\"]):\n return (\"encoding\" in element.attributes and\n element.attributes[\"encoding\"].translate(\n asciiUpper2Lower) in\n (\"text/html\", \"application/xhtml+xml\"))\n else:\n return (element.namespace, element.name) in htmlIntegrationPointElements\n\n def isMathMLTextIntegrationPoint(self, element):\n return (element.namespace, element.name) in mathmlTextIntegrationPointElements\n\n def mainLoop(self):\n CharactersToken = tokenTypes[\"Characters\"]\n SpaceCharactersToken = tokenTypes[\"SpaceCharacters\"]\n StartTagToken = tokenTypes[\"StartTag\"]\n EndTagToken = tokenTypes[\"EndTag\"]\n CommentToken = tokenTypes[\"Comment\"]\n DoctypeToken = tokenTypes[\"Doctype\"]\n ParseErrorToken = tokenTypes[\"ParseError\"]\n\n for token in self.normalizedTokens():\n prev_token = None\n new_token = token\n while new_token is not None:\n prev_token = new_token\n currentNode = self.tree.openElements[-1] if self.tree.openElements else None\n currentNodeNamespace = currentNode.namespace if currentNode else None\n currentNodeName = currentNode.name if currentNode else None\n\n type = new_token[\"type\"]\n\n if type == ParseErrorToken:\n self.parseError(new_token[\"data\"], new_token.get(\"datavars\", {}))\n new_token = None\n else:\n if (len(self.tree.openElements) == 0 or\n currentNodeNamespace == self.tree.defaultNamespace or\n (self.isMathMLTextIntegrationPoint(currentNode) and\n ((type == StartTagToken and\n token[\"name\"] not in frozenset([\"mglyph\", \"malignmark\"])) or\n type in (CharactersToken, SpaceCharactersToken))) or\n (currentNodeNamespace == namespaces[\"mathml\"] and\n currentNodeName == \"annotation-xml\" and\n type == StartTagToken and\n token[\"name\"] == \"svg\") or\n (self.isHTMLIntegrationPoint(currentNode) and\n type in (StartTagToken, CharactersToken, SpaceCharactersToken))):\n phase = self.phase\n else:\n phase = self.phases[\"inForeignContent\"]\n\n if type == CharactersToken:\n new_token = phase.processCharacters(new_token)\n elif type == SpaceCharactersToken:\n new_token = phase.processSpaceCharacters(new_token)\n elif type == StartTagToken:\n new_token = phase.processStartTag(new_token)\n elif type == EndTagToken:\n new_token = phase.processEndTag(new_token)\n elif type == CommentToken:\n new_token = phase.processComment(new_token)\n elif type == DoctypeToken:\n new_token = phase.processDoctype(new_token)\n\n if (type == StartTagToken and prev_token[\"selfClosing\"] and\n not prev_token[\"selfClosingAcknowledged\"]):\n self.parseError(\"non-void-element-with-trailing-solidus\",\n {\"name\": prev_token[\"name\"]})\n\n # When the loop finishes it's EOF\n reprocess = True\n phases = []\n while reprocess:\n phases.append(self.phase)\n reprocess = self.phase.processEOF()\n if reprocess:\n assert self.phase not in phases\n\n def normalizedTokens(self):\n for token in self.tokenizer:\n yield self.normalizeToken(token)\n\n def parse(self, stream, *args, **kwargs):\n \"\"\"Parse a HTML document into a well-formed tree\n\n :arg stream: a file-like object or string containing the HTML to be parsed\n\n The optional encoding parameter must be a string that indicates\n the encoding. If specified, that encoding will be used,\n regardless of any BOM or later declaration (such as in a meta\n element).\n\n :arg scripting: treat noscript elements as if JavaScript was turned on\n\n :returns: parsed tree\n\n Example:\n\n >>> from html5lib.html5parser import HTMLParser\n >>> parser = HTMLParser()\n >>> parser.parse('

This is a doc

')\n \n\n \"\"\"\n self._parse(stream, False, None, *args, **kwargs)\n return self.tree.getDocument()\n\n def parseFragment(self, stream, *args, **kwargs):\n \"\"\"Parse a HTML fragment into a well-formed tree fragment\n\n :arg container: name of the element we're setting the innerHTML\n property if set to None, default to 'div'\n\n :arg stream: a file-like object or string containing the HTML to be parsed\n\n The optional encoding parameter must be a string that indicates\n the encoding. If specified, that encoding will be used,\n regardless of any BOM or later declaration (such as in a meta\n element)\n\n :arg scripting: treat noscript elements as if JavaScript was turned on\n\n :returns: parsed tree\n\n Example:\n\n >>> from html5lib.html5libparser import HTMLParser\n >>> parser = HTMLParser()\n >>> parser.parseFragment('this is a fragment')\n \n\n \"\"\"\n self._parse(stream, True, *args, **kwargs)\n return self.tree.getFragment()\n\n def parseError(self, errorcode=\"XXX-undefined-error\", datavars=None):\n # XXX The idea is to make errorcode mandatory.\n if datavars is None:\n datavars = {}\n self.errors.append((self.tokenizer.stream.position(), errorcode, datavars))\n if self.strict:\n raise ParseError(E[errorcode] % datavars)\n\n def normalizeToken(self, token):\n # HTML5 specific normalizations to the token stream\n if token[\"type\"] == tokenTypes[\"StartTag\"]:\n raw = token[\"data\"]\n token[\"data\"] = OrderedDict(raw)\n if len(raw) > len(token[\"data\"]):\n # we had some duplicated attribute, fix so first wins\n token[\"data\"].update(raw[::-1])\n\n return token\n\n def adjustMathMLAttributes(self, token):\n adjust_attributes(token, adjustMathMLAttributes)\n\n def adjustSVGAttributes(self, token):\n adjust_attributes(token, adjustSVGAttributes)\n\n def adjustForeignAttributes(self, token):\n adjust_attributes(token, adjustForeignAttributesMap)\n\n def reparseTokenNormal(self, token):\n # pylint:disable=unused-argument\n self.parser.phase()\n\n def resetInsertionMode(self):\n # The name of this method is mostly historical. (It's also used in the\n # specification.)\n last = False\n newModes = {\n \"select\": \"inSelect\",\n \"td\": \"inCell\",\n \"th\": \"inCell\",\n \"tr\": \"inRow\",\n \"tbody\": \"inTableBody\",\n \"thead\": \"inTableBody\",\n \"tfoot\": \"inTableBody\",\n \"caption\": \"inCaption\",\n \"colgroup\": \"inColumnGroup\",\n \"table\": \"inTable\",\n \"head\": \"inBody\",\n \"body\": \"inBody\",\n \"frameset\": \"inFrameset\",\n \"html\": \"beforeHead\"\n }\n for node in self.tree.openElements[::-1]:\n nodeName = node.name\n new_phase = None\n if node == self.tree.openElements[0]:\n assert self.innerHTML\n last = True\n nodeName = self.innerHTML\n # Check for conditions that should only happen in the innerHTML\n # case\n if nodeName in (\"select\", \"colgroup\", \"head\", \"html\"):\n assert self.innerHTML\n\n if not last and node.namespace != self.tree.defaultNamespace:\n continue\n\n if nodeName in newModes:\n new_phase = self.phases[newModes[nodeName]]\n break\n elif last:\n new_phase = self.phases[\"inBody\"]\n break\n\n self.phase = new_phase\n\n def parseRCDataRawtext(self, token, contentType):\n # Generic RCDATA/RAWTEXT Parsing algorithm\n assert contentType in (\"RAWTEXT\", \"RCDATA\")\n\n self.tree.insertElement(token)\n\n if contentType == \"RAWTEXT\":\n self.tokenizer.state = self.tokenizer.rawtextState\n else:\n self.tokenizer.state = self.tokenizer.rcdataState\n\n self.originalPhase = self.phase\n\n self.phase = self.phases[\"text\"]\n\n\n@_utils.memoize\ndef getPhases(debug):\n def log(function):\n \"\"\"Logger that records which phase processes each token\"\"\"\n type_names = dict((value, key) for key, value in\n tokenTypes.items())\n\n def wrapped(self, *args, **kwargs):\n if function.__name__.startswith(\"process\") and len(args) > 0:\n token = args[0]\n try:\n info = {\"type\": type_names[token['type']]}\n except:\n raise\n if token['type'] in tagTokenTypes:\n info[\"name\"] = token['name']\n\n self.parser.log.append((self.parser.tokenizer.state.__name__,\n self.parser.phase.__class__.__name__,\n self.__class__.__name__,\n function.__name__,\n info))\n return function(self, *args, **kwargs)\n else:\n return function(self, *args, **kwargs)\n return wrapped\n\n def getMetaclass(use_metaclass, metaclass_func):\n if use_metaclass:\n return method_decorator_metaclass(metaclass_func)\n else:\n return type\n\n # pylint:disable=unused-argument\n class Phase(with_metaclass(getMetaclass(debug, log))):\n \"\"\"Base class for helper object that implements each phase of processing\n \"\"\"\n\n def __init__(self, parser, tree):\n self.parser = parser\n self.tree = tree\n\n def processEOF(self):\n raise NotImplementedError\n\n def processComment(self, token):\n # For most phases the following is correct. Where it's not it will be\n # overridden.\n self.tree.insertComment(token, self.tree.openElements[-1])\n\n def processDoctype(self, token):\n self.parser.parseError(\"unexpected-doctype\")\n\n def processCharacters(self, token):\n self.tree.insertText(token[\"data\"])\n\n def processSpaceCharacters(self, token):\n self.tree.insertText(token[\"data\"])\n\n def processStartTag(self, token):\n return self.startTagHandler[token[\"name\"]](token)\n\n def startTagHtml(self, token):\n if not self.parser.firstStartTag and token[\"name\"] == \"html\":\n self.parser.parseError(\"non-html-root\")\n # XXX Need a check here to see if the first start tag token emitted is\n # this token... If it's not, invoke self.parser.parseError().\n for attr, value in token[\"data\"].items():\n if attr not in self.tree.openElements[0].attributes:\n self.tree.openElements[0].attributes[attr] = value\n self.parser.firstStartTag = False\n\n def processEndTag(self, token):\n return self.endTagHandler[token[\"name\"]](token)\n\n class InitialPhase(Phase):\n def processSpaceCharacters(self, token):\n pass\n\n def processComment(self, token):\n self.tree.insertComment(token, self.tree.document)\n\n def processDoctype(self, token):\n name = token[\"name\"]\n publicId = token[\"publicId\"]\n systemId = token[\"systemId\"]\n correct = token[\"correct\"]\n\n if (name != \"html\" or publicId is not None or\n systemId is not None and systemId != \"about:legacy-compat\"):\n self.parser.parseError(\"unknown-doctype\")\n\n if publicId is None:\n publicId = \"\"\n\n self.tree.insertDoctype(token)\n\n if publicId != \"\":\n publicId = publicId.translate(asciiUpper2Lower)\n\n if (not correct or token[\"name\"] != \"html\" or\n publicId.startswith(\n (\"+//silmaril//dtd html pro v0r11 19970101//\",\n \"-//advasoft ltd//dtd html 3.0 aswedit + extensions//\",\n \"-//as//dtd html 3.0 aswedit + extensions//\",\n \"-//ietf//dtd html 2.0 level 1//\",\n \"-//ietf//dtd html 2.0 level 2//\",\n \"-//ietf//dtd html 2.0 strict level 1//\",\n \"-//ietf//dtd html 2.0 strict level 2//\",\n \"-//ietf//dtd html 2.0 strict//\",\n \"-//ietf//dtd html 2.0//\",\n \"-//ietf//dtd html 2.1e//\",\n \"-//ietf//dtd html 3.0//\",\n \"-//ietf//dtd html 3.2 final//\",\n \"-//ietf//dtd html 3.2//\",\n \"-//ietf//dtd html 3//\",\n \"-//ietf//dtd html level 0//\",\n \"-//ietf//dtd html level 1//\",\n \"-//ietf//dtd html level 2//\",\n \"-//ietf//dtd html level 3//\",\n \"-//ietf//dtd html strict level 0//\",\n \"-//ietf//dtd html strict level 1//\",\n \"-//ietf//dtd html strict level 2//\",\n \"-//ietf//dtd html strict level 3//\",\n \"-//ietf//dtd html strict//\",\n \"-//ietf//dtd html//\",\n \"-//metrius//dtd metrius presentational//\",\n \"-//microsoft//dtd internet explorer 2.0 html strict//\",\n \"-//microsoft//dtd internet explorer 2.0 html//\",\n \"-//microsoft//dtd internet explorer 2.0 tables//\",\n \"-//microsoft//dtd internet explorer 3.0 html strict//\",\n \"-//microsoft//dtd internet explorer 3.0 html//\",\n \"-//microsoft//dtd internet explorer 3.0 tables//\",\n \"-//netscape comm. corp.//dtd html//\",\n \"-//netscape comm. corp.//dtd strict html//\",\n \"-//o'reilly and associates//dtd html 2.0//\",\n \"-//o'reilly and associates//dtd html extended 1.0//\",\n \"-//o'reilly and associates//dtd html extended relaxed 1.0//\",\n \"-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//\",\n \"-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//\",\n \"-//spyglass//dtd html 2.0 extended//\",\n \"-//sq//dtd html 2.0 hotmetal + extensions//\",\n \"-//sun microsystems corp.//dtd hotjava html//\",\n \"-//sun microsystems corp.//dtd hotjava strict html//\",\n \"-//w3c//dtd html 3 1995-03-24//\",\n \"-//w3c//dtd html 3.2 draft//\",\n \"-//w3c//dtd html 3.2 final//\",\n \"-//w3c//dtd html 3.2//\",\n \"-//w3c//dtd html 3.2s draft//\",\n \"-//w3c//dtd html 4.0 frameset//\",\n \"-//w3c//dtd html 4.0 transitional//\",\n \"-//w3c//dtd html experimental 19960712//\",\n \"-//w3c//dtd html experimental 970421//\",\n \"-//w3c//dtd w3 html//\",\n \"-//w3o//dtd w3 html 3.0//\",\n \"-//webtechs//dtd mozilla html 2.0//\",\n \"-//webtechs//dtd mozilla html//\")) or\n publicId in (\"-//w3o//dtd w3 html strict 3.0//en//\",\n \"-/w3c/dtd html 4.0 transitional/en\",\n \"html\") or\n publicId.startswith(\n (\"-//w3c//dtd html 4.01 frameset//\",\n \"-//w3c//dtd html 4.01 transitional//\")) and\n systemId is None or\n systemId and systemId.lower() == \"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd\"):\n self.parser.compatMode = \"quirks\"\n elif (publicId.startswith(\n (\"-//w3c//dtd xhtml 1.0 frameset//\",\n \"-//w3c//dtd xhtml 1.0 transitional//\")) or\n publicId.startswith(\n (\"-//w3c//dtd html 4.01 frameset//\",\n \"-//w3c//dtd html 4.01 transitional//\")) and\n systemId is not None):\n self.parser.compatMode = \"limited quirks\"\n\n self.parser.phase = self.parser.phases[\"beforeHtml\"]\n\n def anythingElse(self):\n self.parser.compatMode = \"quirks\"\n self.parser.phase = self.parser.phases[\"beforeHtml\"]\n\n def processCharacters(self, token):\n self.parser.parseError(\"expected-doctype-but-got-chars\")\n self.anythingElse()\n return token\n\n def processStartTag(self, token):\n self.parser.parseError(\"expected-doctype-but-got-start-tag\",\n {\"name\": token[\"name\"]})\n self.anythingElse()\n return token\n\n def processEndTag(self, token):\n self.parser.parseError(\"expected-doctype-but-got-end-tag\",\n {\"name\": token[\"name\"]})\n self.anythingElse()\n return token\n\n def processEOF(self):\n self.parser.parseError(\"expected-doctype-but-got-eof\")\n self.anythingElse()\n return True\n\n class BeforeHtmlPhase(Phase):\n # helper methods\n def insertHtmlElement(self):\n self.tree.insertRoot(impliedTagToken(\"html\", \"StartTag\"))\n self.parser.phase = self.parser.phases[\"beforeHead\"]\n\n # other\n def processEOF(self):\n self.insertHtmlElement()\n return True\n\n def processComment(self, token):\n self.tree.insertComment(token, self.tree.document)\n\n def processSpaceCharacters(self, token):\n pass\n\n def processCharacters(self, token):\n self.insertHtmlElement()\n return token\n\n def processStartTag(self, token):\n if token[\"name\"] == \"html\":\n self.parser.firstStartTag = True\n self.insertHtmlElement()\n return token\n\n def processEndTag(self, token):\n if token[\"name\"] not in (\"head\", \"body\", \"html\", \"br\"):\n self.parser.parseError(\"unexpected-end-tag-before-html\",\n {\"name\": token[\"name\"]})\n else:\n self.insertHtmlElement()\n return token\n\n class BeforeHeadPhase(Phase):\n def __init__(self, parser, tree):\n Phase.__init__(self, parser, tree)\n\n self.startTagHandler = _utils.MethodDispatcher([\n (\"html\", self.startTagHtml),\n (\"head\", self.startTagHead)\n ])\n self.startTagHandler.default = self.startTagOther\n\n self.endTagHandler = _utils.MethodDispatcher([\n ((\"head\", \"body\", \"html\", \"br\"), self.endTagImplyHead)\n ])\n self.endTagHandler.default = self.endTagOther\n\n def processEOF(self):\n self.startTagHead(impliedTagToken(\"head\", \"StartTag\"))\n return True\n\n def processSpaceCharacters(self, token):\n pass\n\n def processCharacters(self, token):\n self.startTagHead(impliedTagToken(\"head\", \"StartTag\"))\n return token\n\n def startTagHtml(self, token):\n return self.parser.phases[\"inBody\"].processStartTag(token)\n\n def startTagHead(self, token):\n self.tree.insertElement(token)\n self.tree.headPointer = self.tree.openElements[-1]\n self.parser.phase = self.parser.phases[\"inHead\"]\n\n def startTagOther(self, token):\n self.startTagHead(impliedTagToken(\"head\", \"StartTag\"))\n return token\n\n def endTagImplyHead(self, token):\n self.startTagHead(impliedTagToken(\"head\", \"StartTag\"))\n return token\n\n def endTagOther(self, token):\n self.parser.parseError(\"end-tag-after-implied-root\",\n {\"name\": token[\"name\"]})\n\n class InHeadPhase(Phase):\n def __init__(self, parser, tree):\n Phase.__init__(self, parser, tree)\n\n self.startTagHandler = _utils.MethodDispatcher([\n (\"html\", self.startTagHtml),\n (\"title\", self.startTagTitle),\n ((\"noframes\", \"style\"), self.startTagNoFramesStyle),\n (\"noscript\", self.startTagNoscript),\n (\"script\", self.startTagScript),\n ((\"base\", \"basefont\", \"bgsound\", \"command\", \"link\"),\n self.startTagBaseLinkCommand),\n (\"meta\", self.startTagMeta),\n (\"head\", self.startTagHead)\n ])\n self.startTagHandler.default = self.startTagOther\n\n self.endTagHandler = _utils.MethodDispatcher([\n (\"head\", self.endTagHead),\n ((\"br\", \"html\", \"body\"), self.endTagHtmlBodyBr)\n ])\n self.endTagHandler.default = self.endTagOther\n\n # the real thing\n def processEOF(self):\n self.anythingElse()\n return True\n\n def processCharacters(self, token):\n self.anythingElse()\n return token\n\n def startTagHtml(self, token):\n return self.parser.phases[\"inBody\"].processStartTag(token)\n\n def startTagHead(self, token):\n self.parser.parseError(\"two-heads-are-not-better-than-one\")\n\n def startTagBaseLinkCommand(self, token):\n self.tree.insertElement(token)\n self.tree.openElements.pop()\n token[\"selfClosingAcknowledged\"] = True\n\n def startTagMeta(self, token):\n self.tree.insertElement(token)\n self.tree.openElements.pop()\n token[\"selfClosingAcknowledged\"] = True\n\n attributes = token[\"data\"]\n if self.parser.tokenizer.stream.charEncoding[1] == \"tentative\":\n if \"charset\" in attributes:\n self.parser.tokenizer.stream.changeEncoding(attributes[\"charset\"])\n elif (\"content\" in attributes and\n \"http-equiv\" in attributes and\n attributes[\"http-equiv\"].lower() == \"content-type\"):\n # Encoding it as UTF-8 here is a hack, as really we should pass\n # the abstract Unicode string, and just use the\n # ContentAttrParser on that, but using UTF-8 allows all chars\n # to be encoded and as a ASCII-superset works.\n data = _inputstream.EncodingBytes(attributes[\"content\"].encode(\"utf-8\"))\n parser = _inputstream.ContentAttrParser(data)\n codec = parser.parse()\n self.parser.tokenizer.stream.changeEncoding(codec)\n\n def startTagTitle(self, token):\n self.parser.parseRCDataRawtext(token, \"RCDATA\")\n\n def startTagNoFramesStyle(self, token):\n # Need to decide whether to implement the scripting-disabled case\n self.parser.parseRCDataRawtext(token, \"RAWTEXT\")\n\n def startTagNoscript(self, token):\n if self.parser.scripting:\n self.parser.parseRCDataRawtext(token, \"RAWTEXT\")\n else:\n self.tree.insertElement(token)\n self.parser.phase = self.parser.phases[\"inHeadNoscript\"]\n\n def startTagScript(self, token):\n self.tree.insertElement(token)\n self.parser.tokenizer.state = self.parser.tokenizer.scriptDataState\n self.parser.originalPhase = self.parser.phase\n self.parser.phase = self.parser.phases[\"text\"]\n\n def startTagOther(self, token):\n self.anythingElse()\n return token\n\n def endTagHead(self, token):\n node = self.parser.tree.openElements.pop()\n assert node.name == \"head\", \"Expected head got %s\" % node.name\n self.parser.phase = self.parser.phases[\"afterHead\"]\n\n def endTagHtmlBodyBr(self, token):\n self.anythingElse()\n return token\n\n def endTagOther(self, token):\n self.parser.parseError(\"unexpected-end-tag\", {\"name\": token[\"name\"]})\n\n def anythingElse(self):\n self.endTagHead(impliedTagToken(\"head\"))\n\n class InHeadNoscriptPhase(Phase):\n def __init__(self, parser, tree):\n Phase.__init__(self, parser, tree)\n\n self.startTagHandler = _utils.MethodDispatcher([\n (\"html\", self.startTagHtml),\n ((\"basefont\", \"bgsound\", \"link\", \"meta\", \"noframes\", \"style\"), self.startTagBaseLinkCommand),\n ((\"head\", \"noscript\"), self.startTagHeadNoscript),\n ])\n self.startTagHandler.default = self.startTagOther\n\n self.endTagHandler = _utils.MethodDispatcher([\n (\"noscript\", self.endTagNoscript),\n (\"br\", self.endTagBr),\n ])\n self.endTagHandler.default = self.endTagOther\n\n def processEOF(self):\n self.parser.parseError(\"eof-in-head-noscript\")\n self.anythingElse()\n return True\n\n def processComment(self, token):\n return self.parser.phases[\"inHead\"].processComment(token)\n\n def processCharacters(self, token):\n self.parser.parseError(\"char-in-head-noscript\")\n self.anythingElse()\n return token\n\n def processSpaceCharacters(self, token):\n return self.parser.phases[\"inHead\"].processSpaceCharacters(token)\n\n def startTagHtml(self, token):\n return self.parser.phases[\"inBody\"].processStartTag(token)\n\n def startTagBaseLinkCommand(self, token):\n return self.parser.phases[\"inHead\"].processStartTag(token)\n\n def startTagHeadNoscript(self, token):\n self.parser.parseError(\"unexpected-start-tag\", {\"name\": token[\"name\"]})\n\n def startTagOther(self, token):\n self.parser.parseError(\"unexpected-inhead-noscript-tag\", {\"name\": token[\"name\"]})\n self.anythingElse()\n return token\n\n def endTagNoscript(self, token):\n node = self.parser.tree.openElements.pop()\n assert node.name == \"noscript\", \"Expected noscript got %s\" % node.name\n self.parser.phase = self.parser.phases[\"inHead\"]\n\n def endTagBr(self, token):\n self.parser.parseError(\"unexpected-inhead-noscript-tag\", {\"name\": token[\"name\"]})\n self.anythingElse()\n return token\n\n def endTagOther(self, token):\n self.parser.parseError(\"unexpected-end-tag\", {\"name\": token[\"name\"]})\n\n def anythingElse(self):\n # Caller must raise parse error first!\n self.endTagNoscript(impliedTagToken(\"noscript\"))\n\n class AfterHeadPhase(Phase):\n def __init__(self, parser, tree):\n Phase.__init__(self, parser, tree)\n\n self.startTagHandler = _utils.MethodDispatcher([\n (\"html\", self.startTagHtml),\n (\"body\", self.startTagBody),\n (\"frameset\", self.startTagFrameset),\n ((\"base\", \"basefont\", \"bgsound\", \"link\", \"meta\", \"noframes\", \"script\",\n \"style\", \"title\"),\n self.startTagFromHead),\n (\"head\", self.startTagHead)\n ])\n self.startTagHandler.default = self.startTagOther\n self.endTagHandler = _utils.MethodDispatcher([((\"body\", \"html\", \"br\"),\n self.endTagHtmlBodyBr)])\n self.endTagHandler.default = self.endTagOther\n\n def processEOF(self):\n self.anythingElse()\n return True\n\n def processCharacters(self, token):\n self.anythingElse()\n return token\n\n def startTagHtml(self, token):\n return self.parser.phases[\"inBody\"].processStartTag(token)\n\n def startTagBody(self, token):\n self.parser.framesetOK = False\n self.tree.insertElement(token)\n self.parser.phase = self.parser.phases[\"inBody\"]\n\n def startTagFrameset(self, token):\n self.tree.insertElement(token)\n self.parser.phase = self.parser.phases[\"inFrameset\"]\n\n def startTagFromHead(self, token):\n self.parser.parseError(\"unexpected-start-tag-out-of-my-head\",\n {\"name\": token[\"name\"]})\n self.tree.openElements.append(self.tree.headPointer)\n self.parser.phases[\"inHead\"].processStartTag(token)\n for node in self.tree.openElements[::-1]:\n if node.name == \"head\":\n self.tree.openElements.remove(node)\n break\n\n def startTagHead(self, token):\n self.parser.parseError(\"unexpected-start-tag\", {\"name\": token[\"name\"]})\n\n def startTagOther(self, token):\n self.anythingElse()\n return token\n\n def endTagHtmlBodyBr(self, token):\n self.anythingElse()\n return token\n\n def endTagOther(self, token):\n self.parser.parseError(\"unexpected-end-tag\", {\"name\": token[\"name\"]})\n\n def anythingElse(self):\n self.tree.insertElement(impliedTagToken(\"body\", \"StartTag\"))\n self.parser.phase = self.parser.phases[\"inBody\"]\n self.parser.framesetOK = True\n\n class InBodyPhase(Phase):\n # http://www.whatwg.org/specs/web-apps/current-work/#parsing-main-inbody\n # the really-really-really-very crazy mode\n def __init__(self, parser, tree):\n Phase.__init__(self, parser, tree)\n\n # Set this to the default handler\n self.processSpaceCharacters = self.processSpaceCharactersNonPre\n\n self.startTagHandler = _utils.MethodDispatcher([\n (\"html\", self.startTagHtml),\n ((\"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\",\n \"script\", \"style\", \"title\"),\n self.startTagProcessInHead),\n (\"body\", self.startTagBody),\n (\"frameset\", self.startTagFrameset),\n ((\"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\",\n \"dir\", \"div\", \"dl\", \"fieldset\", \"figcaption\", \"figure\",\n \"footer\", \"header\", \"hgroup\", \"main\", \"menu\", \"nav\", \"ol\", \"p\",\n \"section\", \"summary\", \"ul\"),\n self.startTagCloseP),\n (headingElements, self.startTagHeading),\n ((\"pre\", \"listing\"), self.startTagPreListing),\n (\"form\", self.startTagForm),\n ((\"li\", \"dd\", \"dt\"), self.startTagListItem),\n (\"plaintext\", self.startTagPlaintext),\n (\"a\", self.startTagA),\n ((\"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\",\n \"strong\", \"tt\", \"u\"), self.startTagFormatting),\n (\"nobr\", self.startTagNobr),\n (\"button\", self.startTagButton),\n ((\"applet\", \"marquee\", \"object\"), self.startTagAppletMarqueeObject),\n (\"xmp\", self.startTagXmp),\n (\"table\", self.startTagTable),\n ((\"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\"),\n self.startTagVoidFormatting),\n ((\"param\", \"source\", \"track\"), self.startTagParamSource),\n (\"input\", self.startTagInput),\n (\"hr\", self.startTagHr),\n (\"image\", self.startTagImage),\n (\"isindex\", self.startTagIsIndex),\n (\"textarea\", self.startTagTextarea),\n (\"iframe\", self.startTagIFrame),\n (\"noscript\", self.startTagNoscript),\n ((\"noembed\", \"noframes\"), self.startTagRawtext),\n (\"select\", self.startTagSelect),\n ((\"rp\", \"rt\"), self.startTagRpRt),\n ((\"option\", \"optgroup\"), self.startTagOpt),\n ((\"math\"), self.startTagMath),\n ((\"svg\"), self.startTagSvg),\n ((\"caption\", \"col\", \"colgroup\", \"frame\", \"head\",\n \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\",\n \"tr\"), self.startTagMisplaced)\n ])\n self.startTagHandler.default = self.startTagOther\n\n self.endTagHandler = _utils.MethodDispatcher([\n (\"body\", self.endTagBody),\n (\"html\", self.endTagHtml),\n ((\"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\",\n \"details\", \"dialog\", \"dir\", \"div\", \"dl\", \"fieldset\", \"figcaption\", \"figure\",\n \"footer\", \"header\", \"hgroup\", \"listing\", \"main\", \"menu\", \"nav\", \"ol\", \"pre\",\n \"section\", \"summary\", \"ul\"), self.endTagBlock),\n (\"form\", self.endTagForm),\n (\"p\", self.endTagP),\n ((\"dd\", \"dt\", \"li\"), self.endTagListItem),\n (headingElements, self.endTagHeading),\n ((\"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\",\n \"strike\", \"strong\", \"tt\", \"u\"), self.endTagFormatting),\n ((\"applet\", \"marquee\", \"object\"), self.endTagAppletMarqueeObject),\n (\"br\", self.endTagBr),\n ])\n self.endTagHandler.default = self.endTagOther\n\n def isMatchingFormattingElement(self, node1, node2):\n return (node1.name == node2.name and\n node1.namespace == node2.namespace and\n node1.attributes == node2.attributes)\n\n # helper\n def addFormattingElement(self, token):\n self.tree.insertElement(token)\n element = self.tree.openElements[-1]\n\n matchingElements = []\n for node in self.tree.activeFormattingElements[::-1]:\n if node is Marker:\n break\n elif self.isMatchingFormattingElement(node, element):\n matchingElements.append(node)\n\n assert len(matchingElements) <= 3\n if len(matchingElements) == 3:\n self.tree.activeFormattingElements.remove(matchingElements[-1])\n self.tree.activeFormattingElements.append(element)\n\n # the real deal\n def processEOF(self):\n allowed_elements = frozenset((\"dd\", \"dt\", \"li\", \"p\", \"tbody\", \"td\",\n \"tfoot\", \"th\", \"thead\", \"tr\", \"body\",\n \"html\"))\n for node in self.tree.openElements[::-1]:\n if node.name not in allowed_elements:\n self.parser.parseError(\"expected-closing-tag-but-got-eof\")\n break\n # Stop parsing\n\n def processSpaceCharactersDropNewline(self, token):\n # Sometimes (start of
, , and 

				
Subsets and Splits

No community queries yet

The top public SQL queries from the community will appear here once available.