utils.py 25 KB

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