utils.py 24 KB

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