sophhub 0.1.0

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.
Files changed (125) hide show
  1. package/bin/sophhub.js +21 -0
  2. package/package.json +32 -0
  3. package/skills/VERSIONS.md +27 -0
  4. package/skills/builtin/clawhub/SKILL.md +77 -0
  5. package/skills/builtin/flight-booking/SKILL.md +288 -0
  6. package/skills/builtin/flight-booking/scripts/flight_booking.py +1232 -0
  7. package/skills/builtin/inventory-management/SKILL.md +241 -0
  8. package/skills/builtin/inventory-management/scripts/inventory.py +1844 -0
  9. package/skills/builtin/schedule-reminder/SKILL.md +619 -0
  10. package/skills/builtin/schedule-reminder/schedule_template.md +68 -0
  11. package/skills/builtin/schedule-reminder/scripts/append_event.py +204 -0
  12. package/skills/builtin/schedule-reminder/scripts/create_reminders.sh +163 -0
  13. package/skills/builtin/schedule-reminder/scripts/daily_activate.sh +175 -0
  14. package/skills/builtin/schedule-reminder/scripts/parse_schedule.py +704 -0
  15. package/skills/builtin/schedule-reminder/scripts/setup.sh +242 -0
  16. package/skills/builtin/schedule-reminder//347/224/250/346/210/267/346/214/207/345/215/227.md +311 -0
  17. package/skills/builtin/skill-creator/SKILL.md +370 -0
  18. package/skills/builtin/skill-creator/license.txt +202 -0
  19. package/skills/builtin/skill-creator/scripts/init_skill.py +378 -0
  20. package/skills/builtin/skill-creator/scripts/package_skill.py +111 -0
  21. package/skills/builtin/skill-creator/scripts/quick_validate.py +101 -0
  22. package/skills/builtin/sophnet-customer-management/SKILL.md +271 -0
  23. package/skills/builtin/sophnet-customer-management/pyproject.toml +15 -0
  24. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/__init__.py +2 -0
  25. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/__main__.py +5 -0
  26. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/cli.py +67 -0
  27. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/commands/__init__.py +2 -0
  28. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/commands/customer.py +60 -0
  29. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/commands/export_file.py +18 -0
  30. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/commands/import_file.py +15 -0
  31. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/commands/reminder.py +26 -0
  32. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/commands/schema.py +28 -0
  33. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_cli/config.py +54 -0
  34. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/__init__.py +2 -0
  35. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/exporter.py +85 -0
  36. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/models.py +84 -0
  37. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/normalizer.py +144 -0
  38. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/parser.py +241 -0
  39. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/query.py +109 -0
  40. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/reminder.py +121 -0
  41. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/repository.py +397 -0
  42. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/schema.py +106 -0
  43. package/skills/builtin/sophnet-customer-management/src/customer_mgmt_core/service.py +565 -0
  44. package/skills/builtin/sophnet-customer-management/uv.lock +48 -0
  45. package/skills/builtin/sophnet-customized-marketing/SKILL.md +144 -0
  46. package/skills/builtin/sophnet-customized-marketing/playbooks/campaign-planning.md +187 -0
  47. package/skills/builtin/sophnet-customized-marketing/playbooks/content-generation.md +124 -0
  48. package/skills/builtin/sophnet-customized-marketing/playbooks/marketing-calendar.md +59 -0
  49. package/skills/builtin/sophnet-customized-marketing/playbooks/multi-channel-bundle.md +94 -0
  50. package/skills/builtin/sophnet-customized-marketing/playbooks/poster-generation.md +182 -0
  51. package/skills/builtin/sophnet-customized-marketing/playbooks/style-profile-workflow.md +103 -0
  52. package/skills/builtin/sophnet-customized-marketing/pyproject.toml +9 -0
  53. package/skills/builtin/sophnet-customized-marketing/references/campaign-mechanics.md +168 -0
  54. package/skills/builtin/sophnet-customized-marketing/references/content-safety.md +26 -0
  55. package/skills/builtin/sophnet-customized-marketing/references/marketing-date-checklist.md +99 -0
  56. package/skills/builtin/sophnet-customized-marketing/references/platform-writing-guidelines.md +88 -0
  57. package/skills/builtin/sophnet-customized-marketing/references/quality-checklist.md +44 -0
  58. package/skills/builtin/sophnet-customized-marketing/scripts/generate_poster.py +585 -0
  59. package/skills/builtin/sophnet-customized-marketing/scripts/style_profile.py +215 -0
  60. package/skills/builtin/sophnet-face-search/SKILL.md +115 -0
  61. package/skills/builtin/sophnet-face-search/pyproject.toml +11 -0
  62. package/skills/builtin/sophnet-face-search/scripts/face_search.py +336 -0
  63. package/skills/builtin/sophnet-face-search/uv.lock +508 -0
  64. package/skills/builtin/sophnet-image-edit/SKILL.md +140 -0
  65. package/skills/builtin/sophnet-image-edit/pyproject.toml +9 -0
  66. package/skills/builtin/sophnet-image-edit/scripts/edit_and_preview.sh +68 -0
  67. package/skills/builtin/sophnet-image-edit/scripts/edit_image.py +279 -0
  68. package/skills/builtin/sophnet-image-edit/uv.lock +234 -0
  69. package/skills/builtin/sophnet-image-generate/SKILL.md +62 -0
  70. package/skills/builtin/sophnet-image-generate/pyproject.toml +9 -0
  71. package/skills/builtin/sophnet-image-generate/scripts/generate_image.py +156 -0
  72. package/skills/builtin/sophnet-image-generate/uv.lock +234 -0
  73. package/skills/builtin/sophnet-image-ocr/SKILL.md +167 -0
  74. package/skills/builtin/sophnet-image-ocr/pyproject.toml +13 -0
  75. package/skills/builtin/sophnet-image-ocr/scripts/ocr.py +226 -0
  76. package/skills/builtin/sophnet-image-ocr/uv.lock +234 -0
  77. package/skills/builtin/sophnet-infinite-talk/SKILL.md +140 -0
  78. package/skills/builtin/sophnet-infinite-talk/pyproject.toml +9 -0
  79. package/skills/builtin/sophnet-infinite-talk/scripts/gen.py +172 -0
  80. package/skills/builtin/sophnet-oss/SKILL.md +109 -0
  81. package/skills/builtin/sophnet-oss/pyproject.toml +8 -0
  82. package/skills/builtin/sophnet-oss/scripts/upload_file.py +43 -0
  83. package/skills/builtin/sophnet-qa-install/SKILL.md +210 -0
  84. package/skills/builtin/sophnet-qa-install/pyproject.toml +6 -0
  85. package/skills/builtin/sophnet-qa-install/scripts/backup_md.py +35 -0
  86. package/skills/builtin/sophnet-qa-install/scripts/check_installed.py +143 -0
  87. package/skills/builtin/sophnet-qa-install/scripts/update_config.py +142 -0
  88. package/skills/builtin/sophnet-qa-install/scripts/update_md.py +73 -0
  89. package/skills/builtin/sophnet-training-install/SKILL.md +211 -0
  90. package/skills/builtin/sophnet-training-install/pyproject.toml +6 -0
  91. package/skills/builtin/sophnet-training-install/scripts/backup_md.py +35 -0
  92. package/skills/builtin/sophnet-training-install/scripts/check_installed.py +144 -0
  93. package/skills/builtin/sophnet-training-install/scripts/update_config.py +142 -0
  94. package/skills/builtin/sophnet-training-install/scripts/update_md.py +73 -0
  95. package/skills/builtin/sophnet-tts/SKILL.md +79 -0
  96. package/skills/builtin/sophnet-tts/pyproject.toml +9 -0
  97. package/skills/builtin/sophnet-tts/scripts/gen_tts.py +130 -0
  98. package/skills/builtin/sophnet-video-generate/SKILL.md +116 -0
  99. package/skills/builtin/sophnet-video-generate/scripts/gen_video.py +304 -0
  100. package/skills/builtin/video-understand/SKILL.md +79 -0
  101. package/skills/builtin/video-understand/scripts/video_understand.py +204 -0
  102. package/skills/builtin/weather/SKILL.md +112 -0
  103. package/skills/builtin/web-scraper/SKILL.md +101 -0
  104. package/skills/builtin/web-scraper/scripts/scrape.py +270 -0
  105. package/skills/builtin/website-builder/SKILL.md +266 -0
  106. package/skills/builtin/website-builder/scripts/deploy_site.sh +46 -0
  107. package/skills/store/didi-ride/SKILL.md +309 -0
  108. package/skills/store/didi-ride/_meta.json +6 -0
  109. package/skills/store/didi-ride/assets/PREFERENCE.md +58 -0
  110. package/skills/store/didi-ride/package.json +15 -0
  111. package/skills/store/didi-ride/references/api_references.md +171 -0
  112. package/skills/store/didi-ride/references/error_handling.md +68 -0
  113. package/skills/store/didi-ride/references/setup.md +73 -0
  114. package/skills/store/didi-ride/references/workflow.md +150 -0
  115. package/skills/store/flyai/SKILL.md +119 -0
  116. package/skills/store/flyai/references/fliggy-fast-search.md +53 -0
  117. package/skills/store/flyai/references/search-flight.md +89 -0
  118. package/skills/store/flyai/references/search-hotels.md +57 -0
  119. package/skills/store/flyai/references/search-poi.md +49 -0
  120. package/src/commands/download.js +103 -0
  121. package/src/commands/list.js +67 -0
  122. package/src/utils/config.js +24 -0
  123. package/src/utils/gitlab.js +67 -0
  124. package/src/utils/paths.js +19 -0
  125. package/src/utils/versions.js +38 -0
@@ -0,0 +1,44 @@
1
+ # Quality Checklist
2
+
3
+ ## 活动策划检查
4
+
5
+ - [ ] 活动方案是否已经用户确认后才开始生成物料?
6
+ - [ ] 活动机制是否一句话说得清?(用户发朋友圈时能直接当文案用)
7
+ - [ ] 机制数量是否不超过 3 个?
8
+ - [ ] 活动时间线是否覆盖预热 → 正式 → 收尾阶段?
9
+ - [ ] 物料清单是否覆盖了时间线上的每个发布节点?
10
+ - [ ] 不同阶段的内容是否有节奏变化(预热悬念 / 正式转化 / 收尾紧迫)?
11
+
12
+ ## 文案检查
13
+
14
+ - [ ] 产品信息(名称、价格)是否来自真实数据?
15
+ - [ ] 是否符合目标平台的调性和长度要求?
16
+ - [ ] 是否有明确的行动号召(CTA)?
17
+ - [ ] 是否融入了老板的个人风格?
18
+ - [ ] 是否存在 AI 典型句式?
19
+ - [ ] 不同客群的文案是否有实质差异?
20
+ - [ ] 不同平台的文案是否分别重写?
21
+
22
+ ## 海报检查
23
+
24
+ - [ ] 尺寸是否符合目标平台?
25
+ - [ ] 风格是否匹配文案主题和营销场景?
26
+ - [ ] 公众号封面是否成对生成?
27
+ - [ ] 小红书封面是否竖图 3:4?
28
+ - [ ] 是否包含敏感内容?
29
+ - [ ] 文字叠加是否清晰可读?
30
+
31
+ ## 常见错误
32
+
33
+ - 没有拿业务数据就直接写文案
34
+ - 编造产品价格、电话、地址
35
+ - 所有客群使用同一条文案,只改称呼
36
+ - 各平台复用同一篇文案
37
+ - 小红书用横图做封面
38
+ - 公众号只生成头图,没生成方形预览
39
+ - 文案风格与老板风格档案矛盾
40
+ - 首次使用时没建风格档案
41
+ - 把风格信息写入 `MEMORY.md` 而不是 `style_profile.py`
42
+ - 强行蹭无关热点
43
+ - 忘了先确认节日日期
44
+ - 忽略安全红线
@@ -0,0 +1,585 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Marketing poster/image generation via SophNet Gemini API.
4
+
5
+ Generates marketing posters and promotional images for various platforms
6
+ (WeChat Moments, Xiaohongshu, WeChat Official Account, etc.), uploads to OSS,
7
+ and returns a public URL. Supports style presets, fine-grained style dimensions,
8
+ text overlay, and reference images (product photos, logos, etc.).
9
+
10
+ Usage:
11
+ python generate_poster.py --type moments --prompt "..." [--style-preset promo]
12
+ python generate_poster.py --type xiaohongshu --style-preset kawaii --prompt "..."
13
+ python generate_poster.py --type moments --prompt "..." --text-overlay '{"title":"母亲节特惠"}'
14
+ python generate_poster.py --type moments --prompt "..." --reference-image product.jpg --reference-image logo.png
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import base64
21
+ import json
22
+ import math
23
+ import os
24
+ import sys
25
+ import tempfile
26
+ from typing import Any
27
+
28
+ import requests
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # API
32
+ # ---------------------------------------------------------------------------
33
+
34
+ API_URL = (
35
+ "https://www.sophnet.com/api/open-apis/projects/easyllms/imagegenerator/"
36
+ "google/models/gemini-3.1-flash-image-preview:generateContent"
37
+ )
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Safety
41
+ # ---------------------------------------------------------------------------
42
+
43
+ SAFETY_NEGATIVE_PROMPT = (
44
+ "nsfw, nudity, nude, naked, sexual, erotic, pornographic, gore, blood, violence, "
45
+ "bloody, corpse, dead body, weapon, gun, knife, drugs, smoking, alcohol, gambling, "
46
+ "politically sensitive, national flag, national emblem, political leader, "
47
+ "religious symbol, hate symbol, discrimination, racist, offensive, disturbing, "
48
+ "child exploitation, terrorism, self-harm"
49
+ )
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Poster types
53
+ # ---------------------------------------------------------------------------
54
+
55
+ POSTER_TYPES: dict[str, dict[str, str]] = {
56
+ "moments": {
57
+ "size": "1080*1080",
58
+ "aspect_ratio": "1:1",
59
+ "label": "朋友圈海报 (1080×1080)",
60
+ },
61
+ "xiaohongshu": {
62
+ "size": "1080*1440",
63
+ "aspect_ratio": "3:4",
64
+ "label": "小红书封面 (1080×1440)",
65
+ },
66
+ "wechat-header": {
67
+ "size": "900*383",
68
+ "aspect_ratio": "16:9",
69
+ "label": "公众号头图 (900×383)",
70
+ },
71
+ "wechat-square": {
72
+ "size": "200*200",
73
+ "aspect_ratio": "1:1",
74
+ "label": "公众号方形预览 (200×200)",
75
+ },
76
+ "share-card": {
77
+ "size": "500*400",
78
+ "aspect_ratio": "4:3",
79
+ "label": "微信群分享图 (500×400)",
80
+ },
81
+ "product": {
82
+ "size": "1024*1024",
83
+ "aspect_ratio": "1:1",
84
+ "label": "产品展示图 (1024×1024)",
85
+ },
86
+ "guide": {
87
+ "size": "1080*1440",
88
+ "aspect_ratio": "3:4",
89
+ "label": "攻略图/信息图 (1080×1440)",
90
+ },
91
+ }
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Style dimensions
95
+ # ---------------------------------------------------------------------------
96
+
97
+ PALETTES: dict[str, str] = {
98
+ "warm": "Warm color palette: golden yellows, amber oranges, terracotta reds, honey tones. Evokes comfort and warmth.",
99
+ "elegant": "Elegant palette: champagne gold, ivory, dusty rose, soft grey. Refined and sophisticated feel.",
100
+ "cool": "Cool palette: ocean blues, mint greens, silver greys, icy whites. Clean and calming atmosphere.",
101
+ "dark": "Dark palette: deep navy, charcoal, dark teal, muted burgundy. High contrast, dramatic mood.",
102
+ "earth": "Earth palette: olive green, clay brown, sandstone, forest tones. Natural and organic feeling.",
103
+ "vivid": "Vivid palette: saturated primary colors, bold contrasts, bright accents. High energy and eye-catching.",
104
+ "pastel": "Pastel palette: soft pink, baby blue, lavender, mint. Gentle, dreamy, and delicate.",
105
+ "mono": "Monochrome palette: shades of a single hue with tonal variation. Unified and striking.",
106
+ "retro": "Retro palette: mustard yellow, burnt orange, avocado green, faded teal. 1970s nostalgic warmth.",
107
+ }
108
+
109
+ RENDERINGS: dict[str, str] = {
110
+ "flat-vector": "Flat vector illustration style: clean geometric shapes, solid color fills, no gradients or textures, minimal line work.",
111
+ "hand-drawn": "Hand-drawn illustration style: visible sketch lines, organic imperfections, ink-and-paper feel, slightly uneven edges.",
112
+ "painterly": "Painterly style: visible brush strokes, rich textures, soft blended edges, oil or watercolor painting feel.",
113
+ "digital": "Polished digital art style: smooth gradients, clean rendering, precise details, modern and refined.",
114
+ "pixel": "Pixel art style: retro 8-bit aesthetic, blocky shapes, limited color palette, nostalgic gaming feel.",
115
+ "chalk": "Chalk/chalkboard style: white and colored chalk on dark background, hand-lettered feel, educational aesthetic.",
116
+ }
117
+
118
+ MOODS: dict[str, str] = {
119
+ "subtle": "Subtle mood: low contrast, muted tones, generous whitespace, understated and calm composition.",
120
+ "balanced": "Balanced mood: moderate contrast, harmonious composition, professional and approachable.",
121
+ "bold": "Bold mood: high contrast, saturated colors, dynamic composition, strong visual impact.",
122
+ }
123
+
124
+ LAYOUTS: dict[str, str] = {
125
+ "bento-grid": "Bento grid layout: modular grid of varied-size cards, each containing a distinct piece of information.",
126
+ "list": "List layout: enumerated items in a vertical sequence with icons or numbers.",
127
+ "comparison": "Comparison layout: side-by-side or split-screen contrasting two options or concepts.",
128
+ "flow": "Flow layout: connected steps or stages showing a process or timeline with directional arrows.",
129
+ "mindmap": "Mind map layout: central concept radiating outward to connected branches and sub-topics.",
130
+ "hub-spoke": "Hub-spoke layout: central element surrounded by related items in a radial arrangement.",
131
+ "funnel": "Funnel layout: wide-to-narrow stages showing progressive filtering or conversion.",
132
+ "dense-modules": "Dense modules layout: tightly packed information blocks with high data density, guide-style.",
133
+ }
134
+
135
+ STYLE_PRESETS: dict[str, dict[str, str]] = {
136
+ "promo": {"palette": "vivid", "rendering": "flat-vector", "mood": "bold"},
137
+ "elegant": {"palette": "earth", "rendering": "hand-drawn", "mood": "subtle"},
138
+ "minimal": {"palette": "mono", "rendering": "flat-vector", "mood": "subtle"},
139
+ "festive": {"palette": "warm", "rendering": "painterly", "mood": "bold"},
140
+ "cozy": {"palette": "warm", "rendering": "painterly", "mood": "subtle"},
141
+ "kawaii": {"palette": "pastel", "rendering": "flat-vector", "mood": "balanced"},
142
+ "morandi": {"palette": "earth", "rendering": "hand-drawn", "mood": "subtle"},
143
+ "pop-art": {"palette": "vivid", "rendering": "flat-vector", "mood": "bold"},
144
+ "vintage": {"palette": "retro", "rendering": "hand-drawn", "mood": "balanced"},
145
+ "blueprint": {"palette": "dark", "rendering": "chalk", "mood": "bold"},
146
+ "notion": {"palette": "mono", "rendering": "hand-drawn", "mood": "subtle"},
147
+ "watercolor": {"palette": "pastel", "rendering": "painterly", "mood": "subtle"},
148
+ "corporate": {"palette": "cool", "rendering": "flat-vector", "mood": "balanced"},
149
+ }
150
+
151
+ STANDARD_RATIOS = ["1:1", "3:4", "4:3", "9:16", "16:9"]
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Helpers
155
+ # ---------------------------------------------------------------------------
156
+
157
+
158
+ def parse_size(size_str: str) -> tuple[int, int]:
159
+ """Parse '1080x1440', '1080*1440', or '1080×1440' into (width, height)."""
160
+ normalized = size_str.replace("x", "*").replace("×", "*")
161
+ parts = normalized.split("*")
162
+ if len(parts) != 2:
163
+ raise ValueError(f"Invalid size format: {size_str!r}. Use WxH (e.g. 1080x1440).")
164
+ return int(parts[0].strip()), int(parts[1].strip())
165
+
166
+
167
+ def size_to_aspect_ratio(w: int, h: int) -> str:
168
+ target = w / h
169
+ best = "1:1"
170
+ best_diff = float("inf")
171
+ for ratio_str in STANDARD_RATIOS:
172
+ rw, rh = map(int, ratio_str.split(":"))
173
+ diff = abs(math.log(target) - math.log(rw / rh))
174
+ if diff < best_diff:
175
+ best_diff = diff
176
+ best = ratio_str
177
+ return best
178
+
179
+
180
+ def size_to_image_size(w: int, h: int) -> str:
181
+ return "512" if max(w, h) <= 512 else "1K"
182
+
183
+
184
+ def resolve_style(
185
+ preset: str | None,
186
+ palette: str | None,
187
+ rendering: str | None,
188
+ mood: str | None,
189
+ ) -> tuple[str | None, str | None, str | None]:
190
+ """Apply preset defaults, then override with explicit values."""
191
+ p_pal, p_ren, p_mood = None, None, None
192
+ if preset and preset in STYLE_PRESETS:
193
+ cfg = STYLE_PRESETS[preset]
194
+ p_pal, p_ren, p_mood = cfg.get("palette"), cfg.get("rendering"), cfg.get("mood")
195
+ return (palette or p_pal, rendering or p_ren, mood or p_mood)
196
+
197
+
198
+ ALLOWED_IMAGE_EXTENSIONS = {
199
+ ".jpg": "image/jpeg",
200
+ ".jpeg": "image/jpeg",
201
+ ".png": "image/png",
202
+ ".webp": "image/webp",
203
+ ".gif": "image/gif",
204
+ }
205
+
206
+ MAX_REFERENCE_IMAGES = 10
207
+ MAX_IMAGE_BYTES = 20 * 1024 * 1024 # 20 MB
208
+
209
+
210
+ def load_reference_image(path: str) -> dict[str, str]:
211
+ """Read a local image file and return an inline_data dict for the API."""
212
+ from pathlib import Path
213
+
214
+ p = Path(path).expanduser()
215
+ if not p.exists():
216
+ raise FileNotFoundError(f"Reference image not found: {path}")
217
+
218
+ ext = p.suffix.lower()
219
+ mime = ALLOWED_IMAGE_EXTENSIONS.get(ext)
220
+ if not mime:
221
+ raise ValueError(
222
+ f"Unsupported image format '{ext}' for {path}. "
223
+ f"Supported: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}"
224
+ )
225
+
226
+ size = p.stat().st_size
227
+ if size > MAX_IMAGE_BYTES:
228
+ raise ValueError(
229
+ f"Image too large ({size / 1024 / 1024:.1f} MB): {path}. "
230
+ f"Max {MAX_IMAGE_BYTES / 1024 / 1024:.0f} MB."
231
+ )
232
+
233
+ raw = p.read_bytes()
234
+ b64 = base64.b64encode(raw).decode("ascii")
235
+ return {"mime_type": mime, "data": b64}
236
+
237
+
238
+ def strip_oss_signature(url: str) -> str:
239
+ if not url or "?" not in url:
240
+ return url
241
+ bare = url.split("?")[0]
242
+ try:
243
+ r = requests.head(bare, timeout=10, allow_redirects=True)
244
+ if r.status_code == 200:
245
+ return bare
246
+ except requests.RequestException:
247
+ pass
248
+ return url
249
+
250
+
251
+ # ---------------------------------------------------------------------------
252
+ # Prompt construction
253
+ # ---------------------------------------------------------------------------
254
+
255
+
256
+ def build_prompt(
257
+ user_prompt: str,
258
+ width: int,
259
+ height: int,
260
+ palette: str | None = None,
261
+ rendering: str | None = None,
262
+ mood: str | None = None,
263
+ layout: str | None = None,
264
+ text_overlay: dict[str, str] | None = None,
265
+ negative_prompt: str | None = None,
266
+ has_reference_images: bool = False,
267
+ ) -> str:
268
+ merged_negative = SAFETY_NEGATIVE_PROMPT
269
+ if negative_prompt:
270
+ merged_negative = f"{SAFETY_NEGATIVE_PROMPT}, {negative_prompt}"
271
+
272
+ parts = [
273
+ "Generate a marketing poster image with these specifications:",
274
+ f"- Desired dimensions: {width}x{height} pixels",
275
+ ]
276
+
277
+ if has_reference_images:
278
+ parts.append(
279
+ "- Reference images are provided. Incorporate the products, logos, "
280
+ "or elements shown in the reference images into the poster with "
281
+ "high fidelity. Preserve key visual details (colors, shapes, text "
282
+ "on products) from the reference images."
283
+ )
284
+
285
+ if palette and palette in PALETTES:
286
+ parts.append(f"- Color direction: {PALETTES[palette]}")
287
+ if rendering and rendering in RENDERINGS:
288
+ parts.append(f"- Rendering style: {RENDERINGS[rendering]}")
289
+ if mood and mood in MOODS:
290
+ parts.append(f"- Mood: {MOODS[mood]}")
291
+ if layout and layout in LAYOUTS:
292
+ parts.append(f"- Information layout: {LAYOUTS[layout]}")
293
+
294
+ if text_overlay:
295
+ text_parts = []
296
+ if text_overlay.get("title"):
297
+ text_parts.append(f'main title text "{text_overlay["title"]}"')
298
+ if text_overlay.get("subtitle"):
299
+ text_parts.append(f'subtitle text "{text_overlay["subtitle"]}"')
300
+ if text_overlay.get("price"):
301
+ text_parts.append(f'prominent price tag "{text_overlay["price"]}"')
302
+ if text_overlay.get("footer"):
303
+ text_parts.append(f'footer text "{text_overlay["footer"]}"')
304
+ if text_parts:
305
+ parts.append(f"- Text to render on the image: {', '.join(text_parts)}. "
306
+ "Text must be clearly legible, well-positioned, and not overlap key visual elements.")
307
+
308
+ parts.extend([
309
+ f"- {user_prompt}",
310
+ f"- Content safety: The image must NOT contain any of the following: {merged_negative}.",
311
+ "Generate only the image, no extra commentary.",
312
+ ])
313
+ return "\n".join(parts)
314
+
315
+
316
+ # ---------------------------------------------------------------------------
317
+ # API interaction
318
+ # ---------------------------------------------------------------------------
319
+
320
+
321
+ def call_gemini(
322
+ api_key: str,
323
+ prompt: str,
324
+ aspect_ratio: str,
325
+ image_size: str,
326
+ reference_images: list[dict[str, str]] | None = None,
327
+ ) -> dict[str, Any]:
328
+ headers = {
329
+ "Authorization": f"Bearer {api_key}",
330
+ "Content-Type": "application/json",
331
+ }
332
+
333
+ parts: list[dict[str, Any]] = [{"text": prompt}]
334
+ if reference_images:
335
+ for img in reference_images:
336
+ parts.append({"inline_data": img})
337
+
338
+ payload = {
339
+ "contents": [{"parts": parts}],
340
+ "generationConfig": {
341
+ "responseModalities": ["IMAGE"],
342
+ "imageConfig": {
343
+ "aspectRatio": aspect_ratio,
344
+ "imageSize": image_size,
345
+ },
346
+ },
347
+ }
348
+ resp = requests.post(API_URL, json=payload, headers=headers, timeout=300)
349
+ resp.raise_for_status()
350
+ return resp.json()
351
+
352
+
353
+ def extract_image_b64(data: dict[str, Any]) -> tuple[str | None, str | None]:
354
+ for candidate in data.get("candidates", []):
355
+ for part in candidate.get("content", {}).get("parts", []):
356
+ inline = part.get("inlineData") or part.get("inline_data")
357
+ if inline and "data" in inline:
358
+ mime = inline.get("mimeType", inline.get("mime_type", "image/png"))
359
+ ext = mime.split("/")[-1].split(";")[0]
360
+ return inline["data"], ext
361
+ return None, None
362
+
363
+
364
+ def upload_b64_image(b64_data: str, ext: str = "png") -> str | None:
365
+ try:
366
+ raw = base64.b64decode(b64_data)
367
+ except Exception as e:
368
+ print(f"Warning: base64 decode failed: {e}", file=sys.stderr)
369
+ return None
370
+
371
+ fd, tmp_path = tempfile.mkstemp(suffix=f".{ext}", prefix="poster_")
372
+ try:
373
+ with os.fdopen(fd, "wb") as f:
374
+ f.write(raw)
375
+ import sophnet_tools
376
+ signed_url = sophnet_tools.upload_oss(tmp_path)
377
+ if not signed_url:
378
+ print("Warning: upload_oss returned no signed URL", file=sys.stderr)
379
+ return None
380
+ return strip_oss_signature(signed_url)
381
+ finally:
382
+ try:
383
+ os.unlink(tmp_path)
384
+ except OSError:
385
+ pass
386
+
387
+
388
+ # ---------------------------------------------------------------------------
389
+ # Output formatting
390
+ # ---------------------------------------------------------------------------
391
+
392
+
393
+ def format_output(
394
+ poster_type: str,
395
+ w: int,
396
+ h: int,
397
+ palette: str | None,
398
+ rendering: str | None,
399
+ mood: str | None,
400
+ layout: str | None,
401
+ style_preset: str | None,
402
+ status: str,
403
+ image_url: str | None,
404
+ reference_image_count: int = 0,
405
+ fmt: str = "text",
406
+ ) -> str:
407
+ data = {
408
+ "POSTER_TYPE": poster_type,
409
+ "POSTER_SIZE": f"{w}*{h}",
410
+ }
411
+ if style_preset:
412
+ data["STYLE_PRESET"] = style_preset
413
+ if palette:
414
+ data["PALETTE"] = palette
415
+ if rendering:
416
+ data["RENDERING"] = rendering
417
+ if mood:
418
+ data["MOOD"] = mood
419
+ if layout:
420
+ data["LAYOUT"] = layout
421
+ if reference_image_count:
422
+ data["REFERENCE_IMAGES"] = str(reference_image_count)
423
+ data["STATUS"] = status
424
+ if image_url:
425
+ data["IMAGE_URL"] = image_url
426
+
427
+ if fmt == "json":
428
+ return json.dumps(data, ensure_ascii=False, indent=2)
429
+ return "\n".join(f"{k}={v}" for k, v in data.items())
430
+
431
+
432
+ # ---------------------------------------------------------------------------
433
+ # CLI
434
+ # ---------------------------------------------------------------------------
435
+
436
+
437
+ def main(argv: list[str] | None = None) -> None:
438
+ type_names = ", ".join(f"{k} ({v['label']})" for k, v in POSTER_TYPES.items())
439
+ preset_names = ", ".join(STYLE_PRESETS.keys())
440
+
441
+ parser = argparse.ArgumentParser(
442
+ description="Generate marketing posters via SophNet Gemini API.",
443
+ formatter_class=argparse.RawDescriptionHelpFormatter,
444
+ epilog=(
445
+ f"Poster types:\n {type_names}\n\n"
446
+ f"Style presets (shorthand for palette+rendering+mood):\n {preset_names}\n\n"
447
+ f"Palettes:\n {', '.join(PALETTES.keys())}\n\n"
448
+ f"Renderings:\n {', '.join(RENDERINGS.keys())}\n\n"
449
+ f"Moods:\n {', '.join(MOODS.keys())}\n\n"
450
+ f"Layouts (guide type only):\n {', '.join(LAYOUTS.keys())}"
451
+ ),
452
+ )
453
+ parser.add_argument("--type", required=True, choices=POSTER_TYPES.keys(),
454
+ help="Poster type (determines default size and aspect ratio)")
455
+ parser.add_argument("--prompt", required=True,
456
+ help="Image content description (scene, subject, atmosphere)")
457
+ parser.add_argument("--style-preset", default=None, choices=list(STYLE_PRESETS.keys()),
458
+ help="Style shorthand that sets palette+rendering+mood together")
459
+ parser.add_argument("--palette", default=None, choices=list(PALETTES.keys()),
460
+ help="Color palette direction (overrides preset)")
461
+ parser.add_argument("--rendering", default=None, choices=list(RENDERINGS.keys()),
462
+ help="Visual rendering style (overrides preset)")
463
+ parser.add_argument("--mood", default=None, choices=list(MOODS.keys()),
464
+ help="Overall mood intensity (overrides preset)")
465
+ parser.add_argument("--layout", default=None, choices=list(LAYOUTS.keys()),
466
+ help="Information layout (primarily for guide type)")
467
+ parser.add_argument("--text-overlay", default=None,
468
+ help='Text to render on poster, JSON format: \'{"title":"...", "price":"..."}\'')
469
+ parser.add_argument("--size", default=None,
470
+ help="Override size as WxH or W*H (default: auto from --type)")
471
+ parser.add_argument("--reference-image", action="append", default=None,
472
+ help="Path to a reference image (product photo, logo, etc.). "
473
+ "Can be specified multiple times, up to 10 images.")
474
+ parser.add_argument("--negative-prompt", default=None,
475
+ help="Additional negative prompt terms")
476
+ parser.add_argument("--format", default="text", choices=["text", "json"],
477
+ help="Output format (default: text)")
478
+ args = parser.parse_args(argv)
479
+
480
+ # Resolve style
481
+ palette, rendering, mood = resolve_style(
482
+ args.style_preset, args.palette, args.rendering, args.mood,
483
+ )
484
+
485
+ # Resolve size
486
+ poster_cfg = POSTER_TYPES[args.type]
487
+ try:
488
+ w, h = parse_size(args.size) if args.size else parse_size(poster_cfg["size"])
489
+ except ValueError as e:
490
+ print(f"Error: {e}", file=sys.stderr)
491
+ sys.exit(1)
492
+
493
+ aspect_ratio = poster_cfg["aspect_ratio"] if not args.size else size_to_aspect_ratio(w, h)
494
+ image_size = size_to_image_size(w, h)
495
+
496
+ # Parse text overlay
497
+ text_overlay = None
498
+ if args.text_overlay:
499
+ try:
500
+ text_overlay = json.loads(args.text_overlay)
501
+ except json.JSONDecodeError as e:
502
+ print(f"Error: --text-overlay is not valid JSON: {e}", file=sys.stderr)
503
+ sys.exit(1)
504
+
505
+ # Load reference images
506
+ ref_images: list[dict[str, str]] = []
507
+ if args.reference_image:
508
+ if len(args.reference_image) > MAX_REFERENCE_IMAGES:
509
+ print(
510
+ f"Error: too many reference images ({len(args.reference_image)}). "
511
+ f"Max {MAX_REFERENCE_IMAGES}.",
512
+ file=sys.stderr,
513
+ )
514
+ sys.exit(1)
515
+ for img_path in args.reference_image:
516
+ try:
517
+ ref_images.append(load_reference_image(img_path))
518
+ except (FileNotFoundError, ValueError) as e:
519
+ print(f"Error: {e}", file=sys.stderr)
520
+ sys.exit(1)
521
+
522
+ # Get API key
523
+ import sophnet_tools
524
+ api_key = sophnet_tools.get_api_key()
525
+ if not api_key:
526
+ print("Error: No API key found. Set SOPH_API_KEY or configure via sophnet-key skill.",
527
+ file=sys.stderr)
528
+ sys.exit(1)
529
+
530
+ # Build prompt and call API
531
+ prompt = build_prompt(
532
+ args.prompt, w, h,
533
+ palette=palette, rendering=rendering, mood=mood,
534
+ layout=args.layout, text_overlay=text_overlay,
535
+ negative_prompt=args.negative_prompt,
536
+ has_reference_images=bool(ref_images),
537
+ )
538
+ print("STATUS=generating", file=sys.stderr)
539
+
540
+ try:
541
+ result = call_gemini(
542
+ api_key, prompt, aspect_ratio, image_size,
543
+ reference_images=ref_images or None,
544
+ )
545
+ except requests.HTTPError as e:
546
+ status_code = e.response.status_code if e.response is not None else None
547
+ if status_code in (401, 403):
548
+ print("STATUS=permission_denied", file=sys.stderr)
549
+ print(
550
+ "Error: 当前账户没有所调用图片生成模型的使用权限。"
551
+ "请联系 Sophclaw 平台客服开通权限后重试。",
552
+ file=sys.stderr,
553
+ )
554
+ else:
555
+ print(f"STATUS=api_error", file=sys.stderr)
556
+ print(f"Error: SophNet Gemini API call failed (HTTP {status_code}): {e}", file=sys.stderr)
557
+ sys.exit(1)
558
+ except requests.RequestException as e:
559
+ print("STATUS=api_error", file=sys.stderr)
560
+ print(f"Error: SophNet Gemini API call failed: {e}", file=sys.stderr)
561
+ sys.exit(1)
562
+
563
+ b64_data, ext = extract_image_b64(result)
564
+ if not b64_data:
565
+ print("Error: no image data found in response.", file=sys.stderr)
566
+ print(json.dumps(result, ensure_ascii=False, indent=2), file=sys.stderr)
567
+ sys.exit(1)
568
+
569
+ image_url = upload_b64_image(b64_data, ext or "png")
570
+ if not image_url:
571
+ print("Error: failed to upload image to OSS.", file=sys.stderr)
572
+ sys.exit(1)
573
+
574
+ print(format_output(
575
+ poster_type=args.type, w=w, h=h,
576
+ palette=palette, rendering=rendering, mood=mood,
577
+ layout=args.layout, style_preset=args.style_preset,
578
+ status="succeeded", image_url=image_url,
579
+ reference_image_count=len(ref_images),
580
+ fmt=args.format,
581
+ ))
582
+
583
+
584
+ if __name__ == "__main__":
585
+ main()