1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
| import sys import os import json import tempfile import subprocess import urllib.request import urllib.error from datetime import datetime
API_URL = "http://localhost:11434/api/chat" MODEL = "gemma4:e4b-mlx"
PROMPT_TEMPLATE = """请阅读以下动态内容,为这条动态生成 3 个社交媒体风格的标签。 要求: 1. 标签要像社交媒体的 hashtag,简洁、有话题感,适合日常分享 2. 只输出标签,用中文逗号分隔,不要输出其他任何内容 3. 格式示例:日常,美食,生活感悟 {existing_tags_section} 动态内容: """
def read_file(path): with open(path, "r", encoding="utf-8") as f: return f.read()
def write_file(path, content): with open(path, "w", encoding="utf-8") as f: f.write(content)
def append_file(path, content): with open(path, "a", encoding="utf-8") as f: f.write(content)
def build_prompt(essay_content, existing_tags): if existing_tags: tags_str = "、".join(sorted(existing_tags)) section = "4. 以下是本站已有的标签列表,请优先从中选择合适的标签复用,只有当已有标签无法概括时才生成新标签:\n" + tags_str else: section = "" return PROMPT_TEMPLATE.format(existing_tags_section=section) + essay_content
def call_api(essay_content, existing_tags): headers = { "Content-Type": "application/json", } payload = { "model": MODEL, "messages": [{"role": "user", "content": build_prompt(essay_content, existing_tags)}], "stream": False, "temperature": 0.3, } body = json.dumps(payload).encode("utf-8") req = urllib.request.Request(API_URL, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req) as resp: result = json.loads(resp.read().decode("utf-8")) return result["message"]["content"].strip() except urllib.error.HTTPError as e: print("API HTTP error: {} {}".format(e.code, e.reason)) return None except urllib.error.URLError as e: print("API request failed: {}".format(e.reason)) return None
def parse_tags(response): if not response: return [] for sep in [",", ","]: if sep in response: tags = [t.strip().strip('"').strip("'").strip("#") for t in response.split(sep)] tags = [t for t in tags if t] return tags[:3] return [response.strip().strip('"').strip("'").strip("#")][:3]
def load_existing_tags(tags_file): if not os.path.exists(tags_file): return set() content = read_file(tags_file).strip() if not content: return set() return set(line.strip() for line in content.split("\n") if line.strip())
def save_tags_diff(tags_file, new_tags, existing_tags): diff = [t for t in new_tags if t not in existing_tags] all_tags = sorted(existing_tags | set(new_tags)) write_file(tags_file, "\n".join(all_tags) + "\n") if diff: print("New tags added to essay-tags.md: " + ", ".join(diff)) else: print("No new tags to add to essay-tags.md")
def edit_in_vim(initial_text: str = "") -> str | None: editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or "vim" with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8", delete=False, dir="/tmp", suffix=".txt") as f: tmp_path = f.name f.write(initial_text) f.flush() try: stat_before = os.stat(tmp_path) subprocess.run([editor, tmp_path], check=True) stat_after = os.stat(tmp_path) if stat_before.st_mtime_ns == stat_after.st_mtime_ns and stat_before.st_size == stat_after.st_size: return None with open(tmp_path, "r", encoding="utf-8") as fr: return fr.read() finally: os.unlink(tmp_path)
def build_shuoshuo_yaml_entry(dt: datetime, raw_text: str, tags: list[str]) -> str: date_str = dt.strftime("%Y-%m-%d %H:%M:%S") text_stripped = raw_text.rstrip("\n") lines = text_stripped.splitlines()
if len(lines) <= 1: content_block = f" content: {text_stripped}" else: content_block = " content: |-\n" content_block += "\n".join(f" {line}" for line in lines)
tag_lines = " tags:\n" for t in tags: tag_lines += f" - {t}\n"
entry = f"""\n- date: {date_str} {content_block} {tag_lines}""" return entry
def main(): script_dir = os.path.dirname(os.path.abspath(__file__)) tags_file = os.path.join(script_dir, "essay-tags.md") shuoshuo_yml = os.path.join(script_dir, "source", "_data", "shuoshuo.yml")
print("Launch Vim for writing shuoshuo.yml") user_text = edit_in_vim(initial_text="") if user_text is None: print("User cancelled / no content modified, exit.") sys.exit(0) user_text = user_text.rstrip("\n") if not user_text.strip(): print("Empty content, exit.") sys.exit(0)
existing_tags = load_existing_tags(tags_file) print(f"Existing tags count: {len(existing_tags)}") print("Calling LLM to generate 3 tags")
api_resp = call_api(user_text, existing_tags) if api_resp is None: print("API call failed, abort adding this shuoshuo entry.") sys.exit(1)
print(f"API response: {api_resp}") tags = parse_tags(api_resp) while len(tags) < 3: tags.append("日常") tags = tags[:3] print(f"Generated tags: {', '.join(tags)}")
now = datetime.now() new_entry = build_shuoshuo_yaml_entry(now, user_text, tags)
append_file(shuoshuo_yml, new_entry) print(f"Success appended entry into {shuoshuo_yml}")
refreshed_existing = load_existing_tags(tags_file) save_tags_diff(tags_file, tags, refreshed_existing)
if __name__ == "__main__": main()
|