xiaohongshu-images

安装量: 851
排名: #1529

安装

npx skills add https://github.com/iamzifei/xiaohongshu-images-skill --skill xiaohongshu-images

Xiaohongshu Images Skill

This skill transforms markdown, HTML, or text content into beautifully styled HTML pages with AI-generated cover images, then captures them as sequential screenshots at 3:4 ratio for Xiaohongshu posting.

Overview

The skill performs the following workflow:

Accept Content: Receives markdown, HTML, or txt format content from the user Load Prompt Template: Reads the prompt template from prompts/default.md in this skill's directory Generate Cover Image: Uses /baoyu-cover-image skill to generate a cover image based on the article content Generate HTML: Creates a beautifully styled HTML page following the prompt template specifications Save Output: Saves the HTML to ~/Dev/obsidian/articles//xhs-preview.html Capture Screenshots: Takes sequential 3:4 ratio screenshots of the entire page without cutting text Usage

When the user invokes this skill, follow these steps:

Step 1: Identify the Input

The user will provide one of the following:

A file path to a markdown, HTML, or txt file (e.g., /path/to/article.md) Raw content directly in the conversation A URL to fetch content from

If the input is unclear, ask the user to provide either a file path, URL, or paste the content directly.

Step 2: Read the Prompt Template

Read the prompt template from this skill's directory:

{{SKILL_DIR}}/prompts/default.md

Use the Read tool to get the prompt template content. This template defines the HTML/CSS styling specifications.

Step 3: Extract Article Title and Date

From the content, extract:

Title: The main heading (h1) or first significant title in the content Date: Current date in YYYY-MM-DD format

Create the output folder path as: ~/Dev/obsidian/articles/-/

Replace spaces with hyphens Remove special characters Keep the title reasonably short (max 50 characters) All images go in _attachments/ subfolder Step 4: Generate Cover Image with baoyu-cover-image Skill

⚠️ COMPLIANCE CHECK: Before generating, ensure the image concept complies with Xiaohongshu community guidelines (Section 11 of the prompt template). The image must:

Be age-appropriate with no revealing clothing or suggestive poses Avoid political symbols, violence, gambling, smoking, or alcohol abuse Convey positive, constructive messages Be culturally sensitive and original

Use the /baoyu-cover-image skill to generate the cover image:

Invoke the skill with the article content: /baoyu-cover-image ~/Dev/obsidian/articles/-/index.md --style <auto-or-specified> --no-title</p> <p>Or if the content is not yet saved, pass the content directly to the skill.</p> <p>Style Selection:</p> <p>Let baoyu-cover-image auto-select based on content signals, OR Specify a style that matches the article tone: tech - AI, coding, digital topics warm - Personal stories, emotional content bold - Controversial, attention-grabbing topics minimal - Simple, zen-like content playful - Fun, casual, beginner-friendly content nature - Wellness, health, organic topics retro - History, vintage, traditional topics elegant - Business, professional content (default)</p> <p>Special: Mom Reading Club Template</p> <p>When using the mom-reading-club template, override the default cover style with calligraphy & ink-wash illustration (书法水墨风):</p> <p>/baoyu-cover-image <article> --style minimal --no-title --custom-prompt "Chinese calligraphy and ink-wash illustration style (书法水墨风). Zen-like simplicity with generous white space (留白). Include subtle ink-wash brush strokes as background texture. Minimalist botanical elements (bamboo, plum blossoms, orchids, lotus) when appropriate. Color palette: ink black (#1a1a1a), warm gray (#666666), subtle gold accents (#C9A962), warm off-white background (#F5F3EE). If human figures are included, depict an elegant woman aged 30-45 with a contemplative, refined demeanor. NO TEXT on the cover."</p> <p>Use --no-title flag since Xiaohongshu covers typically use visual-only images without embedded text.</p> <p>Move the generated image to the correct location:</p> <p>baoyu-cover-image saves to imgs/cover.png relative to the article Move/copy to ~/Dev/obsidian/articles/<date>-<title>/_attachments/cover-xhs.png mv ~/Dev/obsidian/articles/<date>-<title>/imgs/cover.png ~/Dev/obsidian/articles/<date>-<title>/_attachments/cover-xhs.png</p> <p>Step 5: Generate HTML</p> <p>⚠️ COMPLIANCE CHECK: Before generating HTML, review the text content for compliance:</p> <p>No absolute/superlative claims (最好、第一、国家级、最高级、全网最低价) No exaggerated effect claims (一分钟见效、吃完就变白) No false or unverified medical/financial advice No defamatory or offensive language If health/investment topics are involved, add disclaimer text</p> <p>Using the prompt template and the user's content:</p> <p>Parse the content to identify:</p> <p>Title (h1) Subtitles (h2-h6) Paragraphs Lists Code blocks Links Emphasis/bold text Blockquotes</p> <p>Generate complete HTML following the template specifications:</p> <p>Dark gradient background 600px × 800px cream-colored card Proper typography with Google Fonts (Noto Serif SC, Inter, JetBrains Mono) Cover image at the top All specified styling for text, links, lists, code blocks, etc. Responsive design for mobile</p> <p>Important HTML Structure:</p> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Article Title

Cover

Save the HTML to ~/Dev/obsidian/articles/-/xhs-preview.html Step 6: Take Screenshots</p> <p>After generating the HTML, capture sequential screenshots of the .container element at exact 3:4 aspect ratio:</p> <p>Screenshot Specifications:</p> <p>Container viewport: 600px × 800px (3:4 ratio) Output resolution: 1200px × 1600px (2x device scale factor) Each screenshot captures exactly the .container element, not the full page</p> <p>Capture Process:</p> <p>Open the HTML page using Playwright browser with viewport larger than container Configure browser context: Viewport: 800px × 1000px (larger than container to ensure full visibility) Device scale factor: 2x for high-resolution output Scroll within the container: The .container element has overflow-y: auto, making it internally scrollable Start from scrollTop = 0 and increment through the content Each scroll position captures one 3:4 ratio screenshot Smart text boundary detection: Before each screenshot, analyze visible block elements (p, h1-h6, li, blockquote, pre, img) If an element would be cut at the bottom boundary, end the current screenshot before that element Add whitespace mask to cover partial content, maintaining clean 3:4 frame Next screenshot starts with the cut element at the top Capture the complete .container content: Use container.screenshot() to capture only the container element (excludes page background) Continue until all content is captured (scrollTop reaches scrollHeight - clientHeight) Save screenshots to ~/Dev/obsidian/articles/<date>-<title>/_attachments/: Sequential naming: xhs-01.png, xhs-02.png, xhs-03.png, etc.</p> <p>Use the screenshot script:</p> <p>cd {{SKILL_DIR}} && python scripts/screenshot.py ~/Dev/obsidian/articles/<date>-<title>/xhs-preview.html</p> <p>Script Output:</p> <p>Each screenshot: exactly 1200×1600 pixels (3:4 ratio at 2x scale) Only the cream-colored card content is captured No text is cut off between screenshots Step 7: Report Results</p> <p>After completion, report to the user:</p> <p>HTML file location Number of screenshots generated Screenshots folder location Preview of the first screenshot (if possible) Directory Structure {{SKILL_DIR}}/ ├── SKILL.md # This file ├── prompts/ │ └── default.md # Default HTML/CSS styling prompt ├── scripts/ │ └── screenshot.py # Screenshot capture script └── .gitignore</p> <p>Output directory (outside skill folder): ~/Dev/obsidian/articles/<date>-<title>/ ├── xhs-preview.html # Styled HTML preview page ├── imgs/ # Created by baoyu-cover-image │ ├── prompts/ │ │ └── cover.md # Cover image prompt │ └── cover.png # Generated cover (moved to _attachments/) └── _attachments/ # Obsidian-style attachments folder ├── cover-xhs.png # Cover image (moved from imgs/cover.png) ├── xhs-01.png # Screenshot page 1 (1200×1600) ├── xhs-02.png # Screenshot page 2 └── ...</p> <p>Dependencies</p> <p>This skill depends on:</p> <p>/baoyu-cover-image skill for cover image generation (must be installed in ~/.claude/skills/) Example Workflow</p> <p>User: Create a styled article page from this markdown:</p> <h1 id="my-article-title">My Article Title</h1> <p>This is the introduction paragraph...</p> <h2 id="section-1">Section 1</h2> <p>Content for section 1...</p> <p>Assistant Actions:</p> <p>Read prompt template from prompts/default.md Extract title: "My Article Title" Create output folder: ~/Dev/obsidian/articles/2024-01-14-my-article-title/ Invoke /baoyu-cover-image skill with --no-title flag to generate cover image Move generated cover from imgs/cover.png to _attachments/cover-xhs.png Generate styled HTML following template specifications Save to ~/Dev/obsidian/articles/2024-01-14-my-article-title/xhs-preview.html Open in browser and take 3:4 ratio screenshots Save screenshots to ~/Dev/obsidian/articles/2024-01-14-my-article-title/_attachments/xhs-01.png, etc. Report completion with file locations Custom Prompt Templates</p> <p>Users can provide custom prompt templates by:</p> <p>Placing a .md file in the prompts/ directory Specifying the template name when invoking the skill</p> <p>Example: "Use the xiaohongshu-style template for this article"</p> <p>Available Templates Template Description Best For default Standard style with New Yorker-style illustrations General articles mom-reading-club Calligraphy & ink-wash style with TsangerJinKai02 font Mom Reading Club (妈妈读书会) brand content Mom Reading Club Template</p> <p>Use this template for all "Mom Reading Club" branded content:</p> <p>/xiaohongshu-images <article> --template mom-reading-club</p> <p>Features:</p> <p>Font: TsangerJinKai02 (仓耳今楷02) for titles - requires local installation Cover style: Chinese calligraphy & ink-wash illustration (书法水墨风) Aesthetic: Zen simplicity, elegant restraint, generous white space Color accent: Subtle gold (#C9A962) Target audience: Cultured mothers aged 30-45 Error Handling</p> <p>If the /baoyu-cover-image skill fails:</p> <p>Display the error message to the user Offer to retry or proceed without cover image If proceeding without image, use a placeholder or omit the cover</p> <p>If screenshot capture fails:</p> <p>Verify the HTML file exists and is valid Check browser dependencies Report the specific error to the user System Requirements</p> <p>This skill requires:</p> <p>Python 3.8+ Playwright for screenshot capture (installed via pip: pip install playwright && playwright install chromium) /baoyu-cover-image skill installed in ~/.claude/skills/</p> <p>Install dependencies:</p> <p>pip install playwright playwright install chromium</p> <p>Notes The skill preserves all original content exactly as provided No modifications, simplifications, or deletions to the content The cover image is generated based on the article's main theme Screenshots are optimized for Xiaohongshu's 3:4 aspect ratio Text is never cut off in screenshots - boundaries are adjusted intelligently Community Compliance (社区规范合规)</p> <p>IMPORTANT: All generated content must comply with Xiaohongshu community guidelines.</p> <p>Quick Reference - Prohibited Content: Category Examples Action Absolute claims 最好、最佳、第一、国家级 Remove or rephrase Exaggerated effects 一分钟见效、立刻瘦10斤 Remove or add disclaimers Medical/Financial advice Health tips, investment suggestions Add disclaimer: "本内容不构成医疗/投资建议" Inappropriate imagery Nudity, violence, political symbols Regenerate with appropriate content False information Pseudoscience, unverified claims Verify or remove Defamatory content Attacks on brands/individuals Remove entirely Official Guidelines: 社区规范: https://www.xiaohongshu.com/crown/community/rules 社区公约: https://www.xiaohongshu.com/crown/community/agreement Compliance Workflow: Before image generation: Review theme for appropriateness Before HTML generation: Scan text for prohibited phrases Before final output: Run through compliance checklist in prompt template (Section 11.5)</p> </article> <a href="/" class="back-link">← <span data-i18n="detail.backToLeaderboard">返回排行榜</span></a> </div> <aside class="sidebar"> <section class="related-skills" id="relatedSkillsSection"> <h2 class="related-title" data-i18n="detail.relatedSkills">相关 Skills</h2> <div class="related-list" id="relatedSkillsList"> <div class="skeleton-card"></div> <div class="skeleton-card"></div> <div class="skeleton-card"></div> </div> </section> </aside> </div> </div> <script src="https://unpkg.com/i18next@23.11.5/i18next.min.js" defer></script> <script src="https://unpkg.com/i18next-browser-languagedetector@7.2.1/i18nextBrowserLanguageDetector.min.js" defer></script> <script defer> // Language resources - same pattern as index page const resources = { 'zh-CN': null, 'en': null, 'ja': null, 'ko': null, 'zh-TW': null, 'es': null, 'fr': null }; // Load language files (only current + fallback for performance) async function loadLanguageResources() { const savedLang = localStorage.getItem('i18nextLng') || 'en'; const langsToLoad = new Set([savedLang, 'en']); // current + fallback await Promise.all([...langsToLoad].map(async (lang) => { try { const response = await fetch(`/locales/${lang}.json`); if (response.ok) { resources[lang] = { translation: await response.json() }; } } catch (error) { console.warn(`Failed to load ${lang} language file:`, error); } })); } // Load a single language on demand (for language switching) async function loadLanguage(lang) { if (resources[lang]) return; try { const response = await fetch(`/locales/${lang}.json`); if (response.ok) { resources[lang] = { translation: await response.json() }; i18next.addResourceBundle(lang, 'translation', resources[lang].translation); } } catch (error) { console.warn(`Failed to load ${lang} language file:`, error); } } // Initialize i18next async function initI18n() { try { await loadLanguageResources(); // Filter out null values from resources const validResources = {}; for (const [lang, data] of Object.entries(resources)) { if (data !== null) { validResources[lang] = data; } } console.log('Loaded languages:', Object.keys(validResources)); console.log('zh-CN resource:', validResources['zh-CN']); console.log('detail.home in resource:', validResources['zh-CN']?.translation?.detail?.home); // 检查是否有保存的语言偏好 const savedLang = localStorage.getItem('i18nextLng'); // 如果没有保存的语言偏好,默认使用英文 const defaultLang = savedLang && ['zh-CN', 'en', 'ja', 'ko', 'zh-TW', 'es', 'fr'].includes(savedLang) ? savedLang : 'en'; await i18next .use(i18nextBrowserLanguageDetector) .init({ lng: defaultLang, // 强制设置初始语言 fallbackLng: 'en', supportedLngs: ['zh-CN', 'en', 'ja', 'ko', 'zh-TW', 'es', 'fr'], resources: validResources, detection: { order: ['localStorage'], // 只使用 localStorage,不检测浏览器语言 caches: ['localStorage'], lookupLocalStorage: 'i18nextLng' }, interpolation: { escapeValue: false } }); console.log('i18next initialized, language:', i18next.language); console.log('Test translation:', i18next.t('detail.home')); // Set initial language in selector const langSwitcher = document.getElementById('langSwitcher'); langSwitcher.value = i18next.language; // Update page language updatePageLanguage(); // Language switch event langSwitcher.addEventListener('change', async (e) => { await loadLanguage(e.target.value); // load on demand i18next.changeLanguage(e.target.value).then(() => { updatePageLanguage(); localStorage.setItem('i18nextLng', e.target.value); }); }); } catch (error) { console.error('i18next init failed:', error); } } // Translation helper function t(key, options = {}) { return i18next.t(key, options); } // Update all translatable elements function updatePageLanguage() { // Update HTML lang attribute document.documentElement.lang = i18next.language; // Update elements with data-i18n attribute document.querySelectorAll('[data-i18n]').forEach(el => { const key = el.getAttribute('data-i18n'); el.textContent = t(key); }); } // Copy command function function copyCommand() { const command = document.getElementById('installCommand').textContent; const btn = document.getElementById('copyBtn'); navigator.clipboard.writeText(command).then(() => { btn.textContent = t('copied'); btn.classList.add('copied'); setTimeout(() => { btn.textContent = t('copy'); btn.classList.remove('copied'); }, 2000); }).catch(() => { // Fallback for non-HTTPS const textArea = document.createElement('textarea'); textArea.value = command; textArea.style.position = 'fixed'; textArea.style.left = '-9999px'; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); btn.textContent = t('copied'); btn.classList.add('copied'); setTimeout(() => { btn.textContent = t('copy'); btn.classList.remove('copied'); }, 2000); }); } // Initialize document.getElementById('copyBtn').addEventListener('click', copyCommand); initI18n(); // 异步加载相关 Skills async function loadRelatedSkills() { const owner = 'iamzifei'; const skillName = 'xiaohongshu-images'; const currentLang = 'ja'; const listContainer = document.getElementById('relatedSkillsList'); const section = document.getElementById('relatedSkillsSection'); try { const response = await fetch(`/api/related-skills/${encodeURIComponent(owner)}/${encodeURIComponent(skillName)}?limit=6`); if (!response.ok) { throw new Error('Failed to load'); } const data = await response.json(); const relatedSkills = data.related_skills || []; if (relatedSkills.length === 0) { // 没有相关推荐时隐藏整个区域 section.style.display = 'none'; return; } // 渲染相关 Skills listContainer.innerHTML = relatedSkills.map(skill => { const desc = skill.description || ''; const truncatedDesc = desc.length > 60 ? desc.substring(0, 60) + '...' : desc; return ` <a href="${currentLang === 'en' ? '' : '/' + currentLang}/skill/${skill.owner}/${skill.repo}/${skill.skill_name}" class="related-card"> <div class="related-name">${escapeHtml(skill.skill_name)}</div> <div class="related-meta"> <span class="related-owner">${escapeHtml(skill.owner)}</span> <span class="related-installs">${skill.installs}</span> </div> <div class="related-desc">${escapeHtml(truncatedDesc)}</div> </a> `; }).join(''); } catch (error) { console.error('Failed to load related skills:', error); // 加载失败时显示提示或隐藏 listContainer.innerHTML = '<div class="related-empty">暂无相关推荐</div>'; } } // HTML 转义 function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // 页面加载完成后异步加载相关 Skills if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', loadRelatedSkills); } else { loadRelatedSkills(); } </script> </body> </html>