2022-03-12 09:18:08 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
"""Render SearXNG instance documentation.
|
|
|
|
|
|
|
|
Usage in a Flask app route:
|
|
|
|
|
|
|
|
.. code:: python
|
|
|
|
|
|
|
|
from searx import infopage
|
[refactor] typification of SearXNG (initial) / result items (part 1)
Typification of SearXNG
=======================
This patch introduces the typing of the results. The why and how is described
in the documentation, please generate the documentation ..
$ make docs.clean docs.live
and read the following articles in the "Developer documentation":
- result types --> http://0.0.0.0:8000/dev/result_types/index.html
The result types are available from the `searx.result_types` module. The
following have been implemented so far:
- base result type: `searx.result_type.Result`
--> http://0.0.0.0:8000/dev/result_types/base_result.html
- answer results
--> http://0.0.0.0:8000/dev/result_types/answer.html
including the type for translations (inspired by #3925). For all other
types (which still need to be set up in subsequent PRs), template documentation
has been created for the transition period.
Doc of the fields used in Templates
===================================
The template documentation is the basis for the typing and is the first complete
documentation of the results (needed for engine development). It is the
"working paper" (the plan) with which further typifications can be implemented
in subsequent PRs.
- https://github.com/searxng/searxng/issues/357
Answer Templates
================
With the new (sub) types for `Answer`, the templates for the answers have also
been revised, `Translation` are now displayed with collapsible entries (inspired
by #3925).
!en-de dog
Plugins & Answerer
==================
The implementation for `Plugin` and `Answer` has been revised, see
documentation:
- Plugin: http://0.0.0.0:8000/dev/plugins/index.html
- Answerer: http://0.0.0.0:8000/dev/answerers/index.html
With `AnswerStorage` and `AnswerStorage` to manage those items (in follow up
PRs, `ArticleStorage`, `InfoStorage` and .. will be implemented)
Autocomplete
============
The autocompletion had a bug where the results from `Answer` had not been shown
in the past. To test activate autocompletion and try search terms for which we
have answerers
- statistics: type `min 1 2 3` .. in the completion list you should find an
entry like `[de] min(1, 2, 3) = 1`
- random: type `random uuid` .. in the completion list, the first item is a
random UUID
Extended Types
==============
SearXNG extends e.g. the request and response types of flask and httpx, a module
has been set up for type extensions:
- Extended Types
--> http://0.0.0.0:8000/dev/extended_types.html
Unit-Tests
==========
The unit tests have been completely revised. In the previous implementation,
the runtime (the global variables such as `searx.settings`) was not initialized
before each test, so the runtime environment with which a test ran was always
determined by the tests that ran before it. This was also the reason why we
sometimes had to observe non-deterministic errors in the tests in the past:
- https://github.com/searxng/searxng/issues/2988 is one example for the Runtime
issues, with non-deterministic behavior ..
- https://github.com/searxng/searxng/pull/3650
- https://github.com/searxng/searxng/pull/3654
- https://github.com/searxng/searxng/pull/3642#issuecomment-2226884469
- https://github.com/searxng/searxng/pull/3746#issuecomment-2300965005
Why msgspec.Struct
==================
We have already discussed typing based on e.g. `TypeDict` or `dataclass` in the past:
- https://github.com/searxng/searxng/pull/1562/files
- https://gist.github.com/dalf/972eb05e7a9bee161487132a7de244d2
- https://github.com/searxng/searxng/pull/1412/files
- https://github.com/searxng/searxng/pull/1356
In my opinion, TypeDict is unsuitable because the objects are still dictionaries
and not instances of classes / the `dataclass` are classes but ...
The `msgspec.Struct` combine the advantages of typing, runtime behaviour and
also offer the option of (fast) serializing (incl. type check) the objects.
Currently not possible but conceivable with `msgspec`: Outsourcing the engines
into separate processes, what possibilities this opens up in the future is left
to the imagination!
Internally, we have already defined that it is desirable to decouple the
development of the engines from the development of the SearXNG core / The
serialization of the `Result` objects is a prerequisite for this.
HINT: The threads listed above were the template for this PR, even though the
implementation here is based on msgspec. They should also be an inspiration for
the following PRs of typification, as the models and implementations can provide
a good direction.
Why just one commit?
====================
I tried to create several (thematically separated) commits, but gave up at some
point ... there are too many things to tackle at once / The comprehensibility of
the commits would not be improved by a thematic separation. On the contrary, we
would have to make multiple changes at the same places and the goal of a change
would be vaguely recognizable in the fog of the commits.
Signed-off-by: Markus Heiser <markus.heiser@darmarit.de>
2024-12-15 08:59:50 +00:00
|
|
|
from searx.extended_types import sxng_request
|
2022-03-12 09:18:08 +00:00
|
|
|
|
|
|
|
_INFO_PAGES = infopage.InfoPageSet(infopage.MistletoePage)
|
|
|
|
|
|
|
|
@app.route('/info/<pagename>', methods=['GET'])
|
|
|
|
def info(pagename):
|
|
|
|
|
[refactor] typification of SearXNG (initial) / result items (part 1)
Typification of SearXNG
=======================
This patch introduces the typing of the results. The why and how is described
in the documentation, please generate the documentation ..
$ make docs.clean docs.live
and read the following articles in the "Developer documentation":
- result types --> http://0.0.0.0:8000/dev/result_types/index.html
The result types are available from the `searx.result_types` module. The
following have been implemented so far:
- base result type: `searx.result_type.Result`
--> http://0.0.0.0:8000/dev/result_types/base_result.html
- answer results
--> http://0.0.0.0:8000/dev/result_types/answer.html
including the type for translations (inspired by #3925). For all other
types (which still need to be set up in subsequent PRs), template documentation
has been created for the transition period.
Doc of the fields used in Templates
===================================
The template documentation is the basis for the typing and is the first complete
documentation of the results (needed for engine development). It is the
"working paper" (the plan) with which further typifications can be implemented
in subsequent PRs.
- https://github.com/searxng/searxng/issues/357
Answer Templates
================
With the new (sub) types for `Answer`, the templates for the answers have also
been revised, `Translation` are now displayed with collapsible entries (inspired
by #3925).
!en-de dog
Plugins & Answerer
==================
The implementation for `Plugin` and `Answer` has been revised, see
documentation:
- Plugin: http://0.0.0.0:8000/dev/plugins/index.html
- Answerer: http://0.0.0.0:8000/dev/answerers/index.html
With `AnswerStorage` and `AnswerStorage` to manage those items (in follow up
PRs, `ArticleStorage`, `InfoStorage` and .. will be implemented)
Autocomplete
============
The autocompletion had a bug where the results from `Answer` had not been shown
in the past. To test activate autocompletion and try search terms for which we
have answerers
- statistics: type `min 1 2 3` .. in the completion list you should find an
entry like `[de] min(1, 2, 3) = 1`
- random: type `random uuid` .. in the completion list, the first item is a
random UUID
Extended Types
==============
SearXNG extends e.g. the request and response types of flask and httpx, a module
has been set up for type extensions:
- Extended Types
--> http://0.0.0.0:8000/dev/extended_types.html
Unit-Tests
==========
The unit tests have been completely revised. In the previous implementation,
the runtime (the global variables such as `searx.settings`) was not initialized
before each test, so the runtime environment with which a test ran was always
determined by the tests that ran before it. This was also the reason why we
sometimes had to observe non-deterministic errors in the tests in the past:
- https://github.com/searxng/searxng/issues/2988 is one example for the Runtime
issues, with non-deterministic behavior ..
- https://github.com/searxng/searxng/pull/3650
- https://github.com/searxng/searxng/pull/3654
- https://github.com/searxng/searxng/pull/3642#issuecomment-2226884469
- https://github.com/searxng/searxng/pull/3746#issuecomment-2300965005
Why msgspec.Struct
==================
We have already discussed typing based on e.g. `TypeDict` or `dataclass` in the past:
- https://github.com/searxng/searxng/pull/1562/files
- https://gist.github.com/dalf/972eb05e7a9bee161487132a7de244d2
- https://github.com/searxng/searxng/pull/1412/files
- https://github.com/searxng/searxng/pull/1356
In my opinion, TypeDict is unsuitable because the objects are still dictionaries
and not instances of classes / the `dataclass` are classes but ...
The `msgspec.Struct` combine the advantages of typing, runtime behaviour and
also offer the option of (fast) serializing (incl. type check) the objects.
Currently not possible but conceivable with `msgspec`: Outsourcing the engines
into separate processes, what possibilities this opens up in the future is left
to the imagination!
Internally, we have already defined that it is desirable to decouple the
development of the engines from the development of the SearXNG core / The
serialization of the `Result` objects is a prerequisite for this.
HINT: The threads listed above were the template for this PR, even though the
implementation here is based on msgspec. They should also be an inspiration for
the following PRs of typification, as the models and implementations can provide
a good direction.
Why just one commit?
====================
I tried to create several (thematically separated) commits, but gave up at some
point ... there are too many things to tackle at once / The comprehensibility of
the commits would not be improved by a thematic separation. On the contrary, we
would have to make multiple changes at the same places and the goal of a change
would be vaguely recognizable in the fog of the commits.
Signed-off-by: Markus Heiser <markus.heiser@darmarit.de>
2024-12-15 08:59:50 +00:00
|
|
|
locale = sxng_request.preferences.get_value('locale')
|
2022-03-12 09:18:08 +00:00
|
|
|
page = _INFO_PAGES.get_page(pagename, locale)
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2024-05-28 15:56:54 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
__all__ = ['InfoPage', 'InfoPageSet']
|
2022-03-12 09:18:08 +00:00
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
import os
|
2022-03-12 09:18:08 +00:00
|
|
|
import os.path
|
|
|
|
import logging
|
|
|
|
import typing
|
|
|
|
|
|
|
|
import urllib.parse
|
2024-02-10 07:51:02 +00:00
|
|
|
from functools import cached_property
|
2022-03-12 09:18:08 +00:00
|
|
|
import jinja2
|
|
|
|
from flask.helpers import url_for
|
2022-04-06 13:49:50 +00:00
|
|
|
from markdown_it import MarkdownIt
|
2022-03-12 09:18:08 +00:00
|
|
|
|
|
|
|
from .. import get_setting
|
|
|
|
from ..version import GIT_URL
|
2022-03-13 21:15:27 +00:00
|
|
|
from ..locales import LOCALE_NAMES
|
2022-03-12 09:18:08 +00:00
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger('searx.infopage')
|
|
|
|
_INFO_FOLDER = os.path.abspath(os.path.dirname(__file__))
|
2024-05-28 15:56:54 +00:00
|
|
|
INFO_PAGES: 'InfoPageSet'
|
|
|
|
|
|
|
|
|
|
|
|
def __getattr__(name):
|
|
|
|
if name == 'INFO_PAGES':
|
|
|
|
global INFO_PAGES # pylint: disable=global-statement
|
|
|
|
INFO_PAGES = InfoPageSet()
|
|
|
|
return INFO_PAGES
|
|
|
|
|
|
|
|
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
2022-03-12 09:18:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
class InfoPage:
|
|
|
|
"""A page of the :py:obj:`online documentation <InfoPageSet>`."""
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
def __init__(self, fname):
|
2022-03-12 09:18:08 +00:00
|
|
|
self.fname = fname
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def raw_content(self):
|
|
|
|
"""Raw content of the page (without any jinja rendering)"""
|
|
|
|
with open(self.fname, 'r', encoding='utf-8') as f:
|
|
|
|
return f.read()
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def content(self):
|
2023-09-15 07:53:03 +00:00
|
|
|
"""Content of the page (rendered in a Jinja context)"""
|
2022-03-12 09:18:08 +00:00
|
|
|
ctx = self.get_ctx()
|
|
|
|
template = jinja2.Environment().from_string(self.raw_content)
|
|
|
|
return template.render(**ctx)
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def title(self):
|
|
|
|
"""Title of the content (without any markup)"""
|
|
|
|
t = ""
|
|
|
|
for l in self.raw_content.split('\n'):
|
|
|
|
if l.startswith('# '):
|
|
|
|
t = l.strip('# ')
|
|
|
|
return t
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
@cached_property
|
|
|
|
def html(self):
|
2022-04-06 13:49:50 +00:00
|
|
|
"""Render Markdown (CommonMark_) to HTML by using markdown-it-py_.
|
2022-03-13 21:15:27 +00:00
|
|
|
|
|
|
|
.. _CommonMark: https://commonmark.org/
|
2022-04-06 13:49:50 +00:00
|
|
|
.. _markdown-it-py: https://github.com/executablebooks/markdown-it-py
|
2022-03-13 21:15:27 +00:00
|
|
|
|
|
|
|
"""
|
2022-05-07 16:23:10 +00:00
|
|
|
return (
|
|
|
|
MarkdownIt("commonmark", {"typographer": True}).enable(["replacements", "smartquotes"]).render(self.content)
|
|
|
|
)
|
2022-03-13 21:15:27 +00:00
|
|
|
|
2022-06-03 13:41:52 +00:00
|
|
|
def get_ctx(self):
|
2022-03-12 09:18:08 +00:00
|
|
|
"""Jinja context to render :py:obj:`InfoPage.content`"""
|
|
|
|
|
|
|
|
def _md_link(name, url):
|
2022-03-13 21:15:27 +00:00
|
|
|
url = url_for(url, _external=True)
|
2022-03-12 09:18:08 +00:00
|
|
|
return "[%s](%s)" % (name, url)
|
|
|
|
|
|
|
|
def _md_search(query):
|
2022-03-13 21:15:27 +00:00
|
|
|
url = '%s?q=%s' % (url_for('search', _external=True), urllib.parse.quote(query))
|
2022-03-12 09:18:08 +00:00
|
|
|
return '[%s](%s)' % (query, url)
|
|
|
|
|
|
|
|
ctx = {}
|
|
|
|
ctx['GIT_URL'] = GIT_URL
|
|
|
|
ctx['get_setting'] = get_setting
|
|
|
|
ctx['link'] = _md_link
|
|
|
|
ctx['search'] = _md_search
|
|
|
|
|
|
|
|
return ctx
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
def __repr__(self):
|
|
|
|
return f'<{self.__class__.__name__} fname={self.fname!r}>'
|
2022-03-12 09:18:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
class InfoPageSet: # pylint: disable=too-few-public-methods
|
|
|
|
"""Cached rendering of the online documentation a SearXNG instance has.
|
|
|
|
|
|
|
|
:param page_class: render online documentation by :py:obj:`InfoPage` parser.
|
|
|
|
:type page_class: :py:obj:`InfoPage`
|
2022-03-13 21:15:27 +00:00
|
|
|
|
|
|
|
:param info_folder: information directory
|
|
|
|
:type info_folder: str
|
2022-03-12 09:18:08 +00:00
|
|
|
"""
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
def __init__(
|
|
|
|
self, page_class: typing.Optional[typing.Type[InfoPage]] = None, info_folder: typing.Optional[str] = None
|
|
|
|
):
|
|
|
|
self.page_class = page_class or InfoPage
|
|
|
|
self.folder: str = info_folder or _INFO_FOLDER
|
2023-09-15 07:53:03 +00:00
|
|
|
"""location of the Markdown files"""
|
2022-03-12 09:18:08 +00:00
|
|
|
|
2022-03-16 21:24:35 +00:00
|
|
|
self.CACHE: typing.Dict[tuple, typing.Optional[InfoPage]] = {}
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
self.locale_default: str = 'en'
|
2022-03-12 09:18:08 +00:00
|
|
|
"""default language"""
|
|
|
|
|
2022-03-16 21:24:35 +00:00
|
|
|
self.locales: typing.List[str] = [
|
|
|
|
locale.replace('_', '-') for locale in os.listdir(_INFO_FOLDER) if locale.replace('_', '-') in LOCALE_NAMES
|
|
|
|
]
|
2022-03-12 09:18:08 +00:00
|
|
|
"""list of supported languages (aka locales)"""
|
|
|
|
|
2022-03-16 21:24:35 +00:00
|
|
|
self.toc: typing.List[str] = [
|
2022-03-12 09:18:08 +00:00
|
|
|
'search-syntax',
|
|
|
|
'about',
|
2022-06-13 19:10:44 +00:00
|
|
|
'donate',
|
2022-03-12 09:18:08 +00:00
|
|
|
]
|
|
|
|
"""list of articles in the online documentation"""
|
|
|
|
|
|
|
|
def get_page(self, pagename: str, locale: typing.Optional[str] = None):
|
|
|
|
"""Return ``pagename`` instance of :py:obj:`InfoPage`
|
|
|
|
|
|
|
|
:param pagename: name of the page, a value from :py:obj:`InfoPageSet.toc`
|
|
|
|
:type pagename: str
|
|
|
|
|
|
|
|
:param locale: language of the page, e.g. ``en``, ``zh_Hans_CN``
|
|
|
|
(default: :py:obj:`InfoPageSet.i18n_origin`)
|
|
|
|
:type locale: str
|
|
|
|
|
|
|
|
"""
|
2022-03-13 21:15:27 +00:00
|
|
|
locale = locale or self.locale_default
|
|
|
|
|
2022-03-12 09:18:08 +00:00
|
|
|
if pagename not in self.toc:
|
|
|
|
return None
|
2022-03-13 21:15:27 +00:00
|
|
|
if locale not in self.locales:
|
2022-03-12 09:18:08 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
cache_key = (pagename, locale)
|
|
|
|
|
2022-06-29 17:25:07 +00:00
|
|
|
if cache_key in self.CACHE:
|
|
|
|
return self.CACHE[cache_key]
|
2022-03-12 09:18:08 +00:00
|
|
|
|
|
|
|
# not yet instantiated
|
|
|
|
|
2022-03-16 21:24:35 +00:00
|
|
|
fname = os.path.join(self.folder, locale.replace('-', '_'), pagename) + '.md'
|
2022-03-12 09:18:08 +00:00
|
|
|
if not os.path.exists(fname):
|
2022-03-13 21:15:27 +00:00
|
|
|
logger.info('file %s does not exists', fname)
|
|
|
|
self.CACHE[cache_key] = None
|
2022-03-12 09:18:08 +00:00
|
|
|
return None
|
|
|
|
|
2022-03-13 21:15:27 +00:00
|
|
|
page = self.page_class(fname)
|
2022-03-12 09:18:08 +00:00
|
|
|
self.CACHE[cache_key] = page
|
|
|
|
return page
|
|
|
|
|
2022-03-16 21:24:35 +00:00
|
|
|
def iter_pages(self, locale: typing.Optional[str] = None, fallback_to_default=False):
|
2022-03-13 21:15:27 +00:00
|
|
|
"""Iterate over all pages of the TOC"""
|
|
|
|
locale = locale or self.locale_default
|
2022-03-16 21:24:35 +00:00
|
|
|
for page_name in self.toc:
|
|
|
|
page_locale = locale
|
|
|
|
page = self.get_page(page_name, locale)
|
|
|
|
if fallback_to_default and page is None:
|
|
|
|
page_locale = self.locale_default
|
|
|
|
page = self.get_page(page_name, self.locale_default)
|
2022-06-29 17:25:07 +00:00
|
|
|
if page is not None:
|
|
|
|
# page is None if the page was deleted by the administrator
|
|
|
|
yield page_name, page_locale, page
|