tokzip 1.0.0__tar.gz
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.
- tokzip-1.0.0/LICENSE +22 -0
- tokzip-1.0.0/PKG-INFO +127 -0
- tokzip-1.0.0/README.md +96 -0
- tokzip-1.0.0/pyproject.toml +49 -0
- tokzip-1.0.0/setup.cfg +4 -0
- tokzip-1.0.0/tokzip/__init__.py +5 -0
- tokzip-1.0.0/tokzip/__main__.py +5 -0
- tokzip-1.0.0/tokzip/cleaners/__init__.py +1 -0
- tokzip-1.0.0/tokzip/cleaners/chat.py +116 -0
- tokzip-1.0.0/tokzip/cleaners/code.py +243 -0
- tokzip-1.0.0/tokzip/cleaners/common.py +52 -0
- tokzip-1.0.0/tokzip/cleaners/json_fmt.py +17 -0
- tokzip-1.0.0/tokzip/cleaners/text.py +107 -0
- tokzip-1.0.0/tokzip/cli.py +150 -0
- tokzip-1.0.0/tokzip/clipboard.py +58 -0
- tokzip-1.0.0/tokzip/config.py +130 -0
- tokzip-1.0.0/tokzip/deps.py +53 -0
- tokzip-1.0.0/tokzip/dictionary.py +266 -0
- tokzip-1.0.0/tokzip/gui.py +615 -0
- tokzip-1.0.0/tokzip/logging_setup.py +64 -0
- tokzip-1.0.0/tokzip/pathguard.py +207 -0
- tokzip-1.0.0/tokzip/runner.py +351 -0
- tokzip-1.0.0/tokzip/tokens.py +52 -0
- tokzip-1.0.0/tokzip/version.py +1 -0
- tokzip-1.0.0/tokzip.egg-info/PKG-INFO +127 -0
- tokzip-1.0.0/tokzip.egg-info/SOURCES.txt +28 -0
- tokzip-1.0.0/tokzip.egg-info/dependency_links.txt +1 -0
- tokzip-1.0.0/tokzip.egg-info/entry_points.txt +2 -0
- tokzip-1.0.0/tokzip.egg-info/requires.txt +10 -0
- tokzip-1.0.0/tokzip.egg-info/top_level.txt +1 -0
tokzip-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Islom0111
|
|
4
|
+
Copyright (c) 2022 OpenAI, Shantanu Jain (o200k_base definition from tiktoken)
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
tokzip-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tokzip
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Offline text, chat, source code, and directory compression for AI prompts
|
|
5
|
+
Author: Islom0111
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Islom0111/AI-Token-Compressor
|
|
8
|
+
Project-URL: Repository, https://github.com/Islom0111/AI-Token-Compressor
|
|
9
|
+
Project-URL: Changelog, https://github.com/Islom0111/AI-Token-Compressor/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: llm,tokens,compression,prompt,cli,offline
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Text Processing
|
|
19
|
+
Classifier: Topic :: Utilities
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Provides-Extra: tokens
|
|
24
|
+
Requires-Dist: tiktoken>=0.7; extra == "tokens"
|
|
25
|
+
Provides-Extra: dnd
|
|
26
|
+
Requires-Dist: tkinterdnd2; extra == "dnd"
|
|
27
|
+
Provides-Extra: full
|
|
28
|
+
Requires-Dist: tiktoken>=0.7; extra == "full"
|
|
29
|
+
Requires-Dist: tkinterdnd2; extra == "full"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# tokzip
|
|
33
|
+
|
|
34
|
+

|
|
35
|
+

|
|
36
|
+

|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
Clean up chats, source code, JSON, logs, or entire folders before adding them to an AI prompt. The compressor runs fully offline with Python 3.9+.
|
|
40
|
+
|
|
41
|
+
This is a finished personal tool shared as-is. It may receive occasional updates.
|
|
42
|
+
|
|
43
|
+
[Русская версия](README.ru.md)
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
Download and unpack the repository, then run these commands in a terminal from that folder.
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
python -m tokzip notes.md --no-clip
|
|
51
|
+
python -m tokzip ./project --brutal -o bundle.txt --no-clip
|
|
52
|
+
python -m tokzip --gui
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
On Windows, `tokzip.cmd` accepts the same arguments. Running the module, launcher, or `compress.py` without arguments opens the GUI when launched from a terminal. The GUI uses Tk if it is available in your Python installation.
|
|
56
|
+
|
|
57
|
+
For the installed `tokzip` command, run `python -m pip install .` from the unpacked folder. This uses setuptools at build time. You can use the commands above directly from source with Python alone.
|
|
58
|
+
|
|
59
|
+
## Before → after
|
|
60
|
+
|
|
61
|
+
| Input | Output in `max` |
|
|
62
|
+
| --- | --- |
|
|
63
|
+
| `## Inventory` | `Inventory` |
|
|
64
|
+
| `**Ready** to process.` | `Ready to process.` |
|
|
65
|
+
|
|
66
|
+
| Mode | What it changes |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| `high` | Tidies whitespace, keeps comments and formatting, and looks for clear dictionary savings. |
|
|
69
|
+
| `max` | Default. Removes Markdown emphasis, comments in recognized code, and Python docstrings. Packs repeated lines and finds more dictionary candidates. |
|
|
70
|
+
| `brutal` | Also removes emoji from prose and chat timestamps. Packs directory trees and repeated document blocks. |
|
|
71
|
+
|
|
72
|
+
Chat code fences keep their line breaks and indentation. JSON compaction keeps string contents and number spellings. Code cleanup outside Python uses language-specific patterns and preserves recognized multiline literals.
|
|
73
|
+
|
|
74
|
+
## CLI and local expansion
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
python -m tokzip --stdin --stdout < input.txt
|
|
78
|
+
python -m tokzip - --stdout --lang ru < input.txt
|
|
79
|
+
python -m tokzip notes.md --dry-run
|
|
80
|
+
python -m tokzip --expand bundle.txt --stdout
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
In PowerShell, use `Get-Content -Raw input.txt | python -m tokzip --stdin --stdout` to pipe a file.
|
|
84
|
+
|
|
85
|
+
`--stdout` sends just the result to stdout and reports statistics on stderr. `--dry-run` reports statistics without writing files or using the clipboard. File output copies the file to the clipboard when the OS supports it. Use `--no-clip` to skip copying or `--clip-text` to copy the text. Run `python -m tokzip --help` for all flags.
|
|
86
|
+
|
|
87
|
+
`--expand` (also `--decompress`) expands v1.0 output into the cleaned text. It restores dictionary phrases, line and block repeats, shared blocks, and compact trees. Cleanup itself can discard comments, formatting, chat timestamps, and other content. Use the original files when you need their exact contents.
|
|
88
|
+
|
|
89
|
+
Directory scans skip sensitive names such as `.env`, private keys, and credential JSON files. They also skip symbolic links and known binary files. To add project-specific filters, put a UTF-8 `.compressignore` in the scanned directory. Use one case-sensitive glob per line, such as `*.log`, `drafts/**/private-*.md`, or `generated/` for directories. Blank lines and lines beginning with `#` are ignored. `--include-secrets` overrides the built-in sensitive-name filter. Explicitly selected files are read directly. Review a bundle before sharing it.
|
|
90
|
+
|
|
91
|
+
Saved results go to `./compressed_files/` in your working directory unless you pass `-o`. The OS determines the user log directory.
|
|
92
|
+
|
|
93
|
+
| OS | Log folder |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| Windows | `%LOCALAPPDATA%\tokzip\logs` |
|
|
96
|
+
| macOS | `~/Library/Logs/tokzip/` |
|
|
97
|
+
| Linux | `~/.local/state/tokzip/logs/` or `$XDG_STATE_HOME/tokzip/logs/` |
|
|
98
|
+
|
|
99
|
+
## Optional features
|
|
100
|
+
|
|
101
|
+
Install `".[tokens]"` to use exact `o200k_base` token counts, `".[dnd]"` for drag-and-drop in Tk, or `".[full]"` for both, using `python -m pip install` followed by the extra. For exact counts, run this command once while connected to populate the local tokenizer cache.
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
python -c "import tiktoken; tiktoken.get_encoding('o200k_base')"
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The compressor reads only the local vocabulary cache. When the tokenizer or its cache is unavailable, it reports estimated counts.
|
|
108
|
+
|
|
109
|
+
## Measured examples
|
|
110
|
+
|
|
111
|
+
Measured on Python 3.14.3 by running the CLI on synthetic UTF-8 files. The samples were a 40-line maintenance log, 28 Python functions with comments and docstrings, and four copies of the same Unicode directory tree. Byte counts below are from the exact-token runs.
|
|
112
|
+
|
|
113
|
+
| Sample | Mode | UTF-8 bytes | `o200k_base` tokens | Stdlib estimate |
|
|
114
|
+
| --- | --- | ---: | ---: | ---: |
|
|
115
|
+
| Repeated log | `high` | 4,079 → 945 | 599 → 301 | 999 → 273 |
|
|
116
|
+
| Commented Python | `max` | 4,720 → 1,017 | 896 → 297 | 1,538 → 468 |
|
|
117
|
+
| Repeated directory tree | `brutal` | 5,367 → 814 | 1,903 → 342 | 1,931 → 385 |
|
|
118
|
+
|
|
119
|
+
## Previews
|
|
120
|
+
|
|
121
|
+

|
|
122
|
+
|
|
123
|
+

|
|
124
|
+
|
|
125
|
+
Run the local test suite with `python -m unittest discover`.
|
|
126
|
+
|
|
127
|
+
[Changelog](CHANGELOG.md) · [Pre-Git history](docs/pre-git-history.md) · [MIT license](LICENSE)
|
tokzip-1.0.0/README.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# tokzip
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+

|
|
5
|
+

|
|
6
|
+

|
|
7
|
+
|
|
8
|
+
Clean up chats, source code, JSON, logs, or entire folders before adding them to an AI prompt. The compressor runs fully offline with Python 3.9+.
|
|
9
|
+
|
|
10
|
+
This is a finished personal tool shared as-is. It may receive occasional updates.
|
|
11
|
+
|
|
12
|
+
[Русская версия](README.ru.md)
|
|
13
|
+
|
|
14
|
+
## Quick start
|
|
15
|
+
|
|
16
|
+
Download and unpack the repository, then run these commands in a terminal from that folder.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
python -m tokzip notes.md --no-clip
|
|
20
|
+
python -m tokzip ./project --brutal -o bundle.txt --no-clip
|
|
21
|
+
python -m tokzip --gui
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
On Windows, `tokzip.cmd` accepts the same arguments. Running the module, launcher, or `compress.py` without arguments opens the GUI when launched from a terminal. The GUI uses Tk if it is available in your Python installation.
|
|
25
|
+
|
|
26
|
+
For the installed `tokzip` command, run `python -m pip install .` from the unpacked folder. This uses setuptools at build time. You can use the commands above directly from source with Python alone.
|
|
27
|
+
|
|
28
|
+
## Before → after
|
|
29
|
+
|
|
30
|
+
| Input | Output in `max` |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| `## Inventory` | `Inventory` |
|
|
33
|
+
| `**Ready** to process.` | `Ready to process.` |
|
|
34
|
+
|
|
35
|
+
| Mode | What it changes |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `high` | Tidies whitespace, keeps comments and formatting, and looks for clear dictionary savings. |
|
|
38
|
+
| `max` | Default. Removes Markdown emphasis, comments in recognized code, and Python docstrings. Packs repeated lines and finds more dictionary candidates. |
|
|
39
|
+
| `brutal` | Also removes emoji from prose and chat timestamps. Packs directory trees and repeated document blocks. |
|
|
40
|
+
|
|
41
|
+
Chat code fences keep their line breaks and indentation. JSON compaction keeps string contents and number spellings. Code cleanup outside Python uses language-specific patterns and preserves recognized multiline literals.
|
|
42
|
+
|
|
43
|
+
## CLI and local expansion
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
python -m tokzip --stdin --stdout < input.txt
|
|
47
|
+
python -m tokzip - --stdout --lang ru < input.txt
|
|
48
|
+
python -m tokzip notes.md --dry-run
|
|
49
|
+
python -m tokzip --expand bundle.txt --stdout
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
In PowerShell, use `Get-Content -Raw input.txt | python -m tokzip --stdin --stdout` to pipe a file.
|
|
53
|
+
|
|
54
|
+
`--stdout` sends just the result to stdout and reports statistics on stderr. `--dry-run` reports statistics without writing files or using the clipboard. File output copies the file to the clipboard when the OS supports it. Use `--no-clip` to skip copying or `--clip-text` to copy the text. Run `python -m tokzip --help` for all flags.
|
|
55
|
+
|
|
56
|
+
`--expand` (also `--decompress`) expands v1.0 output into the cleaned text. It restores dictionary phrases, line and block repeats, shared blocks, and compact trees. Cleanup itself can discard comments, formatting, chat timestamps, and other content. Use the original files when you need their exact contents.
|
|
57
|
+
|
|
58
|
+
Directory scans skip sensitive names such as `.env`, private keys, and credential JSON files. They also skip symbolic links and known binary files. To add project-specific filters, put a UTF-8 `.compressignore` in the scanned directory. Use one case-sensitive glob per line, such as `*.log`, `drafts/**/private-*.md`, or `generated/` for directories. Blank lines and lines beginning with `#` are ignored. `--include-secrets` overrides the built-in sensitive-name filter. Explicitly selected files are read directly. Review a bundle before sharing it.
|
|
59
|
+
|
|
60
|
+
Saved results go to `./compressed_files/` in your working directory unless you pass `-o`. The OS determines the user log directory.
|
|
61
|
+
|
|
62
|
+
| OS | Log folder |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| Windows | `%LOCALAPPDATA%\tokzip\logs` |
|
|
65
|
+
| macOS | `~/Library/Logs/tokzip/` |
|
|
66
|
+
| Linux | `~/.local/state/tokzip/logs/` or `$XDG_STATE_HOME/tokzip/logs/` |
|
|
67
|
+
|
|
68
|
+
## Optional features
|
|
69
|
+
|
|
70
|
+
Install `".[tokens]"` to use exact `o200k_base` token counts, `".[dnd]"` for drag-and-drop in Tk, or `".[full]"` for both, using `python -m pip install` followed by the extra. For exact counts, run this command once while connected to populate the local tokenizer cache.
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
python -c "import tiktoken; tiktoken.get_encoding('o200k_base')"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The compressor reads only the local vocabulary cache. When the tokenizer or its cache is unavailable, it reports estimated counts.
|
|
77
|
+
|
|
78
|
+
## Measured examples
|
|
79
|
+
|
|
80
|
+
Measured on Python 3.14.3 by running the CLI on synthetic UTF-8 files. The samples were a 40-line maintenance log, 28 Python functions with comments and docstrings, and four copies of the same Unicode directory tree. Byte counts below are from the exact-token runs.
|
|
81
|
+
|
|
82
|
+
| Sample | Mode | UTF-8 bytes | `o200k_base` tokens | Stdlib estimate |
|
|
83
|
+
| --- | --- | ---: | ---: | ---: |
|
|
84
|
+
| Repeated log | `high` | 4,079 → 945 | 599 → 301 | 999 → 273 |
|
|
85
|
+
| Commented Python | `max` | 4,720 → 1,017 | 896 → 297 | 1,538 → 468 |
|
|
86
|
+
| Repeated directory tree | `brutal` | 5,367 → 814 | 1,903 → 342 | 1,931 → 385 |
|
|
87
|
+
|
|
88
|
+
## Previews
|
|
89
|
+
|
|
90
|
+

|
|
91
|
+
|
|
92
|
+

|
|
93
|
+
|
|
94
|
+
Run the local test suite with `python -m unittest discover`.
|
|
95
|
+
|
|
96
|
+
[Changelog](CHANGELOG.md) · [Pre-Git history](docs/pre-git-history.md) · [MIT license](LICENSE)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tokzip"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Offline text, chat, source code, and directory compression for AI prompts"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Islom0111" },
|
|
15
|
+
]
|
|
16
|
+
keywords = ["llm", "tokens", "compression", "prompt", "cli", "offline"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Text Processing",
|
|
26
|
+
"Topic :: Utilities",
|
|
27
|
+
]
|
|
28
|
+
dependencies = []
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
tokens = ["tiktoken>=0.7"]
|
|
32
|
+
dnd = ["tkinterdnd2"]
|
|
33
|
+
full = ["tiktoken>=0.7", "tkinterdnd2"]
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/Islom0111/AI-Token-Compressor"
|
|
37
|
+
Repository = "https://github.com/Islom0111/AI-Token-Compressor"
|
|
38
|
+
Changelog = "https://github.com/Islom0111/AI-Token-Compressor/blob/main/CHANGELOG.md"
|
|
39
|
+
|
|
40
|
+
[project.scripts]
|
|
41
|
+
tokzip = "tokzip.cli:main"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.dynamic]
|
|
44
|
+
version = {attr = "tokzip.version.__version__"}
|
|
45
|
+
|
|
46
|
+
[tool.setuptools.packages.find]
|
|
47
|
+
include = ["tokzip*"]
|
|
48
|
+
exclude = ["tokzip.tests*"]
|
|
49
|
+
namespaces = false
|
tokzip-1.0.0/setup.cfg
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Content-aware cleaners used by the compression runner."""
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import Counter
|
|
3
|
+
|
|
4
|
+
from ..config import TAGS, ModeCfg
|
|
5
|
+
from .common import EMOJI_RE, _normalize, fenced_lines, strip_markdown_safe
|
|
6
|
+
|
|
7
|
+
_REACT = "👁❤👍👎🔥💋💩🦄🍓🍌🌭💯⭐🫡🙏🎉👏"
|
|
8
|
+
RE_MSG_HEADER = re.compile(r"^\s*>?\s*\*{0,2}(.*?)\*{0,2}\s+·\s+`?(\d{2}:\d{2})`?")
|
|
9
|
+
RE_MSG_HEADER_ML = re.compile(r"(?m)^[ \t]*>?[ \t]*\*{0,2}[^\n]{1,60}?\*{0,2}[ \t]+·[ \t]+`?\d{2}:\d{2}`?")
|
|
10
|
+
RE_DATE = re.compile(r"^###\s+(\d+\s+[а-яА-Яa-zA-Z0-9]+)")
|
|
11
|
+
RE_DATE_ML = re.compile(r"(?m)^###\s+\d+\s+[а-яА-Яa-zA-Z]+")
|
|
12
|
+
RE_REPLY = re.compile(r"^\s*>?\s*\*?↩\s*(.*?):")
|
|
13
|
+
# Reaction rows contain only emoji, optional counts, and surrounding markup.
|
|
14
|
+
RE_REACT_PURE = re.compile(rf"^[\s>*_]*(?:[{_REACT}]\uFE0F?[\s\d×x·,]*)+[*_]*$")
|
|
15
|
+
_INDENTED = re.compile(r"^(?:[ \t]*>[ \t]?)*(?: {2}|\t)")
|
|
16
|
+
_MEDIA_MAP = [
|
|
17
|
+
(re.compile(r"\*?\[(\d+)\s+фото\]\*?"), r"$\1P"),
|
|
18
|
+
(re.compile(r"\*?\[(\d+)\s+видео\]\*?"), r"$\1V"),
|
|
19
|
+
(re.compile(r"\*?\[фото\]\*?"), "$P"),
|
|
20
|
+
(re.compile(r"\*?\[видео\]\*?"), "$V"),
|
|
21
|
+
(re.compile(r"\*?\[стикер\]\*?"), "$S"),
|
|
22
|
+
(re.compile(r"\*?\[голосовое сообщение\]\*?"), "$A"),
|
|
23
|
+
(re.compile(r"\*?\[документ\]\*?"), "$D"),
|
|
24
|
+
]
|
|
25
|
+
_MEDIA_LEGEND = {
|
|
26
|
+
"en": "$P photo, $V video, $S sticker, $A voice, $D document",
|
|
27
|
+
"ru": "$P фото, $V видео, $S стикер, $A голосовое, $D документ",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def looks_like_chat(text: str) -> bool:
|
|
32
|
+
# Message-looking lines inside sample code do not indicate a chat export.
|
|
33
|
+
head = "\n".join(line for line, protected in fenced_lines(text[:30000]) if not protected)
|
|
34
|
+
hdr = len(RE_MSG_HEADER_ML.findall(head))
|
|
35
|
+
return hdr >= 3 or (hdr >= 1 and len(RE_DATE_ML.findall(head)) >= 2)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _is_reaction(line: str) -> bool:
|
|
39
|
+
return bool(RE_REACT_PURE.fullmatch(line))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def clean_chat(text: str, cfg: ModeCfg, lang: str = "en") -> str:
|
|
43
|
+
lines = list(fenced_lines(text.replace("\r\n", "\n").replace("\r", "\n")))
|
|
44
|
+
authors = Counter()
|
|
45
|
+
for line, protected in lines:
|
|
46
|
+
if not protected and not _INDENTED.match(line):
|
|
47
|
+
match = RE_MSG_HEADER.match(line)
|
|
48
|
+
if match:
|
|
49
|
+
authors[match[1].replace("*", "").strip()] += 1
|
|
50
|
+
users = {name: f"U{i}" for i, (name, _) in enumerate(authors.most_common()) if name}
|
|
51
|
+
out = []
|
|
52
|
+
message = []
|
|
53
|
+
sender = stamp = reply = ""
|
|
54
|
+
media_used = False
|
|
55
|
+
previous = None
|
|
56
|
+
|
|
57
|
+
def flush() -> None:
|
|
58
|
+
nonlocal previous
|
|
59
|
+
while message and message[-1] == ("", False):
|
|
60
|
+
message.pop()
|
|
61
|
+
start = next((i for i, line in enumerate(message) if line != ("", False)), len(message))
|
|
62
|
+
if start < len(message):
|
|
63
|
+
content = "\n".join(line for line, _ in message[start:])
|
|
64
|
+
multiline = len(message) - start > 1 or message[start][1]
|
|
65
|
+
key = (sender, reply, stamp)
|
|
66
|
+
if not sender:
|
|
67
|
+
out.append(content)
|
|
68
|
+
previous = None
|
|
69
|
+
elif not multiline and key == previous:
|
|
70
|
+
out[-1] += " // " + content
|
|
71
|
+
else:
|
|
72
|
+
header = (f"{stamp} " if stamp else "") + sender + (f">{reply}" if reply else "")
|
|
73
|
+
out.append(header + (":\n" if multiline else ": ") + content)
|
|
74
|
+
previous = None if multiline else key
|
|
75
|
+
message.clear()
|
|
76
|
+
|
|
77
|
+
for raw, fenced in lines:
|
|
78
|
+
if fenced or _INDENTED.match(raw):
|
|
79
|
+
message.append((raw, True))
|
|
80
|
+
continue
|
|
81
|
+
line = _normalize(raw).strip().replace("\\_", "_")
|
|
82
|
+
date = RE_DATE.match(line)
|
|
83
|
+
header = RE_MSG_HEADER.match(line)
|
|
84
|
+
if date:
|
|
85
|
+
flush()
|
|
86
|
+
out.append(f"#{date[1]}")
|
|
87
|
+
sender = stamp = reply = ""
|
|
88
|
+
previous = None
|
|
89
|
+
elif header:
|
|
90
|
+
flush()
|
|
91
|
+
name = header[1].replace("*", "").strip()
|
|
92
|
+
sender = users.get(name, name)
|
|
93
|
+
stamp = "" if cfg.flatten else header[2]
|
|
94
|
+
reply = ""
|
|
95
|
+
elif sender and (target := RE_REPLY.match(line)):
|
|
96
|
+
name = target[1].replace("*", "").strip()
|
|
97
|
+
reply = users.get(name, name)
|
|
98
|
+
elif line not in ("---", ">", ">>") and not _is_reaction(line):
|
|
99
|
+
for pattern, substitute in _MEDIA_MAP:
|
|
100
|
+
line, changed = pattern.subn(substitute, line)
|
|
101
|
+
media_used |= bool(changed)
|
|
102
|
+
if cfg.strip_markup:
|
|
103
|
+
line = strip_markdown_safe(line)
|
|
104
|
+
if cfg.strip_emoji:
|
|
105
|
+
line = EMOJI_RE.sub("", line)
|
|
106
|
+
message.append((re.sub(r"[ \t]{2,}", " ", line), False))
|
|
107
|
+
flush()
|
|
108
|
+
|
|
109
|
+
tags = TAGS[lang]
|
|
110
|
+
headers = []
|
|
111
|
+
if media_used:
|
|
112
|
+
headers.append(f"[{tags['media']}] {_MEDIA_LEGEND[lang]}")
|
|
113
|
+
if users:
|
|
114
|
+
listing = " ".join(f"{alias}={name}" for name, alias in users.items())
|
|
115
|
+
headers.append(f"[{tags['users']}] {listing}")
|
|
116
|
+
return "\n".join(headers + out)
|