utils.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Utility functions for the engines"""
  3. from __future__ import annotations
  4. import re
  5. import importlib
  6. import importlib.util
  7. import json
  8. import types
  9. from typing import Optional, Union, Any, Set, List, Dict, MutableMapping, Tuple, Callable
  10. from numbers import Number
  11. from os.path import splitext, join
  12. from random import choice
  13. from html.parser import HTMLParser
  14. from html import escape
  15. from urllib.parse import urljoin, urlparse, parse_qs, urlencode
  16. from datetime import timedelta
  17. from markdown_it import MarkdownIt
  18. from lxml import html
  19. from lxml.etree import ElementBase, XPath, XPathError, XPathSyntaxError
  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. _XPATH_CACHE: Dict[str, XPath] = {}
  35. _LANG_TO_LC_CACHE: Dict[str, Dict[str, str]] = {}
  36. _FASTTEXT_MODEL: Optional["fasttext.FastText._FastText"] = None # type: ignore
  37. """fasttext model to predict language of a search term"""
  38. SEARCH_LANGUAGE_CODES = frozenset([searxng_locale[0].split('-')[0] for searxng_locale in sxng_locales])
  39. """Languages supported by most searxng engines (:py:obj:`searx.sxng_locales.sxng_locales`)."""
  40. class _NotSetClass: # pylint: disable=too-few-public-methods
  41. """Internal class for this module, do not create instance of this class.
  42. Replace the None value, allow explicitly pass None as a function argument"""
  43. _NOTSET = _NotSetClass()
  44. def searx_useragent() -> str:
  45. """Return the searx User Agent"""
  46. return 'searx/{searx_version} {suffix}'.format(
  47. searx_version=VERSION_TAG, suffix=settings['outgoing']['useragent_suffix']
  48. ).strip()
  49. def gen_useragent(os_string: Optional[str] = None) -> str:
  50. """Return a random browser User Agent
  51. See searx/data/useragents.json
  52. """
  53. return USER_AGENTS['ua'].format(os=os_string or choice(USER_AGENTS['os']), version=choice(USER_AGENTS['versions']))
  54. class _HTMLTextExtractorException(Exception):
  55. """Internal exception raised when the HTML is invalid"""
  56. class _HTMLTextExtractor(HTMLParser):
  57. """Internal class to extract text from HTML"""
  58. def __init__(self):
  59. HTMLParser.__init__(self)
  60. self.result = []
  61. self.tags = []
  62. def handle_starttag(self, tag, attrs):
  63. self.tags.append(tag)
  64. if tag == 'br':
  65. self.result.append(' ')
  66. def handle_endtag(self, tag):
  67. if not self.tags:
  68. return
  69. if tag != self.tags[-1]:
  70. raise _HTMLTextExtractorException()
  71. self.tags.pop()
  72. def is_valid_tag(self):
  73. return not self.tags or self.tags[-1] not in _BLOCKED_TAGS
  74. def handle_data(self, data):
  75. if not self.is_valid_tag():
  76. return
  77. self.result.append(data)
  78. def handle_charref(self, name):
  79. if not self.is_valid_tag():
  80. return
  81. if name[0] in ('x', 'X'):
  82. codepoint = int(name[1:], 16)
  83. else:
  84. codepoint = int(name)
  85. self.result.append(chr(codepoint))
  86. def handle_entityref(self, name):
  87. if not self.is_valid_tag():
  88. return
  89. # codepoint = htmlentitydefs.name2codepoint[name]
  90. # self.result.append(chr(codepoint))
  91. self.result.append(name)
  92. def get_text(self):
  93. return ''.join(self.result).strip()
  94. def error(self, message):
  95. # error handle is needed in <py3.10
  96. # https://github.com/python/cpython/pull/8562/files
  97. raise AssertionError(message)
  98. def html_to_text(html_str: str) -> str:
  99. """Extract text from a HTML string
  100. Args:
  101. * html_str (str): string HTML
  102. Returns:
  103. * str: extracted text
  104. Examples:
  105. >>> html_to_text('Example <span id="42">#2</span>')
  106. 'Example #2'
  107. >>> html_to_text('<style>.span { color: red; }</style><span>Example</span>')
  108. 'Example'
  109. >>> html_to_text(r'regexp: (?<![a-zA-Z]')
  110. 'regexp: (?<![a-zA-Z]'
  111. """
  112. if not html_str:
  113. return ""
  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. s.close()
  120. except AssertionError:
  121. s = _HTMLTextExtractor()
  122. s.feed(escape(html_str, quote=True))
  123. s.close()
  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, (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 humanize_bytes(size, precision=2):
  252. """Determine the *human readable* value of bytes on 1024 base (1KB=1024B)."""
  253. s = ['B ', 'KB', 'MB', 'GB', 'TB']
  254. x = len(s)
  255. p = 0
  256. while size > 1024 and p < x:
  257. p += 1
  258. size = size / 1024.0
  259. return "%.*f %s" % (precision, size, s[p])
  260. def humanize_number(size, precision=0):
  261. """Determine the *human readable* value of a decimal number."""
  262. s = ['', 'K', 'M', 'B', 'T']
  263. x = len(s)
  264. p = 0
  265. while size > 1000 and p < x:
  266. p += 1
  267. size = size / 1000.0
  268. return "%.*f%s" % (precision, size, s[p])
  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 extr(txt: str, begin: str, end: str, default: str = ""):
  275. """Extract the string between ``begin`` and ``end`` from ``txt``
  276. :param txt: String to search in
  277. :param begin: First string to be searched for
  278. :param end: Second string to be searched for after ``begin``
  279. :param default: Default value if one of ``begin`` or ``end`` is not
  280. found. Defaults to an empty string.
  281. :return: The string between the two search-strings ``begin`` and ``end``.
  282. If at least one of ``begin`` or ``end`` is not found, the value of
  283. ``default`` is returned.
  284. Examples:
  285. >>> extr("abcde", "a", "e")
  286. "bcd"
  287. >>> extr("abcde", "a", "z", deafult="nothing")
  288. "nothing"
  289. """
  290. # From https://github.com/mikf/gallery-dl/blob/master/gallery_dl/text.py#L129
  291. try:
  292. first = txt.index(begin) + len(begin)
  293. return txt[first : txt.index(end, first)]
  294. except ValueError:
  295. return default
  296. def int_or_zero(num: Union[List[str], str]) -> int:
  297. """Convert num to int or 0. num can be either a str or a list.
  298. If num is a list, the first element is converted to int (or return 0 if the list is empty).
  299. If num is a str, see convert_str_to_int
  300. """
  301. if isinstance(num, list):
  302. if len(num) < 1:
  303. return 0
  304. num = num[0]
  305. return convert_str_to_int(num)
  306. def is_valid_lang(lang) -> Optional[Tuple[bool, str, str]]:
  307. """Return language code and name if lang describe a language.
  308. Examples:
  309. >>> is_valid_lang('zz')
  310. None
  311. >>> is_valid_lang('uk')
  312. (True, 'uk', 'ukrainian')
  313. >>> is_valid_lang(b'uk')
  314. (True, 'uk', 'ukrainian')
  315. >>> is_valid_lang('en')
  316. (True, 'en', 'english')
  317. >>> searx.utils.is_valid_lang('Español')
  318. (True, 'es', 'spanish')
  319. >>> searx.utils.is_valid_lang('Spanish')
  320. (True, 'es', 'spanish')
  321. """
  322. if isinstance(lang, bytes):
  323. lang = lang.decode()
  324. is_abbr = len(lang) == 2
  325. lang = lang.lower()
  326. if is_abbr:
  327. for l in sxng_locales:
  328. if l[0][:2] == lang:
  329. return (True, l[0][:2], l[3].lower())
  330. return None
  331. for l in sxng_locales:
  332. if l[1].lower() == lang or l[3].lower() == lang:
  333. return (True, l[0][:2], l[3].lower())
  334. return None
  335. def load_module(filename: str, module_dir: str) -> types.ModuleType:
  336. modname = splitext(filename)[0]
  337. modpath = join(module_dir, filename)
  338. # and https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
  339. spec = importlib.util.spec_from_file_location(modname, modpath)
  340. if not spec:
  341. raise ValueError(f"Error loading '{modpath}' module")
  342. module = importlib.util.module_from_spec(spec)
  343. if not spec.loader:
  344. raise ValueError(f"Error loading '{modpath}' module")
  345. spec.loader.exec_module(module)
  346. return module
  347. def to_string(obj: Any) -> str:
  348. """Convert obj to its string representation."""
  349. if isinstance(obj, str):
  350. return obj
  351. if hasattr(obj, '__str__'):
  352. return str(obj)
  353. return repr(obj)
  354. def ecma_unescape(string: str) -> str:
  355. """Python implementation of the unescape javascript function
  356. https://www.ecma-international.org/ecma-262/6.0/#sec-unescape-string
  357. https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/unescape
  358. Examples:
  359. >>> ecma_unescape('%u5409')
  360. '吉'
  361. >>> ecma_unescape('%20')
  362. ' '
  363. >>> ecma_unescape('%F3')
  364. 'ó'
  365. """
  366. # "%u5409" becomes "吉"
  367. string = _ECMA_UNESCAPE4_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  368. # "%20" becomes " ", "%F3" becomes "ó"
  369. string = _ECMA_UNESCAPE2_RE.sub(lambda e: chr(int(e.group(1), 16)), string)
  370. return string
  371. def remove_pua_from_str(string):
  372. """Removes unicode's "PRIVATE USE CHARACTER"s (PUA_) from a string.
  373. .. _PUA: https://en.wikipedia.org/wiki/Private_Use_Areas
  374. """
  375. pua_ranges = ((0xE000, 0xF8FF), (0xF0000, 0xFFFFD), (0x100000, 0x10FFFD))
  376. s = []
  377. for c in string:
  378. i = ord(c)
  379. if any(a <= i <= b for (a, b) in pua_ranges):
  380. continue
  381. s.append(c)
  382. return "".join(s)
  383. def get_string_replaces_function(replaces: Dict[str, str]) -> Callable[[str], str]:
  384. rep = {re.escape(k): v for k, v in replaces.items()}
  385. pattern = re.compile("|".join(rep.keys()))
  386. def func(text):
  387. return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
  388. return func
  389. def get_engine_from_settings(name: str) -> Dict:
  390. """Return engine configuration from settings.yml of a given engine name"""
  391. if 'engines' not in settings:
  392. return {}
  393. for engine in settings['engines']:
  394. if 'name' not in engine:
  395. continue
  396. if name == engine['name']:
  397. return engine
  398. return {}
  399. def get_xpath(xpath_spec: XPathSpecType) -> XPath:
  400. """Return cached compiled XPath
  401. There is no thread lock.
  402. Worst case scenario, xpath_str is compiled more than one time.
  403. Args:
  404. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  405. Returns:
  406. * result (bool, float, list, str): Results.
  407. Raises:
  408. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  409. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  410. """
  411. if isinstance(xpath_spec, str):
  412. result = _XPATH_CACHE.get(xpath_spec, None)
  413. if result is None:
  414. try:
  415. result = XPath(xpath_spec)
  416. except XPathSyntaxError as e:
  417. raise SearxXPathSyntaxException(xpath_spec, str(e.msg)) from e
  418. _XPATH_CACHE[xpath_spec] = result
  419. return result
  420. if isinstance(xpath_spec, XPath):
  421. return xpath_spec
  422. raise TypeError('xpath_spec must be either a str or a lxml.etree.XPath')
  423. def eval_xpath(element: ElementBase, xpath_spec: XPathSpecType):
  424. """Equivalent of element.xpath(xpath_str) but compile xpath_str once for all.
  425. See https://lxml.de/xpathxslt.html#xpath-return-values
  426. Args:
  427. * element (ElementBase): [description]
  428. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  429. Returns:
  430. * result (bool, float, list, str): Results.
  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: Raise when the XPath can't be evaluated.
  435. """
  436. xpath = get_xpath(xpath_spec)
  437. try:
  438. return xpath(element)
  439. except XPathError as e:
  440. arg = ' '.join([str(i) for i in e.args])
  441. raise SearxEngineXPathException(xpath_spec, arg) from e
  442. def eval_xpath_list(element: ElementBase, xpath_spec: XPathSpecType, min_len: Optional[int] = None):
  443. """Same as eval_xpath, check if the result is a list
  444. Args:
  445. * element (ElementBase): [description]
  446. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath
  447. * min_len (int, optional): [description]. Defaults to None.
  448. Raises:
  449. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  450. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  451. * SearxEngineXPathException: raise if the result is not a list
  452. Returns:
  453. * result (bool, float, list, str): Results.
  454. """
  455. result = eval_xpath(element, xpath_spec)
  456. if not isinstance(result, list):
  457. raise SearxEngineXPathException(xpath_spec, 'the result is not a list')
  458. if min_len is not None and min_len > len(result):
  459. raise SearxEngineXPathException(xpath_spec, 'len(xpath_str) < ' + str(min_len))
  460. return result
  461. def eval_xpath_getindex(elements: ElementBase, xpath_spec: XPathSpecType, index: int, default=_NOTSET):
  462. """Call eval_xpath_list then get one element using the index parameter.
  463. If the index does not exist, either raise an exception is default is not set,
  464. other return the default value (can be None).
  465. Args:
  466. * elements (ElementBase): lxml element to apply the xpath.
  467. * xpath_spec (str|lxml.etree.XPath): XPath as a str or lxml.etree.XPath.
  468. * index (int): index to get
  469. * default (Object, optional): Defaults if index doesn't exist.
  470. Raises:
  471. * TypeError: Raise when xpath_spec is neither a str nor a lxml.etree.XPath
  472. * SearxXPathSyntaxException: Raise when there is a syntax error in the XPath
  473. * SearxEngineXPathException: if the index is not found. Also see eval_xpath.
  474. Returns:
  475. * result (bool, float, list, str): Results.
  476. """
  477. result = eval_xpath_list(elements, xpath_spec)
  478. if -len(result) <= index < len(result):
  479. return result[index]
  480. if default == _NOTSET:
  481. # raise an SearxEngineXPathException instead of IndexError
  482. # to record xpath_spec
  483. raise SearxEngineXPathException(xpath_spec, 'index ' + str(index) + ' not found')
  484. return default
  485. def _get_fasttext_model() -> "fasttext.FastText._FastText": # type: ignore
  486. global _FASTTEXT_MODEL # pylint: disable=global-statement
  487. if _FASTTEXT_MODEL is None:
  488. import fasttext # pylint: disable=import-outside-toplevel
  489. # Monkey patch: prevent fasttext from showing a (useless) warning when loading a model.
  490. fasttext.FastText.eprint = lambda x: None
  491. _FASTTEXT_MODEL = fasttext.load_model(str(data_dir / 'lid.176.ftz'))
  492. return _FASTTEXT_MODEL
  493. def get_embeded_stream_url(url):
  494. """
  495. Converts a standard video URL into its embed format. Supported services include Youtube,
  496. Facebook, Instagram, TikTok, Dailymotion, and Bilibili.
  497. """
  498. parsed_url = urlparse(url)
  499. iframe_src = None
  500. # YouTube
  501. if parsed_url.netloc in ['www.youtube.com', 'youtube.com'] and parsed_url.path == '/watch' and parsed_url.query:
  502. video_id = parse_qs(parsed_url.query).get('v', [])
  503. if video_id:
  504. iframe_src = 'https://www.youtube-nocookie.com/embed/' + video_id[0]
  505. # Facebook
  506. elif parsed_url.netloc in ['www.facebook.com', 'facebook.com']:
  507. encoded_href = urlencode({'href': url})
  508. iframe_src = 'https://www.facebook.com/plugins/video.php?allowfullscreen=true&' + encoded_href
  509. # Instagram
  510. elif parsed_url.netloc in ['www.instagram.com', 'instagram.com'] and parsed_url.path.startswith('/p/'):
  511. if parsed_url.path.endswith('/'):
  512. iframe_src = url + 'embed'
  513. else:
  514. iframe_src = url + '/embed'
  515. # TikTok
  516. elif (
  517. parsed_url.netloc in ['www.tiktok.com', 'tiktok.com']
  518. and parsed_url.path.startswith('/@')
  519. and '/video/' in parsed_url.path
  520. ):
  521. path_parts = parsed_url.path.split('/video/')
  522. video_id = path_parts[1]
  523. iframe_src = 'https://www.tiktok.com/embed/' + video_id
  524. # Dailymotion
  525. elif parsed_url.netloc in ['www.dailymotion.com', 'dailymotion.com'] and parsed_url.path.startswith('/video/'):
  526. path_parts = parsed_url.path.split('/')
  527. if len(path_parts) == 3:
  528. video_id = path_parts[2]
  529. iframe_src = 'https://www.dailymotion.com/embed/video/' + video_id
  530. # Bilibili
  531. elif parsed_url.netloc in ['www.bilibili.com', 'bilibili.com'] and parsed_url.path.startswith('/video/'):
  532. path_parts = parsed_url.path.split('/')
  533. video_id = path_parts[2]
  534. param_key = None
  535. if video_id.startswith('av'):
  536. video_id = video_id[2:]
  537. param_key = 'aid'
  538. elif video_id.startswith('BV'):
  539. param_key = 'bvid'
  540. iframe_src = (
  541. f'https://player.bilibili.com/player.html?{param_key}={video_id}&high_quality=1&autoplay=false&danmaku=0'
  542. )
  543. return iframe_src
  544. def detect_language(text: str, threshold: float = 0.3, only_search_languages: bool = False) -> Optional[str]:
  545. """Detect the language of the ``text`` parameter.
  546. :param str text: The string whose language is to be detected.
  547. :param float threshold: Threshold filters the returned labels by a threshold
  548. on probability. A choice of 0.3 will return labels with at least 0.3
  549. probability.
  550. :param bool only_search_languages: If ``True``, returns only supported
  551. SearXNG search languages. see :py:obj:`searx.languages`
  552. :rtype: str, None
  553. :returns:
  554. The detected language code or ``None``. See below.
  555. :raises ValueError: If ``text`` is not a string.
  556. The language detection is done by using `a fork`_ of the fastText_ library
  557. (`python fasttext`_). fastText_ distributes the `language identification
  558. model`_, for reference:
  559. - `FastText.zip: Compressing text classification models`_
  560. - `Bag of Tricks for Efficient Text Classification`_
  561. The `language identification model`_ support the language codes
  562. (ISO-639-3)::
  563. af als am an ar arz as ast av az azb ba bar bcl be bg bh bn bo bpy br bs
  564. bxr ca cbk ce ceb ckb co cs cv cy da de diq dsb dty dv el eml en eo es
  565. et eu fa fi fr frr fy ga gd gl gn gom gu gv he hi hif hr hsb ht hu hy ia
  566. id ie ilo io is it ja jbo jv ka kk km kn ko krc ku kv kw ky la lb lez li
  567. lmo lo lrc lt lv mai mg mhr min mk ml mn mr mrj ms mt mwl my myv mzn nah
  568. nap nds ne new nl nn no oc or os pa pam pfl pl pms pnb ps pt qu rm ro ru
  569. rue sa sah sc scn sco sd sh si sk sl so sq sr su sv sw ta te tg th tk tl
  570. tr tt tyv ug uk ur uz vec vep vi vls vo wa war wuu xal xmf yi yo yue zh
  571. By using ``only_search_languages=True`` the `language identification model`_
  572. is harmonized with the SearXNG's language (locale) model. General
  573. conditions of SearXNG's locale model are:
  574. a. SearXNG's locale of a query is passed to the
  575. :py:obj:`searx.locales.get_engine_locale` to get a language and/or region
  576. code that is used by an engine.
  577. b. Most of SearXNG's engines do not support all the languages from `language
  578. identification model`_ and there is also a discrepancy in the ISO-639-3
  579. (fasttext) and ISO-639-2 (SearXNG)handling. Further more, in SearXNG the
  580. locales like ``zh-TH`` (``zh-CN``) are mapped to ``zh_Hant``
  581. (``zh_Hans``) while the `language identification model`_ reduce both to
  582. ``zh``.
  583. .. _a fork: https://github.com/searxng/fasttext-predict
  584. .. _fastText: https://fasttext.cc/
  585. .. _python fasttext: https://pypi.org/project/fasttext/
  586. .. _language identification model: https://fasttext.cc/docs/en/language-identification.html
  587. .. _Bag of Tricks for Efficient Text Classification: https://arxiv.org/abs/1607.01759
  588. .. _`FastText.zip: Compressing text classification models`: https://arxiv.org/abs/1612.03651
  589. """
  590. if not isinstance(text, str):
  591. raise ValueError('text must a str')
  592. r = _get_fasttext_model().predict(text.replace('\n', ' '), k=1, threshold=threshold)
  593. if isinstance(r, tuple) and len(r) == 2 and len(r[0]) > 0 and len(r[1]) > 0:
  594. language = r[0][0].split('__label__')[1]
  595. if only_search_languages and language not in SEARCH_LANGUAGE_CODES:
  596. return None
  597. return language
  598. return None
  599. def js_variable_to_python(js_variable):
  600. """Convert a javascript variable into JSON and then load the value
  601. It does not deal with all cases, but it is good enough for now.
  602. chompjs has a better implementation.
  603. """
  604. # when in_string is not None, it contains the character that has opened the string
  605. # either simple quote or double quote
  606. in_string = None
  607. # cut the string:
  608. # r"""{ a:"f\"irst", c:'sec"ond'}"""
  609. # becomes
  610. # ['{ a:', '"', 'f\\', '"', 'irst', '"', ', c:', "'", 'sec', '"', 'ond', "'", '}']
  611. parts = re.split(r'(["\'])', js_variable)
  612. # previous part (to check the escape character antislash)
  613. previous_p = ""
  614. for i, p in enumerate(parts):
  615. # parse characters inside a ECMA string
  616. if in_string:
  617. # we are in a JS string: replace the colon by a temporary character
  618. # so quote_keys_regex doesn't have to deal with colon inside the JS strings
  619. parts[i] = parts[i].replace(':', chr(1))
  620. if in_string == "'":
  621. # the JS string is delimited by simple quote.
  622. # This is not supported by JSON.
  623. # simple quote delimited string are converted to double quote delimited string
  624. # here, inside a JS string, we escape the double quote
  625. parts[i] = parts[i].replace('"', r'\"')
  626. # deal with delimiters and escape character
  627. if not in_string and p in ('"', "'"):
  628. # we are not in string
  629. # but p is double or simple quote
  630. # that's the start of a new string
  631. # replace simple quote by double quote
  632. # (JSON doesn't support simple quote)
  633. parts[i] = '"'
  634. in_string = p
  635. continue
  636. if p == in_string:
  637. # we are in a string and the current part MAY close the string
  638. if len(previous_p) > 0 and previous_p[-1] == '\\':
  639. # there is an antislash just before: the ECMA string continue
  640. continue
  641. # the current p close the string
  642. # replace simple quote by double quote
  643. parts[i] = '"'
  644. in_string = None
  645. if not in_string:
  646. # replace void 0 by null
  647. # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
  648. # we are sure there is no string in p
  649. parts[i] = _JS_VOID_RE.sub("null", p)
  650. # update previous_p
  651. previous_p = p
  652. # join the string
  653. s = ''.join(parts)
  654. # add quote around the key
  655. # { a: 12 }
  656. # becomes
  657. # { "a": 12 }
  658. s = _JS_QUOTE_KEYS_RE.sub(r'\1"\2"\3', s)
  659. s = _JS_DECIMAL_RE.sub(":0.", s)
  660. # replace the surogate character by colon
  661. s = s.replace(chr(1), ':')
  662. # replace single-quote followed by comma with double-quote and comma
  663. # {"a": "\"12\"',"b": "13"}
  664. # becomes
  665. # {"a": "\"12\"","b": "13"}
  666. s = s.replace("',", "\",")
  667. # load the JSON and return the result
  668. return json.loads(s)
  669. def parse_duration_string(duration_str: str) -> timedelta | None:
  670. """Parse a time string in format MM:SS or HH:MM:SS and convert it to a `timedelta` object.
  671. Returns None if the provided string doesn't match any of the formats.
  672. """
  673. duration_str = duration_str.strip()
  674. if not duration_str:
  675. return None
  676. try:
  677. # prepending ["00"] here inits hours to 0 if they are not provided
  678. time_parts = (["00"] + duration_str.split(":"))[:3]
  679. hours, minutes, seconds = map(int, time_parts)
  680. return timedelta(hours=hours, minutes=minutes, seconds=seconds)
  681. except (ValueError, TypeError):
  682. pass
  683. return None