utils.py 25 KB

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