Skill: kaiyuelv/content-writer-pro (version 1.0.0)

# Content Writer Pro / 文案生成专家 ## Metadata / 元数据 | Field | Value | |-------|-------| | **name** | content-writer-pro | | **homepage** | https://clawhub.com/skills/content-writer-pro | | **description** | 专业文案生成工具 - 支持营销文案、社媒内容、广告文案、品牌故事等多种场景 | Professional copywriting generator for marketing, social media, ads, brand storytelling | | **category** | content | | **tags** | content, copywriting, marketing, generator, 文案, 营销, 内容创作 | ## Overview / 概述 Content Writer Pro is a professional copywriting tool for marketers and content creators. It provides templates and AI-powered generation for various content types. 文案生成专家是为营销人员和内容创作者打造的专业文案工具，提供多种内容类型的模板和AI生成能力。 ## Features / 功能特性 - **Marketing Copy** / 营销文案: Product descriptions, value propositions - **Social Media** / 社媒内容: Posts for various platforms - **Ad Copy** / 广告文案: Headlines, body copy, CTAs - **Brand Story** / 品牌故事: Origin stories, mission statements - **Email Templates** / 邮件模板: Newsletters, promotional emails - **Tone Adaptation** / 语调适配: Professional, casual, playful, etc. ## Installation / 安装 ```bash pip install -r requirements.txt ``` ## Quick Start / 快速开始 ```python from content_writer import ContentWriterPro writer = ContentWriterPro() # Generate marketing copy copy = writer.generate_marketing_copy( product="AI Assistant", audience="Small business owners", tone="professional" ) # Create social media post post = writer.create_social_post( platform="linkedin", topic="Productivity tips", tone="casual" ) ``` ## API Reference / API 参考 See `content_writer.py` for full API documentation. ## License / 许可证 MIT License

path: README.md
content: # Content Writer Pro / 文案生成专家

[![Skill](https://img.shields.io/badge/ClawHub-Skill-blue)](https://clawhub.com)
[![Python](https://img.shields.io/badge/Python-3.8+-green.svg)](https://www.python.org/)

> 专业文案生成工具 - 支持营销文案、社媒内容、广告文案、品牌故事等多种场景
> Professional copywriting generator for marketing, social media, ads, brand storytelling

## Features / 功能特性

### Marketing Copy / 营销文案
- Product descriptions / 产品描述
- Value propositions / 价值主张
- Feature highlights / 功能亮点
- Use case scenarios / 使用场景

### Social Media Content / 社媒内容
- LinkedIn posts / LinkedIn动态
- Twitter/X tweets / 推文
- Instagram captions / Instagram文案
- Facebook updates / Facebook更新

### Ad Copy / 广告文案
- Headlines / 标题
- Body copy / 正文
- Call-to-action / 行动号召
- A/B test variations / A/B测试变体

### Brand Story / 品牌故事
- Origin stories / 起源故事
- Mission statements / 使命宣言
- Vision statements / 愿景宣言
- Company values / 企业价值观

### Email Templates / 邮件模板
- Newsletters / 新闻简报
- Promotional emails / 促销邮件
- Welcome sequences / 欢迎序列
- Follow-up emails / 跟进邮件

## Installation / 安装

```bash
# Clone the repository
git clone https://github.com/yourusername/content-writer-pro.git
cd content-writer-pro

# Install dependencies
pip install -r requirements.txt
```

## Quick Start / 快速开始

```python
from content_writer import ContentWriterPro

# Initialize the writer
writer = ContentWriterPro()

# Generate marketing copy
copy = writer.generate_marketing_copy(
    product="AI Writing Assistant",
    audience="Content marketers",
    tone="professional"
)
print(copy)

# Create social media post
post = writer.create_social_post(
    platform="linkedin",
    topic="AI in content creation",
    tone="casual"
)
print(post)
```

## Usage Examples / 使用示例

### Marketing Copy Generation / 营销文案生成

```python
from content_writer import ContentWriterPro

writer = ContentWriterPro()

# Product description
description = writer.write_product_description(
    product_name="Smart Translator",
    features=["Multi-language", "Context-aware", "Terminology preservation"],
    target_audience="Global businesses"
)

# Value proposition
value_prop = writer.write_value_proposition(
    product="SEO Optimizer",
    benefit="Rank higher in search results",
    differentiator="AI-powered analysis"
)
```

### Social Media Content / 社交媒体内容

```python
# LinkedIn post
linkedin_post = writer.create_social_post(
    platform="linkedin",
    topic="Remote work productivity",
    tone="professional",
    length="medium"
)

# Twitter thread
tweets = writer.create_twitter_thread(
    topic="Startup lessons",
    num_tweets=5
)
```

### Ad Copy / 广告文案

```python
# Google Ads style
ad = writer.write_ad_copy(
    product="Project Management Tool",
    headline_options=3,
    description_options=2
)

# Facebook ad
fb_ad = writer.write_facebook_ad(
    product="Online Course",
    hook="Learn in 30 days",
    cta="Enroll now"
)
```

## API Reference / API 参考

### ContentWriterPro Class

```python
class ContentWriterPro:
    """Main class for content generation."""
    
    def generate_marketing_copy(self, product, audience, tone="professional"):
        """Generate marketing copy."""
        pass
    
    def create_social_post(self, platform, topic, tone="casual", length="short"):
        """Create social media post."""
        pass
    
    def write_ad_copy(self, product, headline_options=3, description_options=2):
        """Write advertising copy."""
        pass
    
    def write_brand_story(self, company_name, origin_story, values):
        """Write brand story content."""
        pass
    
    def write_email(self, email_type, purpose, tone="professional"):
        """Write email content."""
        pass
```

## Configuration / 配置

```python
# Custom configuration
config = {
    'default_tone': 'professional',
    'max_length': 500,
    'language': 'zh-CN'
}

writer = ContentWriterPro(config=config)
```

## Running Tests / 运行测试

```bash
# Run all tests
python -m pytest tests/ -v

# Run specific test file
python -m pytest tests/test_writer.py -v

# Run with coverage
python -m pytest tests/ --cov=content_writer --cov-report=html
```

## License / 许可证

MIT License - see [LICENSE](LICENSE) file for details.

## Contributing / 贡献

Contributions are welcome! Please feel free to submit a Pull Request.

欢迎贡献！请随时提交 Pull Request。


path: content_writer.py
content: """
Content Writer Pro - Professional copywriting generator
文案生成专家 - 专业文案生成工具

Features:
- Marketing copy generation / 营销文案生成
- Social media post templates / 社媒内容模板
- Ad copy variations / 广告文案变体
- Brand storytelling / 品牌故事
- Email templates / 邮件模板
- Product descriptions / 产品描述
"""

import random
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from enum import Enum


class ContentTone(Enum):
    """Content tone options / 内容语调选项"""
    PROFESSIONAL = "professional"  # 专业
    CASUAL = "casual"              # 随意
    PLAYFUL = "playful"            # 活泼
    FORMAL = "formal"              # 正式
    FRIENDLY = "friendly"          # 友好
    URGENT = "urgent"              # 紧急
    INSPIRATIONAL = "inspirational"  # 励志


class ContentType(Enum):
    """Content type options / 内容类型选项"""
    MARKETING = "marketing"
    SOCIAL_MEDIA = "social_media"
    AD_COPY = "ad_copy"
    BRAND_STORY = "brand_story"
    EMAIL = "email"
    PRODUCT_DESC = "product_description"


class SocialPlatform(Enum):
    """Social media platforms / 社交媒体平台"""
    LINKEDIN = "linkedin"
    TWITTER = "twitter"
    INSTAGRAM = "instagram"
    FACEBOOK = "facebook"
    WEIBO = "weibo"
    XIAOHONGSHU = "xiaohongshu"


@dataclass
class CopyResult:
    """Result of copy generation / 文案生成结果"""
    content: str
    content_type: str
    tone: str
    variations: List[str] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            "content": self.content,
            "content_type": self.content_type,
            "tone": self.tone,
            "variations": self.variations,
            "metadata": self.metadata
        }


@dataclass
class AdCopyResult:
    """Result of ad copy generation / 广告文案生成结果"""
    headlines: List[str]
    body_copies: List[str]
    ctas: List[str]
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            "headlines": self.headlines,
            "body_copies": self.body_copies,
            "ctas": self.ctas
        }


class ContentWriterError(Exception):
    """Custom exception for content writer errors / 文案生成器自定义异常"""
    pass


class ContentWriterPro:
    """
    Professional copywriting generator
    专业文案生成工具
    """
    
    # Templates for different content types / 不同内容类型的模板
    MARKETING_TEMPLATES = {
        ContentTone.PROFESSIONAL: [
            "Introducing {product}: The solution designed for {audience}. Experience {benefit} with our cutting-edge technology.",
            "{product} empowers {audience} to achieve {benefit}. Join thousands of professionals who trust our platform.",
            "Transform your workflow with {product}. Built specifically for {audience} who demand excellence.",
        ],
        ContentTone.CASUAL: [
            "Hey {audience}! Check out {product} - it's perfect for getting {benefit} without the hassle.",
            "Looking for {benefit}? {product} has got you covered! Made with {audience} in mind.",
            "Meet {product}: your new favorite tool for {benefit}. Designed especially for {audience} like you!",
        ],
        ContentTone.URGENT: [
            "Don't miss out! {product} is helping {audience} achieve {benefit} right now. Limited time offer!",
            "Act fast! {product} is revolutionizing how {audience} achieve {benefit}. Join before it's too late!",
        ],
        ContentTone.INSPIRATIONAL: [
            "Imagine achieving {benefit} effortlessly. With {product}, {audience} everywhere are making it happen.",
            "Your journey to {benefit} starts here. {product} - created for {audience} who dream big.",
        ]
    }
    
    SOCIAL_TEMPLATES = {
        SocialPlatform.LINKEDIN: {
            ContentTone.PROFESSIONAL: [
                "Excited to share insights on {topic}. In my experience, the key is consistent effort and strategic thinking. What are your thoughts? #ProfessionalGrowth",
                "Reflection on {topic}: Success doesn't happen overnight. It takes dedication, learning, and adaptability. Would love to hear your perspective. #Leadership",
                "Just published my thoughts on {topic}. After years in the industry, I've learned that {topic} requires both patience and innovation. Link in comments!",
            ],
            ContentTone.CASUAL: [
                "Quick thought on {topic} - sometimes the simplest approach works best. What's your take?",
                "Been thinking about {topic} lately. Anyone else feeling the same way about where things are headed?",
            ]
        },
        SocialPlatform.TWITTER: {
            ContentTone.PROFESSIONAL: [
                "Key insight on {topic}: Focus on what matters most. The rest will follow. #ProfessionalTips",
                "Thread on {topic} 🧵\n\n1/ Understanding the fundamentals is crucial before diving into advanced strategies.",
            ],
            ContentTone.CASUAL: [
                "Hot take on {topic} 👀\n\nChange my mind.",
                "Unpopular opinion: {topic} isn't as complicated as people make it out to be.",
            ]
        },
        SocialPlatform.INSTAGRAM: {
            ContentTone.CASUAL: [
                "✨ {topic} vibes only ✨\n\nWhat's your {topic} routine? Drop a 🙌 if you're all about it!",
                "When {topic} just clicks 🎯\n\nTag someone who needs to see this!",
            ],
            ContentTone.INSPIRATIONAL: [
                "Your {topic} journey is unique. Don't compare your chapter 1 to someone else's chapter 20. 💪",
                "Dream big. Work hard. Make {topic} happen. 🌟\n\nWho's with me?",
            ]
        }
    }
    
    AD_TEMPLATES = {
        "headlines": {
            ContentTone.URGENT: [
                "Limited Time: Transform Your {product_category} Today",
                "Don't Miss Out - {benefit} Awaits!",
                "Last Chance: Get {benefit} with {product}",
            ],
            ContentTone.PROFESSIONAL: [
                "The {product_category} Solution Trusted by {audience}",
                "Achieve {benefit} with {product}",
                "Professional-Grade {product_category} for {audience}",
            ],
            ContentTone.INSPIRATIONAL: [
                "Unlock Your Potential with {product}",
                "Your Journey to {benefit} Starts Here",
                "Imagine {benefit} - Now Make It Real",
            ]
        },
        "ctas": [
            "Get Started Now",
            "Learn More",
            "Try It Free",
            "Join Today",
            "Discover How",
            "Start Your Journey",
        ]
    }
    
    EMAIL_TEMPLATES = {
        "newsletter": {
            "subject": [
                "This Week's Insights: {topic}",
                "Your Weekly {topic} Digest",
                "What's New in {topic}?",
            ],
            "body": """Hi {name},

Welcome to this week's edition of our newsletter!

{topic} continues to evolve, and we're here to keep you informed. Here are this week's highlights:

{content}

Until next time,
The Team
"""
        },
        "promotional": {
            "subject": [
                "Special Offer: {discount}% Off {product}!",
                "Don't Miss: Exclusive Deal on {product}",
                "Your Invitation: Save on {product}",
            ],
            "body": """Hi {name},

We have something special for you!

For a limited time, enjoy {discount}% off {product}. Here's what you'll get:

{benefits}

[Shop Now - {cta}]

This offer expires soon, so don't wait!

Best regards,
The Team
"""
        },
        "welcome": {
            "subject": [
                "Welcome to {company}!",
                "Your Journey Starts Here",
                "Thanks for Joining {company}",
            ],
            "body": """Hi {name},

Welcome to the {company} family! 🎉

We're thrilled to have you on board. Here's what you can expect:

{onboarding_steps}

If you have any questions, just reply to this email.

Cheers,
The {company} Team
"""
        }
    }
    
    def __init__(self, config: Optional[Dict[str, Any]] = None):
        """
        Initialize ContentWriterPro
        
        Args:
            config: Optional configuration dictionary
                   可选的配置字典
        """
        self.config = config or {}
        self.default_tone = ContentTone(self.config.get('default_tone', 'professional'))
        self.max_length = self.config.get('max_length', 1000)
        self.language = self.config.get('language', 'en')
    
    def _get_random_template(self, templates: List[str]) -> str:
        """Get a random template from the list"""
        return random.choice(templates)
    
    def _validate_input(self, text: str, min_length: int = 1) -> None:
        """Validate input text"""
        if not text or len(text.strip()) < min_length:
            raise ContentWriterError(f"Input must be at least {min_length} characters")
    
    def generate_marketing_copy(
        self,
        product: str,
        audience: str,
        benefit: Optional[str] = None,
        tone: Optional[str] = None
    ) -> CopyResult:
        """
        Generate marketing copy
        生成营销文案
        
        Args:
            product: Product or service name
            audience: Target audience
            benefit: Key benefit (optional)
            tone: Content tone (optional)
            
        Returns:
            CopyResult with generated content
        """
        self._validate_input(product)
        self._validate_input(audience)
        
        tone_enum = ContentTone(tone) if tone else self.default_tone
        benefit = benefit or "amazing results"
        
        if tone_enum not in self.MARKETING_TEMPLATES:
            tone_enum = ContentTone.PROFESSIONAL
        
        templates = self.MARKETING_TEMPLATES[tone_enum]
        template = self._get_random_template(templates)
        
        content = template.format(
            product=product,
            audience=audience,
            benefit=benefit
        )
        
        # Generate variations
        variations = [
            t.format(product=product, audience=audience, benefit=benefit)
            for t in templates[:3]
        ]
        
        return CopyResult(
            content=content,
            content_type="marketing",
            tone=tone_enum.value,
            variations=variations,
            metadata={"product": product, "audience": audience}
        )
    
    def create_social_post(
        self,
        platform: str,
        topic: str,
        tone: Optional[str] = None,
        length: str = "medium"
    ) -> CopyResult:
        """
        Create social media post
        创建社交媒体帖子
        
        Args:
            platform: Social platform (linkedin, twitter, instagram)
            topic: Post topic
            tone: Content tone (optional)
            length: Post length (short, medium, long)
            
        Returns:
            CopyResult with generated post
        """
        self._validate_input(topic)
        
        try:
            platform_enum = SocialPlatform(platform.lower())
        except ValueError:
            platform_enum = SocialPlatform.LINKEDIN
        
        tone_enum = ContentTone(tone) if tone else ContentTone.CASUAL
        
        if platform_enum not in self.SOCIAL_TEMPLATES:
            platform_enum = SocialPlatform.LINKEDIN
        
        platform_templates = self.SOCIAL_TEMPLATES[platform_enum]
        
        if tone_enum not in platform_templates:
            tone_enum = list(platform_templates.keys())[0]
        
        templates = platform_templates[tone_enum]
        content = self._get_random_template(templates).format(topic=topic)
        
        return CopyResult(
            content=content,
            content_type="social_media",
            tone=tone_enum.value,
            variations=[t.format(topic=topic) for t in templates],
            metadata={"platform": platform, "topic": topic, "length": length}
        )
    
    def write_ad_copy(
        self,
        product: str,
        product_category: Optional[str] = None,
        audience: Optional[str] = None,
        benefit: Optional[str] = None,
        headline_options: int = 3,
        description_options: int = 2
    ) -> AdCopyResult:
        """
        Write advertising copy
        撰写广告文案
        
        Args:
            product: Product name
            product_category: Category of product
            audience: Target audience
            benefit: Key benefit
            headline_options: Number of headline variations
            description_options: Number of description variations
            
        Returns:
            AdCopyResult with headlines, body copies, and CTAs
        """
        self._validate_input(product)
        
        product_category = product_category or "Solution"
        audience = audience or "Professionals"
        benefit = benefit or "Success"
        
        headlines = []
        for tone in [ContentTone.URGENT, ContentTone.PROFESSIONAL, ContentTone.INSPIRATIONAL]:
            templates = self.AD_TEMPLATES["headlines"][tone]
            for template in templates[:max(1, headline_options // 3 + 1)]:
                headlines.append(template.format(
                    product=product,
                    product_category=product_category,
                    audience=audience,
                    benefit=benefit
                ))
        
        headlines = headlines[:headline_options]
        
        body_templates = [
            f"Discover how {product} helps {audience} achieve {benefit}. Our innovative approach sets us apart.",
            f"Join thousands of {audience} who trust {product} for {benefit}. Experience the difference today.",
            f"{product} is the {product_category} solution you've been looking for. Get {benefit} starting now.",
        ]
        body_copies = body_templates[:description_options]
        
        ctas = random.sample(self.AD_TEMPLATES["ctas"], min(3, len(self.AD_TEMPLATES["ctas"])))
        
        return AdCopyResult(
            headlines=headlines,
            body_copies=body_copies,
            ctas=ctas
        )
    
    def write_brand_story(
        self,
        company_name: str,
        founder_name: Optional[str] = None,
        origin_story: Optional[str] = None,
        mission: Optional[str] = None,
        values: Optional[List[str]] = None
    ) -> CopyResult:
        """
        Write brand story content
        撰写品牌故事内容
        
        Args:
            company_name: Company name
            founder_name: Founder name (optional)
            origin_story: Brief origin story (optional)
            mission: Company mission (optional)
            values: Company values (optional)
            
        Returns:
            CopyResult with brand story content
        """
        self._validate_input(company_name)
        
        values = values or ["Innovation", "Integrity", "Customer Focus"]
        mission = mission or f"To make a positive impact through our work at {company_name}"
        
        story_parts = [f"Welcome to {company_name}."]
        
        if origin_story:
            story_parts.append(f"Our journey began with a simple idea: {origin_story}")
        
        story_parts.append(f"Our mission is clear: {mission}")
        story_parts.append(f"We live by our values: {', '.join(values)}.")
        
        if founder_name:
            story_parts.append(f"Founded by {founder_name}, we continue to push boundaries every day.")
        
        story_parts.append(f"Join us as we write the next chapter of {company_name}.")
        
        content = "\n\n".join(story_parts)
        
        return CopyResult(
            content=content,
            content_type="brand_story",
            tone="inspirational",
            metadata={"company": company_name, "mission": mission, "values": values}
        )
    
    def write_email(
        self,
        email_type: str,
        topic: Optional[str] = None,
        name: Optional[str] = None,
        tone: Optional[str] = None,
        **kwargs
    ) -> CopyResult:
        """
        Write email content
        撰写邮件内容
        
        Args:
            email_type: Type of email (newsletter, promotional, welcome)
            topic: Email topic (optional)
            name: Recipient name (optional)
            tone: Email tone (optional)
            **kwargs: Additional template variables
            
        Returns:
            CopyResult with email subject and body
        """
        if email_type not in self.EMAIL_TEMPLATES:
            raise ContentWriterError(f"Unknown email type: {email_type}")
        
        topic = topic or "Updates"
        name = name or "there"
        
        templates = self.EMAIL_TEMPLATES[email_type]
        subject = self._get_random_template(templates["subject"]).format(
            topic=topic,
            **kwargs
        )
        
        body = templates["body"].format(
            name=name,
            topic=topic,
            **kwargs
        )
        
        content = f"Subject: {subject}\n\n{body}"
        
        return CopyResult(
            content=content,
            content_type=f"email_{email_type}",
            tone=tone or "professional",
            metadata={"email_type": email_type, "subject": subject}
        )
    
    def write_product_description(
        self,
        product_name: str,
        features: List[str],
        target_audience: Optional[str] = None,
        unique_selling_point: Optional[str] = None
    ) -> CopyResult:
        """
        Write product description
        撰写产品描述
        
        Args:
            product_name: Product name
            features: List of product features
            target_audience: Target audience (optional)
            unique_selling_point: USP (optional)
            
        Returns:
            CopyResult with product description
        """
        self._validate_input(product_name)
        if not features:
            raise ContentWriterError("At least one feature is required")
        
        target_audience = target_audience or "professionals"
        usp = unique_selling_point or f"the best choice for {target_audience}"
        
        intro = f"Introducing {product_name} - {usp}."
        
        feature_text = "Key features include:\n"
        for feature in features:
            feature_text += f"• {feature}\n"
        
        closing = f"Designed for {target_audience} who demand excellence. Experience {product_name} today."
        
        content = f"{intro}\n\n{feature_text}\n{closing}"
        
        return CopyResult(
            content=content,
            content_type="product_description",
            tone="professional",
            metadata={"product": product_name, "features": features}
        )
    
    def create_twitter_thread(
        self,
        topic: str,
        num_tweets: int = 5,
        tone: Optional[str] = None
    ) -> List[str]:
        """
        Create a Twitter thread
        创建 Twitter 串推
        
        Args:
            topic: Thread topic
            num_tweets: Number of tweets in thread
            tone: Content tone (optional)
            
        Returns:
            List of tweet texts
        """
        self._validate_input(topic)
        if num_tweets < 2 or num_tweets > 10:
            raise ContentWriterError("Number of tweets must be between 2 and 10")
        
        tone_enum = ContentTone(tone) if tone else ContentTone.PROFESSIONAL
        
        tweets = []
        
        # Opening tweet
        if tone_enum == ContentTone.PROFESSIONAL:
            tweets.append(f"Thread on {topic} 🧵\n\n1/{num_tweets} Understanding {topic} requires looking at multiple perspectives.")
        else:
            tweets.append(f"{topic} thread incoming 🧵\n\n1/{num_tweets} Let's dive in!")
        
        # Middle tweets
        for i in range(2, num_tweets):
            if tone_enum == ContentTone.PROFESSIONAL:
                tweets.append(f"{i}/{num_tweets} Key insight: {topic} is about continuous learning and adaptation.")
            else:
                tweets.append(f"{i}/{num_tweets} Here's something interesting about {topic}...")
        
        # Closing tweet
        if tone_enum == ContentTone.PROFESSIONAL:
            tweets.append(f"{num_tweets}/{num_tweets} Thanks for reading! What's your experience with {topic}? Let's discuss. 👇")
        else:
            tweets.append(f"{num_tweets}/{num_tweets} That's a wrap! Thoughts on {topic}? Drop a comment! 💬")
        
        return tweets
    
    def get_supported_tones(self) -> List[str]:
        """Get list of supported tones / 获取支持的语调列表"""
        return [tone.value for tone in ContentTone]
    
    def get_supported_platforms(self) -> List[str]:
        """Get list of supported social platforms / 获取支持的社交平台列表"""
        return [platform.value for platform in SocialPlatform]


# Convenience function for quick copy generation
def quick_marketing_copy(product: str, audience: str, benefit: str = "great results") -> str:
    """
    Quick function to generate marketing copy
    快速生成营销文案的函数
    
    Args:
        product: Product name
        audience: Target audience
        benefit: Key benefit
        
    Returns:
        Generated marketing copy string
    """
    writer = ContentWriterPro()
    result = writer.generate_marketing_copy(product, audience, benefit)
    return result.content


path: examples/basic_usage.py
content: #!/usr/bin/env python3
"""
Basic usage examples for Content Writer Pro
文案生成专家基础使用示例
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from content_writer import ContentWriterPro, quick_marketing_copy


def example_marketing_copy():
    """Example: Generate marketing copy / 生成营销文案示例"""
    print("=" * 60)
    print("Marketing Copy Example / 营销文案示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    # Professional tone / 专业语调
    result = writer.generate_marketing_copy(
        product="AI Analytics Platform",
        audience="Data Scientists",
        benefit="faster insights",
        tone="professional"
    )
    print("\nProfessional Tone:")
    print(result.content)
    
    # Casual tone / 随意语调
    result = writer.generate_marketing_copy(
        product="Task Manager App",
        audience="Freelancers",
        benefit="staying organized",
        tone="casual"
    )
    print("\nCasual Tone:")
    print(result.content)
    
    # Urgent tone / 紧急语调
    result = writer.generate_marketing_copy(
        product="SEO Masterclass",
        audience="Marketers",
        benefit="higher rankings",
        tone="urgent"
    )
    print("\nUrgent Tone:")
    print(result.content)


def example_social_media():
    """Example: Create social media posts / 创建社交媒体帖子示例"""
    print("\n" + "=" * 60)
    print("Social Media Example / 社媒内容示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    # LinkedIn post / LinkedIn帖子
    result = writer.create_social_post(
        platform="linkedin",
        topic="Remote Work Best Practices",
        tone="professional"
    )
    print("\nLinkedIn Post:")
    print(result.content)
    
    # Twitter post / Twitter帖子
    result = writer.create_social_post(
        platform="twitter",
        topic="AI Tools",
        tone="casual"
    )
    print("\nTwitter Post:")
    print(result.content)


def example_ad_copy():
    """Example: Write ad copy / 撰写广告文案示例"""
    print("\n" + "=" * 60)
    print("Ad Copy Example / 广告文案示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    result = writer.write_ad_copy(
        product="Cloud Storage Pro",
        product_category="Cloud Storage",
        audience="Small Businesses",
        benefit="secure file management",
        headline_options=3,
        description_options=2
    )
    
    print("\nHeadlines:")
    for i, headline in enumerate(result.headlines, 1):
        print(f"  {i}. {headline}")
    
    print("\nBody Copies:")
    for i, body in enumerate(result.body_copies, 1):
        print(f"  {i}. {body}")
    
    print("\nCTAs:")
    for i, cta in enumerate(result.ctas, 1):
        print(f"  {i}. {cta}")


def example_brand_story():
    """Example: Write brand story / 撰写品牌故事示例"""
    print("\n" + "=" * 60)
    print("Brand Story Example / 品牌故事示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    result = writer.write_brand_story(
        company_name="TechFlow",
        founder_name="Sarah Chen",
        origin_story="a passion for making technology accessible to everyone",
        mission="to democratize tech education",
        values=["Innovation", "Accessibility", "Community"]
    )
    
    print("\nBrand Story:")
    print(result.content)


def example_email():
    """Example: Write emails / 撰写邮件示例"""
    print("\n" + "=" * 60)
    print("Email Example / 邮件示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    # Newsletter / 新闻简报
    result = writer.write_email(
        email_type="newsletter",
        topic="AI Trends",
        name="John",
        content="• New AI models released\n• Industry insights\n• Upcoming events"
    )
    print("\nNewsletter:")
    print(result.content)
    
    # Promotional email / 促销邮件
    result = writer.write_email(
        email_type="promotional",
        name="Jane",
        product="Premium Plan",
        discount=20,
        benefits="• Unlimited storage\n• Priority support\n• Advanced analytics",
        cta="Get 20% Off"
    )
    print("\nPromotional Email:")
    print(result.content)


def example_product_description():
    """Example: Write product description / 撰写产品描述示例"""
    print("\n" + "=" * 60)
    print("Product Description Example / 产品描述示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    result = writer.write_product_description(
        product_name="Smart Hub X1",
        features=[
            "Voice control with AI assistant",
            "Compatible with 500+ smart devices",
            "Privacy-first design",
            "Energy monitoring dashboard"
        ],
        target_audience="smart home enthusiasts",
        unique_selling_point="the smartest home hub that actually respects your privacy"
    )
    
    print("\nProduct Description:")
    print(result.content)


def example_twitter_thread():
    """Example: Create Twitter thread / 创建Twitter串推示例"""
    print("\n" + "=" * 60)
    print("Twitter Thread Example / Twitter串推示例")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    tweets = writer.create_twitter_thread(
        topic="Startup Fundraising",
        num_tweets=5,
        tone="professional"
    )
    
    print("\nTwitter Thread:")
    for tweet in tweets:
        print(f"\n---\n{tweet}")


def example_quick_function():
    """Example: Quick marketing copy function / 快速营销文案函数示例"""
    print("\n" + "=" * 60)
    print("Quick Function Example / 快速函数示例")
    print("=" * 60)
    
    copy = quick_marketing_copy(
        product="Fitness App",
        audience="Busy Professionals",
        benefit="staying fit"
    )
    
    print("\nQuick Marketing Copy:")
    print(copy)


def example_list_options():
    """Example: List supported options / 列出支持的选项示例"""
    print("\n" + "=" * 60)
    print("Available Options / 可用选项")
    print("=" * 60)
    
    writer = ContentWriterPro()
    
    print("\nSupported Tones / 支持语调:")
    for tone in writer.get_supported_tones():
        print(f"  - {tone}")
    
    print("\nSupported Platforms / 支持平台:")
    for platform in writer.get_supported_platforms():
        print(f"  - {platform}")


if __name__ == "__main__":
    # Run all examples / 运行所有示例
    example_marketing_copy()
    example_social_media()
    example_ad_copy()
    example_brand_story()
    example_email()
    example_product_description()
    example_twitter_thread()
    example_quick_function()
    example_list_options()
    
    print("\n" + "=" * 60)
    print("All examples completed! / 所有示例完成！")
    print("=" * 60)


path: requirements.txt
content: # Content Writer Pro - Requirements
# 文案生成专家 - 依赖

# Core dependencies
jinja2>=3.0.0
pyyaml>=6.0

# Development dependencies
pytest>=7.0.0
pytest-cov>=4.0.0


path: tests/test_writer.py
content: #!/usr/bin/env python3
"""
Unit tests for Content Writer Pro / 文案生成专家的单元测试

Run with: python -m pytest tests/test_writer.py -v
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import unittest
from content_writer import (
    ContentWriterPro,
    ContentTone,
    ContentType,
    SocialPlatform,
    CopyResult,
    AdCopyResult,
    ContentWriterError,
    quick_marketing_copy,
)


class TestContentWriterPro(unittest.TestCase):
    """Test cases for ContentWriterPro class"""
    
    def setUp(self):
        """Set up test fixtures"""
        self.writer = ContentWriterPro()
    
    # =================================================================
    # Marketing Copy Tests / 营销文案测试
    # =================================================================
    
    def test_generate_marketing_copy_basic(self):
        """Test basic marketing copy generation"""
        result = self.writer.generate_marketing_copy(
            product="Test Product",
            audience="Testers"
        )
        self.assertIsInstance(result, CopyResult)
        self.assertEqual(result.content_type, "marketing")
        self.assertGreater(len(result.content), 0)
    
    def test_generate_marketing_copy_with_benefit(self):
        """Test marketing copy with benefit specified"""
        result = self.writer.generate_marketing_copy(
            product="AI Tool",
            audience="Developers",
            benefit="faster coding"
        )
        self.assertIn("faster", result.content.lower())
    
    def test_generate_marketing_copy_with_tone(self):
        """Test marketing copy with specific tone"""
        result = self.writer.generate_marketing_copy(
            product="App",
            audience="Users",
            tone="casual"
        )
        self.assertEqual(result.tone, "casual")
    
    def test_generate_marketing_copy_empty_product_raises_error(self):
        """Test that empty product raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.generate_marketing_copy("", "Audience")
    
    def test_generate_marketing_copy_empty_audience_raises_error(self):
        """Test that empty audience raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.generate_marketing_copy("Product", "")
    
    def test_generate_marketing_copy_has_variations(self):
        """Test that result includes variations"""
        result = self.writer.generate_marketing_copy("Product", "Audience")
        self.assertIsInstance(result.variations, list)
        self.assertGreater(len(result.variations), 0)
    
    # =================================================================
    # Social Media Tests / 社媒内容测试
    # =================================================================
    
    def test_create_social_post_basic(self):
        """Test basic social post creation"""
        result = self.writer.create_social_post(
            platform="linkedin",
            topic="AI"
        )
        self.assertIsInstance(result, CopyResult)
        self.assertEqual(result.content_type, "social_media")
    
    def test_create_social_post_different_platforms(self):
        """Test social posts for different platforms"""
        platforms = ["linkedin", "twitter", "instagram"]
        for platform in platforms:
            result = self.writer.create_social_post(
                platform=platform,
                topic="Test"
            )
            self.assertIsInstance(result, CopyResult)
            self.assertEqual(result.metadata["platform"], platform)
    
    def test_create_social_post_empty_topic_raises_error(self):
        """Test that empty topic raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.create_social_post("linkedin", "")
    
    def test_create_social_post_with_tone(self):
        """Test social post with specific tone"""
        result = self.writer.create_social_post(
            platform="twitter",
            topic="Startup",
            tone="casual"
        )
        self.assertEqual(result.tone, "casual")
    
    # =================================================================
    # Ad Copy Tests / 广告文案测试
    # =================================================================
    
    def test_write_ad_copy_basic(self):
        """Test basic ad copy generation"""
        result = self.writer.write_ad_copy(product="Test Product")
        self.assertIsInstance(result, AdCopyResult)
        self.assertGreater(len(result.headlines), 0)
        self.assertGreater(len(result.body_copies), 0)
        self.assertGreater(len(result.ctas), 0)
    
    def test_write_ad_copy_with_options(self):
        """Test ad copy with specific option counts"""
        result = self.writer.write_ad_copy(
            product="Product",
            headline_options=5,
            description_options=3
        )
        self.assertLessEqual(len(result.headlines), 5)
        self.assertLessEqual(len(result.body_copies), 3)
    
    def test_write_ad_copy_empty_product_raises_error(self):
        """Test that empty product raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.write_ad_copy("")
    
    def test_write_ad_copy_has_ctas(self):
        """Test that ad copy includes CTAs"""
        result = self.writer.write_ad_copy(product="Product")
        self.assertIsInstance(result.ctas, list)
        self.assertGreater(len(result.ctas), 0)
    
    # =================================================================
    # Brand Story Tests / 品牌故事测试
    # =================================================================
    
    def test_write_brand_story_basic(self):
        """Test basic brand story generation"""
        result = self.writer.write_brand_story(company_name="Test Co")
        self.assertIsInstance(result, CopyResult)
        self.assertEqual(result.content_type, "brand_story")
        self.assertIn("Test Co", result.content)
    
    def test_write_brand_story_with_all_params(self):
        """Test brand story with all parameters"""
        result = self.writer.write_brand_story(
            company_name="TechCorp",
            founder_name="John Doe",
            origin_story="a garage project",
            mission="to change the world",
            values=["Innovation", "Integrity"]
        )
        self.assertIn("John Doe", result.content)
        self.assertIn("change the world", result.content)
    
    def test_write_brand_story_empty_company_raises_error(self):
        """Test that empty company name raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.write_brand_story("")
    
    # =================================================================
    # Email Tests / 邮件测试
    # =================================================================
    
    def test_write_email_newsletter(self):
        """Test newsletter email generation"""
        result = self.writer.write_email(
            email_type="newsletter",
            topic="AI News",
            name="Reader"
        )
        self.assertIsInstance(result, CopyResult)
        self.assertEqual(result.content_type, "email_newsletter")
    
    def test_write_email_promotional(self):
        """Test promotional email generation"""
        result = self.writer.write_email(
            email_type="promotional",
            product="Pro Plan",
            discount=20
        )
        self.assertIn("20%", result.content)
    
    def test_write_email_welcome(self):
        """Test welcome email generation"""
        result = self.writer.write_email(
            email_type="welcome",
            company="Startup",
            name="New User"
        )
        self.assertIn("Startup", result.content)
    
    def test_write_email_unknown_type_raises_error(self):
        """Test that unknown email type raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.write_email(email_type="unknown")
    
    # =================================================================
    # Product Description Tests / 产品描述测试
    # =================================================================
    
    def test_write_product_description_basic(self):
        """Test basic product description generation"""
        result = self.writer.write_product_description(
            product_name="Test Product",
            features=["Feature 1", "Feature 2"]
        )
        self.assertIsInstance(result, CopyResult)
        self.assertEqual(result.content_type, "product_description")
        self.assertIn("Test Product", result.content)
    
    def test_write_product_description_empty_features_raises_error(self):
        """Test that empty features list raises error"""
        with self.assertRaises(ContentWriterError):
            self.writer.write_product_description("Product", [])
    
    def test_write_product_description_includes_features(self):
        """Test that description includes all features"""
        features = ["AI-powered", "Cloud-based", "Secure"]
        result = self.writer.write_product_description(
            product_name="App",
            features=features
        )
        for feature in features:
            self.assertIn(feature, result.content)
    
    # =================================================================
    # Twitter Thread Tests / Twitter串推测试
    # =================================================================
    
    def test_create_twitter_thread_basic(self):
        """Test basic Twitter thread creation"""
        tweets = self.writer.create_twitter_thread(
            topic="Startup",
            num_tweets=5
        )
        self.assertIsInstance(tweets, list)
        self.assertEqual(len(tweets), 5)
    
    def test_create_twitter_thread_min_max(self):
        """Test Twitter thread with min and max tweet counts"""
        with self.assertRaises(ContentWriterError):
            self.writer.create_twitter_thread("Topic", 1)
        
        with self.assertRaises(ContentWriterError):
            self.writer.create_twitter_thread("Topic", 11)
    
    def test_create_twitter_thread_has_numbering(self):
        """Test that tweets have numbering"""
        tweets = self.writer.create_twitter_thread("Topic", 3)
        self.assertIn("1/3", tweets[0])
        self.assertIn("2/3", tweets[1])
        self.assertIn("3/3", tweets[2])
    
    # =================================================================
    # Configuration Tests / 配置测试
    # =================================================================
    
    def test_default_config(self):
        """Test default configuration"""
        writer = ContentWriterPro()
        self.assertEqual(writer.default_tone, ContentTone.PROFESSIONAL)
        self.assertEqual(writer.max_length, 1000)
    
    def test_custom_config(self):
        """Test custom configuration"""
        config = {
            'default_tone': 'casual',
            'max_length': 500,
            'language': 'zh'
        }
        writer = ContentWriterPro(config=config)
        self.assertEqual(writer.default_tone, ContentTone.CASUAL)
        self.assertEqual(writer.max_length, 500)
    
    # =================================================================
    # List Options Tests / 选项列表测试
    # =================================================================
    
    def test_get_supported_tones(self):
        """Test getting supported tones"""
        tones = self.writer.get_supported_tones()
        self.assertIsInstance(tones, list)
        self.assertIn("professional", tones)
        self.assertIn("casual", tones)
    
    def test_get_supported_platforms(self):
        """Test getting supported platforms"""
        platforms = self.writer.get_supported_platforms()
        self.assertIsInstance(platforms, list)
        self.assertIn("linkedin", platforms)
        self.assertIn("twitter", platforms)
    
    # =================================================================
    # Quick Function Tests / 快速函数测试
    # =================================================================
    
    def test_quick_marketing_copy(self):
        """Test quick marketing copy function"""
        copy = quick_marketing_copy("Product", "Audience")
        self.assertIsInstance(copy, str)
        self.assertGreater(len(copy), 0)
    
    def test_quick_marketing_copy_with_benefit(self):
        """Test quick marketing copy with benefit"""
        copy = quick_marketing_copy("Tool", "Devs", "efficiency")
        self.assertIn("Tool", copy)


class TestCopyResult(unittest.TestCase):
    """Test cases for CopyResult dataclass"""
    
    def test_default_creation(self):
        """Test default CopyResult creation"""
        result = CopyResult(
            content="Test content",
            content_type="marketing",
            tone="professional"
        )
        self.assertEqual(result.content, "Test content")
        self.assertEqual(result.content_type, "marketing")
        self.assertEqual(result.tone, "professional")
    
    def test_to_dict(self):
        """Test to_dict method"""
        result = CopyResult(
            content="Test",
            content_type="test",
            tone="neutral",
            variations=["v1", "v2"]
        )
        d = result.to_dict()
        self.assertIsInstance(d, dict)
        self.assertEqual(d['content'], "Test")
        self.assertEqual(d['variations'], ["v1", "v2"])


class TestAdCopyResult(unittest.TestCase):
    """Test cases for AdCopyResult dataclass"""
    
    def test_to_dict(self):
        """Test to_dict method"""
        result = AdCopyResult(
            headlines=["H1", "H2"],
            body_copies=["B1"],
            ctas=["CTA1"]
        )
        d = result.to_dict()
        self.assertIsInstance(d, dict)
        self.assertEqual(len(d['headlines']), 2)


class TestContentWriterError(unittest.TestCase):
    """Test cases for ContentWriterError exception"""
    
    def test_error_message(self):
        """Test error message"""
        error = ContentWriterError("Test error")
        self.assertEqual(str(error), "Test error")
    
    def test_error_is_exception(self):
        """Test that ContentWriterError is an Exception"""
        with self.assertRaises(Exception):
            raise ContentWriterError("test")


class TestEnums(unittest.TestCase):
    """Test cases for Enum classes"""
    
    def test_content_tone_values(self):
        """Test ContentTone enum values"""
        self.assertEqual(ContentTone.PROFESSIONAL.value, "professional")
        self.assertEqual(ContentTone.CASUAL.value, "casual")
    
    def test_social_platform_values(self):
        """Test SocialPlatform enum values"""
        self.assertEqual(SocialPlatform.LINKEDIN.value, "linkedin")
        self.assertEqual(SocialPlatform.TWITTER.value, "twitter")


if __name__ == '__main__':
    unittest.main(verbosity=2)


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)