utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pyright: basic
  4. """Utility functions for the engines
  5. """
  6. import re
  7. import importlib
  8. import importlib.util
  9. import types
  10. from typing import Optional, Union, Any, Set, List, Dict, MutableMapping, Tuple, Callable
  11. from numbers import Number
  12. from os.path import splitext, join
  13. from random import choice
  14. from html.parser import HTMLParser
  15. from urllib.parse import urljoin, urlparse
  16. import fasttext
  17. from lxml import html
  18. from lxml.etree import ElementBase, XPath, XPathError, XPathSyntaxError, _ElementStringResult, _ElementUnicodeResult
  19. from babel.core import get_global
  20. from searx import settings
  21. from searx.data import USER_AGENTS, data_dir
  22. from searx.version import VERSION_TAG
  23. from searx.languages import language_codes
  24. from searx.exceptions import SearxXPathSyntaxException, SearxEngineXPathException
  25. from searx import logger
  26. logger = logger.getChild('utils')
  27. XPathSpecType = Union[str, XPath]
  28. _BLOCKED_TAGS = ('script', 'style')
  29. _ECMA_UNESCAPE4_RE = re.compile(r'%u([0-9a-fA-F]{4})', re.UNICODE)
  30. _ECMA_UNESCAPE2_RE = re.compile(r'%([0-9a-fA-F]{2})', re.UNICODE)
  31. _STORAGE_UNIT_VALUE: Dict[str, int] = {
  32. 'TB': 1024 * 1024 * 1024 * 1024,
  33. 'GB': 1024 * 1024 * 1024,
  34. 'MB': 1024 * 1024,
  35. 'TiB': 1000 * 1000 * 1000 * 1000,
  36. 'MiB': 1000 * 1000,
  37. 'KiB': 1000,
  38. }
  39. _XPATH_CACHE: Dict[str, XPath] = {}
  40. _LANG_TO_LC_CACHE: Dict[str, Dict[str, str]] = {}
  41. _FASTTEXT_MODEL: Optional[fasttext.FastText._FastText] = None
  42. """fasttext model to predict laguage of a search term"""
  43. # Monkey patch: prevent fasttext from showing a (useless) warning when loading a model.
  44. fasttext.FastText.eprint = lambda x: None
  45. class _NotSetClass: # pylint: disable=too-few-public-methods
  46. """Internal class for this module, do not create instance of this class.
  47. Replace the None value, allow explicitly pass None as a function argument"""
  48. _NOTSET = _NotSetClass()
  49. def searx_useragent() -> str:
  50. """Return the searx User Agent"""
  51. return 'searx/{searx_version} {suffix}'.format(
  52. searx_version=VERSION_TAG, suffix=settings['outgoing']['useragent_suffix']
  53. ).strip()
  54. def gen_useragent(os_string: Optional[str] = None) -> str:
  55. """Return a random browser User Agent
  56. See searx/data/useragents.json
  57. """
  58. return USER_AGENTS['ua'].format(os=os_string or choice(USER_AGENTS['os']), version=choice(USER_AGENTS['versions']))
  59. class _HTMLTextExtractorException(Exception):
  60. """Internal exception raised when the HTML is invalid"""
  61. class _HTMLTextExtractor(HTMLParser): # pylint: disable=W0223 # (see https://bugs.python.org/issue31844)
  62. """Internal class to extract text from HTML"""
  63. def __init__(self):
  64. HTMLParser.__init__(self)
  65. self.result = []
  66. self.tags = []
  67. def handle_starttag(self, tag, attrs):
  68. self.tags.append(tag)
  69. if tag == 'br':
  70. self.result.append(' ')
  71. def handle_endtag(self, tag):
  72. if not self.tags:
  73. return
  74. if tag != self.tags[-1]:
  75. raise _HTMLTextExtractorException()
  76. self.tags.pop()
  77. def is_valid_tag(self):
  78. return not self.tags or self.tags[-1] not in _BLOCKED_TAGS
  79. def handle_data(self, data):
  80. if not self.is_valid_tag():
  81. return
  82. self.result.append(data)
  83. def handle_charref(self, name):
  84. if not self.is_valid_tag():
  85. return
  86. if name[0] in ('x', 'X'):
  87. codepoint = int(name[1:], 16)
  88. else:
  89. codepoint = int(name)
  90. self.result.append(chr(codepoint))
  91. def handle_entityref(self, name):
  92. if not self.is_valid_tag():
  93. return
  94. # codepoint = htmlentitydefs.name2codepoint[name]
  95. # self.result.append(chr(codepoint))
  96. self.result.append(name)
  97. def get_text(self):
  98. return ''.join(self.result).strip()
  99. def html_to_text(html_str: str) -> str:
  100. """Extract text from a HTML string
  101. Args:
  102. * html_str (str): string HTML
  103. Returns:
  104. * str: extracted text
  105. Examples:
  106. >>> html_to_text('Example <span id="42">#2</span>')
  107. 'Example #2'
  108. >>> html_to_text('<style>.span { color: red; }</style><span>Example</span>')
  109. 'Example'
  110. """
  111. html_str = html_str.replace('\n', ' ').replace('\r', ' ')
  112. html_str = ' '.join(html_str.split())
  113. s = _HTMLTextExtractor()
  114. try:
  115. s.feed(html_str)
  116. except _HTMLTextExtractorException:
  117. logger.debug("HTMLTextExtractor: invalid HTML\n%s", html_str)
  118. return s.get_text()
  119. def extract_text(xpath_results, allow_none: bool = False) -> Optional[str]:
  120. """Extract text from a lxml result
  121. * if xpath_results is list, extract the text from each result and concat the list
  122. * if xpath_results is a xml element, extract all the text node from it
  123. ( text_content() method from lxml )
  124. * if xpath_results is a string element, then it's already done
  125. """
  126. if isinstance(xpath_results, list):
  127. # it's list of result : concat everything using recursive call
  128. result = ''
  129. for e in xpath_results:
  130. result = result + (extract_text(e) or '')
  131. return result.strip()
  132. if isinstance(xpath_results, ElementBase):
  133. # it's a element
  134. text: str = html.tostring(xpath_results, encoding='unicode', method='text', with_tail=False)
  135. text = text.strip().replace('\n', ' ')
  136. return ' '.join(text.split())
  137. if isinstance(xpath_results, (_ElementStringResult, _ElementUnicodeResult, str, Number, bool)):
  138. return str(xpath_results)
  139. if xpath_results is None and allow_none:
  140. return None
  141. if xpath_results is None and not allow_none:
  142. raise ValueError('extract_text(None, allow_none=False)')
  143. raise ValueError('unsupported type')
  144. def normalize_url(url: str, base_url: str) -> str:
  145. """Normalize URL: add protocol, join URL with base_url, add trailing slash if there is no path
  146. Args:
  147. * url (str): Relative URL
  148. * base_url (str): Base URL, it must be an absolute URL.
  149. Example:
  150. >>> normalize_url('https://example.com', 'http://example.com/')
  151. 'https://example.com/'
  152. >>> normalize_url('//example.com', 'http://example.com/')
  153. 'http://example.com/'
  154. >>> normalize_url('//example.com', 'https://example.com/')
  155. 'https://example.com/'
  156. >>> normalize_url('/path?a=1', 'https://example.com')
  157. 'https://example.com/path?a=1'
  158. >>> normalize_url('', 'https://example.com')
  159. 'https://example.com/'
  160. >>> normalize_url('/test', '/path')
  161. raise ValueError
  162. Raises:
  163. * lxml.etree.ParserError
  164. Returns:
  165. * str: normalized URL
  166. """
  167. if url.startswith('//'):
  168. # add http or https to this kind of url //example.com/
  169. parsed_search_url = urlparse(base_url)
  170. url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
  171. elif url.startswith('/'):
  172. # fix relative url to the search engine
  173. url = urljoin(base_url, url)
  174. # fix relative urls that fall through the crack
  175. if '://' not in url:
  176. url = urljoin(base_url, url)
  177. parsed_url = urlparse(url)
  178. # add a / at this end of the url if there is no path
  179. if not parsed_url.netloc:
  180. raise ValueError('Cannot parse url')
  181. if not parsed_url.path:
  182. url += '/'
  183. return url
  184. def extract_url(xpath_results, base_url) -> str:
  185. """Extract and normalize URL from lxml Element
  186. Args:
  187. * xpath_results (Union[List[html.HtmlElement], html.HtmlElement]): lxml Element(s)
  188. * base_url (str): Base URL
  189. Example:
  190. >>> def f(s, search_url):
  191. >>> return searx.utils.extract_url(html.fromstring(s), search_url)
  192. >>> f('<span id="42">https://example.com</span>', 'http://example.com/')
  193. 'https://example.com/'
  194. >>> f('https://example.com', 'http://example.com/')
  195. 'https://example.com/'
  196. >>> f('//example.com', 'http://example.com/')
  197. 'http://example.com/'
  198. >>> f('//example.com', 'https://example.com/')
  199. 'https://example.com/'
  200. >>> f('/path?a=1', 'https://example.com')
  201. 'https://example.com/path?a=1'
  202. >>> f('', 'https://example.com')
  203. raise lxml.etree.ParserError
  204. >>> searx.utils.extract_url([], 'https://example.com')
  205. raise ValueError
  206. Raises:
  207. * ValueError
  208. * lxml.etree.ParserError
  209. Returns:
  210. * str: normalized URL
  211. """
  212. if xpath_results == []:
  213. raise ValueError('Empty url resultset')
  214. url = extract_text(xpath_results)
  215. if url:
  216. return normalize_url(url, base_url)
  217. raise ValueError('URL not found')
  218. def dict_subset(dictionary: MutableMapping, properties: Set[str]) -> Dict:
  219. """Extract a subset of a dict
  220. Examples:
  221. >>> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'C'])
  222. {'A': 'a', 'C': 'c'}
  223. >>> >> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'D'])
  224. {'A': 'a'}
  225. """
  226. return {k: dictionary[k] for k in properties if k in dictionary}
  227. def get_torrent_size(filesize: str, filesize_multiplier: str) -> Optional[int]:
  228. """
  229. Args:
  230. * filesize (str): size
  231. * filesize_multiplier (str): TB, GB, .... TiB, GiB...
  232. Returns:
  233. * int: number of bytes
  234. Example:
  235. >>> get_torrent_size('5', 'GB')
  236. 5368709120
  237. >>> get_torrent_size('3.14', 'MiB')
  238. 3140000
  239. """
  240. try:
  241. multiplier = _STORAGE_UNIT_VALUE.get(filesize_multiplier, 1)
  242. return int(float(filesize) * multiplier)
  243. except ValueError:
  244. return None
  245. def convert_str_to_int(number_str: str) -> int:
  246. """Convert number_str to int or 0 if number_str is not a number."""
  247. if number_str.isdigit():
  248. return int(number_str)
  249. return 0
  250. def int_or_zero(num: Union[List[str], str]) -> int:
  251. """Convert num to int or 0. num can be either a str or a list.
  252. If num is a list, the first element is converted to int (or return 0 if the list is empty).
  253. If num is a str, see convert_str_to_int
  254. """
  255. if isinstance(num, list):
  256. if len(num) < 1:
  257. return 0
  258. num = num[0]
  259. return convert_str_to_int(num)
  260. def is_valid_lang(lang) -> Optional[Tuple[bool, str, str]]:
  261. """Return language code and name if lang describe a language.
  262. Examples:
  263. >>> is_valid_lang('zz')
  264. None
  265. >>> is_valid_lang('uk')
  266. (True, 'uk', 'ukrainian')
  267. >>> is_valid_lang(b'uk')
  268. (True, 'uk', 'ukrainian')
  269. >>> is_valid_lang('en')
  270. (True, 'en', 'english')
  271. >>> searx.utils.is_valid_lang('Español')
  272. (True, 'es', 'spanish')
  273. >>> searx.utils.is_valid_lang('Spanish')
  274. (True, 'es', 'spanish')
  275. """
  276. if isinstance(lang, bytes):
  277. lang = lang.decode()
  278. is_abbr = len(lang) == 2
  279. lang = lang.lower()
  280. if is_abbr:
  281. for l in language_codes:
  282. if l[0][:2] == lang:
  283. return (True, l[0][:2], l[3].lower())
  284. return None
  285. for l in language_codes:
  286. if l[1].lower() == lang or l[3].lower() == lang:
  287. return (True, l[0][:2], l[3].lower())
  288. return None
  289. def _get_lang_to_lc_dict(lang_list: List[str]) -> Dict[str, str]:
  290. key = str(lang_list)
  291. value = _LANG_TO_LC_CACHE.get(key, None)
  292. if value is None:
  293. value = {}
  294. for lang in lang_list:
  295. value.setdefault(lang.split('-')[0], lang)
  296. _LANG_TO_LC_CACHE[key] = value
  297. return value
  298. # babel's get_global contains all sorts of miscellaneous locale and territory related data
  299. # see get_global in: https://github.com/python-babel/babel/blob/master/babel/core.py
  300. def _get_from_babel(lang_code: str, key):
  301. match = get_global(key).get(lang_code.replace('-', '_'))
  302. # for some keys, such as territory_aliases, match may be a list
  303. if isinstance(match, str):
  304. return match.replace('_', '-')
  305. return match
  306. def _match_language(lang_code: str, lang_list=[], custom_aliases={}) -> Optional[str]: # pylint: disable=W0102
  307. """auxiliary function to match lang_code in lang_list"""
  308. # replace language code with a custom alias if necessary
  309. if lang_code in custom_aliases:
  310. lang_code = custom_aliases[lang_code]
  311. if lang_code in lang_list:
  312. return lang_code
  313. # try to get the most likely country for this language
  314. subtags = _get_from_babel(lang_code, 'likely_subtags')
  315. if subtags:
  316. if subtags in lang_list:
  317. return subtags
  318. subtag_parts = subtags.split('-')
  319. new_code = subtag_parts[0] + '-' + subtag_parts[-1]
  320. if new_code in custom_aliases:
  321. new_code = custom_aliases[new_code]
  322. if new_code in lang_list:
  323. return new_code
  324. # try to get the any supported country for this language
  325. return _get_lang_to_lc_dict(lang_list).get(lang_code)
  326. def match_language( # pylint: disable=W0102
  327. locale_code, lang_list=[], custom_aliases={}, fallback: Optional[str] = 'en-US'
  328. ) -> Optional[str]:
  329. """get the language code from lang_list that best matches locale_code"""
  330. # try to get language from given locale_code
  331. language = _match_language(locale_code, lang_list, custom_aliases)
  332. if language:
  333. return language
  334. locale_parts = locale_code.split('-')
  335. lang_code = locale_parts[0]
  336. # if locale_code has script, try matching without it
  337. if len(locale_parts) > 2:
  338. language = _match_language(lang_code + '-' + locale_parts[-1], lang_list, custom_aliases)
  339. if language:
  340. return language
  341. # try to get language using an equivalent country code
  342. if len(locale_parts) > 1:
  343. country_alias = _get_from_babel(locale_parts[-1], 'territory_aliases')
  344. if country_alias:
  345. language = _match_language(lang_code + '-' + country_alias[0], lang_list, custom_aliases)
  346. if language:
  347. return language
  348. # try to get language using an equivalent language code
  349. alias = _get_from_babel(lang_code, 'language_aliases')
  350. if alias:
  351. language = _match_language(alias, lang_list, custom_aliases)
  352. if language:
  353. return language
  354. if lang_code != locale_code:
  355. # try to get language from given language without giving the country
  356. language = _match_language(lang_code, lang_list, custom_aliases)
  357. return language or fallback
  358. def load_module(filename: str, module_dir: str) -> types.ModuleType:
  359. modname = splitext(filename)[0]
  360. modpath = join(module_dir, filename)
  361. # and https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
  362. spec = importlib.util.spec_from_file_location(modname, modpath)
  363. if not spec:
  364. raise ValueError(f"Error loading '{modpath}' module")
  365. module = importlib.util.module_from_spec(spec)
  366. if not spec.loader:
  367. raise ValueError(f"Error loading '{modpath}' module")
  368. spec.loader.exec_module(module)
  369. return module
  370. def to_string(obj: Any) -> str:
  371. """Convert obj to its string representation."""
  372. if isinstance(obj, str):
  373. return obj
  374. if hasattr(obj, '__str__'):
  375. return str(obj)
  376. return repr(obj)
  377. def ecma_unescape(string: str) -> str:
  378. """Python implementation of the unescape javascript function
  379. https://www.ecma-international.org/ecma-262/6.0/#sec-unescape-string
  380. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/unescape
  381. Examples:
  382. >>> ecma_unescape('%u5409')
  383. '吉'
  384. >>> ecma_unescape('%20')
  385. ' '
  386. >>> ecma_unescape('%F3')
  387. 'ó'
  388. """
  389. # "%u5409" becomes "吉"
  390. string = _ECMA_UNESCAPE4_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  391. # "%20" becomes " ", "%F3" becomes "ó"
  392. string = _ECMA_UNESCAPE2_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  393. return string
  394. def get_string_replaces_function(replaces: Dict[str, str]) -> Callable[[str], str]:
  395. rep = {re.escape(k): v for k, v in replaces.items()}
  396. pattern = re.compile("|".join(rep.keys()))
  397. def func(text):
  398. return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
  399. return func
  400. def get_engine_from_settings(name: str) -> Dict:
  401. """Return engine configuration from settings.yml of a given engine name"""
  402. if 'engines' not in settings:
  403. return {}
  404. for engine in settings['engines']:
  405. if 'name' not in engine:
  406. continue
  407. if name == engine['name']:
  408. return engine
  409. return {}
  410. def get_xpath(xpath_spec: XPathSpecType) -> XPath:
  411. """Return cached compiled XPath
  412. There is no thread lock.
  413. Worst case scenario, xpath_str is compiled more than one time.
  414. Args:
  415. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  416. Returns:
  417. * result (bool, float, list, str): Results.
  418. Raises:
  419. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  420. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  421. """
  422. if isinstance(xpath_spec, str):
  423. result = _XPATH_CACHE.get(xpath_spec, None)
  424. if result is None:
  425. try:
  426. result = XPath(xpath_spec)
  427. except XPathSyntaxError as e:
  428. raise SearxXPathSyntaxException(xpath_spec, str(e.msg)) from e
  429. _XPATH_CACHE[xpath_spec] = result
  430. return result
  431. if isinstance(xpath_spec, XPath):
  432. return xpath_spec
  433. raise TypeError('xpath_spec must be either a str or a lxml.etree.XPath')
  434. def eval_xpath(element: ElementBase, xpath_spec: XPathSpecType):
  435. """Equivalent of element.xpath(xpath_str) but compile xpath_str once for all.
  436. See https://lxml.de/xpathxslt.html#xpath-return-values
  437. Args:
  438. * element (ElementBase): [description]
  439. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  440. Returns:
  441. * result (bool, float, list, str): Results.
  442. Raises:
  443. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  444. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  445. * SearxEngineXPathException: Raise when the XPath can't be evaluated.
  446. """
  447. xpath = get_xpath(xpath_spec)
  448. try:
  449. return xpath(element)
  450. except XPathError as e:
  451. arg = ' '.join([str(i) for i in e.args])
  452. raise SearxEngineXPathException(xpath_spec, arg) from e
  453. def eval_xpath_list(element: ElementBase, xpath_spec: XPathSpecType, min_len: Optional[int] = None):
  454. """Same as eval_xpath, check if the result is a list
  455. Args:
  456. * element (ElementBase): [description]
  457. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  458. * min_len (int, optional): [description]. Defaults to None.
  459. Raises:
  460. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  461. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  462. * SearxEngineXPathException: raise if the result is not a list
  463. Returns:
  464. * result (bool, float, list, str): Results.
  465. """
  466. result = eval_xpath(element, xpath_spec)
  467. if not isinstance(result, list):
  468. raise SearxEngineXPathException(xpath_spec, 'the result is not a list')
  469. if min_len is not None and min_len > len(result):
  470. raise SearxEngineXPathException(xpath_spec, 'len(xpath_str) < ' + str(min_len))
  471. return result
  472. def eval_xpath_getindex(elements: ElementBase, xpath_spec: XPathSpecType, index: int, default=_NOTSET):
  473. """Call eval_xpath_list then get one element using the index parameter.
  474. If the index does not exist, either aise an exception is default is not set,
  475. other return the default value (can be None).
  476. Args:
  477. * elements (ElementBase): lxml element to apply the xpath.
  478. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath.
  479. * index (int): index to get
  480. * default (Object, optional): Defaults if index doesn't exist.
  481. Raises:
  482. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  483. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  484. * SearxEngineXPathException: if the index is not found. Also see eval_xpath.
  485. Returns:
  486. * result (bool, float, list, str): Results.
  487. """
  488. result = eval_xpath_list(elements, xpath_spec)
  489. if -len(result) <= index < len(result):
  490. return result[index]
  491. if default == _NOTSET:
  492. # raise an SearxEngineXPathException instead of IndexError
  493. # to record xpath_spec
  494. raise SearxEngineXPathException(xpath_spec, 'index ' + str(index) + ' not found')
  495. return default
  496. def _get_fasttext_model() -> fasttext.FastText._FastText:
  497. global _FASTTEXT_MODEL # pylint: disable=global-statement
  498. if _FASTTEXT_MODEL is None:
  499. _FASTTEXT_MODEL = fasttext.load_model(str(data_dir / 'lid.176.ftz'))
  500. return _FASTTEXT_MODEL
  501. def detect_language(text: str, threshold: float = 0.3, min_probability: float = 0.5) -> Optional[str]:
  502. """https://fasttext.cc/docs/en/language-identification.html"""
  503. if not isinstance(text, str):
  504. raise ValueError('text must a str')
  505. r = _get_fasttext_model().predict(text.replace('\n', ' '), k=1, threshold=threshold)
  506. if isinstance(r, tuple) and len(r) == 2 and len(r[0]) > 0 and len(r[1]) > 0 and r[1][0] > min_probability:
  507. return r[0][0].split('__label__')[1]
  508. return None