utils.py 27 KB

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