telegram-sticker-utils 0.1.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.
- telegram_sticker_utils-0.1.0/LICENSE +201 -0
- telegram_sticker_utils-0.1.0/PKG-INFO +86 -0
- telegram_sticker_utils-0.1.0/README.md +71 -0
- telegram_sticker_utils-0.1.0/pyproject.toml +40 -0
- telegram_sticker_utils-0.1.0/src/telegram_sticker_utils/__init__.py +25 -0
- telegram_sticker_utils-0.1.0/src/telegram_sticker_utils/custom.py +6 -0
- telegram_sticker_utils-0.1.0/src/telegram_sticker_utils/resize.py +265 -0
- telegram_sticker_utils-0.1.0/tests/__init__.py +0 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: telegram-sticker-utils
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: easy and fast processing of telegram stickers
|
|
5
|
+
Keywords: telegram sticker image video processing ffmpeg pillow pngquant
|
|
6
|
+
Author-Email: sudoskys <coldlando@hotmail.com>
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
Project-URL: Repository, https://github.com/sudoskys/telegram-sticker-utils
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Requires-Dist: ffmpy>=0.3.2
|
|
11
|
+
Requires-Dist: loguru>=0.7.2
|
|
12
|
+
Requires-Dist: Pillow>=10.2.0
|
|
13
|
+
Requires-Dist: pngquant>=1.0.7
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# 📦 Telegram Sticker Utils SDK
|
|
17
|
+
|
|
18
|
+
[](https://badge.fury.io/py/telegram-sticker-utils)
|
|
19
|
+
[](https://pepy.tech/project/telegram-sticker-utils)
|
|
20
|
+
|
|
21
|
+
This SDK provides a set of utilities for working with Telegram stickers.
|
|
22
|
+
|
|
23
|
+
- Convert image formats without losing transparency.
|
|
24
|
+
- Auto optimize output size for sticker, make it valid for Telegram.
|
|
25
|
+
|
|
26
|
+
## 🛠 Supported Pack Types
|
|
27
|
+
|
|
28
|
+
- [x] Video Sticker
|
|
29
|
+
- [x] Static Sticker
|
|
30
|
+
- [ ] Animated Sticker
|
|
31
|
+
|
|
32
|
+
## 🚀 Installation
|
|
33
|
+
|
|
34
|
+
You need install [ffmpeg](https://ffmpeg.org/download.html) and [pngquant](https://pngquant.org/) before using this SDK.
|
|
35
|
+
|
|
36
|
+
```shell
|
|
37
|
+
apt install ffmpeg
|
|
38
|
+
apt install pngquant
|
|
39
|
+
pip install telegram-sticker-utils
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## 📝 Usage
|
|
43
|
+
|
|
44
|
+
Here is a brief overview of the classes and methods provided by this SDK:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from telegram_sticker_utils import TelegramStickerUtils
|
|
48
|
+
|
|
49
|
+
# Create an instance of the class
|
|
50
|
+
utils = TelegramStickerUtils()
|
|
51
|
+
GIF_PATH = "path_to_your_image.gif"
|
|
52
|
+
PNG_PATH = "path_to_your_image.png"
|
|
53
|
+
|
|
54
|
+
# Check if an image is an animated GIF
|
|
55
|
+
is_animated = utils.is_animated_gif('path_to_your_image.gif') # It will return True if the image is a TRUE GIF
|
|
56
|
+
print(is_animated)
|
|
57
|
+
|
|
58
|
+
bytes_io, suffix = utils.make_video_sticker(GIF_PATH, scale=512, master_edge="width") # or PNG_PATH
|
|
59
|
+
print(suffix)
|
|
60
|
+
with open("512.webm", "wb") as f:
|
|
61
|
+
f.write(bytes_io.getvalue())
|
|
62
|
+
|
|
63
|
+
bytes_io, suffix2 = utils.make_static_sticker(PNG_PATH, scale=512, master_edge="width") # or PNG_PATH
|
|
64
|
+
print(suffix2)
|
|
65
|
+
with open("512.png", "wb") as f:
|
|
66
|
+
f.write(bytes_io.getvalue())
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### 📚 TelegramStickerUtils API
|
|
70
|
+
|
|
71
|
+
This is the main class that provides all the functionality. It includes the following methods:
|
|
72
|
+
|
|
73
|
+
- `is_animated_gif(image_path: str) -> bool`: Checks if an image is an animated GIF.
|
|
74
|
+
- `resize_gif(input_path: str, output_path: str, new_width: int, new_height: int = -1) -> pathlib.Path`: Resizes a GIF
|
|
75
|
+
file using ffmpeg.
|
|
76
|
+
- `resize_png(input_path: str, output_path: str, new_width: int, new_height: int = -1) -> pathlib.Path`: Resizes an
|
|
77
|
+
image file using ffmpeg.
|
|
78
|
+
- `convert_gif_png(input_path: str, output_path: str, width: int, height: int) -> pathlib.Path`: Converts a GIF file to
|
|
79
|
+
a PNG file.
|
|
80
|
+
- `convert_gif_webm(input_path, sec: float = 2.9, bit_rate: str = '2000k', crf: int = 10, cpu_used: int = 2) -> BytesIO`:
|
|
81
|
+
Converts a GIF file to a WebM file.
|
|
82
|
+
- `make_static_sticker(input_path: str, *, scale: int = 512, master_edge: Literal["width", "height"] = "width", size_limit=500 * 1024, max_iterations=3) -> Tuple[BytesIO, str]`:
|
|
83
|
+
Resizes a PNG file and optimizes it using pngquant.
|
|
84
|
+
- `make_video_sticker(input_path: str, *, scale: int = 512, master_edge: Literal["width", "height"] = "width", size_limit=256 * 1024) -> Tuple[BytesIO, str]`:
|
|
85
|
+
Resizes a gif/png file and optimizes it using pngquant.
|
|
86
|
+
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# 📦 Telegram Sticker Utils SDK
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/py/telegram-sticker-utils)
|
|
4
|
+
[](https://pepy.tech/project/telegram-sticker-utils)
|
|
5
|
+
|
|
6
|
+
This SDK provides a set of utilities for working with Telegram stickers.
|
|
7
|
+
|
|
8
|
+
- Convert image formats without losing transparency.
|
|
9
|
+
- Auto optimize output size for sticker, make it valid for Telegram.
|
|
10
|
+
|
|
11
|
+
## 🛠 Supported Pack Types
|
|
12
|
+
|
|
13
|
+
- [x] Video Sticker
|
|
14
|
+
- [x] Static Sticker
|
|
15
|
+
- [ ] Animated Sticker
|
|
16
|
+
|
|
17
|
+
## 🚀 Installation
|
|
18
|
+
|
|
19
|
+
You need install [ffmpeg](https://ffmpeg.org/download.html) and [pngquant](https://pngquant.org/) before using this SDK.
|
|
20
|
+
|
|
21
|
+
```shell
|
|
22
|
+
apt install ffmpeg
|
|
23
|
+
apt install pngquant
|
|
24
|
+
pip install telegram-sticker-utils
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 📝 Usage
|
|
28
|
+
|
|
29
|
+
Here is a brief overview of the classes and methods provided by this SDK:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from telegram_sticker_utils import TelegramStickerUtils
|
|
33
|
+
|
|
34
|
+
# Create an instance of the class
|
|
35
|
+
utils = TelegramStickerUtils()
|
|
36
|
+
GIF_PATH = "path_to_your_image.gif"
|
|
37
|
+
PNG_PATH = "path_to_your_image.png"
|
|
38
|
+
|
|
39
|
+
# Check if an image is an animated GIF
|
|
40
|
+
is_animated = utils.is_animated_gif('path_to_your_image.gif') # It will return True if the image is a TRUE GIF
|
|
41
|
+
print(is_animated)
|
|
42
|
+
|
|
43
|
+
bytes_io, suffix = utils.make_video_sticker(GIF_PATH, scale=512, master_edge="width") # or PNG_PATH
|
|
44
|
+
print(suffix)
|
|
45
|
+
with open("512.webm", "wb") as f:
|
|
46
|
+
f.write(bytes_io.getvalue())
|
|
47
|
+
|
|
48
|
+
bytes_io, suffix2 = utils.make_static_sticker(PNG_PATH, scale=512, master_edge="width") # or PNG_PATH
|
|
49
|
+
print(suffix2)
|
|
50
|
+
with open("512.png", "wb") as f:
|
|
51
|
+
f.write(bytes_io.getvalue())
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 📚 TelegramStickerUtils API
|
|
55
|
+
|
|
56
|
+
This is the main class that provides all the functionality. It includes the following methods:
|
|
57
|
+
|
|
58
|
+
- `is_animated_gif(image_path: str) -> bool`: Checks if an image is an animated GIF.
|
|
59
|
+
- `resize_gif(input_path: str, output_path: str, new_width: int, new_height: int = -1) -> pathlib.Path`: Resizes a GIF
|
|
60
|
+
file using ffmpeg.
|
|
61
|
+
- `resize_png(input_path: str, output_path: str, new_width: int, new_height: int = -1) -> pathlib.Path`: Resizes an
|
|
62
|
+
image file using ffmpeg.
|
|
63
|
+
- `convert_gif_png(input_path: str, output_path: str, width: int, height: int) -> pathlib.Path`: Converts a GIF file to
|
|
64
|
+
a PNG file.
|
|
65
|
+
- `convert_gif_webm(input_path, sec: float = 2.9, bit_rate: str = '2000k', crf: int = 10, cpu_used: int = 2) -> BytesIO`:
|
|
66
|
+
Converts a GIF file to a WebM file.
|
|
67
|
+
- `make_static_sticker(input_path: str, *, scale: int = 512, master_edge: Literal["width", "height"] = "width", size_limit=500 * 1024, max_iterations=3) -> Tuple[BytesIO, str]`:
|
|
68
|
+
Resizes a PNG file and optimizes it using pngquant.
|
|
69
|
+
- `make_video_sticker(input_path: str, *, scale: int = 512, master_edge: Literal["width", "height"] = "width", size_limit=256 * 1024) -> Tuple[BytesIO, str]`:
|
|
70
|
+
Resizes a gif/png file and optimizes it using pngquant.
|
|
71
|
+
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "telegram-sticker-utils"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "easy and fast processing of telegram stickers"
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "sudoskys", email = "coldlando@hotmail.com" },
|
|
7
|
+
]
|
|
8
|
+
dependencies = [
|
|
9
|
+
"ffmpy>=0.3.2",
|
|
10
|
+
"loguru>=0.7.2",
|
|
11
|
+
"Pillow>=10.2.0",
|
|
12
|
+
"pngquant>=1.0.7",
|
|
13
|
+
]
|
|
14
|
+
requires-python = ">=3.8"
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
keywords = [
|
|
17
|
+
"telegram",
|
|
18
|
+
"sticker",
|
|
19
|
+
"image",
|
|
20
|
+
"video",
|
|
21
|
+
"processing",
|
|
22
|
+
"ffmpeg",
|
|
23
|
+
"pillow",
|
|
24
|
+
"pngquant",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.license]
|
|
28
|
+
text = "Apache-2.0"
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Repository = "https://github.com/sudoskys/telegram-sticker-utils"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = [
|
|
35
|
+
"pdm-backend",
|
|
36
|
+
]
|
|
37
|
+
build-backend = "pdm.backend"
|
|
38
|
+
|
|
39
|
+
[tool.pdm]
|
|
40
|
+
distribution = true
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
|
|
3
|
+
import pngquant
|
|
4
|
+
|
|
5
|
+
from .resize import TelegramStickerUtils
|
|
6
|
+
from .custom import IGNORE_CHECKS
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def check_ffmpeg():
|
|
10
|
+
if not shutil.which("ffmpeg"):
|
|
11
|
+
raise FileNotFoundError(
|
|
12
|
+
"ffmpeg doesn't seem to be installed, or its path is not added to the PATH environment variable."
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check_pngquant():
|
|
17
|
+
if not shutil.which("pngquant"):
|
|
18
|
+
raise FileNotFoundError(
|
|
19
|
+
"pngquant doesn't seem to be installed, or its path is not added to the PATH environment variable."
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
if not IGNORE_CHECKS:
|
|
24
|
+
check_ffmpeg()
|
|
25
|
+
check_pngquant()
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import pathlib
|
|
3
|
+
import tempfile
|
|
4
|
+
from io import BytesIO
|
|
5
|
+
from typing import Literal, Tuple
|
|
6
|
+
|
|
7
|
+
import ffmpy
|
|
8
|
+
import pngquant
|
|
9
|
+
from loguru import logger
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from .custom import FFMPEG_EXECUTABLE, PNGQUANT_EXECUTABLE
|
|
13
|
+
|
|
14
|
+
pngquant.config(PNGQUANT_EXECUTABLE)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TelegramStickerUtils(object):
|
|
18
|
+
@staticmethod
|
|
19
|
+
def is_animated_gif(image_path: str) -> bool:
|
|
20
|
+
"""
|
|
21
|
+
Check if an image is an animated GIF.
|
|
22
|
+
:param image_path:
|
|
23
|
+
:return:
|
|
24
|
+
"""
|
|
25
|
+
assert os.path.exists(image_path), FileNotFoundError(f"Input File {image_path} does not exist")
|
|
26
|
+
gif = Image.open(image_path)
|
|
27
|
+
try:
|
|
28
|
+
gif.seek(1)
|
|
29
|
+
except EOFError:
|
|
30
|
+
return False
|
|
31
|
+
else:
|
|
32
|
+
return True
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
def resize_gif(input_path: str, output_path: str, new_width: int, new_height: int = -1) -> pathlib.Path:
|
|
36
|
+
"""
|
|
37
|
+
Resize a GIF file using ffmpeg.
|
|
38
|
+
:param input_path: Path to the input GIF file.
|
|
39
|
+
:param output_path: Path to the output GIF file.
|
|
40
|
+
:param new_width: New width of the GIF file.
|
|
41
|
+
:param new_height: New height of the GIF file. Default is -1.
|
|
42
|
+
:return: output_path
|
|
43
|
+
"""
|
|
44
|
+
assert os.path.exists(input_path), FileNotFoundError(f"Input File {input_path} does not exist")
|
|
45
|
+
assert new_width >= -1, f"Invalid new width {new_width}"
|
|
46
|
+
assert new_height >= -1, f"Invalid new height {new_height}"
|
|
47
|
+
assert not (new_width == -1 and new_height == -1), "Both new width and new height cannot be -1"
|
|
48
|
+
# 使用ffmpy调整GIF大小
|
|
49
|
+
ff = ffmpy.FFmpeg(
|
|
50
|
+
executable=FFMPEG_EXECUTABLE,
|
|
51
|
+
inputs={
|
|
52
|
+
input_path: None
|
|
53
|
+
},
|
|
54
|
+
outputs={
|
|
55
|
+
output_path:
|
|
56
|
+
'-vf "scale={}:{},split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -y -loglevel 0'.format(
|
|
57
|
+
new_width, new_height)}
|
|
58
|
+
)
|
|
59
|
+
ff.run()
|
|
60
|
+
assert os.path.exists(output_path), f"Failed to create {output_path}"
|
|
61
|
+
assert os.path.getsize(output_path) > 1, f"File {output_path} is empty"
|
|
62
|
+
return pathlib.Path(output_path)
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def resize_png(input_path: str, output_path: str, new_width: int, new_height: int = -1) -> pathlib.Path:
|
|
66
|
+
"""
|
|
67
|
+
Resize an image file using ffmpeg.
|
|
68
|
+
:param input_path: Path to the input image file.
|
|
69
|
+
:param output_path: Path to the output image file.
|
|
70
|
+
:param new_width: New width of the image file.
|
|
71
|
+
:param new_height: New height of the image file. Default is -1.
|
|
72
|
+
:return: output_path
|
|
73
|
+
"""
|
|
74
|
+
assert os.path.exists(input_path), FileNotFoundError(f"Input File {input_path} does not exist")
|
|
75
|
+
assert new_width >= -1, f"Invalid new width {new_width}"
|
|
76
|
+
assert new_height >= -1, f"Invalid new height {new_height}"
|
|
77
|
+
assert not (new_width == -1 and new_height == -1), "Both new width and new height cannot be -1"
|
|
78
|
+
scale = f'{new_width}:{new_height}'
|
|
79
|
+
try:
|
|
80
|
+
ff = ffmpy.FFmpeg(
|
|
81
|
+
executable=FFMPEG_EXECUTABLE,
|
|
82
|
+
inputs={input_path: None},
|
|
83
|
+
outputs={output_path: f'-vf scale={scale} -y -loglevel 0'}
|
|
84
|
+
)
|
|
85
|
+
ff.run()
|
|
86
|
+
except Exception as e:
|
|
87
|
+
if "234" not in str(e):
|
|
88
|
+
raise e
|
|
89
|
+
assert os.path.exists(output_path), f"Failed to create {output_path}"
|
|
90
|
+
assert os.path.getsize(output_path) > 1, f"File {output_path} is empty"
|
|
91
|
+
return pathlib.Path(output_path)
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def convert_gif_png(input_path: str, output_path: str, width: int, height: int) -> pathlib.Path:
|
|
95
|
+
"""
|
|
96
|
+
Convert a GIF file to a PNG file.
|
|
97
|
+
:param input_path: Path to the input GIF file.
|
|
98
|
+
:param output_path: Path to the output PNG file.
|
|
99
|
+
:param width: Width of the PNG file.
|
|
100
|
+
:param height: Height of the PNG file.
|
|
101
|
+
:return:
|
|
102
|
+
"""
|
|
103
|
+
assert os.path.exists(input_path), FileNotFoundError(f"Input File {input_path} does not exist")
|
|
104
|
+
if os.path.exists(output_path):
|
|
105
|
+
logger.warning(f"Output File {output_path} already exists, overwriting")
|
|
106
|
+
assert not (width == -1 and height == -1), "Both new width and new height cannot be -1"
|
|
107
|
+
img = Image.open(input_path)
|
|
108
|
+
# 将 -1 调整为比例尺寸
|
|
109
|
+
if width == -1:
|
|
110
|
+
width = int(img.width * height / img.height)
|
|
111
|
+
if height == -1:
|
|
112
|
+
height = int(img.height * width / img.width)
|
|
113
|
+
# 将 GIF 转换为 PNG
|
|
114
|
+
img = img.resize((width, height), Image.Resampling.LANCZOS)
|
|
115
|
+
img.save(output_path, 'PNG')
|
|
116
|
+
assert os.path.exists(output_path), f"Failed to create {output_path}"
|
|
117
|
+
assert os.path.getsize(output_path) > 1, f"File {output_path} is empty"
|
|
118
|
+
return pathlib.Path(output_path)
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
def convert_gif_webm(
|
|
122
|
+
input_path,
|
|
123
|
+
sec: float = 2.9,
|
|
124
|
+
bit_rate: str = '2000k',
|
|
125
|
+
crf: int = 10,
|
|
126
|
+
cpu_used: int = 2) -> BytesIO:
|
|
127
|
+
"""
|
|
128
|
+
Convert a GIF file to a WebM file.
|
|
129
|
+
:param input_path: Path to the input GIF file.
|
|
130
|
+
:param sec: Duration of the WebM file. Default is 2.9 seconds.
|
|
131
|
+
:param bit_rate: Bit rate of the WebM file. Default is 2000k.
|
|
132
|
+
:param crf: Constant Rate Factor of the WebM file. Default is 10.
|
|
133
|
+
:param cpu_used: CPU used of the WebM file. Default is 2.
|
|
134
|
+
:return: BytesIO
|
|
135
|
+
"""
|
|
136
|
+
assert os.path.exists(input_path), FileNotFoundError(f"The file {input_path} doesn't exist")
|
|
137
|
+
assert sec > 0, ValueError("Duration must be greater than 0")
|
|
138
|
+
|
|
139
|
+
attempts = 0
|
|
140
|
+
bit_rates = [bit_rate, '1000k', '500k', '320k'] # List of bit_rates to try
|
|
141
|
+
|
|
142
|
+
while sec > 1 and attempts < 10:
|
|
143
|
+
for br in bit_rates:
|
|
144
|
+
with tempfile.NamedTemporaryFile(suffix=".webm", delete=False) as temp:
|
|
145
|
+
output_filename = temp.name
|
|
146
|
+
output = {
|
|
147
|
+
output_filename: f'-c:v libvpx-vp9 -b:v {br} -crf {crf} -cpu-used {cpu_used} -an -pix_fmt yuva420p -auto-alt-ref 0 -metadata:s:v:0 alpha_mode="1"'
|
|
148
|
+
}
|
|
149
|
+
ff = ffmpy.FFmpeg(
|
|
150
|
+
executable=FFMPEG_EXECUTABLE,
|
|
151
|
+
inputs={input_path: f'-y -loglevel 0 -ss 00:00:0.0 -t {sec}'},
|
|
152
|
+
outputs=output
|
|
153
|
+
)
|
|
154
|
+
ff.run()
|
|
155
|
+
|
|
156
|
+
_size = os.path.getsize(output_filename)
|
|
157
|
+
if _size <= 256 * 1024:
|
|
158
|
+
with open(output_filename, 'rb') as f:
|
|
159
|
+
output_bytes = BytesIO(f.read())
|
|
160
|
+
pathlib.Path(output_filename).unlink(missing_ok=True)
|
|
161
|
+
return output_bytes
|
|
162
|
+
pathlib.Path(output_filename).unlink(missing_ok=True)
|
|
163
|
+
sec = round(sec - 0.5, 1)
|
|
164
|
+
logger.warning(f"File size {_size} exceeds 256 KB limit, retry with {sec} seconds")
|
|
165
|
+
attempts += 1
|
|
166
|
+
|
|
167
|
+
logger.error(f"File Size {_size}")
|
|
168
|
+
raise ValueError(f'Failed to generate a video: size exceeds 256 KB limit after {attempts} attempts.')
|
|
169
|
+
|
|
170
|
+
def make_static_sticker(self,
|
|
171
|
+
input_path: str,
|
|
172
|
+
*,
|
|
173
|
+
scale: int = 512,
|
|
174
|
+
master_edge: Literal["width", "height"] = "width",
|
|
175
|
+
size_limit=500 * 1024,
|
|
176
|
+
max_iterations=3
|
|
177
|
+
) -> Tuple[BytesIO, str]:
|
|
178
|
+
"""
|
|
179
|
+
Resize a PNG file and optimize it using pngquant.
|
|
180
|
+
:param input_path: Path to the input PNG file.
|
|
181
|
+
:param scale: New width or height of the PNG file.
|
|
182
|
+
:param master_edge: Master edge to scale. Default is "width".
|
|
183
|
+
:param size_limit: Maximum size of the PNG file in bytes. Default is 500 KB.
|
|
184
|
+
:param max_iterations: Maximum number of iterations to optimize the PNG file. Default is 3.
|
|
185
|
+
:return: BytesIO, File Extension
|
|
186
|
+
"""
|
|
187
|
+
# Check if the input file exists
|
|
188
|
+
assert os.path.exists(input_path), f"Input File {input_path} does not exist"
|
|
189
|
+
# Check if the scale is valid
|
|
190
|
+
assert scale > 0, f"Invalid scale {scale}"
|
|
191
|
+
# Check if the file size is within the limit
|
|
192
|
+
assert os.path.getsize(input_path) <= size_limit * 25, f"File {input_path} too large"
|
|
193
|
+
# Calculate the new width and height
|
|
194
|
+
new_width, new_height = (scale, -1) if master_edge == "width" else (-1, scale)
|
|
195
|
+
# Get the file extension
|
|
196
|
+
suffix = pathlib.Path(input_path).suffix
|
|
197
|
+
# Ensure the input is not an animated GIF
|
|
198
|
+
if self.is_animated_gif(input_path):
|
|
199
|
+
raise ValueError("Input cannot be an animated GIF")
|
|
200
|
+
# Temporary file to store the output
|
|
201
|
+
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as temp:
|
|
202
|
+
output_path = temp.name
|
|
203
|
+
self.resize_png(input_path, output_path, new_width, new_height)
|
|
204
|
+
for i in range(max_iterations):
|
|
205
|
+
filesize = os.path.getsize(output_path)
|
|
206
|
+
if filesize <= size_limit:
|
|
207
|
+
break
|
|
208
|
+
logger.debug(f"Optimizing {input_path} PNG FILESIZE iteration {i + 1}")
|
|
209
|
+
try:
|
|
210
|
+
codes, bytes_image = pngquant.quant_image(output_path)
|
|
211
|
+
except Exception as e:
|
|
212
|
+
logger.error(f"Error while zip PNG using pngquant: {e}")
|
|
213
|
+
raise e
|
|
214
|
+
with open(output_path, 'wb') as f:
|
|
215
|
+
f.write(bytes_image)
|
|
216
|
+
with open(output_path, 'rb') as f:
|
|
217
|
+
bytes_io = BytesIO(f.read())
|
|
218
|
+
os.remove(output_path)
|
|
219
|
+
return bytes_io, suffix
|
|
220
|
+
|
|
221
|
+
def make_video_sticker(self,
|
|
222
|
+
input_path: str,
|
|
223
|
+
*,
|
|
224
|
+
scale: int = 512,
|
|
225
|
+
master_edge: Literal["width", "height"] = "width",
|
|
226
|
+
size_limit=256 * 1024,
|
|
227
|
+
) -> Tuple[BytesIO, str]:
|
|
228
|
+
"""
|
|
229
|
+
Resize a gif/png file and optimize it using pngquant.
|
|
230
|
+
:param input_path: Path to the input video file.
|
|
231
|
+
:param scale: New width or height of the video file.
|
|
232
|
+
:param master_edge: Master edge to scale. Default is "width".
|
|
233
|
+
:param size_limit: Maximum size of the video file in bytes. Default is 256 KB.
|
|
234
|
+
:return: BytesIO, File Extension
|
|
235
|
+
"""
|
|
236
|
+
# Check if the input file exists
|
|
237
|
+
assert os.path.exists(input_path), f"Input File {input_path} does not exist"
|
|
238
|
+
# Check if the scale is valid
|
|
239
|
+
assert scale > 0, f"Invalid scale {scale}"
|
|
240
|
+
# Check if the file size is within the limit
|
|
241
|
+
assert os.path.getsize(input_path) <= size_limit * 25, f"File {input_path} too large"
|
|
242
|
+
# Calculate the new width and height
|
|
243
|
+
new_width, new_height = (scale, -1) if master_edge == "width" else (-1, scale)
|
|
244
|
+
# 判断input 是不是真的 GIF
|
|
245
|
+
if not self.is_animated_gif(input_path):
|
|
246
|
+
logger.debug(f"Input File {input_path} is not a GIF")
|
|
247
|
+
# 转换为 PNG,同时变换input_path
|
|
248
|
+
input_path = self.convert_gif_png(input_path, input_path, new_width, new_height)
|
|
249
|
+
input_path = str(input_path)
|
|
250
|
+
# Get the file extension
|
|
251
|
+
suffix = pathlib.Path(input_path).suffix
|
|
252
|
+
# Temporary file to store the output
|
|
253
|
+
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as temp:
|
|
254
|
+
output_path = temp.name
|
|
255
|
+
if suffix == '.gif':
|
|
256
|
+
self.resize_gif(input_path, output_path, new_width, new_height)
|
|
257
|
+
else:
|
|
258
|
+
self.resize_png(input_path, output_path, new_width, new_height)
|
|
259
|
+
if suffix in ['.gif', '.png']:
|
|
260
|
+
# 转换为 WebM
|
|
261
|
+
bytes_io = self.convert_gif_webm(output_path)
|
|
262
|
+
else:
|
|
263
|
+
raise ValueError(f"Unsupported file type {suffix}")
|
|
264
|
+
os.remove(output_path)
|
|
265
|
+
return bytes_io, ".webm"
|
|
File without changes
|