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