utils.py 25 KB

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