poemcard 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: poemcard
3
+ Version: 0.1.0
4
+ Summary: Poem card generator
5
+ Author: Group66
6
+ Project-URL: Homepage, https://github.com/wenyuchen66/66
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: Pillow>=9.0
10
+
11
+ # poemcard
12
+ Group project for acrostic poem card generator
13
+
14
+ ## Installation
15
+ Install package directly from GitHub
16
+ ```bash
17
+ pip install git+https://github.com/wenyuchen66/66.git
18
+ ```
19
+
20
+ ## Import Example
21
+ ```python
22
+ import poemcard
23
+ ```
@@ -0,0 +1,13 @@
1
+ # poemcard
2
+ Group project for acrostic poem card generator
3
+
4
+ ## Installation
5
+ Install package directly from GitHub
6
+ ```bash
7
+ pip install git+https://github.com/wenyuchen66/66.git
8
+ ```
9
+
10
+ ## Import Example
11
+ ```python
12
+ import poemcard
13
+ ```
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "poemcard"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name="Group66" }
10
+ ]
11
+ description = "Poem card generator"
12
+ requires-python = ">=3.9"
13
+ dependencies = [
14
+ "Pillow>=9.0"
15
+ ]
16
+ readme = "README.md"
17
+ [project.urls]
18
+ "Homepage" = "https://github.com/wenyuchen66/66"
19
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,59 @@
1
+ import argparse
2
+ import sys
3
+ from .generator import generate_poem
4
+ from .validation import validate_poem
5
+ from .visualizer import render_card
6
+
7
+
8
+ def main():
9
+ parser = argparse.ArgumentParser(description="Acrostic Poem System - All-in-One English Acrostic CLI" )
10
+ parser.add_argument("word", type=str, help="Acrostic word (3–8 English letters, e.g., CODE)" )
11
+ parser.add_argument("--theme", type=str, required=True, help="Poem theme (e.g., Python debugging)")
12
+ parser.add_argument("--output",type=str,default="poem.png",help="Output path for the exported poem card PNG (default: poem.png)",)
13
+ args = parser.parse_args()
14
+
15
+ print(f"\n [Pipeline] Command received -> Acrostic word: {args.word} | Theme: {args.theme}")
16
+ # Step 1: Calling generation module
17
+
18
+ print("Step 1: Calling generation module...")
19
+ try:
20
+ poem_lines = generate_poem(args.word, args.theme)
21
+ except Exception as e:
22
+ print(f" Generation module error: {e}")
23
+ sys.exit(1)
24
+ # Step 2: Calling validation module
25
+ print("Step 2: Calling validation module...")
26
+ errors = validate_poem(args.word, poem_lines)
27
+ if errors:
28
+ print(" Validation check failed:")
29
+ for err in errors:
30
+ print(f" -{err}")
31
+ sys.exit(1)
32
+ print(" Validation passed!")
33
+ #正式版可删
34
+ # 3. Used for previewing in the terminal
35
+ print("\n" + "=" * 40)
36
+ for line in poem_lines:
37
+ print(" ", line)
38
+ print("=" * 40 + "\n")
39
+
40
+ # Step 3: Invoking real visual rendering and export module
41
+ print(f"Step 3: Invoking layout & rendering module, exporting to {args.output}...")
42
+ try:
43
+ # Generating PNG
44
+ render_card(poem_lines, args.output)
45
+ print(f" Success! Poem card rendered and saved to local file: {args.output}")
46
+ except Exception as e:
47
+ print(f" Failed to render or export image: {e}")
48
+ sys.exit(1)
49
+ #正式版可删
50
+ print("\n Clear!\n")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
55
+
56
+
57
+
58
+
59
+
@@ -0,0 +1,4 @@
1
+ from .generator import generate_poem
2
+ from .validation import validate_poem
3
+ from .visualizer import render_card
4
+ from . import Englishpoem
@@ -0,0 +1,152 @@
1
+ """Generate English acrostics with a local Ollama language model.
2
+
3
+ Public interface: generate_poem(word, theme) -> list[str].
4
+ Requires Python 3.9+ and a running Ollama server with the chosen model.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import re
10
+ from urllib.error import HTTPError, URLError
11
+ from urllib.request import Request, urlopen
12
+
13
+
14
+ DEFAULT_MODEL = "qwen2.5:3b"
15
+ _INSTRUCTIONS = (
16
+ "Write English acrostic poems in simple, natural language. "
17
+ "Use concrete details about the theme to tell a small, coherent story. "
18
+ "Each verse should be a meaningful phrase of about 6 to 12 words. "
19
+ "Start each verse with a normal English word beginning with the requested letter. "
20
+ "Rhyme is optional. Return a JSON object with one verse per requested field. "
21
+ "Exclude headings, numbering, Markdown, and isolated acrostic letters."
22
+ )
23
+
24
+
25
+ def _request_poem(messages: list[dict], schema: dict) -> str:
26
+ model = os.environ.get("POEM_MODEL", DEFAULT_MODEL)
27
+ base_url = os.environ.get("POEM_OLLAMA_URL", "http://127.0.0.1:11434")
28
+ request = Request(
29
+ base_url.rstrip("/") + "/api/chat",
30
+ data=json.dumps({
31
+ "model": model,
32
+ "messages": messages,
33
+ "stream": False,
34
+ "format": schema,
35
+ "options": {"temperature": 0.7, "num_predict": 800},
36
+ }).encode("utf-8"),
37
+ headers={"Content-Type": "application/json"},
38
+ )
39
+ try:
40
+ with urlopen(request, timeout=120) as response:
41
+ content = json.load(response)["message"]["content"]
42
+ except HTTPError as exc:
43
+ if exc.code == 404:
44
+ raise RuntimeError(f"Model unavailable. Download it with: ollama pull {model}") from exc
45
+ raise RuntimeError(f"Ollama returned HTTP {exc.code}. Check the Ollama server.") from exc
46
+ except (URLError, OSError) as exc:
47
+ raise RuntimeError(
48
+ "Could not connect to Ollama or generation timed out. "
49
+ "Start Ollama and check POEM_OLLAMA_URL."
50
+ ) from exc
51
+ except (KeyError, TypeError, ValueError) as exc:
52
+ raise RuntimeError("Ollama returned an invalid response.") from exc
53
+ if not isinstance(content, str):
54
+ raise RuntimeError("Ollama returned invalid poem content.")
55
+ return content
56
+
57
+
58
+ def generate_poem(word: str, theme: str) -> list[str]:
59
+ """Return an English acrostic about a freely supplied theme.
60
+
61
+ word must contain 3–8 ASCII letters, ignoring surrounding whitespace.
62
+ Letter comparisons ignore case. theme must be a nonempty string.
63
+ Returns a list containing one verse per letter, in order.
64
+ Raises ValueError for invalid input and RuntimeError if generation fails.
65
+ """
66
+ if not isinstance(word, str) or not re.fullmatch(r"[A-Za-z]{3,8}", word.strip()):
67
+ raise ValueError("word must contain 3 to 8 English letters (A–Z).")
68
+ if not isinstance(theme, str) or not theme.strip():
69
+ raise ValueError("theme must be a nonempty string.")
70
+
71
+ initials = word.strip().upper()
72
+ fields = [f"line_{index}" for index in range(1, len(initials) + 1)]
73
+ schema = {
74
+ "type": "object",
75
+ "properties": {
76
+ field: {
77
+ "type": "string",
78
+ "description": f"A verse starting with an English word beginning with {letter}.",
79
+ "pattern": rf"^[{letter}{letter.lower()}][^\r\n]+$",
80
+ }
81
+ for field, letter in zip(fields, initials)
82
+ },
83
+ "required": fields,
84
+ "additionalProperties": False,
85
+ }
86
+ prompt = (
87
+ f"Write an English poem specifically about {json.dumps(theme.strip(), ensure_ascii=False)}. "
88
+ "Show someone experiencing this theme through concrete actions and details. "
89
+ f"Write exactly {len(initials)} lines.\n"
90
+ "Return a JSON object with the following verses in order:\n"
91
+ + "\n".join(
92
+ f"{field} must begin with an English word starting with {letter}."
93
+ for field, letter in zip(fields, initials)
94
+ )
95
+ )
96
+ messages = [
97
+ {"role": "system", "content": _INSTRUCTIONS},
98
+ {"role": "user", "content": prompt},
99
+ ]
100
+ for attempt in range(3):
101
+ content = _request_poem(messages, schema)
102
+ try:
103
+ poem = json.loads(content)
104
+ except json.JSONDecodeError:
105
+ poem = None
106
+ if isinstance(poem, dict) and poem.keys() == schema["properties"].keys():
107
+ lines = [poem[field].strip() if isinstance(poem[field], str) else "" for field in fields]
108
+ if all(
109
+ len(line.splitlines()) == 1
110
+ and len(line.split()) > 1
111
+ and line[0].isascii()
112
+ and line[0].upper() == letter
113
+ for line, letter in zip(lines, initials)
114
+ ):
115
+ return lines
116
+ if attempt < 2:
117
+ messages.append({
118
+ "role": "user",
119
+ "content": (
120
+ "The previous output had an invalid structure. Generate the whole poem again. "
121
+ f"Return exactly these fields in order: {', '.join(fields)}. "
122
+ f"Their first letters must be {', '.join(initials)}. "
123
+ "Each field must contain one complete line."
124
+ ),
125
+ })
126
+ raise RuntimeError(f"The model failed to produce a valid {initials} poem after 3 attempts.")
127
+
128
+
129
+ def _main() -> None:
130
+ print("英文藏头诗生成器\n")
131
+ while True:
132
+ try:
133
+ word = input("藏头词(3–8 个英文字母,直接回车退出)> ")
134
+ if not word.strip():
135
+ return
136
+ theme = input("主题(自由填写)> ")
137
+ print("正在写诗…", flush=True)
138
+ lines = generate_poem(word, theme)
139
+ except (EOFError, KeyboardInterrupt):
140
+ print()
141
+ return
142
+ except ValueError as error:
143
+ print(f"输入有误。{error}\n")
144
+ except RuntimeError as error:
145
+ print(f"生成失败。{error}\n")
146
+ else:
147
+ print(f"\n{word.strip().upper()} / {theme.strip()}")
148
+ print(*lines, sep="\n", end="\n\n")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ _main()
@@ -0,0 +1,30 @@
1
+ """Check whether the first letters of a poem spell a given word."""
2
+
3
+ import re
4
+
5
+
6
+ def validate_poem(word: str, lines: list[str]) -> list[str]:
7
+ """Return an empty list for a valid acrostic, or a list of errors.
8
+
9
+ The word must contain 3 to 8 ASCII letters. Surrounding whitespace
10
+ and letter case are ignored. Each list entry counts as one line,
11
+ including blank entries. Leading whitespace in a line is ignored.
12
+ """
13
+ if not isinstance(word, str) or re.fullmatch(r"[A-Za-z]{3,8}", word.strip()) is None:
14
+ return ["The acrostic word must contain 3 to 8 English letters."]
15
+ if not isinstance(lines, list) or any(not isinstance(line, str) for line in lines):
16
+ return ["Poem lines must be provided as a list of strings."]
17
+
18
+ word = word.strip().upper()
19
+ errors = []
20
+ if len(lines) != len(word):
21
+ errors.append(f"Expected {len(word)} lines, got {len(lines)}.")
22
+
23
+ for number, (expected, line) in enumerate(zip(word, lines), start=1):
24
+ first = line.lstrip()[:1]
25
+ if not first:
26
+ errors.append(f"Line {number}: expected {expected}, but the line is blank.")
27
+ elif not first.isascii() or first.upper() != expected:
28
+ errors.append(f"Line {number}: expected {expected}, got {first.upper()!r}.")
29
+
30
+ return errors
@@ -0,0 +1,80 @@
1
+ from PIL import Image, ImageDraw, ImageFont
2
+ import os
3
+
4
+ correct_poem = []
5
+
6
+
7
+ WIDTH, HEIGHT = 900, 550
8
+
9
+ # 生成从上到下的渐变背景
10
+ def make_gradient(width, height, c1, c2):
11
+ img = Image.new("RGB", (width, height))
12
+ draw = ImageDraw.Draw(img)
13
+ for y in range(height):
14
+ r = int(c1[0] * (1 - y / height) + c2[0] * (y / height))
15
+ g = int(c1[1] * (1 - y / height) + c2[1] * (y / height))
16
+ b = int(c1[2] * (1 - y / height) + c2[2] * (y / height))
17
+ draw.line((0, y, width, y), fill=(r, g, b))
18
+ return img
19
+
20
+ def render_card(poem_lines: list[str], output: str="poem.png") -> None:
21
+
22
+ # 柔和渐变:米黄 → 浅淡蓝紫
23
+ img = make_gradient(WIDTH, HEIGHT, (255, 250, 235), (225, 235, 255))
24
+ draw = ImageDraw.Draw(img)
25
+
26
+ # 字体
27
+ try:
28
+ font = ImageFont.truetype("Helvetica.ttc", 28)
29
+ big_font = ImageFont.truetype("Helvetica.ttc", 36)
30
+ except:
31
+ font = ImageFont.load_default()
32
+ big_font = ImageFont.load_default()
33
+
34
+ TITLE_COLOR = (60, 70, 90)
35
+ TEXT_COLOR = (30, 30, 30)
36
+ CODE_COLOR = (180, 20, 60) # 高亮红色
37
+ LINE_COLOR = (180, 180, 180)
38
+
39
+ # 参考线(如果调试排版布局可以用来参考)
40
+ #draw.line((WIDTH / 2, 0, WIDTH / 2, HEIGHT), fill=LINE_COLOR, width=1)
41
+ #draw.line((0, HEIGHT / 2, WIDTH, HEIGHT / 2), fill=LINE_COLOR, width=1)
42
+
43
+ # 标题
44
+ title = ""
45
+ bbox_title = draw.textbbox((0, 0), title, font=big_font)
46
+ tw = bbox_title[2] - bbox_title[0]
47
+ draw.text(((WIDTH - tw) / 2, 25), title, font=big_font, fill=TITLE_COLOR)
48
+
49
+
50
+ # 关键:固定首字母列
51
+ margin_top = 140
52
+ line_gap = 55
53
+ # 固定:所有首字母都在这一列
54
+ FIXED_CODE_X = 220
55
+
56
+ print("===== 排版调试信息 =====")
57
+ y = margin_top
58
+
59
+ for idx, line in enumerate(poem_lines):
60
+ if not line:
61
+ continue
62
+ first_char = line[0]
63
+ rest_text = line[1:]
64
+
65
+ # 首字母(固定 x)
66
+ draw.text((FIXED_CODE_X, y), first_char, font=font, fill=CODE_COLOR)
67
+
68
+ # 剩余文字紧跟在首字母后面
69
+ bbox_code = draw.textbbox((0, 0), first_char, font=font)
70
+ char_width = bbox_code[2] - bbox_code[0]
71
+ rest_x = FIXED_CODE_X + char_width
72
+
73
+ draw.text((rest_x, y), rest_text, font=font, fill=TEXT_COLOR)
74
+
75
+ print(f"第 {idx+1} 行 | y={y:.0f} | 首字母 x = {FIXED_CODE_X}")
76
+ y += line_gap
77
+
78
+ # 保存到桌面
79
+ img.save(output)
80
+ print(f"\n✅ 诗歌卡片已成功保存至:{output}")
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: poemcard
3
+ Version: 0.1.0
4
+ Summary: Poem card generator
5
+ Author: Group66
6
+ Project-URL: Homepage, https://github.com/wenyuchen66/66
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: Pillow>=9.0
10
+
11
+ # poemcard
12
+ Group project for acrostic poem card generator
13
+
14
+ ## Installation
15
+ Install package directly from GitHub
16
+ ```bash
17
+ pip install git+https://github.com/wenyuchen66/66.git
18
+ ```
19
+
20
+ ## Import Example
21
+ ```python
22
+ import poemcard
23
+ ```
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/poemcard/Englishpoem.py
4
+ src/poemcard/__init__.py
5
+ src/poemcard/generator.py
6
+ src/poemcard/validation.py
7
+ src/poemcard/visualizer.py
8
+ src/poemcard.egg-info/PKG-INFO
9
+ src/poemcard.egg-info/SOURCES.txt
10
+ src/poemcard.egg-info/dependency_links.txt
11
+ src/poemcard.egg-info/requires.txt
12
+ src/poemcard.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ Pillow>=9.0
@@ -0,0 +1 @@
1
+ poemcard