Spaces:
Running on Zero
Running on Zero
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +69 -0
- __init__.py +28 -0
- app.py +192 -126
- cli.py +228 -0
- compat.py +96 -0
- config.py +71 -0
- dirs.py +224 -0
- download.py +116 -0
- exception.py +104 -0
- log.py +87 -0
- manager.py +111 -0
- meme.py +167 -0
- memes/5000choyen/__init__.py +202 -0
- memes/abstinence/__init__.py +93 -0
- memes/abstinence/images/base.png +3 -0
- memes/abstinence/images/stamp.png +0 -0
- memes/ace_attorney_dialog/__init__.py +122 -0
- memes/ace_attorney_dialog/images/bubble.png +0 -0
- memes/ace_attorney_dialog/images/mark.png +0 -0
- memes/acg_entrance/__init__.py +47 -0
- memes/acg_entrance/images/0.png +3 -0
- memes/add_chaos/__init__.py +29 -0
- memes/add_chaos/images/0.png +0 -0
- memes/addiction/__init__.py +41 -0
- memes/addiction/images/0.png +0 -0
- memes/alike/__init__.py +32 -0
- memes/alipay/__init__.py +89 -0
- memes/alipay/images/0.png +3 -0
- memes/always/__init__.py +138 -0
- memes/always_like/__init__.py +96 -0
- memes/always_like/images/0.png +0 -0
- memes/anti_kidnap/__init__.py +26 -0
- memes/anti_kidnap/images/0.png +3 -0
- memes/anya_suki/__init__.py +50 -0
- memes/anya_suki/images/0.png +3 -0
- memes/applaud/__init__.py +39 -0
- memes/applaud/images/0.png +0 -0
- memes/applaud/images/1.png +0 -0
- memes/applaud/images/2.png +0 -0
- memes/applaud/images/3.png +0 -0
- memes/applaud/images/4.png +0 -0
- memes/arona_throw/__init__.py +64 -0
- memes/arona_throw/images/0.png +0 -0
- memes/arona_throw/images/1.png +0 -0
- memes/arona_throw/images/10.png +0 -0
- memes/arona_throw/images/11.png +0 -0
- memes/arona_throw/images/12.png +0 -0
- memes/arona_throw/images/13.png +0 -0
- memes/arona_throw/images/14.png +0 -0
- memes/arona_throw/images/15.png +0 -0
.gitattributes
CHANGED
|
@@ -1,2 +1,71 @@
|
|
| 1 |
*.ttf filter=lfs diff=lfs merge=lfs -text
|
| 2 |
*.otf filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
*.ttf filter=lfs diff=lfs merge=lfs -text
|
| 2 |
*.otf filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
memes/abstinence/images/base.png filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
memes/acg_entrance/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
memes/alipay/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
memes/anti_kidnap/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
memes/anya_suki/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
memes/ascension/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
memes/atri_pillow/images/no.png filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
memes/atri_pillow/images/yes.png filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
memes/ayachi_holdsign/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
memes/ba_say/images/arisu.png filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
memes/ba_say/images/izuna.png filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
memes/ba_say/images/key.png filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
memes/ba_say/images/kokona.png filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
memes/ba_say/images/mari.png filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
memes/ba_say/images/sena.png filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
memes/ba_say/images/yuuka.png filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
memes/back_to_work/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
memes/bad_news/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
memes/blamed_mahiro/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
memes/blamed_mahiro/images/1.png filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
memes/blamed_mahiro/images/10.png filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
memes/blamed_mahiro/images/11.png filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
memes/blamed_mahiro/images/12.png filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
memes/blamed_mahiro/images/13.png filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
memes/blamed_mahiro/images/14.png filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
memes/blamed_mahiro/images/15.png filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
memes/blamed_mahiro/images/16.png filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
memes/blamed_mahiro/images/17.png filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
memes/blamed_mahiro/images/18.png filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
memes/blamed_mahiro/images/19.png filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
memes/blamed_mahiro/images/2.png filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
memes/blamed_mahiro/images/20.png filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
memes/blamed_mahiro/images/21.png filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
memes/blamed_mahiro/images/22.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
memes/blamed_mahiro/images/23.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
memes/blamed_mahiro/images/3.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
memes/blamed_mahiro/images/4.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
memes/blamed_mahiro/images/5.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
memes/blamed_mahiro/images/6.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
memes/blamed_mahiro/images/7.png filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
memes/blamed_mahiro/images/8.png filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
memes/blamed_mahiro/images/9.png filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
memes/blood_pressure/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
memes/bocchi_draft/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
memes/bocchi_draft/images/1.png filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
memes/bocchi_draft/images/10.png filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
memes/bocchi_draft/images/11.png filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
memes/bocchi_draft/images/12.png filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
memes/bocchi_draft/images/13.png filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
memes/bocchi_draft/images/14.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
memes/bocchi_draft/images/15.png filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
memes/bocchi_draft/images/16.png filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
memes/bocchi_draft/images/17.png filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
memes/bocchi_draft/images/18.png filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
memes/bocchi_draft/images/19.png filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
memes/bocchi_draft/images/2.png filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
memes/bocchi_draft/images/20.png filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
memes/bocchi_draft/images/21.png filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
memes/bocchi_draft/images/22.png filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
memes/bocchi_draft/images/3.png filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
memes/bocchi_draft/images/4.png filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
memes/bocchi_draft/images/5.png filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
memes/bocchi_draft/images/6.png filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
memes/bocchi_draft/images/7.png filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
memes/bocchi_draft/images/8.png filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
memes/bocchi_draft/images/9.png filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
memes/bronya_holdsign/images/0.jpg filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
memes/caused_by_this/images/0.png filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
memes/certificate/images/0.png filter=lfs diff=lfs merge=lfs -text
|
__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
# from meme_generator.config import meme_config as config
|
| 4 |
+
from meme_generator.manager import add_meme as add_meme
|
| 5 |
+
from meme_generator.manager import get_meme as get_meme
|
| 6 |
+
from meme_generator.manager import get_meme_keys as get_meme_keys
|
| 7 |
+
from meme_generator.manager import get_memes as get_memes
|
| 8 |
+
from meme_generator.manager import load_meme as load_meme
|
| 9 |
+
from meme_generator.manager import load_memes as load_memes
|
| 10 |
+
from meme_generator.meme import CommandShortcut as CommandShortcut
|
| 11 |
+
from meme_generator.meme import Meme as Meme
|
| 12 |
+
from meme_generator.meme import MemeArgsModel as MemeArgsModel
|
| 13 |
+
from meme_generator.meme import MemeArgsType as MemeArgsType
|
| 14 |
+
from meme_generator.meme import MemeParamsType as MemeParamsType
|
| 15 |
+
from meme_generator.meme import ParserArg as ParserArg
|
| 16 |
+
from meme_generator.meme import ParserOption as ParserOption
|
| 17 |
+
from meme_generator.version import __version__ as __version__
|
| 18 |
+
|
| 19 |
+
MEME_DIRS = ["memes", "memes_jj", "memes_emoji", "memes_other", "memes_emoji_nsfw"]
|
| 20 |
+
|
| 21 |
+
for dir_name in MEME_DIRS:
|
| 22 |
+
meme_dir = Path(__file__).parent / dir_name
|
| 23 |
+
if not meme_dir.exists():
|
| 24 |
+
continue
|
| 25 |
+
module_prefix = f"meme_generator.{dir_name}"
|
| 26 |
+
for path in meme_dir.iterdir():
|
| 27 |
+
if path.is_dir():
|
| 28 |
+
load_meme(f"{module_prefix}.{path.name}")
|
app.py
CHANGED
|
@@ -1,142 +1,208 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
from
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
from meme_generator import get_meme, get_memes
|
| 18 |
-
from meme_generator.
|
| 19 |
-
from meme_generator.
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
meme = _meme_map[meme_key]
|
| 46 |
-
p = meme.params_type
|
| 47 |
-
defaults = p.default_texts or []
|
| 48 |
-
|
| 49 |
-
updates = []
|
| 50 |
-
for i in range(MAX_IMAGES):
|
| 51 |
-
if i < p.max_images:
|
| 52 |
-
req = "必需" if i < p.min_images else "可选"
|
| 53 |
-
updates.append(gr.update(visible=True, label=f"图片 {i+1}({req})"))
|
| 54 |
-
else:
|
| 55 |
-
updates.append(gr.update(visible=False))
|
| 56 |
-
|
| 57 |
-
for i in range(MAX_TEXTS):
|
| 58 |
-
if i < p.max_texts:
|
| 59 |
-
req = "必需" if i < p.min_texts else "可选"
|
| 60 |
-
val = defaults[i] if i < len(defaults) else ""
|
| 61 |
-
updates.append(gr.update(visible=True, value=val, label=f"文本 {i+1}({req})"))
|
| 62 |
-
else:
|
| 63 |
-
updates.append(gr.update(visible=False))
|
| 64 |
-
|
| 65 |
-
info = (
|
| 66 |
-
f"**{meme.key}**\n\n"
|
| 67 |
-
f"关键词:{', '.join(meme.keywords) or '无'}\n\n"
|
| 68 |
-
f"图片:{p.min_images}–{p.max_images} 张 | 文本:{p.min_texts}–{p.max_texts} 条"
|
| 69 |
-
)
|
| 70 |
-
updates.append(gr.update(value=info))
|
| 71 |
-
return updates
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
@spaces.GPU
|
| 75 |
-
def _generate(meme_key, *args):
|
| 76 |
-
if not meme_key or meme_key not in _meme_map:
|
| 77 |
-
return None, "⚠️ 请先选择一个表情包"
|
| 78 |
-
|
| 79 |
-
images = [a for a in args[:MAX_IMAGES] if a is not None]
|
| 80 |
-
texts = [a for a in args[MAX_IMAGES:] if a is not None and str(a).strip() != ""]
|
| 81 |
-
|
| 82 |
-
meme = _meme_map[meme_key]
|
| 83 |
-
try:
|
| 84 |
-
result = meme(images=images, texts=texts)
|
| 85 |
-
return result.getvalue(), "✅ 生成成功!右键图片可保存"
|
| 86 |
-
except MemeGeneratorException as e:
|
| 87 |
-
return None, f"❌ {e}"
|
| 88 |
-
except Exception as e:
|
| 89 |
-
return None, f"❌ 未知错误:{type(e).__name__}: {e}"
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
# ---- Gradio 界面 ----
|
| 93 |
-
with gr.Blocks(title="表情包生成器") as demo:
|
| 94 |
-
gr.Markdown(
|
| 95 |
-
"# 🎭 表情包生成器\n\n"
|
| 96 |
-
"选择模板 → 上传图片 → 填写文字 → 一键生成。\n\n"
|
| 97 |
-
"**API**:原生端点已启用,前缀 `/api`,如 `/api/memes/keys`、`/api/memes/{key}/`。"
|
| 98 |
-
)
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
)
|
| 108 |
-
info = gr.Markdown("*请先选择一个表情包*")
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
|
|
|
|
|
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
out_status = gr.Markdown("")
|
| 123 |
|
| 124 |
-
dd.change(
|
| 125 |
-
fn=_update_ui,
|
| 126 |
-
inputs=[dd],
|
| 127 |
-
outputs=img_inputs + txt_inputs + [info],
|
| 128 |
-
)
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
)
|
| 135 |
|
| 136 |
-
# ---- 把 meme_generator 原生 API 挂载到 Gradio 的 /api 路径 ----
|
| 137 |
-
# /api/memes/* 由 meme_generator 原生 FastAPI 处理(无 CSRF,可跨站调用)
|
| 138 |
-
# 其他路径由 Gradio 界面处理
|
| 139 |
-
demo.app.mount("/api", meme_app)
|
| 140 |
|
| 141 |
if __name__ == "__main__":
|
| 142 |
-
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Any, Literal, Optional
|
| 4 |
+
|
| 5 |
+
import filetype
|
| 6 |
+
from fastapi import Depends, FastAPI, Form, HTTPException, Response, UploadFile
|
| 7 |
+
from pydantic import BaseModel, ValidationError
|
| 8 |
+
|
| 9 |
+
from meme_generator.compat import model_dump, model_json_schema, type_validate_python
|
| 10 |
+
from meme_generator.config import meme_config
|
| 11 |
+
from meme_generator.exception import (
|
| 12 |
+
ArgModelMismatch,
|
| 13 |
+
MemeGeneratorException,
|
| 14 |
+
NoSuchMeme,
|
| 15 |
+
)
|
| 16 |
+
from meme_generator.log import LOGGING_CONFIG, setup_logger
|
| 17 |
+
from meme_generator.manager import get_meme, get_meme_keys, get_memes
|
| 18 |
+
from meme_generator.meme import CommandShortcut, Meme, MemeArgsModel, ParserOption
|
| 19 |
+
from meme_generator.utils import MemeProperties, render_meme_list, run_sync
|
| 20 |
+
from meme_generator.version import __version__
|
| 21 |
+
|
| 22 |
+
app = FastAPI()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MemeArgsResponse(BaseModel):
|
| 26 |
+
args_model: dict[str, Any]
|
| 27 |
+
args_examples: list[dict[str, Any]]
|
| 28 |
+
parser_options: list[ParserOption]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class MemeParamsResponse(BaseModel):
|
| 32 |
+
min_images: int
|
| 33 |
+
max_images: int
|
| 34 |
+
min_texts: int
|
| 35 |
+
max_texts: int
|
| 36 |
+
default_texts: list[str]
|
| 37 |
+
args_type: Optional[MemeArgsResponse] = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class MemeInfoResponse(BaseModel):
|
| 41 |
+
key: str
|
| 42 |
+
params_type: MemeParamsResponse
|
| 43 |
+
keywords: list[str]
|
| 44 |
+
shortcuts: list[CommandShortcut]
|
| 45 |
+
tags: set[str]
|
| 46 |
+
date_created: datetime
|
| 47 |
+
date_modified: datetime
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def register_router(meme: Meme):
|
| 51 |
+
if args_type := meme.params_type.args_type:
|
| 52 |
+
args_model = args_type.args_model
|
| 53 |
+
else:
|
| 54 |
+
args_model = MemeArgsModel
|
| 55 |
+
|
| 56 |
+
def args_checker(
|
| 57 |
+
args: Optional[str] = Form(default=json.dumps(model_dump(args_model()))),
|
| 58 |
+
):
|
| 59 |
+
if not args:
|
| 60 |
+
return MemeArgsModel()
|
| 61 |
+
try:
|
| 62 |
+
model = type_validate_python(args_model, json.loads(args))
|
| 63 |
+
except ValidationError as e:
|
| 64 |
+
e = ArgModelMismatch(str(e))
|
| 65 |
+
raise HTTPException(status_code=552, detail=e.message)
|
| 66 |
+
return model
|
| 67 |
+
|
| 68 |
+
@app.post(f"/memes/{meme.key}/")
|
| 69 |
+
async def _(
|
| 70 |
+
images: list[UploadFile] = [],
|
| 71 |
+
texts: list[str] = meme.params_type.default_texts,
|
| 72 |
+
args: args_model = Depends(args_checker), # type: ignore
|
| 73 |
+
):
|
| 74 |
+
imgs: list[bytes] = []
|
| 75 |
+
for image in images:
|
| 76 |
+
imgs.append(await image.read())
|
| 77 |
+
|
| 78 |
+
texts = [text for text in texts if text]
|
| 79 |
+
|
| 80 |
+
assert isinstance(args, args_model)
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
result = await run_sync(meme)(
|
| 84 |
+
images=imgs, texts=texts, args=model_dump(args)
|
| 85 |
+
)
|
| 86 |
+
except MemeGeneratorException as e:
|
| 87 |
+
raise HTTPException(status_code=e.status_code, detail=e.message)
|
| 88 |
|
| 89 |
+
content = result.getvalue()
|
| 90 |
+
media_type = str(filetype.guess_mime(content)) or "text/plain"
|
| 91 |
+
return Response(content=content, media_type=media_type)
|
| 92 |
|
| 93 |
|
| 94 |
+
class MemeKeyWithProperties(BaseModel):
|
| 95 |
+
meme_key: str
|
| 96 |
+
disabled: bool = False
|
| 97 |
+
labels: list[Literal["new", "hot"]] = []
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
default_meme_list = [
|
| 101 |
+
MemeKeyWithProperties(meme_key=meme.key)
|
| 102 |
+
for meme in sorted(get_memes(), key=lambda meme: meme.key)
|
| 103 |
+
]
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
class RenderMemeListRequest(BaseModel):
|
| 107 |
+
meme_list: list[MemeKeyWithProperties] = default_meme_list
|
| 108 |
+
text_template: str = "{keywords}"
|
| 109 |
+
add_category_icon: bool = True
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def register_routers():
|
| 113 |
+
@app.post("/memes/render_list")
|
| 114 |
+
def _(params: RenderMemeListRequest = RenderMemeListRequest()):
|
| 115 |
+
try:
|
| 116 |
+
meme_list = [
|
| 117 |
+
(
|
| 118 |
+
get_meme(p.meme_key),
|
| 119 |
+
MemeProperties(disabled=p.disabled, labels=p.labels),
|
| 120 |
+
)
|
| 121 |
+
for p in params.meme_list
|
| 122 |
+
]
|
| 123 |
+
except NoSuchMeme as e:
|
| 124 |
+
raise HTTPException(status_code=e.status_code, detail=e.message)
|
| 125 |
+
|
| 126 |
+
result = render_meme_list(
|
| 127 |
+
meme_list,
|
| 128 |
+
text_template=params.text_template,
|
| 129 |
+
add_category_icon=params.add_category_icon,
|
| 130 |
+
)
|
| 131 |
+
content = result.getvalue()
|
| 132 |
+
media_type = str(filetype.guess_mime(content)) or "text/plain"
|
| 133 |
+
return Response(content=content, media_type=media_type)
|
| 134 |
+
|
| 135 |
+
@app.get("/meme/version")
|
| 136 |
+
def _():
|
| 137 |
+
return __version__
|
| 138 |
+
|
| 139 |
+
@app.get("/memes/keys")
|
| 140 |
+
def _():
|
| 141 |
+
return get_meme_keys()
|
| 142 |
+
|
| 143 |
+
@app.get("/memes/{key}/info")
|
| 144 |
+
def _(key: str):
|
| 145 |
+
try:
|
| 146 |
+
meme = get_meme(key)
|
| 147 |
+
except NoSuchMeme as e:
|
| 148 |
+
raise HTTPException(status_code=e.status_code, detail=e.message)
|
| 149 |
+
|
| 150 |
+
args_type_response = None
|
| 151 |
+
if args_type := meme.params_type.args_type:
|
| 152 |
+
args_model = args_type.args_model
|
| 153 |
+
args_type_response = MemeArgsResponse(
|
| 154 |
+
args_model=model_json_schema(args_model),
|
| 155 |
+
args_examples=[
|
| 156 |
+
model_dump(example) for example in args_type.args_examples
|
| 157 |
+
],
|
| 158 |
+
parser_options=args_type.parser_options,
|
| 159 |
)
|
|
|
|
| 160 |
|
| 161 |
+
return MemeInfoResponse(
|
| 162 |
+
key=meme.key,
|
| 163 |
+
params_type=MemeParamsResponse(
|
| 164 |
+
min_images=meme.params_type.min_images,
|
| 165 |
+
max_images=meme.params_type.max_images,
|
| 166 |
+
min_texts=meme.params_type.min_texts,
|
| 167 |
+
max_texts=meme.params_type.max_texts,
|
| 168 |
+
default_texts=meme.params_type.default_texts,
|
| 169 |
+
args_type=args_type_response,
|
| 170 |
+
),
|
| 171 |
+
keywords=meme.keywords,
|
| 172 |
+
shortcuts=meme.shortcuts,
|
| 173 |
+
tags=meme.tags,
|
| 174 |
+
date_created=meme.date_created,
|
| 175 |
+
date_modified=meme.date_modified,
|
| 176 |
+
)
|
| 177 |
|
| 178 |
+
@app.get("/memes/{key}/preview")
|
| 179 |
+
async def _(key: str):
|
| 180 |
+
try:
|
| 181 |
+
meme = get_meme(key)
|
| 182 |
+
result = await run_sync(meme.generate_preview)()
|
| 183 |
+
except MemeGeneratorException as e:
|
| 184 |
+
raise HTTPException(status_code=e.status_code, detail=e.message)
|
| 185 |
|
| 186 |
+
content = result.getvalue()
|
| 187 |
+
media_type = str(filetype.guess_mime(content)) or "text/plain"
|
| 188 |
+
return Response(content=content, media_type=media_type)
|
| 189 |
|
| 190 |
+
for meme in sorted(get_memes(), key=lambda meme: meme.key):
|
| 191 |
+
register_router(meme)
|
|
|
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
def run_server():
|
| 195 |
+
import uvicorn
|
| 196 |
+
|
| 197 |
+
register_routers()
|
| 198 |
+
uvicorn.run(
|
| 199 |
+
app,
|
| 200 |
+
host=meme_config.server.host,
|
| 201 |
+
port=meme_config.server.port,
|
| 202 |
+
log_config=LOGGING_CONFIG,
|
| 203 |
)
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
if __name__ == "__main__":
|
| 207 |
+
setup_logger()
|
| 208 |
+
run_server()
|
cli.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import filetype
|
| 6 |
+
from arclet.alconna import (
|
| 7 |
+
Alconna,
|
| 8 |
+
Args,
|
| 9 |
+
CommandMeta,
|
| 10 |
+
MultiVar,
|
| 11 |
+
Option,
|
| 12 |
+
Subcommand,
|
| 13 |
+
TextFormatter,
|
| 14 |
+
)
|
| 15 |
+
from arclet.alconna.exceptions import SpecialOptionTriggered
|
| 16 |
+
from arclet.alconna.tools import RichConsoleFormatter
|
| 17 |
+
|
| 18 |
+
from meme_generator.app import run_server
|
| 19 |
+
from meme_generator.config import meme_config
|
| 20 |
+
from meme_generator.download import check_resources
|
| 21 |
+
from meme_generator.exception import MemeGeneratorException, NoSuchMeme
|
| 22 |
+
from meme_generator.log import setup_logger
|
| 23 |
+
from meme_generator.manager import get_meme, get_memes
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def construct_parser() -> Alconna:
|
| 27 |
+
sub_commands: list[Subcommand] = []
|
| 28 |
+
for meme in get_memes():
|
| 29 |
+
options: list[Option] = []
|
| 30 |
+
if args_type := meme.params_type.args_type:
|
| 31 |
+
for option in args_type.parser_options:
|
| 32 |
+
options.append(option.option())
|
| 33 |
+
sub_command = Subcommand(
|
| 34 |
+
meme.key,
|
| 35 |
+
*options,
|
| 36 |
+
Option(
|
| 37 |
+
"--images",
|
| 38 |
+
Args["images", MultiVar(str, "+")],
|
| 39 |
+
help_text="输入图片路径",
|
| 40 |
+
),
|
| 41 |
+
Option("--texts", Args["texts", MultiVar(str, "+")], help_text="输入文字"),
|
| 42 |
+
help_text="/".join(meme.keywords),
|
| 43 |
+
)
|
| 44 |
+
sub_commands.append(sub_command)
|
| 45 |
+
|
| 46 |
+
parser = Alconna(
|
| 47 |
+
"meme",
|
| 48 |
+
Subcommand("list", alias=["ls"], help_text="查看表情列表"),
|
| 49 |
+
Subcommand(
|
| 50 |
+
"info", Args["key#表情名", str], alias=["show"], help_text="查看表情详情"
|
| 51 |
+
),
|
| 52 |
+
Subcommand("preview", Args["key#表情名", str], help_text="生成表情预览"),
|
| 53 |
+
Subcommand("generate", *sub_commands, alias=["make"], help_text="制作表情"),
|
| 54 |
+
Subcommand("run", alias=["start"], help_text="启动 web server"),
|
| 55 |
+
Subcommand(
|
| 56 |
+
"download",
|
| 57 |
+
Option("--url", Args["url", str], help_text="指定资源链接"),
|
| 58 |
+
help_text="下载内置表情图片",
|
| 59 |
+
),
|
| 60 |
+
meta=CommandMeta(
|
| 61 |
+
description="表情包生成器",
|
| 62 |
+
example="meme generate petpet --images /path/to/image/file",
|
| 63 |
+
),
|
| 64 |
+
formatter_type=RichConsoleFormatter,
|
| 65 |
+
)
|
| 66 |
+
return parser
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def list_memes() -> str:
|
| 70 |
+
memes = sorted(get_memes(), key=lambda meme: meme.key)
|
| 71 |
+
return "\n".join(
|
| 72 |
+
f"{i}. {meme.key} ({'/'.join(meme.keywords)})"
|
| 73 |
+
for i, meme in enumerate(memes, start=1)
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def meme_info(key: str) -> str:
|
| 78 |
+
try:
|
| 79 |
+
meme = get_meme(key)
|
| 80 |
+
except NoSuchMeme:
|
| 81 |
+
return f'表情 "{key}" 不存在!'
|
| 82 |
+
|
| 83 |
+
keywords = "、".join([f'"{keyword}"' for keyword in meme.keywords])
|
| 84 |
+
shortcuts = "、".join(
|
| 85 |
+
[f'"{shortcut.humanized or shortcut.key}"' for shortcut in meme.shortcuts]
|
| 86 |
+
)
|
| 87 |
+
tags = "、".join([f'"{tag}"' for tag in sorted(meme.tags)])
|
| 88 |
+
|
| 89 |
+
image_num = f"{meme.params_type.min_images}"
|
| 90 |
+
if meme.params_type.max_images > meme.params_type.min_images:
|
| 91 |
+
image_num += f" ~ {meme.params_type.max_images}"
|
| 92 |
+
|
| 93 |
+
text_num = f"{meme.params_type.min_texts}"
|
| 94 |
+
if meme.params_type.max_texts > meme.params_type.min_texts:
|
| 95 |
+
text_num += f" ~ {meme.params_type.max_texts}"
|
| 96 |
+
|
| 97 |
+
default_texts = ", ".join([f'"{text}"' for text in meme.params_type.default_texts])
|
| 98 |
+
|
| 99 |
+
args_info = ""
|
| 100 |
+
if args_type := meme.params_type.args_type:
|
| 101 |
+
formater = TextFormatter()
|
| 102 |
+
for option in args_type.parser_options:
|
| 103 |
+
opt = option.option()
|
| 104 |
+
alias_text = (
|
| 105 |
+
" ".join(opt.requires)
|
| 106 |
+
+ (" " if opt.requires else "")
|
| 107 |
+
+ "│".join(sorted(opt.aliases, key=len))
|
| 108 |
+
)
|
| 109 |
+
args_info += (
|
| 110 |
+
f"\n * {alias_text}{opt.separators[0]}"
|
| 111 |
+
f"{formater.parameters(opt.args)} {opt.help_text}"
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
return (
|
| 115 |
+
f"表情名:{meme.key}\n"
|
| 116 |
+
+ f"关键词:{keywords}\n"
|
| 117 |
+
+ (f"快捷指令:{shortcuts}\n" if shortcuts else "")
|
| 118 |
+
+ (f"标签:{tags}\n" if tags else "")
|
| 119 |
+
+ f"需要图片数目:{image_num}\n"
|
| 120 |
+
+ f"需要文字数目:{text_num}\n"
|
| 121 |
+
+ (f"默认文字:[{default_texts}]\n" if default_texts else "")
|
| 122 |
+
+ (f"其他参数:{args_info}" if args_info else "")
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def generate_meme_preview(key: str) -> str:
|
| 127 |
+
try:
|
| 128 |
+
meme = get_meme(key)
|
| 129 |
+
except NoSuchMeme:
|
| 130 |
+
return f'表情 "{key}" 不存在!'
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
result = meme.generate_preview()
|
| 134 |
+
content = result.getvalue()
|
| 135 |
+
ext = filetype.guess_extension(content)
|
| 136 |
+
filename = f"result.{ext}"
|
| 137 |
+
with open(filename, "wb") as f:
|
| 138 |
+
f.write(content)
|
| 139 |
+
return f'表情制作成功!生成的表情文件为 "{filename}"'
|
| 140 |
+
except MemeGeneratorException as e:
|
| 141 |
+
return str(e)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def generate_meme(
|
| 145 |
+
key: str, images: list[str], texts: list[str], args: dict[str, Any]
|
| 146 |
+
) -> str:
|
| 147 |
+
try:
|
| 148 |
+
meme = get_meme(key)
|
| 149 |
+
except NoSuchMeme:
|
| 150 |
+
return f'表情 "{key}" 不存在!'
|
| 151 |
+
|
| 152 |
+
for image in images:
|
| 153 |
+
if not Path(image).exists():
|
| 154 |
+
return f'图片路径 "{image}" 不存在!'
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
result = meme(images=images, texts=texts, args=args)
|
| 158 |
+
content = result.getvalue()
|
| 159 |
+
ext = filetype.guess_extension(content)
|
| 160 |
+
filename = f"result.{ext}"
|
| 161 |
+
with open(filename, "wb") as f:
|
| 162 |
+
f.write(content)
|
| 163 |
+
return f'表情制作成功!生成的表情文件为 "{filename}"'
|
| 164 |
+
except MemeGeneratorException as e:
|
| 165 |
+
return str(e)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def main():
|
| 169 |
+
setup_logger()
|
| 170 |
+
parser = construct_parser()
|
| 171 |
+
result = parser()
|
| 172 |
+
|
| 173 |
+
if not result.matched:
|
| 174 |
+
if not isinstance(result.error_info, SpecialOptionTriggered):
|
| 175 |
+
print(result.error_info) # noqa: T201
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
if not result.subcommands:
|
| 179 |
+
print(parser.get_help()) # noqa: T201
|
| 180 |
+
|
| 181 |
+
for subcommand, sub_result in result.subcommands.items():
|
| 182 |
+
if subcommand == "list":
|
| 183 |
+
print(list_memes()) # noqa: T201
|
| 184 |
+
|
| 185 |
+
elif subcommand == "info":
|
| 186 |
+
key = str(sub_result.args["key"])
|
| 187 |
+
print(meme_info(key)) # noqa: T201
|
| 188 |
+
|
| 189 |
+
elif subcommand == "preview":
|
| 190 |
+
key = str(sub_result.args["key"])
|
| 191 |
+
print(generate_meme_preview(key)) # noqa: T201
|
| 192 |
+
|
| 193 |
+
elif subcommand == "generate":
|
| 194 |
+
for key, subsub_result in sub_result.subcommands.items():
|
| 195 |
+
images = (
|
| 196 |
+
list(subsub_result.options["images"].args["images"])
|
| 197 |
+
if "images" in subsub_result.options
|
| 198 |
+
else []
|
| 199 |
+
)
|
| 200 |
+
texts = (
|
| 201 |
+
list(subsub_result.options["texts"].args["texts"])
|
| 202 |
+
if "texts" in subsub_result.options
|
| 203 |
+
else []
|
| 204 |
+
)
|
| 205 |
+
options = subsub_result.options
|
| 206 |
+
options.pop("images", None)
|
| 207 |
+
options.pop("texts", None)
|
| 208 |
+
args = {}
|
| 209 |
+
for option, option_result in options.items():
|
| 210 |
+
if option_result.value is None:
|
| 211 |
+
args.update(option_result.args)
|
| 212 |
+
else:
|
| 213 |
+
args[option] = option_result.value
|
| 214 |
+
print(generate_meme(key, images, texts, args)) # noqa: T201
|
| 215 |
+
|
| 216 |
+
elif subcommand == "run":
|
| 217 |
+
run_server()
|
| 218 |
+
|
| 219 |
+
elif subcommand == "download":
|
| 220 |
+
if "url" in sub_result.options:
|
| 221 |
+
url = sub_result.options["url"].args["url"]
|
| 222 |
+
meme_config.resource.resource_url = url
|
| 223 |
+
loop = asyncio.new_event_loop()
|
| 224 |
+
loop.run_until_complete(check_resources())
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|
compat.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""本模块为 Pydantic 版本兼容层模块
|
| 2 |
+
|
| 3 |
+
为兼容 Pydantic V1 与 V2 版本,定义了一系列兼容函数与类供使用。
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Any, Optional, TypeVar, Union
|
| 7 |
+
|
| 8 |
+
from pydantic import VERSION, BaseModel
|
| 9 |
+
|
| 10 |
+
T = TypeVar("T")
|
| 11 |
+
|
| 12 |
+
PYDANTIC_V2 = int(VERSION.split(".", 1)[0]) == 2
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
__all__ = (
|
| 16 |
+
"model_dump",
|
| 17 |
+
"model_json_schema",
|
| 18 |
+
"type_validate_python",
|
| 19 |
+
"type_validate_json",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if PYDANTIC_V2: # pragma: pydantic-v2
|
| 24 |
+
from pydantic import TypeAdapter as TypeAdapter
|
| 25 |
+
from pydantic.json_schema import DEFAULT_REF_TEMPLATE
|
| 26 |
+
|
| 27 |
+
def model_dump(
|
| 28 |
+
model: BaseModel,
|
| 29 |
+
include: Optional[set[str]] = None,
|
| 30 |
+
exclude: Optional[set[str]] = None,
|
| 31 |
+
by_alias: bool = False,
|
| 32 |
+
exclude_unset: bool = False,
|
| 33 |
+
exclude_defaults: bool = False,
|
| 34 |
+
exclude_none: bool = False,
|
| 35 |
+
) -> dict[str, Any]:
|
| 36 |
+
return model.model_dump(
|
| 37 |
+
include=include,
|
| 38 |
+
exclude=exclude,
|
| 39 |
+
by_alias=by_alias,
|
| 40 |
+
exclude_unset=exclude_unset,
|
| 41 |
+
exclude_defaults=exclude_defaults,
|
| 42 |
+
exclude_none=exclude_none,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def model_json_schema(
|
| 46 |
+
model: type[BaseModel],
|
| 47 |
+
by_alias: bool = True,
|
| 48 |
+
ref_template: str = DEFAULT_REF_TEMPLATE,
|
| 49 |
+
) -> dict[str, Any]:
|
| 50 |
+
return model.model_json_schema(by_alias=by_alias, ref_template=ref_template)
|
| 51 |
+
|
| 52 |
+
def type_validate_python(type_: type[T], data: Any) -> T:
|
| 53 |
+
"""Validate data with given type."""
|
| 54 |
+
return TypeAdapter(type_).validate_python(data)
|
| 55 |
+
|
| 56 |
+
def type_validate_json(type_: type[T], data: Union[str, bytes]) -> T:
|
| 57 |
+
"""Validate JSON with given type."""
|
| 58 |
+
return TypeAdapter(type_).validate_json(data)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
else: # pragma: pydantic-v1
|
| 62 |
+
from pydantic import parse_obj_as, parse_raw_as
|
| 63 |
+
from pydantic.schema import default_ref_template
|
| 64 |
+
|
| 65 |
+
def model_dump(
|
| 66 |
+
model: BaseModel,
|
| 67 |
+
include: Optional[set[str]] = None,
|
| 68 |
+
exclude: Optional[set[str]] = None,
|
| 69 |
+
by_alias: bool = False,
|
| 70 |
+
exclude_unset: bool = False,
|
| 71 |
+
exclude_defaults: bool = False,
|
| 72 |
+
exclude_none: bool = False,
|
| 73 |
+
) -> dict[str, Any]:
|
| 74 |
+
return model.dict(
|
| 75 |
+
include=include,
|
| 76 |
+
exclude=exclude,
|
| 77 |
+
by_alias=by_alias,
|
| 78 |
+
exclude_unset=exclude_unset,
|
| 79 |
+
exclude_defaults=exclude_defaults,
|
| 80 |
+
exclude_none=exclude_none,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def model_json_schema(
|
| 84 |
+
model: type[BaseModel],
|
| 85 |
+
by_alias: bool = True,
|
| 86 |
+
ref_template: str = default_ref_template,
|
| 87 |
+
) -> dict[str, Any]:
|
| 88 |
+
return model.schema(by_alias=by_alias, ref_template=ref_template)
|
| 89 |
+
|
| 90 |
+
def type_validate_python(type_: type[T], data: Any) -> T:
|
| 91 |
+
"""Validate data with given type."""
|
| 92 |
+
return parse_obj_as(type_, data)
|
| 93 |
+
|
| 94 |
+
def type_validate_json(type_: type[T], data: Union[str, bytes]) -> T:
|
| 95 |
+
"""Validate JSON with given type."""
|
| 96 |
+
return parse_raw_as(type_, data)
|
config.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Optional, Union
|
| 3 |
+
|
| 4 |
+
import toml
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
from .compat import model_dump, type_validate_python
|
| 8 |
+
from .dirs import get_config_file
|
| 9 |
+
|
| 10 |
+
config_file_path = get_config_file("config.toml")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class MemeConfig(BaseModel):
|
| 14 |
+
load_builtin_memes: bool = True
|
| 15 |
+
meme_dirs: list[Path] = []
|
| 16 |
+
meme_disabled_list: list[str] = []
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ResourceConfig(BaseModel):
|
| 20 |
+
resource_url: Optional[str] = None
|
| 21 |
+
resource_urls: list[str] = [
|
| 22 |
+
"https://raw.githubusercontent.com/ClarityJS/meme-generator/",
|
| 23 |
+
"https://mirror.ghproxy.com/https://raw.githubusercontent.com/ClarityJS/meme-generator/",
|
| 24 |
+
"https://cdn.jsdelivr.net/gh/ClarityJS/meme-generator@",
|
| 25 |
+
"https://fastly.jsdelivr.net/gh/ClarityJS/meme-generator@",
|
| 26 |
+
"https://raw.gitmirror.com/ClarityJS/meme-generator/",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class GifConfig(BaseModel):
|
| 31 |
+
gif_max_size: float = 10
|
| 32 |
+
gif_max_frames: int = 100
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# 已由大佬提供翻译相关技术,无需配置了
|
| 36 |
+
# class TranslatorConfig(BaseModel):
|
| 37 |
+
# baidu_trans_appid: str = ""
|
| 38 |
+
# baidu_trans_apikey: str = ""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ServerConfig(BaseModel):
|
| 42 |
+
host: str = "127.0.0.1"
|
| 43 |
+
port: int = 2233
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class LogConfig(BaseModel):
|
| 47 |
+
log_level: Union[int, str] = "INFO"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Config(BaseModel):
|
| 51 |
+
meme: MemeConfig = MemeConfig()
|
| 52 |
+
resource: ResourceConfig = ResourceConfig()
|
| 53 |
+
gif: GifConfig = GifConfig()
|
| 54 |
+
# translate: TranslatorConfig = TranslatorConfig()
|
| 55 |
+
server: ServerConfig = ServerConfig()
|
| 56 |
+
log: LogConfig = LogConfig()
|
| 57 |
+
|
| 58 |
+
@classmethod
|
| 59 |
+
def load(cls) -> "Config":
|
| 60 |
+
return type_validate_python(cls, toml.load(config_file_path))
|
| 61 |
+
|
| 62 |
+
def dump(self):
|
| 63 |
+
with open(config_file_path, "w", encoding="utf-8") as f:
|
| 64 |
+
toml.dump(model_dump(self), f)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if not config_file_path.exists():
|
| 68 |
+
meme_config = Config()
|
| 69 |
+
config_file_path.write_text("", encoding="utf8")
|
| 70 |
+
else:
|
| 71 |
+
meme_config = Config.load()
|
dirs.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/nonebot/plugin-localstore
|
| 2 |
+
"""
|
| 3 |
+
MIT License
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2021 NoneBot
|
| 6 |
+
|
| 7 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 9 |
+
in the Software without restriction, including without limitation the rights
|
| 10 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 11 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
furnished to do so, subject to the following conditions:
|
| 13 |
+
|
| 14 |
+
The above copyright notice and this permission notice shall be included in all
|
| 15 |
+
copies or substantial portions of the Software.
|
| 16 |
+
|
| 17 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 22 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 23 |
+
SOFTWARE.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Callable, Literal
|
| 30 |
+
|
| 31 |
+
from typing_extensions import ParamSpec
|
| 32 |
+
|
| 33 |
+
WINDOWS = sys.platform.startswith("win") or (sys.platform == "cli" and os.name == "nt")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def user_cache_dir(appname: str) -> Path:
|
| 37 |
+
r"""
|
| 38 |
+
Return full path to the user-specific cache dir for this application.
|
| 39 |
+
"appname" is the name of application.
|
| 40 |
+
Typical user cache directories are:
|
| 41 |
+
macOS: ~/Library/Caches/<AppName>
|
| 42 |
+
Unix: ~/.cache/<AppName> (XDG default)
|
| 43 |
+
Windows: C:\Users\<username>\AppData\Local\<AppName>\Cache
|
| 44 |
+
On Windows the only suggestion in the MSDN docs is that local settings go
|
| 45 |
+
in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the
|
| 46 |
+
non-roaming app data dir (the default returned by `user_data_dir`). Apps
|
| 47 |
+
typically put cache data somewhere *under* the given dir here. Some
|
| 48 |
+
examples:
|
| 49 |
+
...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
|
| 50 |
+
...\Acme\SuperApp\Cache\1.0
|
| 51 |
+
OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
|
| 52 |
+
"""
|
| 53 |
+
if WINDOWS:
|
| 54 |
+
return _get_win_folder("CSIDL_LOCAL_APPDATA") / appname / "Cache"
|
| 55 |
+
elif sys.platform == "darwin":
|
| 56 |
+
return Path("~/Library/Caches").expanduser() / appname
|
| 57 |
+
else:
|
| 58 |
+
return Path(os.getenv("XDG_CACHE_HOME", "~/.cache")).expanduser() / appname
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def user_data_dir(appname: str, roaming: bool = False) -> Path:
|
| 62 |
+
r"""
|
| 63 |
+
Return full path to the user-specific data dir for this application.
|
| 64 |
+
"appname" is the name of application.
|
| 65 |
+
If None, just the system directory is returned.
|
| 66 |
+
"roaming" (boolean, default False) can be set True to use the Windows
|
| 67 |
+
roaming appdata directory. That means that for users on a Windows
|
| 68 |
+
network setup for roaming profiles, this user data will be
|
| 69 |
+
sync'd on login. See
|
| 70 |
+
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
|
| 71 |
+
for a discussion of issues.
|
| 72 |
+
Typical user data directories are:
|
| 73 |
+
macOS: ~/Library/Application Support/<AppName>
|
| 74 |
+
Unix: ~/.local/share/<AppName> # or in
|
| 75 |
+
$XDG_DATA_HOME, if defined
|
| 76 |
+
Win XP (not roaming): C:\Documents and Settings\<username>\ ...
|
| 77 |
+
...Application Data\<AppName>
|
| 78 |
+
Win XP (roaming): C:\Documents and Settings\<username>\Local ...
|
| 79 |
+
...Settings\Application Data\<AppName>
|
| 80 |
+
Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppName>
|
| 81 |
+
Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppName>
|
| 82 |
+
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
|
| 83 |
+
That means, by default "~/.local/share/<AppName>".
|
| 84 |
+
"""
|
| 85 |
+
if WINDOWS:
|
| 86 |
+
const = "CSIDL_APPDATA" if roaming else "CSIDL_LOCAL_APPDATA"
|
| 87 |
+
return Path(_get_win_folder(const)) / appname
|
| 88 |
+
elif sys.platform == "darwin":
|
| 89 |
+
return Path("~/Library/Application Support/").expanduser() / appname
|
| 90 |
+
else:
|
| 91 |
+
return Path(os.getenv("XDG_DATA_HOME", "~/.local/share")).expanduser() / appname
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def user_config_dir(appname: str, roaming: bool = True) -> Path:
|
| 95 |
+
"""Return full path to the user-specific config dir for this application.
|
| 96 |
+
"appname" is the name of application.
|
| 97 |
+
If None, just the system directory is returned.
|
| 98 |
+
"roaming" (boolean, default True) can be set False to not use the
|
| 99 |
+
Windows roaming appdata directory. That means that for users on a
|
| 100 |
+
Windows network setup for roaming profiles, this user data will be
|
| 101 |
+
sync'd on login. See
|
| 102 |
+
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
|
| 103 |
+
for a discussion of issues.
|
| 104 |
+
Typical user data directories are:
|
| 105 |
+
macOS: same as user_data_dir
|
| 106 |
+
Unix: ~/.config/<AppName>
|
| 107 |
+
Win *: same as user_data_dir
|
| 108 |
+
For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
|
| 109 |
+
That means, by default "~/.config/<AppName>".
|
| 110 |
+
"""
|
| 111 |
+
if WINDOWS:
|
| 112 |
+
return user_data_dir(appname, roaming=roaming)
|
| 113 |
+
elif sys.platform == "darwin":
|
| 114 |
+
return user_data_dir(appname)
|
| 115 |
+
else:
|
| 116 |
+
return Path(os.getenv("XDG_CONFIG_HOME", "~/.config")).expanduser() / appname
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# -- Windows support functions --
|
| 120 |
+
def _get_win_folder_from_registry(
|
| 121 |
+
csidl_name: Literal["CSIDL_APPDATA", "CSIDL_COMMON_APPDATA", "CSIDL_LOCAL_APPDATA"],
|
| 122 |
+
) -> Path:
|
| 123 |
+
"""
|
| 124 |
+
This is a fallback technique at best. I'm not sure if using the
|
| 125 |
+
registry for this guarantees us the correct answer for all CSIDL_*
|
| 126 |
+
names.
|
| 127 |
+
"""
|
| 128 |
+
import winreg
|
| 129 |
+
|
| 130 |
+
shell_folder_name = {
|
| 131 |
+
"CSIDL_APPDATA": "AppData",
|
| 132 |
+
"CSIDL_COMMON_APPDATA": "Common AppData",
|
| 133 |
+
"CSIDL_LOCAL_APPDATA": "Local AppData",
|
| 134 |
+
}[csidl_name]
|
| 135 |
+
|
| 136 |
+
key = winreg.OpenKey(
|
| 137 |
+
winreg.HKEY_CURRENT_USER,
|
| 138 |
+
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders",
|
| 139 |
+
)
|
| 140 |
+
directory, _type = winreg.QueryValueEx(key, shell_folder_name)
|
| 141 |
+
return Path(directory)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _get_win_folder_with_ctypes(
|
| 145 |
+
csidl_name: Literal["CSIDL_APPDATA", "CSIDL_COMMON_APPDATA", "CSIDL_LOCAL_APPDATA"],
|
| 146 |
+
) -> Path:
|
| 147 |
+
csidl_const = {
|
| 148 |
+
"CSIDL_APPDATA": 26,
|
| 149 |
+
"CSIDL_COMMON_APPDATA": 35,
|
| 150 |
+
"CSIDL_LOCAL_APPDATA": 28,
|
| 151 |
+
}[csidl_name]
|
| 152 |
+
|
| 153 |
+
buf = ctypes.create_unicode_buffer(1024)
|
| 154 |
+
ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
|
| 155 |
+
|
| 156 |
+
# Downgrade to short path name if have highbit chars. See
|
| 157 |
+
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
|
| 158 |
+
has_high_char = any(ord(c) > 255 for c in buf)
|
| 159 |
+
if has_high_char:
|
| 160 |
+
buf2 = ctypes.create_unicode_buffer(1024)
|
| 161 |
+
if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
|
| 162 |
+
buf = buf2
|
| 163 |
+
|
| 164 |
+
return Path(buf.value)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if WINDOWS:
|
| 168 |
+
try:
|
| 169 |
+
import ctypes
|
| 170 |
+
|
| 171 |
+
_get_win_folder = _get_win_folder_with_ctypes
|
| 172 |
+
except ImportError:
|
| 173 |
+
_get_win_folder = _get_win_folder_from_registry
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
P = ParamSpec("P")
|
| 177 |
+
|
| 178 |
+
APP_NAME = "meme_generator"
|
| 179 |
+
BASE_CACHE_DIR = user_cache_dir(APP_NAME).resolve()
|
| 180 |
+
BASE_CONFIG_DIR = user_config_dir(APP_NAME).resolve()
|
| 181 |
+
BASE_DATA_DIR = user_data_dir(APP_NAME).resolve()
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _ensure_dir(path: Path) -> None:
|
| 185 |
+
if not path.exists():
|
| 186 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 187 |
+
elif not path.is_dir():
|
| 188 |
+
raise RuntimeError(f"{path} is not a directory")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _auto_create_dir(func: Callable[P, Path]) -> Callable[P, Path]:
|
| 192 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Path:
|
| 193 |
+
path = func(*args, **kwargs)
|
| 194 |
+
_ensure_dir(path)
|
| 195 |
+
return path
|
| 196 |
+
|
| 197 |
+
return wrapper
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@_auto_create_dir
|
| 201 |
+
def get_cache_dir() -> Path:
|
| 202 |
+
return BASE_CACHE_DIR
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def get_cache_file(filename: str) -> Path:
|
| 206 |
+
return get_cache_dir() / filename
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@_auto_create_dir
|
| 210 |
+
def get_config_dir() -> Path:
|
| 211 |
+
return BASE_CONFIG_DIR
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def get_config_file(filename: str) -> Path:
|
| 215 |
+
return get_config_dir() / filename
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
@_auto_create_dir
|
| 219 |
+
def get_data_dir() -> Path:
|
| 220 |
+
return BASE_DATA_DIR
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def get_data_file(filename: str) -> Path:
|
| 224 |
+
return get_data_dir() / filename
|
download.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import httpx
|
| 8 |
+
from rich.progress import Progress
|
| 9 |
+
|
| 10 |
+
from .config import meme_config
|
| 11 |
+
from .log import logger
|
| 12 |
+
from .version import __version__
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _resource_url(base_url: str, name: str) -> str:
|
| 16 |
+
return f"{base_url}v{__version__}/{name}"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# https://github.com/mnixry/nonebot-plugin-gocqhttp/blob/main/nonebot_plugin_gocqhttp/process/download.py
|
| 20 |
+
async def get_fastest_mirror() -> list[str]:
|
| 21 |
+
assert meme_config.resource.resource_urls, "No resource url specified."
|
| 22 |
+
|
| 23 |
+
async def head_mirror(client: httpx.AsyncClient, base_url: str):
|
| 24 |
+
begin_time = time.time()
|
| 25 |
+
response = await client.head(
|
| 26 |
+
_resource_url(base_url, "resources/fonts/NotoSansSC-Regular.ttf"), timeout=5
|
| 27 |
+
)
|
| 28 |
+
response.raise_for_status()
|
| 29 |
+
elapsed_time = (time.time() - begin_time) * 1000
|
| 30 |
+
return {"base_url": base_url, "elapsed_time": elapsed_time}
|
| 31 |
+
|
| 32 |
+
async with httpx.AsyncClient() as client:
|
| 33 |
+
results = await asyncio.gather(
|
| 34 |
+
*(
|
| 35 |
+
head_mirror(client, domain)
|
| 36 |
+
for domain in meme_config.resource.resource_urls
|
| 37 |
+
),
|
| 38 |
+
return_exceptions=True,
|
| 39 |
+
)
|
| 40 |
+
results = sorted(
|
| 41 |
+
(result for result in results if not isinstance(result, BaseException)),
|
| 42 |
+
key=lambda r: r["elapsed_time"],
|
| 43 |
+
)
|
| 44 |
+
return [result["base_url"] for result in results]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
async def check_resources():
|
| 48 |
+
semaphore = asyncio.Semaphore(10)
|
| 49 |
+
|
| 50 |
+
available_urls = (
|
| 51 |
+
[meme_config.resource.resource_url]
|
| 52 |
+
if meme_config.resource.resource_url
|
| 53 |
+
else (await get_fastest_mirror())
|
| 54 |
+
)
|
| 55 |
+
logger.debug(f"Available resource urls: {available_urls}")
|
| 56 |
+
if not available_urls:
|
| 57 |
+
logger.warning("No resource url available.")
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
async def _download(client: httpx.AsyncClient, name: str):
|
| 61 |
+
async with semaphore:
|
| 62 |
+
for base_url in available_urls:
|
| 63 |
+
url = _resource_url(base_url, name)
|
| 64 |
+
try:
|
| 65 |
+
resp = await client.get(url, timeout=20, follow_redirects=True)
|
| 66 |
+
resp.raise_for_status()
|
| 67 |
+
return resp.content
|
| 68 |
+
except httpx.HTTPError:
|
| 69 |
+
pass
|
| 70 |
+
logger.warning(f"{name} download failed!")
|
| 71 |
+
|
| 72 |
+
async with httpx.AsyncClient() as client:
|
| 73 |
+
if content := await _download(client, "resources/resource_list.json"):
|
| 74 |
+
resource_list = json.loads(content.decode("utf-8"))
|
| 75 |
+
else:
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
download_list: list[tuple[Path, str]] = []
|
| 79 |
+
for resource in resource_list:
|
| 80 |
+
file_name = str(resource["path"])
|
| 81 |
+
file_hash = str(resource["hash"])
|
| 82 |
+
file_path = Path(__file__).parent / "memes" / file_name
|
| 83 |
+
if (
|
| 84 |
+
file_path.exists()
|
| 85 |
+
and hashlib.md5(file_path.read_bytes()).hexdigest() == file_hash
|
| 86 |
+
):
|
| 87 |
+
continue
|
| 88 |
+
else:
|
| 89 |
+
download_list.append((file_path, f"meme_generator/memes/{file_name}"))
|
| 90 |
+
|
| 91 |
+
if len(download_list):
|
| 92 |
+
logger.info("Downloading images ...")
|
| 93 |
+
else:
|
| 94 |
+
return
|
| 95 |
+
|
| 96 |
+
async with httpx.AsyncClient() as client:
|
| 97 |
+
|
| 98 |
+
async def download_image(file_path: Path, file_name: str):
|
| 99 |
+
if content := await _download(client, file_name):
|
| 100 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 101 |
+
with file_path.open("wb") as f:
|
| 102 |
+
f.write(content)
|
| 103 |
+
|
| 104 |
+
with Progress(
|
| 105 |
+
*Progress.get_default_columns(), "[yellow]{task.completed}/{task.total}"
|
| 106 |
+
) as progress:
|
| 107 |
+
progress_task = progress.add_task(
|
| 108 |
+
"[green]Downloading...", total=len(download_list)
|
| 109 |
+
)
|
| 110 |
+
tasks = [
|
| 111 |
+
download_image(file_path, file_name)
|
| 112 |
+
for file_path, file_name in download_list
|
| 113 |
+
]
|
| 114 |
+
for task in asyncio.as_completed(tasks):
|
| 115 |
+
await task
|
| 116 |
+
progress.update(progress_task, advance=1)
|
exception.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class MemeGeneratorException(Exception):
|
| 5 |
+
status_code: int = 520
|
| 6 |
+
|
| 7 |
+
def __init__(self, message: str):
|
| 8 |
+
self.message = message
|
| 9 |
+
|
| 10 |
+
def __str__(self) -> str:
|
| 11 |
+
return self.__repr__()
|
| 12 |
+
|
| 13 |
+
def __repr__(self) -> str:
|
| 14 |
+
return f"表情制作出错!{self.message}"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class NoSuchMeme(MemeGeneratorException):
|
| 18 |
+
status_code: int = 531
|
| 19 |
+
|
| 20 |
+
def __init__(self, meme_key: str):
|
| 21 |
+
self.meme_key = meme_key
|
| 22 |
+
message = f"表情“{self.meme_key}”不存在"
|
| 23 |
+
super().__init__(message)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TextOverLength(MemeGeneratorException):
|
| 27 |
+
status_code: int = 532
|
| 28 |
+
|
| 29 |
+
def __init__(self, text: str):
|
| 30 |
+
self.text = text
|
| 31 |
+
repr = text if len(text) <= 10 else (text[:10] + "...")
|
| 32 |
+
message = f"文本“{repr}”过长"
|
| 33 |
+
super().__init__(message)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class OpenImageFailed(MemeGeneratorException):
|
| 37 |
+
status_code: int = 533
|
| 38 |
+
|
| 39 |
+
def __init__(self, error_message: str):
|
| 40 |
+
self.error_message = error_message
|
| 41 |
+
message = f"图片加载失败({self.error_message})"
|
| 42 |
+
super().__init__(message)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ParamsMismatch(MemeGeneratorException):
|
| 46 |
+
status_code: int = 540
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ImageNumberMismatch(ParamsMismatch):
|
| 50 |
+
status_code: int = 541
|
| 51 |
+
|
| 52 |
+
def __init__(self, min_images: int = 0, max_images: int = 0):
|
| 53 |
+
self.min_images = min_images
|
| 54 |
+
self.max_images = max_images
|
| 55 |
+
message = f"图片数量不符,图片数量应为 {min_images}" + (
|
| 56 |
+
f" ~ {max_images}" if max_images > min_images else ""
|
| 57 |
+
)
|
| 58 |
+
super().__init__(message)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class TextNumberMismatch(ParamsMismatch):
|
| 62 |
+
status_code: int = 542
|
| 63 |
+
|
| 64 |
+
def __init__(self, min_texts: int = 0, max_texts: int = 0):
|
| 65 |
+
self.min_texts = min_texts
|
| 66 |
+
self.max_texts = max_texts
|
| 67 |
+
message = f"文本数量不符,文本数量应为 {min_texts}" + (
|
| 68 |
+
f" ~ {max_texts}" if max_texts > min_texts else ""
|
| 69 |
+
)
|
| 70 |
+
super().__init__(message)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TextOrNameNotEnough(ParamsMismatch):
|
| 74 |
+
status_code: int = 543
|
| 75 |
+
|
| 76 |
+
def __init__(self, message: Optional[str] = None):
|
| 77 |
+
message = message or "文本或用户名数量不足"
|
| 78 |
+
super().__init__(message)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ArgMismatch(ParamsMismatch):
|
| 82 |
+
status_code: int = 550
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ArgParserMismatch(ArgMismatch):
|
| 86 |
+
status_code: int = 551
|
| 87 |
+
|
| 88 |
+
def __init__(self, error_message: str):
|
| 89 |
+
self.error_message = error_message
|
| 90 |
+
message = f"参数解析失败({self.error_message})"
|
| 91 |
+
super().__init__(message)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class ArgModelMismatch(ArgMismatch):
|
| 95 |
+
status_code: int = 552
|
| 96 |
+
|
| 97 |
+
def __init__(self, error_message: str):
|
| 98 |
+
self.error_message = error_message
|
| 99 |
+
message = f"参数模型验证失败({self.error_message})"
|
| 100 |
+
super().__init__(message)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class MemeFeedback(MemeGeneratorException):
|
| 104 |
+
status_code: int = 560
|
log.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/nonebot/nonebot2/blob/master/nonebot/log.py
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
from typing import TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
import loguru
|
| 7 |
+
|
| 8 |
+
from .compat import model_dump
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from loguru import Logger, Record
|
| 12 |
+
|
| 13 |
+
logger: "Logger" = loguru.logger
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LoguruHandler(logging.Handler):
|
| 17 |
+
"""logging 与 loguru 之间的桥梁,将 logging 的日志转发到 loguru。"""
|
| 18 |
+
|
| 19 |
+
def emit(self, record: logging.LogRecord):
|
| 20 |
+
try:
|
| 21 |
+
level = logger.level(record.levelname).name
|
| 22 |
+
except ValueError:
|
| 23 |
+
level = record.levelno
|
| 24 |
+
|
| 25 |
+
frame, depth = logging.currentframe(), 2
|
| 26 |
+
while frame and frame.f_code.co_filename == logging.__file__:
|
| 27 |
+
frame = frame.f_back
|
| 28 |
+
depth += 1
|
| 29 |
+
|
| 30 |
+
logger.opt(depth=depth, exception=record.exc_info).log(
|
| 31 |
+
level, record.getMessage()
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# https://github.com/nonebot/nonebot2/blob/master/nonebot/drivers/fastapi.py#L182
|
| 36 |
+
LOGGING_CONFIG = {
|
| 37 |
+
"version": 1,
|
| 38 |
+
"disable_existing_loggers": False,
|
| 39 |
+
"handlers": {
|
| 40 |
+
"default": {
|
| 41 |
+
"class": "meme_generator.log.LoguruHandler",
|
| 42 |
+
},
|
| 43 |
+
},
|
| 44 |
+
"loggers": {
|
| 45 |
+
"uvicorn.error": {"handlers": ["default"], "level": "INFO"},
|
| 46 |
+
"uvicorn.access": {
|
| 47 |
+
"handlers": ["default"],
|
| 48 |
+
"level": "INFO",
|
| 49 |
+
},
|
| 50 |
+
},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def setup_logger():
|
| 55 |
+
from .config import config_file_path, meme_config
|
| 56 |
+
|
| 57 |
+
def default_filter(record: "Record"):
|
| 58 |
+
"""默认的日志过滤器,根据 `log_level` 配置改变日志等级。"""
|
| 59 |
+
log_level = meme_config.log.log_level
|
| 60 |
+
levelno = (
|
| 61 |
+
logger.level(log_level).no if isinstance(log_level, str) else log_level
|
| 62 |
+
)
|
| 63 |
+
return record["level"].no >= levelno
|
| 64 |
+
|
| 65 |
+
default_format: str = (
|
| 66 |
+
"<g>{time:MM-DD HH:mm:ss}</g> "
|
| 67 |
+
"[<lvl>{level}</lvl>] "
|
| 68 |
+
"<c><u>{name}</u></c> | "
|
| 69 |
+
# "<c>{function}:{line}</c>| "
|
| 70 |
+
"{message}"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
logger.remove()
|
| 74 |
+
logger.add(
|
| 75 |
+
sys.stdout,
|
| 76 |
+
level=0,
|
| 77 |
+
diagnose=False,
|
| 78 |
+
filter=default_filter,
|
| 79 |
+
format=default_format,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
logger.opt(colors=True).info(
|
| 83 |
+
f"Config file path: <y><d>{config_file_path.resolve()}</d></y>"
|
| 84 |
+
)
|
| 85 |
+
logger.opt(colors=True).debug(
|
| 86 |
+
f"Loaded config: <y><d>{model_dump(meme_config)}</d></y>"
|
| 87 |
+
)
|
manager.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import importlib.util
|
| 3 |
+
import pkgutil
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Optional, Union
|
| 7 |
+
|
| 8 |
+
from .config import meme_config
|
| 9 |
+
from .exception import NoSuchMeme
|
| 10 |
+
from .log import logger
|
| 11 |
+
from .meme import CommandShortcut, Meme, MemeArgsType, MemeFunction, MemeParamsType
|
| 12 |
+
|
| 13 |
+
_memes: dict[str, Meme] = {}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def path_to_module_name(path: Path) -> str:
|
| 17 |
+
rel_path = path.resolve().relative_to(Path.cwd().resolve())
|
| 18 |
+
if rel_path.stem == "__init__":
|
| 19 |
+
return ".".join(rel_path.parts[:-1])
|
| 20 |
+
else:
|
| 21 |
+
return ".".join(rel_path.parts[:-1] + (rel_path.stem,))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_meme(module_path: Union[str, Path]):
|
| 25 |
+
module_name = (
|
| 26 |
+
path_to_module_name(module_path)
|
| 27 |
+
if isinstance(module_path, Path)
|
| 28 |
+
else module_path
|
| 29 |
+
)
|
| 30 |
+
try:
|
| 31 |
+
importlib.import_module(module_name)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
logger.opt(colors=True, exception=e).error(f"Failed to import {module_path}!")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_memes(dir_path: Union[str, Path]):
|
| 37 |
+
if isinstance(dir_path, Path):
|
| 38 |
+
dir_path = str(dir_path.resolve())
|
| 39 |
+
|
| 40 |
+
for module_info in pkgutil.iter_modules([dir_path]):
|
| 41 |
+
if module_info.name.startswith("_"):
|
| 42 |
+
continue
|
| 43 |
+
if not (
|
| 44 |
+
module_spec := module_info.module_finder.find_spec(module_info.name, None)
|
| 45 |
+
):
|
| 46 |
+
continue
|
| 47 |
+
if not (module_path := module_spec.origin):
|
| 48 |
+
continue
|
| 49 |
+
if not (module_loader := module_spec.loader):
|
| 50 |
+
continue
|
| 51 |
+
try:
|
| 52 |
+
module = importlib.util.module_from_spec(module_spec)
|
| 53 |
+
module_loader.exec_module(module)
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.opt(colors=True, exception=e).error(
|
| 56 |
+
f"Failed to import {module_path}!"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def add_meme(
|
| 61 |
+
key: str,
|
| 62 |
+
function: MemeFunction,
|
| 63 |
+
*,
|
| 64 |
+
min_images: int = 0,
|
| 65 |
+
max_images: int = 0,
|
| 66 |
+
min_texts: int = 0,
|
| 67 |
+
max_texts: int = 0,
|
| 68 |
+
default_texts: list[str] = [],
|
| 69 |
+
args_type: Optional[MemeArgsType] = None,
|
| 70 |
+
keywords: list[str] = [],
|
| 71 |
+
shortcuts: list[CommandShortcut] = [],
|
| 72 |
+
tags: set[str] = set(),
|
| 73 |
+
date_created: datetime = datetime(2021, 5, 4),
|
| 74 |
+
date_modified: datetime = datetime.now(),
|
| 75 |
+
):
|
| 76 |
+
if key in _memes:
|
| 77 |
+
logger.warning(f'Meme with key "{key}" already exists!')
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
if key in meme_config.meme.meme_disabled_list:
|
| 81 |
+
logger.warning(f'The key "{key}" is in the disabled list!')
|
| 82 |
+
return
|
| 83 |
+
|
| 84 |
+
meme = Meme(
|
| 85 |
+
key,
|
| 86 |
+
function,
|
| 87 |
+
MemeParamsType(
|
| 88 |
+
min_images, max_images, min_texts, max_texts, default_texts, args_type
|
| 89 |
+
),
|
| 90 |
+
keywords=keywords,
|
| 91 |
+
shortcuts=shortcuts,
|
| 92 |
+
tags=tags,
|
| 93 |
+
date_created=date_created,
|
| 94 |
+
date_modified=date_modified,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
_memes[key] = meme
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_meme(key: str) -> Meme:
|
| 101 |
+
if key not in _memes:
|
| 102 |
+
raise NoSuchMeme(key)
|
| 103 |
+
return _memes[key]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def get_memes() -> list[Meme]:
|
| 107 |
+
return list(_memes.values())
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_meme_keys() -> list[str]:
|
| 111 |
+
return list(_memes.keys())
|
meme.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any, Callable, Literal, Optional, TypeVar, Union
|
| 6 |
+
|
| 7 |
+
from arclet.alconna import ArgFlag, Args, Empty, Option
|
| 8 |
+
from arclet.alconna.action import Action
|
| 9 |
+
from pil_utils import BuildImage
|
| 10 |
+
from pydantic import BaseModel, ValidationError
|
| 11 |
+
|
| 12 |
+
from .compat import type_validate_python
|
| 13 |
+
from .exception import (
|
| 14 |
+
ArgModelMismatch,
|
| 15 |
+
ImageNumberMismatch,
|
| 16 |
+
OpenImageFailed,
|
| 17 |
+
TextNumberMismatch,
|
| 18 |
+
TextOrNameNotEnough,
|
| 19 |
+
)
|
| 20 |
+
from .utils import random_image, random_text
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class UserInfo(BaseModel):
|
| 24 |
+
name: str = ""
|
| 25 |
+
gender: Literal["male", "female", "unknown"] = "unknown"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class MemeArgsModel(BaseModel):
|
| 29 |
+
user_infos: list[UserInfo] = []
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
ArgsModel = TypeVar("ArgsModel", bound=MemeArgsModel)
|
| 33 |
+
|
| 34 |
+
MemeFunction = Callable[[list[BuildImage], list[str], ArgsModel], BytesIO]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class ParserArg(BaseModel):
|
| 38 |
+
name: str
|
| 39 |
+
value: str
|
| 40 |
+
default: Optional[Any] = None
|
| 41 |
+
flags: Optional[list[ArgFlag]] = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ParserOption(BaseModel):
|
| 45 |
+
names: list[str]
|
| 46 |
+
args: Optional[list[ParserArg]] = None
|
| 47 |
+
dest: Optional[str] = None
|
| 48 |
+
default: Optional[Any] = None
|
| 49 |
+
action: Optional[Action] = None
|
| 50 |
+
help_text: Optional[str] = None
|
| 51 |
+
compact: bool = False
|
| 52 |
+
|
| 53 |
+
def option(self) -> Option:
|
| 54 |
+
args = Args()
|
| 55 |
+
for arg in self.args or []:
|
| 56 |
+
args.add(
|
| 57 |
+
name=arg.name,
|
| 58 |
+
value=arg.value,
|
| 59 |
+
default=arg.default or Empty,
|
| 60 |
+
flags=arg.flags,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
return Option(
|
| 64 |
+
name="|".join(self.names),
|
| 65 |
+
args=args,
|
| 66 |
+
dest=self.dest,
|
| 67 |
+
default=self.default or Empty,
|
| 68 |
+
action=self.action,
|
| 69 |
+
help_text=self.help_text,
|
| 70 |
+
compact=self.compact,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class CommandShortcut(BaseModel):
|
| 75 |
+
key: str
|
| 76 |
+
args: Optional[list[str]] = None
|
| 77 |
+
humanized: Optional[str] = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
class MemeArgsType:
|
| 82 |
+
args_model: type[MemeArgsModel]
|
| 83 |
+
args_examples: list[MemeArgsModel] = field(default_factory=list)
|
| 84 |
+
parser_options: list[ParserOption] = field(default_factory=list)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclass
|
| 88 |
+
class MemeParamsType:
|
| 89 |
+
min_images: int = 0
|
| 90 |
+
max_images: int = 0
|
| 91 |
+
min_texts: int = 0
|
| 92 |
+
max_texts: int = 0
|
| 93 |
+
default_texts: list[str] = field(default_factory=list)
|
| 94 |
+
args_type: Optional[MemeArgsType] = None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@dataclass
|
| 98 |
+
class Meme:
|
| 99 |
+
key: str
|
| 100 |
+
function: MemeFunction
|
| 101 |
+
params_type: MemeParamsType
|
| 102 |
+
keywords: list[str] = field(default_factory=list)
|
| 103 |
+
shortcuts: list[CommandShortcut] = field(default_factory=list)
|
| 104 |
+
tags: set[str] = field(default_factory=set)
|
| 105 |
+
date_created: datetime = datetime(2021, 5, 4)
|
| 106 |
+
date_modified: datetime = datetime.now()
|
| 107 |
+
|
| 108 |
+
def __call__(
|
| 109 |
+
self,
|
| 110 |
+
*,
|
| 111 |
+
images: Union[list[str], list[Path], list[bytes], list[BytesIO]] = [],
|
| 112 |
+
texts: list[str] = [],
|
| 113 |
+
args: dict[str, Any] = {},
|
| 114 |
+
) -> BytesIO:
|
| 115 |
+
if not (
|
| 116 |
+
self.params_type.min_images <= len(images) <= self.params_type.max_images
|
| 117 |
+
):
|
| 118 |
+
raise ImageNumberMismatch(
|
| 119 |
+
self.params_type.min_images, self.params_type.max_images
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
if not (self.params_type.min_texts <= len(texts) <= self.params_type.max_texts):
|
| 123 |
+
raise TextNumberMismatch(
|
| 124 |
+
self.params_type.min_texts, self.params_type.max_texts
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if args_type := self.params_type.args_type:
|
| 128 |
+
args_model = args_type.args_model
|
| 129 |
+
else:
|
| 130 |
+
args_model = MemeArgsModel
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
model = type_validate_python(args_model, args)
|
| 134 |
+
except ValidationError as e:
|
| 135 |
+
raise ArgModelMismatch(str(e))
|
| 136 |
+
|
| 137 |
+
imgs: list[BuildImage] = []
|
| 138 |
+
try:
|
| 139 |
+
for image in images:
|
| 140 |
+
if isinstance(image, bytes):
|
| 141 |
+
image = BytesIO(image)
|
| 142 |
+
imgs.append(BuildImage.open(image))
|
| 143 |
+
except Exception as e:
|
| 144 |
+
raise OpenImageFailed(str(e))
|
| 145 |
+
|
| 146 |
+
return self.function(imgs, texts, model)
|
| 147 |
+
|
| 148 |
+
def generate_preview(self, *, args: dict[str, Any] = {}) -> BytesIO:
|
| 149 |
+
default_images = [random_image() for _ in range(self.params_type.min_images)]
|
| 150 |
+
default_texts = (
|
| 151 |
+
self.params_type.default_texts.copy()
|
| 152 |
+
if (
|
| 153 |
+
self.params_type.min_texts
|
| 154 |
+
<= len(self.params_type.default_texts)
|
| 155 |
+
<= self.params_type.max_texts
|
| 156 |
+
)
|
| 157 |
+
else [random_text() for _ in range(self.params_type.min_texts)]
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def _generate_preview(images: list[bytes], texts: list[str]):
|
| 161 |
+
try:
|
| 162 |
+
return self.__call__(images=images, texts=texts, args=args)
|
| 163 |
+
except TextOrNameNotEnough:
|
| 164 |
+
texts.append(random_text())
|
| 165 |
+
return _generate_preview(images, texts)
|
| 166 |
+
|
| 167 |
+
return _generate_preview(default_images, default_texts)
|
memes/5000choyen/__init__.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
from PIL.Image import Image as IMG
|
| 4 |
+
from PIL.Image import Resampling, Transform
|
| 5 |
+
from pil_utils import BuildImage, Text2Image
|
| 6 |
+
from pil_utils.gradient import ColorStop, LinearGradient
|
| 7 |
+
|
| 8 |
+
from meme_generator import add_meme
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def fivethousand_choyen(images, texts: list[str], args):
|
| 12 |
+
fontsize = 200
|
| 13 |
+
font_families = ["Noto Sans SC"]
|
| 14 |
+
text = texts[0]
|
| 15 |
+
pos_x = 20
|
| 16 |
+
pos_y = 0
|
| 17 |
+
imgs: list[tuple[IMG, tuple[int, int]]] = []
|
| 18 |
+
|
| 19 |
+
def transform(img: IMG) -> IMG:
|
| 20 |
+
skew = 0.45
|
| 21 |
+
dw = round(img.height * skew)
|
| 22 |
+
return img.transform(
|
| 23 |
+
(img.width + dw, img.height),
|
| 24 |
+
Transform.AFFINE,
|
| 25 |
+
(1, skew, -dw, 0, 1, 0),
|
| 26 |
+
Resampling.BILINEAR,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def add_color_text(stroke_width: int, fill: str, pos: tuple[int, int]):
|
| 30 |
+
t2m = Text2Image.from_text(
|
| 31 |
+
text,
|
| 32 |
+
fontsize,
|
| 33 |
+
font_families=font_families,
|
| 34 |
+
fill=fill,
|
| 35 |
+
stroke_width=stroke_width,
|
| 36 |
+
stroke_fill=fill,
|
| 37 |
+
)
|
| 38 |
+
imgs.append(
|
| 39 |
+
(transform(t2m.to_image(padding=(20, 0))), (pos_x + pos[0], pos_y + pos[1]))
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def add_gradient_text(
|
| 43 |
+
stroke_width: int,
|
| 44 |
+
dir: tuple[int, int, int, int],
|
| 45 |
+
color_stops: list[tuple[float, tuple[int, int, int]]],
|
| 46 |
+
pos: tuple[int, int],
|
| 47 |
+
):
|
| 48 |
+
gradient = LinearGradient(
|
| 49 |
+
(dir[0] - pos_x, dir[1] - pos_y, dir[2] - pos_x, dir[3] - pos_y),
|
| 50 |
+
[ColorStop(*color_stop) for color_stop in color_stops],
|
| 51 |
+
)
|
| 52 |
+
paint = gradient.create_paint()
|
| 53 |
+
t2m = Text2Image.from_text(
|
| 54 |
+
text,
|
| 55 |
+
fontsize,
|
| 56 |
+
font_families=font_families,
|
| 57 |
+
fill=paint,
|
| 58 |
+
stroke_width=stroke_width,
|
| 59 |
+
stroke_fill=paint,
|
| 60 |
+
)
|
| 61 |
+
imgs.append(
|
| 62 |
+
(transform(t2m.to_image(padding=(20, 0))), (pos_x + pos[0], pos_y + pos[1]))
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# 黑
|
| 66 |
+
add_color_text(22, "black", (8, 8))
|
| 67 |
+
# 银
|
| 68 |
+
add_gradient_text(
|
| 69 |
+
20,
|
| 70 |
+
(0, 38, 0, 234),
|
| 71 |
+
[
|
| 72 |
+
(0.0, (0, 15, 36)),
|
| 73 |
+
(0.1, (255, 255, 255)),
|
| 74 |
+
(0.18, (55, 58, 59)),
|
| 75 |
+
(0.25, (55, 58, 59)),
|
| 76 |
+
(0.5, (200, 200, 200)),
|
| 77 |
+
(0.75, (55, 58, 59)),
|
| 78 |
+
(0.85, (25, 20, 31)),
|
| 79 |
+
(0.91, (240, 240, 240)),
|
| 80 |
+
(0.95, (166, 175, 194)),
|
| 81 |
+
(1, (50, 50, 50)),
|
| 82 |
+
],
|
| 83 |
+
(8, 8),
|
| 84 |
+
)
|
| 85 |
+
# 黑
|
| 86 |
+
add_color_text(16, "black", (0, 0))
|
| 87 |
+
# 金
|
| 88 |
+
add_gradient_text(
|
| 89 |
+
10,
|
| 90 |
+
(0, 40, 0, 200),
|
| 91 |
+
[
|
| 92 |
+
(0, (253, 241, 0)),
|
| 93 |
+
(0.25, (245, 253, 187)),
|
| 94 |
+
(0.4, (255, 255, 255)),
|
| 95 |
+
(0.75, (253, 219, 9)),
|
| 96 |
+
(0.9, (127, 53, 0)),
|
| 97 |
+
(1, (243, 196, 11)),
|
| 98 |
+
],
|
| 99 |
+
(0, 0),
|
| 100 |
+
)
|
| 101 |
+
# 黑
|
| 102 |
+
add_color_text(6, "black", (4, -6))
|
| 103 |
+
# 白
|
| 104 |
+
add_color_text(6, "white", (0, -6))
|
| 105 |
+
# 红
|
| 106 |
+
add_gradient_text(
|
| 107 |
+
4,
|
| 108 |
+
(0, 50, 0, 200),
|
| 109 |
+
[
|
| 110 |
+
(0, (255, 100, 0)),
|
| 111 |
+
(0.5, (123, 0, 0)),
|
| 112 |
+
(0.51, (240, 0, 0)),
|
| 113 |
+
(1, (5, 0, 0)),
|
| 114 |
+
],
|
| 115 |
+
(0, -6),
|
| 116 |
+
)
|
| 117 |
+
# 红
|
| 118 |
+
add_gradient_text(
|
| 119 |
+
0,
|
| 120 |
+
(0, 50, 0, 200),
|
| 121 |
+
[
|
| 122 |
+
(0, (230, 0, 0)),
|
| 123 |
+
(0.5, (123, 0, 0)),
|
| 124 |
+
(0.51, (240, 0, 0)),
|
| 125 |
+
(1, (5, 0, 0)),
|
| 126 |
+
],
|
| 127 |
+
(0, -6),
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
text = texts[1]
|
| 131 |
+
font_families = ["Noto Serif SC"]
|
| 132 |
+
pos_x = 280
|
| 133 |
+
pos_y = 260
|
| 134 |
+
# 黑
|
| 135 |
+
add_color_text(22, "black", (10, 4))
|
| 136 |
+
# 银
|
| 137 |
+
add_gradient_text(
|
| 138 |
+
19,
|
| 139 |
+
(0, 320, 0, 506),
|
| 140 |
+
[
|
| 141 |
+
(0, (0, 15, 36)),
|
| 142 |
+
(0.25, (250, 250, 250)),
|
| 143 |
+
(0.5, (150, 150, 150)),
|
| 144 |
+
(0.75, (55, 58, 59)),
|
| 145 |
+
(0.85, (25, 20, 31)),
|
| 146 |
+
(0.91, (240, 240, 240)),
|
| 147 |
+
(0.95, (166, 175, 194)),
|
| 148 |
+
(1, (50, 50, 50)),
|
| 149 |
+
],
|
| 150 |
+
(10, 4),
|
| 151 |
+
)
|
| 152 |
+
# 黑
|
| 153 |
+
add_color_text(17, "#10193A", (0, 0))
|
| 154 |
+
# 白
|
| 155 |
+
add_color_text(8, "#D0D0D0", (0, 0))
|
| 156 |
+
# 绀
|
| 157 |
+
add_gradient_text(
|
| 158 |
+
7,
|
| 159 |
+
(0, 320, 0, 480),
|
| 160 |
+
[
|
| 161 |
+
(0, (16, 25, 58)),
|
| 162 |
+
(0.03, (255, 255, 255)),
|
| 163 |
+
(0.08, (16, 25, 58)),
|
| 164 |
+
(0.2, (16, 25, 58)),
|
| 165 |
+
(1, (16, 25, 58)),
|
| 166 |
+
],
|
| 167 |
+
(0, 0),
|
| 168 |
+
)
|
| 169 |
+
# 银
|
| 170 |
+
add_gradient_text(
|
| 171 |
+
0,
|
| 172 |
+
(0, 320, 0, 480),
|
| 173 |
+
[
|
| 174 |
+
(0, (245, 246, 248)),
|
| 175 |
+
(0.15, (255, 255, 255)),
|
| 176 |
+
(0.35, (195, 213, 220)),
|
| 177 |
+
(0.5, (160, 190, 201)),
|
| 178 |
+
(0.51, (160, 190, 201)),
|
| 179 |
+
(0.52, (196, 215, 222)),
|
| 180 |
+
(1.0, (255, 255, 255)),
|
| 181 |
+
],
|
| 182 |
+
(0, -6),
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
img_h = 580
|
| 186 |
+
img_w = max([img.width + pos[0] for img, pos in imgs])
|
| 187 |
+
frame = BuildImage.new("RGBA", (img_w, img_h), "white")
|
| 188 |
+
for img, pos in imgs:
|
| 189 |
+
frame.paste(img, pos, alpha=True)
|
| 190 |
+
return frame.save_jpg()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
add_meme(
|
| 194 |
+
"5000choyen",
|
| 195 |
+
fivethousand_choyen,
|
| 196 |
+
min_texts=2,
|
| 197 |
+
max_texts=2,
|
| 198 |
+
default_texts=["我去", "洛天依"],
|
| 199 |
+
keywords=["5000兆"],
|
| 200 |
+
date_created=datetime(2022, 10, 29),
|
| 201 |
+
date_modified=datetime(2024, 11, 2),
|
| 202 |
+
)
|
memes/abstinence/__init__.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import dateparser
|
| 5 |
+
from pil_utils import BuildImage
|
| 6 |
+
from pydantic import Field
|
| 7 |
+
|
| 8 |
+
from meme_generator import (
|
| 9 |
+
MemeArgsModel,
|
| 10 |
+
MemeArgsType,
|
| 11 |
+
ParserArg,
|
| 12 |
+
ParserOption,
|
| 13 |
+
add_meme,
|
| 14 |
+
)
|
| 15 |
+
from meme_generator.exception import TextOverLength
|
| 16 |
+
|
| 17 |
+
img_dir = Path(__file__).parent / "images"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Model(MemeArgsModel):
|
| 21 |
+
time: str = Field("", description="指定时间")
|
| 22 |
+
name: str = Field("", description="指定名字")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
args_type = MemeArgsType(
|
| 26 |
+
args_model=Model,
|
| 27 |
+
parser_options=[
|
| 28 |
+
ParserOption(
|
| 29 |
+
names=["-t", "--time"],
|
| 30 |
+
args=[ParserArg(name="time", value="str")],
|
| 31 |
+
help_text="指定时间",
|
| 32 |
+
),
|
| 33 |
+
ParserOption(
|
| 34 |
+
names=["-n", "--name"],
|
| 35 |
+
args=[ParserArg(name="name", value="str")],
|
| 36 |
+
help_text="指定名字",
|
| 37 |
+
),
|
| 38 |
+
],
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def abstinence(images: list[BuildImage], texts: list[str], args: Model):
|
| 43 |
+
time = datetime.now()
|
| 44 |
+
if args.time and (parsed_time := dateparser.parse(args.time)):
|
| 45 |
+
time = parsed_time
|
| 46 |
+
name = args.name or (args.user_infos[-1].name if args.user_infos else "")
|
| 47 |
+
|
| 48 |
+
img = (
|
| 49 |
+
images[0]
|
| 50 |
+
.convert("RGBA")
|
| 51 |
+
.resize((300, 300), keep_ratio=True, inside=True, bg_color="white")
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
frame = BuildImage.open(img_dir / "base.png").convert("RGBA")
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
frame.paste(img, (80, 400))
|
| 58 |
+
frame.draw_bbcode_text(
|
| 59 |
+
(150, 650, 760, 800),
|
| 60 |
+
text=f"戒导人:[u] {name} [/u]",
|
| 61 |
+
max_fontsize=20,
|
| 62 |
+
min_fontsize=10,
|
| 63 |
+
halign="center",
|
| 64 |
+
)
|
| 65 |
+
except ValueError:
|
| 66 |
+
raise TextOverLength(name)
|
| 67 |
+
frame.draw_bbcode_text(
|
| 68 |
+
(150, 750, 760, 800),
|
| 69 |
+
text=f"[u] {time.year} [/u]年[u] {time.month} [/u]月[u] {time.day} [/u]日",
|
| 70 |
+
max_fontsize=20,
|
| 71 |
+
min_fontsize=10,
|
| 72 |
+
halign="center",
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
stamp = BuildImage.open(img_dir / "stamp.png").convert("RGBA")
|
| 76 |
+
stamp = stamp.resize((200, 200))
|
| 77 |
+
frame.paste(stamp, (350, 650), alpha=True)
|
| 78 |
+
|
| 79 |
+
return frame.save_jpg()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
add_meme(
|
| 83 |
+
"abstinence",
|
| 84 |
+
abstinence,
|
| 85 |
+
min_images=1,
|
| 86 |
+
max_images=1,
|
| 87 |
+
min_texts=0,
|
| 88 |
+
max_texts=0,
|
| 89 |
+
args_type=args_type,
|
| 90 |
+
keywords=["戒导"],
|
| 91 |
+
date_created=datetime(2024, 12, 13),
|
| 92 |
+
date_modified=datetime(2024, 12, 14),
|
| 93 |
+
)
|
memes/abstinence/images/base.png
ADDED
|
Git LFS Details
|
memes/abstinence/images/stamp.png
ADDED
|
memes/ace_attorney_dialog/__init__.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from pil_utils import BuildImage, Text2Image
|
| 6 |
+
|
| 7 |
+
from meme_generator import add_meme
|
| 8 |
+
from meme_generator.exception import TextOverLength
|
| 9 |
+
|
| 10 |
+
img_dir = Path(__file__).parent / "images"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def ace_attorney_dialog(images, texts: list[str], args):
|
| 14 |
+
def shadow_text(text: str, fontsize: int) -> BuildImage:
|
| 15 |
+
fontname = "PangMenZhengDao-Cu"
|
| 16 |
+
inner = Text2Image.from_text(
|
| 17 |
+
text,
|
| 18 |
+
fontsize,
|
| 19 |
+
fill="#e60012",
|
| 20 |
+
font_families=[fontname],
|
| 21 |
+
stroke_width=4,
|
| 22 |
+
stroke_fill="#500000",
|
| 23 |
+
).to_image()
|
| 24 |
+
shadow_width = 10
|
| 25 |
+
shadow = Text2Image.from_text(
|
| 26 |
+
text,
|
| 27 |
+
fontsize,
|
| 28 |
+
fill="#500000",
|
| 29 |
+
font_families=[fontname],
|
| 30 |
+
stroke_width=shadow_width,
|
| 31 |
+
stroke_fill="#500000",
|
| 32 |
+
).to_image()
|
| 33 |
+
dy = 30
|
| 34 |
+
dx = 15
|
| 35 |
+
img = BuildImage.new(
|
| 36 |
+
"RGBA", (inner.width + dx + shadow_width, inner.height + dy + shadow_width)
|
| 37 |
+
)
|
| 38 |
+
img.paste(shadow, (dx - shadow_width, dy - shadow_width), alpha=True)
|
| 39 |
+
img.paste(inner, (0, 0), alpha=True)
|
| 40 |
+
return img
|
| 41 |
+
|
| 42 |
+
text = texts[0]
|
| 43 |
+
text_imgs: list[BuildImage] = []
|
| 44 |
+
for char in text:
|
| 45 |
+
text_imgs.append(shadow_text(char, 650))
|
| 46 |
+
|
| 47 |
+
total_width = sum(img.width for img in text_imgs)
|
| 48 |
+
if total_width > 4000:
|
| 49 |
+
raise TextOverLength(text)
|
| 50 |
+
|
| 51 |
+
def combine_text(text_imgs: list[BuildImage]) -> BuildImage:
|
| 52 |
+
ratio = 0.4
|
| 53 |
+
text_w = sum(img.width for img in text_imgs) - sum(
|
| 54 |
+
round(img.width * ratio) for img in text_imgs[1:]
|
| 55 |
+
)
|
| 56 |
+
text_h = max(img.height for img in text_imgs)
|
| 57 |
+
text_img = BuildImage.new("RGBA", (text_w, text_h))
|
| 58 |
+
x = 0
|
| 59 |
+
for img in text_imgs:
|
| 60 |
+
text_img.paste(img, (x, round((text_h - img.height) / 2)), alpha=True)
|
| 61 |
+
x += img.width - round(img.width * ratio)
|
| 62 |
+
return text_img
|
| 63 |
+
|
| 64 |
+
frame = BuildImage.open(img_dir / "bubble.png")
|
| 65 |
+
mark = BuildImage.open(img_dir / "mark.png")
|
| 66 |
+
|
| 67 |
+
if total_width <= 2000:
|
| 68 |
+
text_img = combine_text(text_imgs)
|
| 69 |
+
max_width = 900
|
| 70 |
+
if total_width > max_width:
|
| 71 |
+
text_img = text_img.resize(
|
| 72 |
+
(max_width, round(max_width / text_img.width * text_img.height))
|
| 73 |
+
)
|
| 74 |
+
text_img = text_img.rotate(10, expand=True)
|
| 75 |
+
frame.paste(
|
| 76 |
+
text_img,
|
| 77 |
+
(
|
| 78 |
+
round((frame.width - text_img.width) / 2),
|
| 79 |
+
round((frame.height - text_img.height) / 2),
|
| 80 |
+
),
|
| 81 |
+
alpha=True,
|
| 82 |
+
)
|
| 83 |
+
frame.paste(mark, (630, 230), alpha=True)
|
| 84 |
+
|
| 85 |
+
else:
|
| 86 |
+
index = math.ceil(len(text_imgs) / 2)
|
| 87 |
+
text_img1 = combine_text(text_imgs[:index])
|
| 88 |
+
text_img2 = combine_text(text_imgs[index:])
|
| 89 |
+
ratio = 0.6
|
| 90 |
+
text_img1 = text_img1.resize(
|
| 91 |
+
(round(text_img1.width * ratio), round(text_img1.height * ratio))
|
| 92 |
+
)
|
| 93 |
+
text_img2 = text_img2.resize(
|
| 94 |
+
(round(text_img2.width * ratio), round(text_img2.height * ratio))
|
| 95 |
+
)
|
| 96 |
+
text_img1 = text_img1.rotate(10, expand=True)
|
| 97 |
+
text_img2 = text_img2.rotate(10, expand=True)
|
| 98 |
+
frame.paste(
|
| 99 |
+
text_img1,
|
| 100 |
+
(round((frame.width - text_img1.width) / 2) - 50, 775 - text_img1.height),
|
| 101 |
+
alpha=True,
|
| 102 |
+
)
|
| 103 |
+
frame.paste(
|
| 104 |
+
text_img2,
|
| 105 |
+
(round((frame.width - text_img2.width) / 2) + 50, 325),
|
| 106 |
+
alpha=True,
|
| 107 |
+
)
|
| 108 |
+
frame.paste(mark, (680, 320), alpha=True)
|
| 109 |
+
|
| 110 |
+
return frame.save_png()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
add_meme(
|
| 114 |
+
"ace_attorney_dialog",
|
| 115 |
+
ace_attorney_dialog,
|
| 116 |
+
min_texts=1,
|
| 117 |
+
max_texts=1,
|
| 118 |
+
default_texts=["表情包制作"],
|
| 119 |
+
keywords=["逆转裁判气泡"],
|
| 120 |
+
date_created=datetime(2024, 5, 3),
|
| 121 |
+
date_modified=datetime(2024, 5, 3),
|
| 122 |
+
)
|
memes/ace_attorney_dialog/images/bubble.png
ADDED
|
memes/ace_attorney_dialog/images/mark.png
ADDED
|
memes/acg_entrance/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pil_utils import BuildImage
|
| 5 |
+
|
| 6 |
+
from meme_generator import add_meme
|
| 7 |
+
from meme_generator.exception import TextOverLength
|
| 8 |
+
from meme_generator.utils import make_jpg_or_gif
|
| 9 |
+
|
| 10 |
+
img_dir = Path(__file__).parent / "images"
|
| 11 |
+
|
| 12 |
+
default_text = "走,跟我去二次元吧"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def acg_entrance(images: list[BuildImage], texts: list[str], args):
|
| 16 |
+
text = texts[0] if texts else default_text
|
| 17 |
+
frame = BuildImage.open(img_dir / "0.png")
|
| 18 |
+
try:
|
| 19 |
+
frame.draw_text(
|
| 20 |
+
(30, 720, frame.width - 30, 810),
|
| 21 |
+
text,
|
| 22 |
+
max_fontsize=50,
|
| 23 |
+
min_fontsize=25,
|
| 24 |
+
fill="white",
|
| 25 |
+
)
|
| 26 |
+
except ValueError:
|
| 27 |
+
raise TextOverLength(text)
|
| 28 |
+
|
| 29 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 30 |
+
img = imgs[0].convert("RGBA").resize((290, 410), keep_ratio=True)
|
| 31 |
+
return frame.copy().paste(img, (190, 265), below=True)
|
| 32 |
+
|
| 33 |
+
return make_jpg_or_gif(images, make)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
add_meme(
|
| 37 |
+
"acg_entrance",
|
| 38 |
+
acg_entrance,
|
| 39 |
+
min_images=1,
|
| 40 |
+
max_images=1,
|
| 41 |
+
min_texts=0,
|
| 42 |
+
max_texts=1,
|
| 43 |
+
default_texts=[default_text],
|
| 44 |
+
keywords=["二次元入口"],
|
| 45 |
+
date_created=datetime(2023, 3, 30),
|
| 46 |
+
date_modified=datetime(2023, 3, 30),
|
| 47 |
+
)
|
memes/acg_entrance/images/0.png
ADDED
|
Git LFS Details
|
memes/add_chaos/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pil_utils import BuildImage
|
| 5 |
+
|
| 6 |
+
from meme_generator import add_meme
|
| 7 |
+
from meme_generator.utils import make_jpg_or_gif
|
| 8 |
+
|
| 9 |
+
img_dir = Path(__file__).parent / "images"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def add_chaos(images: list[BuildImage], texts, args):
|
| 13 |
+
banner = BuildImage.open(img_dir / "0.png")
|
| 14 |
+
|
| 15 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 16 |
+
return imgs[0].convert("RGBA").resize_width(240).paste(banner)
|
| 17 |
+
|
| 18 |
+
return make_jpg_or_gif(images, make)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
add_meme(
|
| 22 |
+
"add_chaos",
|
| 23 |
+
add_chaos,
|
| 24 |
+
min_images=1,
|
| 25 |
+
max_images=1,
|
| 26 |
+
keywords=["添乱", "给社会添乱"],
|
| 27 |
+
date_created=datetime(2023, 6, 21),
|
| 28 |
+
date_modified=datetime(2023, 6, 21),
|
| 29 |
+
)
|
memes/add_chaos/images/0.png
ADDED
|
memes/addiction/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pil_utils import BuildImage
|
| 5 |
+
|
| 6 |
+
from meme_generator import add_meme
|
| 7 |
+
from meme_generator.exception import TextOverLength
|
| 8 |
+
from meme_generator.utils import make_jpg_or_gif
|
| 9 |
+
|
| 10 |
+
img_dir = Path(__file__).parent / "images"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def addiction(images: list[BuildImage], texts: list[str], args):
|
| 14 |
+
frame = BuildImage.open(img_dir / "0.png")
|
| 15 |
+
|
| 16 |
+
if texts:
|
| 17 |
+
text = texts[0]
|
| 18 |
+
frame = frame.resize_canvas((246, 286), direction="north", bg_color="white")
|
| 19 |
+
try:
|
| 20 |
+
frame.draw_text((10, 246, 236, 286), texts[0], max_fontsize=45)
|
| 21 |
+
except ValueError:
|
| 22 |
+
raise TextOverLength(text)
|
| 23 |
+
|
| 24 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 25 |
+
img = imgs[0].convert("RGBA").resize((91, 91), keep_ratio=True)
|
| 26 |
+
return frame.copy().paste(img, alpha=True)
|
| 27 |
+
|
| 28 |
+
return make_jpg_or_gif(images, make)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
add_meme(
|
| 32 |
+
"addiction",
|
| 33 |
+
addiction,
|
| 34 |
+
min_images=1,
|
| 35 |
+
max_images=1,
|
| 36 |
+
min_texts=0,
|
| 37 |
+
max_texts=1,
|
| 38 |
+
keywords=["上瘾", "毒瘾发作"],
|
| 39 |
+
date_created=datetime(2022, 8, 17),
|
| 40 |
+
date_modified=datetime(2023, 2, 14),
|
| 41 |
+
)
|
memes/addiction/images/0.png
ADDED
|
memes/alike/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
from pil_utils import BuildImage
|
| 4 |
+
|
| 5 |
+
from meme_generator import add_meme
|
| 6 |
+
from meme_generator.utils import make_jpg_or_gif
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def alike(images: list[BuildImage], texts, args):
|
| 10 |
+
frame = BuildImage.new("RGBA", (470, 180), "white")
|
| 11 |
+
frame.draw_text(
|
| 12 |
+
(10, 10, 185, 140), "你怎么跟", max_fontsize=40, min_fontsize=30, halign="right"
|
| 13 |
+
).draw_text(
|
| 14 |
+
(365, 10, 460, 140), "一样", max_fontsize=40, min_fontsize=30, halign="left"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 18 |
+
img = imgs[0].convert("RGBA").resize((150, 150), keep_ratio=True)
|
| 19 |
+
return frame.copy().paste(img, (200, 15), alpha=True)
|
| 20 |
+
|
| 21 |
+
return make_jpg_or_gif(images, make)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
add_meme(
|
| 25 |
+
"alike",
|
| 26 |
+
alike,
|
| 27 |
+
min_images=1,
|
| 28 |
+
max_images=1,
|
| 29 |
+
keywords=["一样"],
|
| 30 |
+
date_created=datetime(2022, 1, 2),
|
| 31 |
+
date_modified=datetime(2023, 2, 22),
|
| 32 |
+
)
|
memes/alipay/__init__.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import qrcode
|
| 5 |
+
from pil_utils import BuildImage
|
| 6 |
+
from pydantic import Field
|
| 7 |
+
from qrcode.image.pil import PilImage
|
| 8 |
+
|
| 9 |
+
from meme_generator import (
|
| 10 |
+
MemeArgsModel,
|
| 11 |
+
MemeArgsType,
|
| 12 |
+
ParserArg,
|
| 13 |
+
ParserOption,
|
| 14 |
+
add_meme,
|
| 15 |
+
)
|
| 16 |
+
from meme_generator.exception import TextOrNameNotEnough, TextOverLength
|
| 17 |
+
|
| 18 |
+
img_dir = Path(__file__).parent / "images"
|
| 19 |
+
|
| 20 |
+
help_text = "二维码内容"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Model(MemeArgsModel):
|
| 24 |
+
message: str = Field("", description=help_text)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
args_type = MemeArgsType(
|
| 28 |
+
args_model=Model,
|
| 29 |
+
parser_options=[
|
| 30 |
+
ParserOption(
|
| 31 |
+
names=["-m", "--message"],
|
| 32 |
+
args=[ParserArg(name="message", value="str")],
|
| 33 |
+
help_text=help_text,
|
| 34 |
+
),
|
| 35 |
+
],
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
default_message = "https://github.com/MemeCrafters/meme-generator"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def alipay(images: list[BuildImage], texts: list[str], args: Model):
|
| 42 |
+
message = args.message or default_message
|
| 43 |
+
if not texts and not args.user_infos:
|
| 44 |
+
raise TextOrNameNotEnough()
|
| 45 |
+
name = texts[0] if texts else args.user_infos[0].name
|
| 46 |
+
avatar = images[0]
|
| 47 |
+
|
| 48 |
+
frame = BuildImage.open(img_dir / "0.png")
|
| 49 |
+
|
| 50 |
+
qr = qrcode.QRCode(version=5, border=0, error_correction=qrcode.ERROR_CORRECT_Q)
|
| 51 |
+
qr.add_data(message)
|
| 52 |
+
qr.make(fit=True)
|
| 53 |
+
qr_img = BuildImage(qr.make_image(image_factory=PilImage)) # type: ignore
|
| 54 |
+
qr_img = qr_img.resize((658, 658))
|
| 55 |
+
frame.paste(qr_img, (211, 606))
|
| 56 |
+
|
| 57 |
+
block = BuildImage.new("RGBA", (116, 116), "white").circle_corner(12)
|
| 58 |
+
frame.paste(block, (482, 877), alpha=True)
|
| 59 |
+
|
| 60 |
+
avatar = avatar.convert("RGBA").resize((108, 108), keep_ratio=True).circle_corner(8)
|
| 61 |
+
frame.paste(avatar, (486, 881), alpha=True)
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
frame.draw_text(
|
| 65 |
+
(230, 1290, 850, 1380),
|
| 66 |
+
name,
|
| 67 |
+
allow_wrap=False,
|
| 68 |
+
max_fontsize=70,
|
| 69 |
+
min_fontsize=40,
|
| 70 |
+
fill="black",
|
| 71 |
+
)
|
| 72 |
+
except ValueError:
|
| 73 |
+
raise TextOverLength(name)
|
| 74 |
+
|
| 75 |
+
return frame.save_jpg()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
add_meme(
|
| 79 |
+
"alipay",
|
| 80 |
+
alipay,
|
| 81 |
+
min_images=1,
|
| 82 |
+
max_images=1,
|
| 83 |
+
min_texts=0,
|
| 84 |
+
max_texts=1,
|
| 85 |
+
args_type=args_type,
|
| 86 |
+
keywords=["支付宝支付"],
|
| 87 |
+
date_created=datetime(2024, 10, 30),
|
| 88 |
+
date_modified=datetime(2024, 10, 30),
|
| 89 |
+
)
|
memes/alipay/images/0.png
ADDED
|
Git LFS Details
|
memes/always/__init__.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
from arclet.alconna import store_value
|
| 5 |
+
from pil_utils import BuildImage
|
| 6 |
+
from pydantic import Field
|
| 7 |
+
|
| 8 |
+
from meme_generator import (
|
| 9 |
+
CommandShortcut,
|
| 10 |
+
MemeArgsModel,
|
| 11 |
+
MemeArgsType,
|
| 12 |
+
ParserArg,
|
| 13 |
+
ParserOption,
|
| 14 |
+
add_meme,
|
| 15 |
+
)
|
| 16 |
+
from meme_generator.utils import (
|
| 17 |
+
FrameAlignPolicy,
|
| 18 |
+
Maker,
|
| 19 |
+
make_gif_or_combined_gif,
|
| 20 |
+
make_jpg_or_gif,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
help_text = "生成模式,包含 normal、loop、circle"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Model(MemeArgsModel):
|
| 27 |
+
mode: Literal["normal", "loop", "circle"] = Field("normal", description=help_text)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
args_type = MemeArgsType(
|
| 31 |
+
args_model=Model,
|
| 32 |
+
args_examples=[Model(mode="normal"), Model(mode="circle"), Model(mode="loop")],
|
| 33 |
+
parser_options=[
|
| 34 |
+
ParserOption(
|
| 35 |
+
names=["--mode"],
|
| 36 |
+
args=[ParserArg(name="mode", value="str")],
|
| 37 |
+
help_text=help_text,
|
| 38 |
+
),
|
| 39 |
+
ParserOption(
|
| 40 |
+
names=["--circle", "套娃"],
|
| 41 |
+
dest="mode",
|
| 42 |
+
action=store_value("circle"),
|
| 43 |
+
help_text="套娃模式",
|
| 44 |
+
),
|
| 45 |
+
ParserOption(
|
| 46 |
+
names=["--loop", "循环"],
|
| 47 |
+
dest="mode",
|
| 48 |
+
action=store_value("loop"),
|
| 49 |
+
help_text="循环模式",
|
| 50 |
+
),
|
| 51 |
+
],
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def always_normal(img: BuildImage):
|
| 56 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 57 |
+
img = imgs[0]
|
| 58 |
+
img_big = img.convert("RGBA").resize_width(500)
|
| 59 |
+
img_small = img.convert("RGBA").resize_width(100)
|
| 60 |
+
h1 = img_big.height
|
| 61 |
+
h2 = max(img_small.height, 80)
|
| 62 |
+
frame = BuildImage.new("RGBA", (500, h1 + h2 + 10), "white")
|
| 63 |
+
frame.paste(img_big, alpha=True).paste(
|
| 64 |
+
img_small, (290, h1 + 5 + (h2 - img_small.height) // 2), alpha=True
|
| 65 |
+
)
|
| 66 |
+
frame.draw_text(
|
| 67 |
+
(20, h1 + 5, 280, h1 + h2 + 5), "要我一直", halign="right", max_fontsize=60
|
| 68 |
+
)
|
| 69 |
+
frame.draw_text(
|
| 70 |
+
(400, h1 + 5, 480, h1 + h2 + 5), "吗", halign="left", max_fontsize=60
|
| 71 |
+
)
|
| 72 |
+
return frame
|
| 73 |
+
|
| 74 |
+
return make_jpg_or_gif([img], make)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def always_always(img: BuildImage, loop: bool = False):
|
| 78 |
+
tmp_img = img.convert("RGBA").resize_width(500)
|
| 79 |
+
img_h = tmp_img.height
|
| 80 |
+
text_h = tmp_img.resize_width(100).height + tmp_img.resize_width(20).height + 10
|
| 81 |
+
text_h = max(text_h, 80)
|
| 82 |
+
frame_h = img_h + text_h
|
| 83 |
+
text_frame = BuildImage.new("RGBA", (500, frame_h), "white")
|
| 84 |
+
text_frame.draw_text(
|
| 85 |
+
(0, img_h, 280, frame_h), "要我一直", halign="right", max_fontsize=60
|
| 86 |
+
).draw_text((400, img_h, 500, frame_h), "吗", halign="left", max_fontsize=60)
|
| 87 |
+
|
| 88 |
+
frame_num = 20
|
| 89 |
+
coeff = 5 ** (1 / frame_num)
|
| 90 |
+
|
| 91 |
+
def maker(i: int) -> Maker:
|
| 92 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 93 |
+
img = imgs[0].convert("RGBA").resize_width(500)
|
| 94 |
+
base_frame = text_frame.copy().paste(img, alpha=True)
|
| 95 |
+
frame = BuildImage.new("RGBA", base_frame.size, "white")
|
| 96 |
+
r = coeff**i
|
| 97 |
+
for _ in range(4):
|
| 98 |
+
x = round(358 * (1 - r))
|
| 99 |
+
y = round(frame_h * (1 - r))
|
| 100 |
+
w = round(500 * r)
|
| 101 |
+
h = round(frame_h * r)
|
| 102 |
+
frame.paste(base_frame.resize((w, h)), (x, y))
|
| 103 |
+
r /= 5
|
| 104 |
+
return frame
|
| 105 |
+
|
| 106 |
+
return make
|
| 107 |
+
|
| 108 |
+
if not loop:
|
| 109 |
+
return make_jpg_or_gif([img], maker(0))
|
| 110 |
+
|
| 111 |
+
return make_gif_or_combined_gif(
|
| 112 |
+
[img], maker, frame_num, 0.1, FrameAlignPolicy.extend_loop
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def always(images: list[BuildImage], texts, args: Model):
|
| 117 |
+
img = images[0]
|
| 118 |
+
mode = args.mode
|
| 119 |
+
|
| 120 |
+
if mode == "normal":
|
| 121 |
+
return always_normal(img)
|
| 122 |
+
elif mode == "circle":
|
| 123 |
+
return always_always(img, loop=False)
|
| 124 |
+
else:
|
| 125 |
+
return always_always(img, loop=True)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
add_meme(
|
| 129 |
+
"always",
|
| 130 |
+
always,
|
| 131 |
+
min_images=1,
|
| 132 |
+
max_images=1,
|
| 133 |
+
args_type=args_type,
|
| 134 |
+
keywords=["一直"],
|
| 135 |
+
shortcuts=[CommandShortcut(key="一直一直", args=["--loop"])],
|
| 136 |
+
date_created=datetime(2021, 12, 2),
|
| 137 |
+
date_modified=datetime(2024, 8, 9),
|
| 138 |
+
)
|
memes/always_like/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from pil_utils import BuildImage, Text2Image
|
| 6 |
+
|
| 7 |
+
from meme_generator import MemeArgsModel, add_meme
|
| 8 |
+
from meme_generator.exception import TextOrNameNotEnough, TextOverLength
|
| 9 |
+
|
| 10 |
+
img_dir = Path(__file__).parent / "images"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def always_like(images: list[BuildImage], texts: list[str], args: MemeArgsModel):
|
| 14 |
+
names = [info.name for info in args.user_infos]
|
| 15 |
+
|
| 16 |
+
if len(images) > len(texts) + len(names):
|
| 17 |
+
raise TextOrNameNotEnough()
|
| 18 |
+
texts = texts + names
|
| 19 |
+
|
| 20 |
+
img = images[0].convert("RGBA")
|
| 21 |
+
name = texts[0]
|
| 22 |
+
text = "我永远喜欢" + name
|
| 23 |
+
|
| 24 |
+
frame = BuildImage.open(img_dir / "0.png")
|
| 25 |
+
frame.paste(
|
| 26 |
+
img.resize((350, 400), keep_ratio=True, inside=True), (25, 35), alpha=True
|
| 27 |
+
)
|
| 28 |
+
try:
|
| 29 |
+
frame.draw_text(
|
| 30 |
+
(20, 470, frame.width - 20, 570),
|
| 31 |
+
text,
|
| 32 |
+
max_fontsize=70,
|
| 33 |
+
min_fontsize=30,
|
| 34 |
+
font_style="bold",
|
| 35 |
+
)
|
| 36 |
+
except ValueError:
|
| 37 |
+
raise TextOverLength(text)
|
| 38 |
+
|
| 39 |
+
def random_color():
|
| 40 |
+
return random.choice(
|
| 41 |
+
["red", "darkorange", "gold", "darkgreen", "blue", "cyan", "purple"]
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if len(images) > 1:
|
| 45 |
+
text_w = Text2Image.from_text(text, 70).longest_line
|
| 46 |
+
ratio = min((frame.width - 40) / text_w, 1)
|
| 47 |
+
text_w *= ratio
|
| 48 |
+
name_w = Text2Image.from_text(name, 70).longest_line * ratio
|
| 49 |
+
start_w = text_w - name_w + (frame.width - text_w) // 2
|
| 50 |
+
frame.draw_line(
|
| 51 |
+
(start_w, 525, start_w + name_w, 525), fill=random_color(), width=10
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
current_h = 400
|
| 55 |
+
for i, (image, name) in enumerate(zip(images[1:], texts[1:]), start=1):
|
| 56 |
+
img = image.convert("RGBA")
|
| 57 |
+
frame.paste(
|
| 58 |
+
img.resize((350, 400), keep_ratio=True, inside=True),
|
| 59 |
+
(10 + random.randint(0, 50), 20 + random.randint(0, 70)),
|
| 60 |
+
alpha=True,
|
| 61 |
+
)
|
| 62 |
+
try:
|
| 63 |
+
frame.draw_text(
|
| 64 |
+
(400, current_h, frame.width - 20, current_h + 80),
|
| 65 |
+
name,
|
| 66 |
+
max_fontsize=70,
|
| 67 |
+
min_fontsize=30,
|
| 68 |
+
font_style="bold",
|
| 69 |
+
)
|
| 70 |
+
except ValueError:
|
| 71 |
+
raise TextOverLength(text)
|
| 72 |
+
|
| 73 |
+
if len(images) > i + 1:
|
| 74 |
+
name_w = min(Text2Image.from_text(name, 70).longest_line, 380)
|
| 75 |
+
start_w = 400 + (410 - name_w) // 2
|
| 76 |
+
line_h = current_h + 40
|
| 77 |
+
frame.draw_line(
|
| 78 |
+
(start_w, line_h, start_w + name_w, line_h),
|
| 79 |
+
fill=random_color(),
|
| 80 |
+
width=10,
|
| 81 |
+
)
|
| 82 |
+
current_h -= 70
|
| 83 |
+
return frame.save_jpg()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
add_meme(
|
| 87 |
+
"always_like",
|
| 88 |
+
always_like,
|
| 89 |
+
min_images=1,
|
| 90 |
+
max_images=6,
|
| 91 |
+
min_texts=0,
|
| 92 |
+
max_texts=6,
|
| 93 |
+
keywords=["我永远喜欢"],
|
| 94 |
+
date_created=datetime(2022, 3, 14),
|
| 95 |
+
date_modified=datetime(2023, 2, 14),
|
| 96 |
+
)
|
memes/always_like/images/0.png
ADDED
|
memes/anti_kidnap/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pil_utils import BuildImage
|
| 5 |
+
|
| 6 |
+
from meme_generator import add_meme
|
| 7 |
+
|
| 8 |
+
img_dir = Path(__file__).parent / "images"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def anti_kidnap(images: list[BuildImage], texts, args):
|
| 12 |
+
img = images[0].convert("RGBA").resize((450, 450), keep_ratio=True)
|
| 13 |
+
frame = BuildImage.open(img_dir / "0.png")
|
| 14 |
+
frame.paste(img, (30, 78), below=True)
|
| 15 |
+
return frame.save_jpg()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
add_meme(
|
| 19 |
+
"anti_kidnap",
|
| 20 |
+
anti_kidnap,
|
| 21 |
+
min_images=1,
|
| 22 |
+
max_images=1,
|
| 23 |
+
keywords=["防诱拐"],
|
| 24 |
+
date_created=datetime(2022, 7, 9),
|
| 25 |
+
date_modified=datetime(2023, 2, 14),
|
| 26 |
+
)
|
memes/anti_kidnap/images/0.png
ADDED
|
Git LFS Details
|
memes/anya_suki/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pil_utils import BuildImage
|
| 5 |
+
|
| 6 |
+
from meme_generator import add_meme
|
| 7 |
+
from meme_generator.exception import TextOverLength
|
| 8 |
+
from meme_generator.tags import MemeTags
|
| 9 |
+
from meme_generator.utils import make_jpg_or_gif
|
| 10 |
+
|
| 11 |
+
img_dir = Path(__file__).parent / "images"
|
| 12 |
+
|
| 13 |
+
default_text = "阿尼亚喜欢这个"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def anya_suki(images: list[BuildImage], texts: list[str], args):
|
| 17 |
+
text = texts[0] if texts else default_text
|
| 18 |
+
frame = BuildImage.open(img_dir / "0.png")
|
| 19 |
+
try:
|
| 20 |
+
frame.draw_text(
|
| 21 |
+
(5, frame.height - 60, frame.width - 5, frame.height - 10),
|
| 22 |
+
text,
|
| 23 |
+
max_fontsize=40,
|
| 24 |
+
fill="white",
|
| 25 |
+
stroke_fill="black",
|
| 26 |
+
stroke_ratio=0.06,
|
| 27 |
+
)
|
| 28 |
+
except ValueError:
|
| 29 |
+
raise TextOverLength(text)
|
| 30 |
+
|
| 31 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 32 |
+
img = imgs[0].convert("RGBA").resize((305, 235), keep_ratio=True)
|
| 33 |
+
return frame.copy().paste(img, (106, 72), below=True)
|
| 34 |
+
|
| 35 |
+
return make_jpg_or_gif(images, make)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
add_meme(
|
| 39 |
+
"anya_suki",
|
| 40 |
+
anya_suki,
|
| 41 |
+
min_images=1,
|
| 42 |
+
max_images=1,
|
| 43 |
+
min_texts=0,
|
| 44 |
+
max_texts=1,
|
| 45 |
+
default_texts=[default_text],
|
| 46 |
+
keywords=["阿尼亚喜欢"],
|
| 47 |
+
tags=MemeTags.anya,
|
| 48 |
+
date_created=datetime(2022, 5, 10),
|
| 49 |
+
date_modified=datetime(2023, 2, 14),
|
| 50 |
+
)
|
memes/anya_suki/images/0.png
ADDED
|
Git LFS Details
|
memes/applaud/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from PIL.Image import Image as IMG
|
| 5 |
+
from pil_utils import BuildImage
|
| 6 |
+
|
| 7 |
+
from meme_generator import add_meme
|
| 8 |
+
from meme_generator.utils import save_gif
|
| 9 |
+
|
| 10 |
+
img_dir = Path(__file__).parent / "images"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def applaud(images: list[BuildImage], texts, args):
|
| 14 |
+
img = images[0].convert("RGBA").square().resize((110, 110))
|
| 15 |
+
frames: list[IMG] = []
|
| 16 |
+
locs = [
|
| 17 |
+
(109, 102, 27, 17),
|
| 18 |
+
(107, 105, 28, 15),
|
| 19 |
+
(110, 106, 27, 14),
|
| 20 |
+
(109, 106, 27, 14),
|
| 21 |
+
(107, 108, 29, 12),
|
| 22 |
+
]
|
| 23 |
+
for i in range(5):
|
| 24 |
+
frame = BuildImage.open(img_dir / f"{i}.png")
|
| 25 |
+
w, h, x, y = locs[i]
|
| 26 |
+
frame.paste(img.resize((w, h)), (x, y), below=True)
|
| 27 |
+
frames.append(frame.image)
|
| 28 |
+
return save_gif(frames, 0.1)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
add_meme(
|
| 32 |
+
"applaud",
|
| 33 |
+
applaud,
|
| 34 |
+
min_images=1,
|
| 35 |
+
max_images=1,
|
| 36 |
+
keywords=["鼓掌"],
|
| 37 |
+
date_created=datetime(2023, 1, 8),
|
| 38 |
+
date_modified=datetime(2023, 2, 14),
|
| 39 |
+
)
|
memes/applaud/images/0.png
ADDED
|
memes/applaud/images/1.png
ADDED
|
memes/applaud/images/2.png
ADDED
|
memes/applaud/images/3.png
ADDED
|
memes/applaud/images/4.png
ADDED
|
memes/arona_throw/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
from pil_utils import BuildImage
|
| 5 |
+
|
| 6 |
+
from meme_generator import add_meme
|
| 7 |
+
from meme_generator.tags import MemeTags
|
| 8 |
+
from meme_generator.utils import FrameAlignPolicy, Maker, make_gif_or_combined_gif
|
| 9 |
+
|
| 10 |
+
img_dir = Path(__file__).parent / "images"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def arona_throw(images: list[BuildImage], texts, args):
|
| 14 |
+
position_list = [
|
| 15 |
+
(270, 295),
|
| 16 |
+
(154, 291),
|
| 17 |
+
(154, 291),
|
| 18 |
+
(89, 211),
|
| 19 |
+
(41, 195),
|
| 20 |
+
(28, 192),
|
| 21 |
+
(16, 200),
|
| 22 |
+
(-10, 206),
|
| 23 |
+
(-40, 210),
|
| 24 |
+
(-80, 214),
|
| 25 |
+
(324, 245),
|
| 26 |
+
(324, 256),
|
| 27 |
+
(331, 251),
|
| 28 |
+
(331, 251),
|
| 29 |
+
(318, 260),
|
| 30 |
+
(318, 260),
|
| 31 |
+
]
|
| 32 |
+
position_list2 = [
|
| 33 |
+
(324, 15),
|
| 34 |
+
(324, 106),
|
| 35 |
+
(324, 161),
|
| 36 |
+
(324, 192),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
def maker(i: int) -> Maker:
|
| 40 |
+
def make(imgs: list[BuildImage]) -> BuildImage:
|
| 41 |
+
pyroxenes = (
|
| 42 |
+
imgs[0].convert("RGBA").resize((120, 120), keep_ratio=True).circle()
|
| 43 |
+
)
|
| 44 |
+
arona = BuildImage.open(img_dir / f"{i}.png").convert("RGBA")
|
| 45 |
+
arona.paste(pyroxenes, position_list[i], alpha=True)
|
| 46 |
+
if i in [6, 7, 8, 9]:
|
| 47 |
+
arona.paste(pyroxenes, position_list2[i - 6], alpha=True)
|
| 48 |
+
return arona
|
| 49 |
+
|
| 50 |
+
return make
|
| 51 |
+
|
| 52 |
+
return make_gif_or_combined_gif(images, maker, 16, 0.04, FrameAlignPolicy.no_extend)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
add_meme(
|
| 56 |
+
"arona_throw",
|
| 57 |
+
arona_throw,
|
| 58 |
+
min_images=1,
|
| 59 |
+
max_images=1,
|
| 60 |
+
keywords=["阿罗娜扔"],
|
| 61 |
+
tags=MemeTags.arona,
|
| 62 |
+
date_created=datetime(2024, 12, 10),
|
| 63 |
+
date_modified=datetime(2024, 12, 10),
|
| 64 |
+
)
|
memes/arona_throw/images/0.png
ADDED
|
memes/arona_throw/images/1.png
ADDED
|
memes/arona_throw/images/10.png
ADDED
|
memes/arona_throw/images/11.png
ADDED
|
memes/arona_throw/images/12.png
ADDED
|
memes/arona_throw/images/13.png
ADDED
|
memes/arona_throw/images/14.png
ADDED
|
memes/arona_throw/images/15.png
ADDED
|