chatgpt-md-converter 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,21 @@
1
+ import re
2
+
3
+
4
+ def convert_html_chars(text: str) -> str:
5
+ """
6
+ Converts HTML reserved symbols to their respective character references.
7
+ """
8
+ text = text.replace("&", "&")
9
+ text = text.replace("<", "&lt;")
10
+ text = text.replace(">", "&gt;")
11
+ return text
12
+
13
+
14
+ def split_by_tag(out_text: str, md_tag: str, html_tag: str) -> str:
15
+ """
16
+ Splits the text by markdown tag and replaces it with the specified HTML tag.
17
+ """
18
+ tag_pattern = re.compile(
19
+ r"{}(.*?){}".format(re.escape(md_tag), re.escape(md_tag)), re.DOTALL
20
+ )
21
+ return tag_pattern.sub(r"<{}>\1</{}>".format(html_tag, html_tag), out_text)
@@ -0,0 +1,55 @@
1
+ import re
2
+
3
+
4
+ def ensure_closing_delimiters(text: str) -> str:
5
+ """
6
+ Ensures that if an opening ` or ``` is found without a matching closing delimiter,
7
+ the missing delimiter is appended to the end of the text.
8
+ """
9
+ # For triple backticks
10
+ if text.count("```") % 2 != 0:
11
+ text += "```"
12
+ # For single backticks
13
+ if text.count("`") % 2 != 0:
14
+ text += "`"
15
+ return text
16
+
17
+
18
+ def extract_and_convert_code_blocks(text: str):
19
+ """
20
+ Extracts code blocks from the text, converting them to HTML <pre><code> format,
21
+ and replaces them with placeholders. Also ensures closing delimiters for unmatched blocks.
22
+ """
23
+ text = ensure_closing_delimiters(text)
24
+ placeholders = []
25
+ code_blocks = {}
26
+
27
+ def replacer(match):
28
+ language = match.group(1) if match.group(1) else ""
29
+ code_content = match.group(3)
30
+ placeholder = f"CODEBLOCKPLACEHOLDER{len(placeholders)}"
31
+ placeholders.append(placeholder)
32
+ if not language:
33
+ html_code_block = f"<pre><code>{code_content}</code></pre>"
34
+ else:
35
+ html_code_block = (
36
+ f'<pre><code class="language-{language}">{code_content}</code></pre>'
37
+ )
38
+ return (placeholder, html_code_block)
39
+
40
+ modified_text = text
41
+ for match in re.finditer(r"```(\w*)?(\n)?(.*?)```", text, flags=re.DOTALL):
42
+ placeholder, html_code_block = replacer(match)
43
+ code_blocks[placeholder] = html_code_block
44
+ modified_text = modified_text.replace(match.group(0), placeholder, 1)
45
+
46
+ return modified_text, code_blocks
47
+
48
+
49
+ def reinsert_code_blocks(text: str, code_blocks: dict) -> str:
50
+ """
51
+ Reinserts HTML code blocks into the text, replacing their placeholders.
52
+ """
53
+ for placeholder, html_code_block in code_blocks.items():
54
+ text = text.replace(placeholder, html_code_block, 1)
55
+ return text
@@ -0,0 +1,31 @@
1
+ import re
2
+
3
+
4
+ def combine_blockquotes(text: str) -> str:
5
+ """
6
+ Combines multiline blockquotes into a single blockquote.
7
+ """
8
+ lines = text.split("\n")
9
+ combined_lines = []
10
+ blockquote_lines = []
11
+ in_blockquote = False
12
+
13
+ for line in lines:
14
+ if line.startswith(">"):
15
+ in_blockquote = True
16
+ blockquote_lines.append(line[1:].strip())
17
+ else:
18
+ if in_blockquote:
19
+ combined_lines.append(
20
+ "<blockquote>" + " ".join(blockquote_lines) + "</blockquote>"
21
+ )
22
+ blockquote_lines = []
23
+ in_blockquote = False
24
+ combined_lines.append(line)
25
+
26
+ if in_blockquote:
27
+ combined_lines.append(
28
+ "<blockquote>" + " ".join(blockquote_lines) + "</blockquote>"
29
+ )
30
+
31
+ return "\n".join(combined_lines)
@@ -0,0 +1,8 @@
1
+ def remove_blockquote_escaping(output: str) -> str:
2
+ """
3
+ Removes the escaping from blockquote tags.
4
+ """
5
+ output = output.replace("&lt;blockquote&gt;", "<blockquote>").replace(
6
+ "&lt;/blockquote&gt;", "</blockquote>"
7
+ )
8
+ return output
@@ -0,0 +1,56 @@
1
+ import re
2
+ from .converters import convert_html_chars, split_by_tag
3
+ from .extractors import extract_and_convert_code_blocks, reinsert_code_blocks
4
+ from .formatters import combine_blockquotes
5
+ from .helpers import remove_blockquote_escaping
6
+
7
+
8
+ def telegram_format(text: str) -> str:
9
+ """
10
+ Converts markdown in the provided text to HTML supported by Telegram.
11
+ """
12
+ # Step 0: Combine blockquotes
13
+ text = combine_blockquotes(text)
14
+
15
+ # Step 1: Convert HTML reserved symbols
16
+ text = convert_html_chars(text)
17
+
18
+ # Step 2: Extract and convert code blocks first
19
+ output, code_blocks = extract_and_convert_code_blocks(text)
20
+
21
+ # Step 3: Escape HTML special characters in the output text
22
+ output = output.replace("<", "&lt;").replace(">", "&gt;")
23
+
24
+ # Inline code
25
+ output = re.sub(r"`(.*?)`", r"<code>\1</code>", output)
26
+
27
+ # Nested Bold and Italic
28
+ output = re.sub(r"\*\*\*(.*?)\*\*\*", r"<b><i>\1</i></b>", output)
29
+
30
+ # Process markdown formatting tags (bold, underline, italic, strikethrough)
31
+ # and convert them to their respective HTML tags
32
+ output = split_by_tag(output, "**", "b")
33
+ output = split_by_tag(output, "__", "u")
34
+ output = split_by_tag(output, "_", "i")
35
+ output = split_by_tag(output, "*", "i")
36
+ output = split_by_tag(output, "~~", "s")
37
+
38
+ # Remove storage links
39
+ output = re.sub(r"【[^】]+】", "", output)
40
+
41
+ # Convert links
42
+ output = re.sub(r"\[(.*?)\]\((.*?)\)", r'<a href="\2">\1</a>', output)
43
+
44
+ # Convert lists
45
+ output = re.sub(r"^\s*[\-\*] (.+)", r"• \1", output, flags=re.MULTILINE)
46
+
47
+ # Convert headings
48
+ output = re.sub(r"^\s*#+ (.+)", r"<b>\1</b>", output, flags=re.MULTILINE)
49
+
50
+ # Step 4: Reinsert the converted HTML code blocks
51
+ output = reinsert_code_blocks(output, code_blocks)
52
+
53
+ # Step 5: Remove blockquote escaping
54
+ output = remove_blockquote_escaping(output)
55
+
56
+ return output
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Kostiantyn Kriuchkov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.1
2
+ Name: chatgpt_md_converter
3
+ Version: 0.1.0
4
+ Summary: A package for converting markdown to HTML for chat Telegram bots
5
+ Home-page: https://github.com/Latand/formatter-chatgpt-telegram
6
+ Author: Kostiantyn Kriuchkov
7
+ Author-email: latand666@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+
15
+ # ChatGPT Markdown to Telegram HTML Parser
16
+
17
+ ## Overview
18
+
19
+ This project provides a solution for converting Markdown formatted text into HTML markup supported by the Telegram Bot API, specifically tailored for use in ChatGPT bots developed with the OpenAI API. It includes features for handling various Markdown elements and ensures proper tag closure, making it suitable for streaming mode applications.
20
+
21
+ ## Features
22
+
23
+ - Converts Markdown syntax to Telegram-compatible HTML.
24
+ - Supports inline code, bold, italic, underline, and strikethrough formatting.
25
+ - Handles nested bold and italic formatting.
26
+ - Converts Markdown links and lists to their HTML equivalents.
27
+ - Processes code blocks with optional language specification, preserving formatting within `<pre><code>` tags.
28
+ - Automatically appends missing closing delimiters for code blocks.
29
+ - Escapes HTML special characters to prevent unwanted HTML rendering outside code blocks.
30
+
31
+ ## Usage
32
+
33
+ To use the Markdown to Telegram HTML Parser in your ChatGPT bot, integrate the provided Python functions into your bot's processing pipeline. Here is a brief overview of how to incorporate the parser:
34
+
35
+ 1. **Ensure Closing Delimiters**: Automatically appends missing closing delimiters for `` ` `` and ``` ``` ``` to ensure proper parsing.
36
+
37
+ 2. **Extract and Convert Code Blocks**: Extracts Markdown code blocks, converts them to HTML `<pre><code>` format, and replaces them with placeholders to prevent formatting within code blocks.
38
+
39
+ 3. **Markdown to HTML Conversion**: Applies various regex substitutions and custom logic to convert supported Markdown formatting to Telegram-compatible HTML tags.
40
+
41
+ 4. **Reinsert Code Blocks**: Reinserts the previously extracted and converted code blocks back into the main text, replacing placeholders with the appropriate HTML content.
42
+
43
+ Simply call the `telegram_format(text: str) -> str` function with your Markdown-formatted text as input to receive the converted HTML output ready for use with the Telegram Bot API.
44
+
45
+ ## Example
46
+
47
+ ```python
48
+ formatted_text = telegram_format("Here is some **bold**, __underline__, and `inline code`.\n```python\nprint('Hello, world!')\n```")
49
+ print(formatted_text)
50
+ ```
51
+
52
+ ## Requirements
53
+
54
+ - Python 3.x
55
+ - No external libraries required (uses built-in `re` module for regex operations)
56
+
57
+ ## Contribution
58
+
59
+ Feel free to contribute to this project by submitting pull requests or opening issues for bugs, feature requests, or improvements.
@@ -0,0 +1,11 @@
1
+ chatgpt_md_converter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ chatgpt_md_converter/converters.py,sha256=-SbsAiMetDZVkC7PrEQrrKlpoagnUycCL1WNBozd7u0,635
3
+ chatgpt_md_converter/extractors.py,sha256=RNwo57_6jCe-HoX5eCvvZcjSTc2uPax-6QEtXqXA5QQ,1880
4
+ chatgpt_md_converter/formatters.py,sha256=T85JwXI7t3PpqAHvkV7FFrmBar6pYRYLVLpET0TeRp0,856
5
+ chatgpt_md_converter/helpers.py,sha256=9CtBeMzKYrymECNPl0MXsW0Vscp4A02a64a5z0sVWqE,261
6
+ chatgpt_md_converter/telegram_formatter.py,sha256=3TrQpuVm1P4Qv1ZMrcBwD7sA2GI-yCDGuTUwUZSlw3E,1896
7
+ chatgpt_md_converter-0.1.0.dist-info/LICENSE,sha256=SDr2jeP-s2g4vf17-jdLXrrqA4_mU7L_RtSJlv4Y2mk,1077
8
+ chatgpt_md_converter-0.1.0.dist-info/METADATA,sha256=rBcqhTdfIBkEriZfkGlKC6baX883byezFhJ_oaGLEDQ,2935
9
+ chatgpt_md_converter-0.1.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
10
+ chatgpt_md_converter-0.1.0.dist-info/top_level.txt,sha256=T2o7csVtZgr-Pwm83aSUkZn0humJmDFNqW38tRSsNqw,21
11
+ chatgpt_md_converter-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ chatgpt_md_converter