utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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 searx import settings
  19. from searx.data import USER_AGENTS, data_dir
  20. from searx.version import VERSION_TAG
  21. from searx.sxng_locales import sxng_locales
  22. from searx.exceptions import SearxXPathSyntaxException, SearxEngineXPathException
  23. from searx import logger
  24. logger = logger.getChild('utils')
  25. XPathSpecType = Union[str, XPath]
  26. _BLOCKED_TAGS = ('script', 'style')
  27. _ECMA_UNESCAPE4_RE = re.compile(r'%u([0-9a-fA-F]{4})', re.UNICODE)
  28. _ECMA_UNESCAPE2_RE = re.compile(r'%([0-9a-fA-F]{2})', re.UNICODE)
  29. _STORAGE_UNIT_VALUE: Dict[str, int] = {
  30. 'TB': 1024 * 1024 * 1024 * 1024,
  31. 'GB': 1024 * 1024 * 1024,
  32. 'MB': 1024 * 1024,
  33. 'TiB': 1000 * 1000 * 1000 * 1000,
  34. 'MiB': 1000 * 1000,
  35. 'KiB': 1000,
  36. }
  37. _XPATH_CACHE: Dict[str, XPath] = {}
  38. _LANG_TO_LC_CACHE: Dict[str, Dict[str, str]] = {}
  39. _FASTTEXT_MODEL: Optional["fasttext.FastText._FastText"] = None
  40. """fasttext model to predict laguage of a search term"""
  41. SEARCH_LANGUAGE_CODES = frozenset([searxng_locale[0].split('-')[0] for searxng_locale in sxng_locales])
  42. """Languages supported by most searxng engines (:py:obj:`searx.sxng_locales.sxng_locales`)."""
  43. class _NotSetClass: # pylint: disable=too-few-public-methods
  44. """Internal class for this module, do not create instance of this class.
  45. Replace the None value, allow explicitly pass None as a function argument"""
  46. _NOTSET = _NotSetClass()
  47. def searx_useragent() -> str:
  48. """Return the searx User Agent"""
  49. return 'searx/{searx_version} {suffix}'.format(
  50. searx_version=VERSION_TAG, suffix=settings['outgoing']['useragent_suffix']
  51. ).strip()
  52. def gen_useragent(os_string: Optional[str] = None) -> str:
  53. """Return a random browser User Agent
  54. See searx/data/useragents.json
  55. """
  56. return USER_AGENTS['ua'].format(os=os_string or choice(USER_AGENTS['os']), version=choice(USER_AGENTS['versions']))
  57. class _HTMLTextExtractorException(Exception):
  58. """Internal exception raised when the HTML is invalid"""
  59. class _HTMLTextExtractor(HTMLParser): # pylint: disable=W0223 # (see https://bugs.python.org/issue31844)
  60. """Internal class to extract text from HTML"""
  61. def __init__(self):
  62. HTMLParser.__init__(self)
  63. self.result = []
  64. self.tags = []
  65. def handle_starttag(self, tag, attrs):
  66. self.tags.append(tag)
  67. if tag == 'br':
  68. self.result.append(' ')
  69. def handle_endtag(self, tag):
  70. if not self.tags:
  71. return
  72. if tag != self.tags[-1]:
  73. raise _HTMLTextExtractorException()
  74. self.tags.pop()
  75. def is_valid_tag(self):
  76. return not self.tags or self.tags[-1] not in _BLOCKED_TAGS
  77. def handle_data(self, data):
  78. if not self.is_valid_tag():
  79. return
  80. self.result.append(data)
  81. def handle_charref(self, name):
  82. if not self.is_valid_tag():
  83. return
  84. if name[0] in ('x', 'X'):
  85. codepoint = int(name[1:], 16)
  86. else:
  87. codepoint = int(name)
  88. self.result.append(chr(codepoint))
  89. def handle_entityref(self, name):
  90. if not self.is_valid_tag():
  91. return
  92. # codepoint = htmlentitydefs.name2codepoint[name]
  93. # self.result.append(chr(codepoint))
  94. self.result.append(name)
  95. def get_text(self):
  96. return ''.join(self.result).strip()
  97. def html_to_text(html_str: str) -> str:
  98. """Extract text from a HTML string
  99. Args:
  100. * html_str (str): string HTML
  101. Returns:
  102. * str: extracted text
  103. Examples:
  104. >>> html_to_text('Example <span id="42">#2</span>')
  105. 'Example #2'
  106. >>> html_to_text('<style>.span { color: red; }</style><span>Example</span>')
  107. 'Example'
  108. """
  109. html_str = html_str.replace('\n', ' ').replace('\r', ' ')
  110. html_str = ' '.join(html_str.split())
  111. s = _HTMLTextExtractor()
  112. try:
  113. s.feed(html_str)
  114. except _HTMLTextExtractorException:
  115. logger.debug("HTMLTextExtractor: invalid HTML\n%s", html_str)
  116. return s.get_text()
  117. def extract_text(xpath_results, allow_none: bool = False) -> Optional[str]:
  118. """Extract text from a lxml result
  119. * if xpath_results is list, extract the text from each result and concat the list
  120. * if xpath_results is a xml element, extract all the text node from it
  121. ( text_content() method from lxml )
  122. * if xpath_results is a string element, then it's already done
  123. """
  124. if isinstance(xpath_results, list):
  125. # it's list of result : concat everything using recursive call
  126. result = ''
  127. for e in xpath_results:
  128. result = result + (extract_text(e) or '')
  129. return result.strip()
  130. if isinstance(xpath_results, ElementBase):
  131. # it's a element
  132. text: str = html.tostring(xpath_results, encoding='unicode', method='text', with_tail=False)
  133. text = text.strip().replace('\n', ' ')
  134. return ' '.join(text.split())
  135. if isinstance(xpath_results, (_ElementStringResult, _ElementUnicodeResult, str, Number, bool)):
  136. return str(xpath_results)
  137. if xpath_results is None and allow_none:
  138. return None
  139. if xpath_results is None and not allow_none:
  140. raise ValueError('extract_text(None, allow_none=False)')
  141. raise ValueError('unsupported type')
  142. def normalize_url(url: str, base_url: str) -> str:
  143. """Normalize URL: add protocol, join URL with base_url, add trailing slash if there is no path
  144. Args:
  145. * url (str): Relative URL
  146. * base_url (str): Base URL, it must be an absolute URL.
  147. Example:
  148. >>> normalize_url('https://example.com', 'http://example.com/')
  149. 'https://example.com/'
  150. >>> normalize_url('//example.com', 'http://example.com/')
  151. 'http://example.com/'
  152. >>> normalize_url('//example.com', 'https://example.com/')
  153. 'https://example.com/'
  154. >>> normalize_url('/path?a=1', 'https://example.com')
  155. 'https://example.com/path?a=1'
  156. >>> normalize_url('', 'https://example.com')
  157. 'https://example.com/'
  158. >>> normalize_url('/test', '/path')
  159. raise ValueError
  160. Raises:
  161. * lxml.etree.ParserError
  162. Returns:
  163. * str: normalized URL
  164. """
  165. if url.startswith('//'):
  166. # add http or https to this kind of url //example.com/
  167. parsed_search_url = urlparse(base_url)
  168. url = '{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
  169. elif url.startswith('/'):
  170. # fix relative url to the search engine
  171. url = urljoin(base_url, url)
  172. # fix relative urls that fall through the crack
  173. if '://' not in url:
  174. url = urljoin(base_url, url)
  175. parsed_url = urlparse(url)
  176. # add a / at this end of the url if there is no path
  177. if not parsed_url.netloc:
  178. raise ValueError('Cannot parse url')
  179. if not parsed_url.path:
  180. url += '/'
  181. return url
  182. def extract_url(xpath_results, base_url) -> str:
  183. """Extract and normalize URL from lxml Element
  184. Args:
  185. * xpath_results (Union[List[html.HtmlElement], html.HtmlElement]): lxml Element(s)
  186. * base_url (str): Base URL
  187. Example:
  188. >>> def f(s, search_url):
  189. >>> return searx.utils.extract_url(html.fromstring(s), search_url)
  190. >>> f('<span id="42">https://example.com</span>', 'http://example.com/')
  191. 'https://example.com/'
  192. >>> f('https://example.com', 'http://example.com/')
  193. 'https://example.com/'
  194. >>> f('//example.com', 'http://example.com/')
  195. 'http://example.com/'
  196. >>> f('//example.com', 'https://example.com/')
  197. 'https://example.com/'
  198. >>> f('/path?a=1', 'https://example.com')
  199. 'https://example.com/path?a=1'
  200. >>> f('', 'https://example.com')
  201. raise lxml.etree.ParserError
  202. >>> searx.utils.extract_url([], 'https://example.com')
  203. raise ValueError
  204. Raises:
  205. * ValueError
  206. * lxml.etree.ParserError
  207. Returns:
  208. * str: normalized URL
  209. """
  210. if xpath_results == []:
  211. raise ValueError('Empty url resultset')
  212. url = extract_text(xpath_results)
  213. if url:
  214. return normalize_url(url, base_url)
  215. raise ValueError('URL not found')
  216. def dict_subset(dictionary: MutableMapping, properties: Set[str]) -> Dict:
  217. """Extract a subset of a dict
  218. Examples:
  219. >>> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'C'])
  220. {'A': 'a', 'C': 'c'}
  221. >>> >> dict_subset({'A': 'a', 'B': 'b', 'C': 'c'}, ['A', 'D'])
  222. {'A': 'a'}
  223. """
  224. return {k: dictionary[k] for k in properties if k in dictionary}
  225. def get_torrent_size(filesize: str, filesize_multiplier: str) -> Optional[int]:
  226. """
  227. Args:
  228. * filesize (str): size
  229. * filesize_multiplier (str): TB, GB, .... TiB, GiB...
  230. Returns:
  231. * int: number of bytes
  232. Example:
  233. >>> get_torrent_size('5', 'GB')
  234. 5368709120
  235. >>> get_torrent_size('3.14', 'MiB')
  236. 3140000
  237. """
  238. try:
  239. multiplier = _STORAGE_UNIT_VALUE.get(filesize_multiplier, 1)
  240. return int(float(filesize) * multiplier)
  241. except ValueError:
  242. return None
  243. def convert_str_to_int(number_str: str) -> int:
  244. """Convert number_str to int or 0 if number_str is not a number."""
  245. if number_str.isdigit():
  246. return int(number_str)
  247. return 0
  248. def int_or_zero(num: Union[List[str], str]) -> int:
  249. """Convert num to int or 0. num can be either a str or a list.
  250. If num is a list, the first element is converted to int (or return 0 if the list is empty).
  251. If num is a str, see convert_str_to_int
  252. """
  253. if isinstance(num, list):
  254. if len(num) < 1:
  255. return 0
  256. num = num[0]
  257. return convert_str_to_int(num)
  258. def is_valid_lang(lang) -> Optional[Tuple[bool, str, str]]:
  259. """Return language code and name if lang describe a language.
  260. Examples:
  261. >>> is_valid_lang('zz')
  262. None
  263. >>> is_valid_lang('uk')
  264. (True, 'uk', 'ukrainian')
  265. >>> is_valid_lang(b'uk')
  266. (True, 'uk', 'ukrainian')
  267. >>> is_valid_lang('en')
  268. (True, 'en', 'english')
  269. >>> searx.utils.is_valid_lang('Español')
  270. (True, 'es', 'spanish')
  271. >>> searx.utils.is_valid_lang('Spanish')
  272. (True, 'es', 'spanish')
  273. """
  274. if isinstance(lang, bytes):
  275. lang = lang.decode()
  276. is_abbr = len(lang) == 2
  277. lang = lang.lower()
  278. if is_abbr:
  279. for l in sxng_locales:
  280. if l[0][:2] == lang:
  281. return (True, l[0][:2], l[3].lower())
  282. return None
  283. for l in sxng_locales:
  284. if l[1].lower() == lang or l[3].lower() == lang:
  285. return (True, l[0][:2], l[3].lower())
  286. return None
  287. def load_module(filename: str, module_dir: str) -> types.ModuleType:
  288. modname = splitext(filename)[0]
  289. modpath = join(module_dir, filename)
  290. # and https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
  291. spec = importlib.util.spec_from_file_location(modname, modpath)
  292. if not spec:
  293. raise ValueError(f"Error loading '{modpath}' module")
  294. module = importlib.util.module_from_spec(spec)
  295. if not spec.loader:
  296. raise ValueError(f"Error loading '{modpath}' module")
  297. spec.loader.exec_module(module)
  298. return module
  299. def to_string(obj: Any) -> str:
  300. """Convert obj to its string representation."""
  301. if isinstance(obj, str):
  302. return obj
  303. if hasattr(obj, '__str__'):
  304. return str(obj)
  305. return repr(obj)
  306. def ecma_unescape(string: str) -> str:
  307. """Python implementation of the unescape javascript function
  308. https://www.ecma-international.org/ecma-262/6.0/#sec-unescape-string
  309. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/unescape
  310. Examples:
  311. >>> ecma_unescape('%u5409')
  312. '吉'
  313. >>> ecma_unescape('%20')
  314. ' '
  315. >>> ecma_unescape('%F3')
  316. 'ó'
  317. """
  318. # "%u5409" becomes "吉"
  319. string = _ECMA_UNESCAPE4_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  320. # "%20" becomes " ", "%F3" becomes "ó"
  321. string = _ECMA_UNESCAPE2_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  322. return string
  323. def get_string_replaces_function(replaces: Dict[str, str]) -> Callable[[str], str]:
  324. rep = {re.escape(k): v for k, v in replaces.items()}
  325. pattern = re.compile("|".join(rep.keys()))
  326. def func(text):
  327. return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
  328. return func
  329. def get_engine_from_settings(name: str) -> Dict:
  330. """Return engine configuration from settings.yml of a given engine name"""
  331. if 'engines' not in settings:
  332. return {}
  333. for engine in settings['engines']:
  334. if 'name' not in engine:
  335. continue
  336. if name == engine['name']:
  337. return engine
  338. return {}
  339. def get_xpath(xpath_spec: XPathSpecType) -> XPath:
  340. """Return cached compiled XPath
  341. There is no thread lock.
  342. Worst case scenario, xpath_str is compiled more than one time.
  343. Args:
  344. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  345. Returns:
  346. * result (bool, float, list, str): Results.
  347. Raises:
  348. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  349. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  350. """
  351. if isinstance(xpath_spec, str):
  352. result = _XPATH_CACHE.get(xpath_spec, None)
  353. if result is None:
  354. try:
  355. result = XPath(xpath_spec)
  356. except XPathSyntaxError as e:
  357. raise SearxXPathSyntaxException(xpath_spec, str(e.msg)) from e
  358. _XPATH_CACHE[xpath_spec] = result
  359. return result
  360. if isinstance(xpath_spec, XPath):
  361. return xpath_spec
  362. raise TypeError('xpath_spec must be either a str or a lxml.etree.XPath')
  363. def eval_xpath(element: ElementBase, xpath_spec: XPathSpecType):
  364. """Equivalent of element.xpath(xpath_str) but compile xpath_str once for all.
  365. See https://lxml.de/xpathxslt.html#xpath-return-values
  366. Args:
  367. * element (ElementBase): [description]
  368. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  369. Returns:
  370. * result (bool, float, list, str): Results.
  371. Raises:
  372. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  373. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  374. * SearxEngineXPathException: Raise when the XPath can't be evaluated.
  375. """
  376. xpath = get_xpath(xpath_spec)
  377. try:
  378. return xpath(element)
  379. except XPathError as e:
  380. arg = ' '.join([str(i) for i in e.args])
  381. raise SearxEngineXPathException(xpath_spec, arg) from e
  382. def eval_xpath_list(element: ElementBase, xpath_spec: XPathSpecType, min_len: Optional[int] = None):
  383. """Same as eval_xpath, check if the result is a list
  384. Args:
  385. * element (ElementBase): [description]
  386. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  387. * min_len (int, optional): [description]. Defaults to None.
  388. Raises:
  389. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  390. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  391. * SearxEngineXPathException: raise if the result is not a list
  392. Returns:
  393. * result (bool, float, list, str): Results.
  394. """
  395. result = eval_xpath(element, xpath_spec)
  396. if not isinstance(result, list):
  397. raise SearxEngineXPathException(xpath_spec, 'the result is not a list')
  398. if min_len is not None and min_len > len(result):
  399. raise SearxEngineXPathException(xpath_spec, 'len(xpath_str) < ' + str(min_len))
  400. return result
  401. def eval_xpath_getindex(elements: ElementBase, xpath_spec: XPathSpecType, index: int, default=_NOTSET):
  402. """Call eval_xpath_list then get one element using the index parameter.
  403. If the index does not exist, either aise an exception is default is not set,
  404. other return the default value (can be None).
  405. Args:
  406. * elements (ElementBase): lxml element to apply the xpath.
  407. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath.
  408. * index (int): index to get
  409. * default (Object, optional): Defaults if index doesn't exist.
  410. Raises:
  411. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  412. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  413. * SearxEngineXPathException: if the index is not found. Also see eval_xpath.
  414. Returns:
  415. * result (bool, float, list, str): Results.
  416. """
  417. result = eval_xpath_list(elements, xpath_spec)
  418. if -len(result) <= index < len(result):
  419. return result[index]
  420. if default == _NOTSET:
  421. # raise an SearxEngineXPathException instead of IndexError
  422. # to record xpath_spec
  423. raise SearxEngineXPathException(xpath_spec, 'index ' + str(index) + ' not found')
  424. return default
  425. def _get_fasttext_model() -> "fasttext.FastText._FastText":
  426. global _FASTTEXT_MODEL # pylint: disable=global-statement
  427. if _FASTTEXT_MODEL is None:
  428. import fasttext # pylint: disable=import-outside-toplevel
  429. # Monkey patch: prevent fasttext from showing a (useless) warning when loading a model.
  430. fasttext.FastText.eprint = lambda x: None
  431. _FASTTEXT_MODEL = fasttext.load_model(str(data_dir / 'lid.176.ftz'))
  432. return _FASTTEXT_MODEL
  433. def detect_language(text: str, threshold: float = 0.3, only_search_languages: bool = False) -> Optional[str]:
  434. """Detect the language of the ``text`` parameter.
  435. :param str text: The string whose language is to be detected.
  436. :param float threshold: Threshold filters the returned labels by a threshold
  437. on probability. A choice of 0.3 will return labels with at least 0.3
  438. probability.
  439. :param bool only_search_languages: If ``True``, returns only supported
  440. SearXNG search languages. see :py:obj:`searx.languages`
  441. :rtype: str, None
  442. :returns:
  443. The detected language code or ``None``. See below.
  444. :raises ValueError: If ``text`` is not a string.
  445. The language detection is done by using `a fork`_ of the fastText_ library
  446. (`python fasttext`_). fastText_ distributes the `language identification
  447. model`_, for reference:
  448. - `FastText.zip: Compressing text classification models`_
  449. - `Bag of Tricks for Efficient Text Classification`_
  450. The `language identification model`_ support the language codes
  451. (ISO-639-3)::
  452. af als am an ar arz as ast av az azb ba bar bcl be bg bh bn bo bpy br bs
  453. bxr ca cbk ce ceb ckb co cs cv cy da de diq dsb dty dv el eml en eo es
  454. et eu fa fi fr frr fy ga gd gl gn gom gu gv he hi hif hr hsb ht hu hy ia
  455. id ie ilo io is it ja jbo jv ka kk km kn ko krc ku kv kw ky la lb lez li
  456. lmo lo lrc lt lv mai mg mhr min mk ml mn mr mrj ms mt mwl my myv mzn nah
  457. nap nds ne new nl nn no oc or os pa pam pfl pl pms pnb ps pt qu rm ro ru
  458. rue sa sah sc scn sco sd sh si sk sl so sq sr su sv sw ta te tg th tk tl
  459. tr tt tyv ug uk ur uz vec vep vi vls vo wa war wuu xal xmf yi yo yue zh
  460. By using ``only_search_languages=True`` the `language identification model`_
  461. is harmonized with the SearXNG's language (locale) model. General
  462. conditions of SearXNG's locale model are:
  463. a. SearXNG's locale of a query is passed to the
  464. :py:obj:`searx.locales.get_engine_locale` to get a language and/or region
  465. code that is used by an engine.
  466. b. Most of SearXNG's engines do not support all the languages from `language
  467. identification model`_ and there is also a discrepancy in the ISO-639-3
  468. (fastext) and ISO-639-2 (SearXNG)handling. Further more, in SearXNG the
  469. locales like ``zh-TH`` (``zh-CN``) are mapped to ``zh_Hant``
  470. (``zh_Hans``) while the `language identification model`_ reduce both to
  471. ``zh``.
  472. .. _a fork: https://github.com/searxng/fasttext-predict
  473. .. _fastText: https://fasttext.cc/
  474. .. _python fasttext: https://pypi.org/project/fasttext/
  475. .. _language identification model: https://fasttext.cc/docs/en/language-identification.html
  476. .. _Bag of Tricks for Efficient Text Classification: https://arxiv.org/abs/1607.01759
  477. .. _`FastText.zip: Compressing text classification models`: https://arxiv.org/abs/1612.03651
  478. """
  479. if not isinstance(text, str):
  480. raise ValueError('text must a str')
  481. r = _get_fasttext_model().predict(text.replace('\n', ' '), k=1, threshold=threshold)
  482. if isinstance(r, tuple) and len(r) == 2 and len(r[0]) > 0 and len(r[1]) > 0:
  483. language = r[0][0].split('__label__')[1]
  484. if only_search_languages and language not in SEARCH_LANGUAGE_CODES:
  485. return None
  486. return language
  487. return None