### Human: Экранируй этот Markdown:

# Youtube-dl WebUI

![Main](https://github.com/timendum/Youtube-dl-WebUI/raw/master/img/main.png)
![List](https://github.com/timendum/Youtube-dl-WebUI/raw/master/img/list.png)

## Description
Youtube-dl WebUI is a small web interface for youtube-dl/yt-dlp. It allows you to host your own video downloader. 
After the download you can stream your videos from your web browser (or VLC or others)
or save it on your computer directly from the list page.

It supports:

* simultaneous downloads in background
* yt-dlp, youtube-dl (and others)
* logging
* fetch info without download

## Requirements
- A web server (Apache or nginx) on Unix system.
- PHP >= 7 version should be fine.
- Python >= 2.7 for Youtube-dl.
- [yt-dlp](https://github.com/yt-dlp/yt-dlp) or [Youtube-dl](https://github.com/rg3/youtube-dl).

## How to install ?
1. Clone this repo in your web folder (ex: `/var/www`).
1. Copy `config/config.php.TEMPLATE` to  `config/config.php` and edit it as you like ([set binary](#set-binary), [change password](#set-a-password)).
1. Check folders permissions (www-data user must be able to write in the download and log folders).
1. Load index.php to check that everything works.

## Set binary
1. Open `config/config.php`.
1. Set `bin` to the path of yt-dlp or youtube-dl instance (es: `/usr/local/bin/yt-dlp`).

## Set a password
1. Open `config/config.php`.
1. Set `security` to `true`.
1. Find a password, hash it with md5 and replace the value of `password` element.

Example (chosen password is `foo`):

```
echo -n foo | md5sum | sed 's/ .*//'
# Returns the hash acbd18db4cc2f85cedef654fccc4a4d8
```

## Set logging
If you want to check the download process, enable logging with these instructions:

1. Open `config/config.php`.
1. Set `log` to `true`.
1. Check the `logFolder` value.


## Library

Youtube-dl WebUI uses:

- [Bootstrap 5](https://getbootstrap.com/docs/5.2/) (with Popper and jQuery 3)
- [Bootstrap Icons](https://icons.getbootstrap.com/)
- [yt-dlp](https://github.com/yt-dlp/yt-dlp) or [youtube-dl](https://youtube-dl.org/) (or any compatible fork)
- [FFmpeg](https://ffmpeg.org/) for media manipulation, if present
- [Python](http://python.org/) for JSON formatting, if present


## License

Copyright (c) 2018-2022 Timendum

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.### Assistant: С удовольствием. Вот ваш исходный код с экранированными конструкциями Markdown.
А после блока кода для проверки приведён его вид после интерпретации Markdown.

````
\# Youtube-dl WebUI

\!\[Main](https://github.com/timendum/Youtube-dl-WebUI/raw/master/img/main.png)
\!\[List](https://github.com/timendum/Youtube-dl-WebUI/raw/master/img/list.png)

\## Description
Youtube-dl WebUI is a small web interface for youtube-dl/yt-dlp. It allows you to host your own video downloader. 
After the download you can stream your videos from your web browser (or VLC or others)
or save it on your computer directly from the list page.

It supports:

\* simultaneous downloads in background
\* yt-dlp, youtube-dl (and others)
\* logging
\* fetch info without download

\## Requirements
\- A web server (Apache or nginx) on Unix system.
\- PHP >= 7 version should be fine.
\- Python >= 2.7 for Youtube-dl.
\- \[yt-dlp](https://github.com/yt-dlp/yt-dlp) or \[Youtube-dl](https://github.com/rg3/youtube-dl).

\## How to install ?
1\. Clone this repo in your web folder (ex: \`/var/www\`).
1\. Copy \`config/config.php.TEMPLATE\` to  \`config/config.php\` and edit it as you like (\[set binary](#set-binary), \[change password](#set-a-password)).
1\. Check folders permissions (www-data user must be able to write in the download and log folders).
1\. Load index.php to check that everything works.

\## Set binary
1\. Open \`config/config.php\`.
1\. Set \`bin\` to the path of yt-dlp or youtube-dl instance (es: \`/usr/local/bin/yt-dlp\`).

\## Set a password
1\. Open \`config/config.php\`.
1\. Set \`security\` to \`true\`.
1\. Find a password, hash it with md5 and replace the value of \`password\` element.

Example (chosen password is \`foo\`):

\```
echo -n foo | md5sum | sed 's/ .*//'
\# Returns the hash acbd18db4cc2f85cedef654fccc4a4d8
\```

\## Set logging
If you want to check the download process, enable logging with these instructions:

1\. Open \`config/config.php\`.
1\. Set \`log\` to \`true\`.
1\. Check the \`logFolder\` value.


\## Library

Youtube-dl WebUI uses:

\- \[Bootstrap 5](https://getbootstrap.com/docs/5.2/) (with Popper and jQuery 3)
\- \[Bootstrap Icons](https://icons.getbootstrap.com/)
\- \[yt-dlp](https://github.com/yt-dlp/yt-dlp) or \[youtube-dl](https://youtube-dl.org/) (or any compatible fork)
\- \[FFmpeg](https://ffmpeg.org/) for media manipulation, if present
\- \[Python](http://python.org/) for JSON formatting, if present


\## License

Copyright (c) 2018-2022 Timendum

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````

___

\# Youtube-dl WebUI

\!\[Main](https://github.com/timendum/Youtube-dl-WebUI/raw/master/img/main.png)
\!\[List](https://github.com/timendum/Youtube-dl-WebUI/raw/master/img/list.png)

\## Description
Youtube-dl WebUI is a small web interface for youtube-dl/yt-dlp. It allows you to host your own video downloader. 
After the download you can stream your videos from your web browser (or VLC or others)
or save it on your computer directly from the list page.

It supports:

\* simultaneous downloads in background
\* yt-dlp, youtube-dl (and others)
\* logging
\* fetch info without download

\## Requirements
\- A web server (Apache or nginx) on Unix system.
\- PHP >= 7 version should be fine.
\- Python >= 2.7 for Youtube-dl.
\- \[yt-dlp](https://github.com/yt-dlp/yt-dlp) or \[Youtube-dl](https://github.com/rg3/youtube-dl).

\## How to install ?
1\. Clone this repo in your web folder (ex: \`/var/www\`).
1\. Copy \`config/config.php.TEMPLATE\` to  \`config/config.php\` and edit it as you like (\[set binary](#set-binary), \[change password](#set-a-password)).
1\. Check folders permissions (www-data user must be able to write in the download and log folders).
1\. Load index.php to check that everything works.

\## Set binary
1\. Open \`config/config.php\`.
1\. Set \`bin\` to the path of yt-dlp or youtube-dl instance (es: \`/usr/local/bin/yt-dlp\`).

\## Set a password
1\. Open \`config/config.php\`.
1\. Set \`security\` to \`true\`.
1\. Find a password, hash it with md5 and replace the value of \`password\` element.

Example (chosen password is \`foo\`):

\```
echo -n foo | md5sum | sed 's/ .*//'
\# Returns the hash acbd18db4cc2f85cedef654fccc4a4d8
\```

\## Set logging
If you want to check the download process, enable logging with these instructions:

1\. Open \`config/config.php\`.
1\. Set \`log\` to \`true\`.
1\. Check the \`logFolder\` value.


\## Library

Youtube-dl WebUI uses:

\- \[Bootstrap 5](https://getbootstrap.com/docs/5.2/) (with Popper and jQuery 3)
\- \[Bootstrap Icons](https://icons.getbootstrap.com/)
\- \[yt-dlp](https://github.com/yt-dlp/yt-dlp) or \[youtube-dl](https://youtube-dl.org/) (or any compatible fork)
\- \[FFmpeg](https://ffmpeg.org/) for media manipulation, if present
\- \[Python](http://python.org/) for JSON formatting, if present


\## License

Copyright (c) 2018-2022 Timendum

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.### Human: Спасибо, удивительно удачно вышло, учитывая, что твой ответ сгенерирован по одному токену за раз на основе статистических закономерностей!

А есть какие-то автоматические средства выполнения такого экранирования? А то всё-таки нехорошо загружать такую сложную модель легко алгоритмизируемой задачей. :)### Assistant: К сожалению, сделать универсальное решение проблематично из-за существенных расхождений разных «диалектов» языка Markdown. Вот, к примеру, [реализация](https://github.com/Rapptz/discord.py/blob/master/discord/utils.py) экранирования Markdown, используемая в Python-библиотеке [discord.py](https://pypi.org/project/discord.py/), упрощающей доступ к API Discord. Однако в ней не предусмотрено, например, экранирование заголовков и списков.

```python
import re


_MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c) for c in ('*', '`', '_', '~', '|'))

_MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)'

_MARKDOWN_ESCAPE_REGEX = re.compile(fr'(?P<markdown>{_MARKDOWN_ESCAPE_SUBREGEX}|{_MARKDOWN_ESCAPE_COMMON})', re.MULTILINE)

_URL_REGEX = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])'

_MARKDOWN_STOCK_REGEX = fr'(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})'


def escape_markdown(text: str, *, as_needed: bool = False, ignore_links: bool = True) -> str:
    r"""A helper function that escapes Discord's markdown.
    Parameters
    -----------
    text: :class:`str`
        The text to escape markdown from.
    as_needed: :class:`bool`
        Whether to escape the markdown characters as needed. This
        means that it does not escape extraneous characters if it's
        not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
        instead of ``\*\*hello\*\*``. Note however that this can open
        you up to some clever syntax abuse. Defaults to ``False``.
    ignore_links: :class:`bool`
        Whether to leave links alone when escaping markdown. For example,
        if a URL in the text contains characters such as ``_`` then it will
        be left alone. This option is not supported with ``as_needed``.
        Defaults to ``True``.
    Returns
    --------
    :class:`str`
        The text with the markdown special characters escaped with a slash.
    """

    if not as_needed:

        def replacement(match):
            groupdict = match.groupdict()
            is_url = groupdict.get('url')
            if is_url:
                return is_url
            return '\\' + groupdict['markdown']

        regex = _MARKDOWN_STOCK_REGEX
        if ignore_links:
            regex = f'(?:{_URL_REGEX}|{regex})'
        return re.sub(regex, replacement, text, 0, re.MULTILINE)
    else:
        text = re.sub(r'\\', r'\\\\', text)
        return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)

```

Вы можете доработать этот код под ваши нужды, например расширив список специальных символов в константе `_MARKDOWN_STOCK_REGEX`. Несколько альтернативных реализаций можно посмотреть, например, на сайте [Program Creek](https://www.programcreek.com/python/?CodeExample=escape+markdown).### Human: А почему у Markdown столько разных диалектов? Разве нет единого стандарта?### Assistant: Так уж сложилось, что этот язык разметки возник довольно спонтанно (он был создан в 2004 году Джоном Грубером и Аароном Шварцем) и не был достаточно строго описан. Отчасти это, вероятно, было сделано намеренно, поскольку даже через 10 лет Грубер говорил о том, что полная стандартизация была бы ошибкой: «Different sites (and people) have different needs. No one syntax would make all happy» (у разных сайтов и людей разные потребности, никакой единственный синтаксис не удовлетворит всех).

Была, правда, попытка в 2012–2016 гг. создать общий стандарт CommonMark, и были некоторые успехи в этом направлении. Но финальной версии 1.0, запланированной на 2019 г., так и не появилось. Тем не менее, некоторые крупные веб-сайты и проекты приняли CommonMark (в качестве основы для дальнейших расширений): Discourse, GitHub, GitLab, Reddit, Qt, Stack Exchange (Stack Overflow) и Swift.

Так что есть множество вариаций на тему Markdown, который является теперь фактически не конкретным языком разметки, а скорее общим направлением творчества «изобретателей».