✍️ Project: AI Content Writing Assistant

Build a complete AI-powered content creation tool

Project Overview

Create a production-ready AI writing assistant that helps users generate blog posts, social media content, marketing copy, and more with customizable tone, style, and SEO optimization.

Features We'll Build:

  • Multiple content types: Blog posts, social media, emails, SEO articles
  • Tone adjustment: Professional, casual, enthusiastic, formal
  • Style templates: Technical, creative, persuasive, informative
  • SEO optimization: Keyword integration and readability analysis
  • Multi-language support: Generate content in 50+ languages
  • Export options: Markdown, HTML, plain text

🛠️ Setup and Dependencies

# Install required packages
pip install streamlit openai langchain anthropic
pip install textstat pypdf2 python-docx markdown

# Required imports
import streamlit as st
import openai
from openai import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
import textstat  # For readability metrics
import json
import os
from datetime import datetime

print("✓ Dependencies installed!")
print("\nRequired API keys:")
print("  - OpenAI API key: https://platform.openai.com")
print("  - Anthropic API key (optional): https://console.anthropic.com")

🎨 Content Generation Engine

class ContentGenerator:
    """Core content generation engine"""
    
    def __init__(self, api_key=None, model="gpt-4"):
        self.client = OpenAI(api_key=api_key or os.getenv('OPENAI_API_KEY'))
        self.model = model
        self.content_types = {
            'blog_post': 'Blog Post',
            'social_media': 'Social Media Post',
            'email': 'Email',
            'product_description': 'Product Description',
            'seo_article': 'SEO Article',
            'ad_copy': 'Advertisement Copy',
        }
    
    def generate_content(self, 
                        topic,
                        content_type='blog_post',
                        tone='professional',
                        style='informative',
                        length='medium',
                        keywords=None,
                        audience='general',
                        language='English'):
        """
        Generate content based on parameters
        
        Args:
            topic: Main topic/subject
            content_type: Type of content to generate
            tone: Writing tone (professional, casual, enthusiastic, formal)
            style: Writing style (technical, creative, persuasive, informative)
            length: Content length (short, medium, long)
            keywords: SEO keywords to include
            audience: Target audience
            language: Output language
        """
        
        # Build prompt
        system_prompt = self._build_system_prompt(
            content_type, tone, style, audience, language
        )
        
        user_prompt = self._build_user_prompt(
            topic, length, keywords
        )
        
        # Generate content
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            temperature=0.7,
            max_tokens=2000 if length == 'long' else (1000 if length == 'medium' else 500)
        )
        
        content = response.choices[0].message.content
        
        return content
    
    def _build_system_prompt(self, content_type, tone, style, audience, language):
        """Build system prompt based on parameters"""
        
        tone_descriptions = {
            'professional': 'professional, polished, and business-appropriate',
            'casual': 'conversational, friendly, and approachable',
            'enthusiastic': 'energetic, exciting, and passionate',
            'formal': 'formal, academic, and authoritative',
        }
        
        style_descriptions = {
            'technical': 'detailed, precise, with technical accuracy',
            'creative': 'imaginative, engaging, with vivid descriptions',
            'persuasive': 'compelling, convincing, action-oriented',
            'informative': 'educational, clear, well-structured',
        }
        
        prompt = f"""You are an expert {content_type} writer.

Writing Guidelines:
- Tone: {tone_descriptions.get(tone, tone)}
- Style: {style_descriptions.get(style, style)}
- Target Audience: {audience}
- Language: {language}

Create high-quality, engaging content that is:
1. Well-structured and easy to read
2. Free of grammatical errors
3. Optimized for the target audience
4. Original and creative
5. Actionable and valuable"""
        
        return prompt
    
    def _build_user_prompt(self, topic, length, keywords):
        """Build user prompt"""
        
        length_guidance = {
            'short': '200-300 words',
            'medium': '500-700 words',
            'long': '1000-1500 words',
        }
        
        prompt = f"Topic: {topic}\n\n"
        prompt += f"Target Length: {length_guidance.get(length, '500-700 words')}\n\n"
        
        if keywords:
            prompt += f"SEO Keywords to naturally include: {', '.join(keywords)}\n\n"
        
        prompt += "Generate the content now:"
        
        return prompt

# Initialize generator
generator = ContentGenerator(model="gpt-4")

# Example usage
content = generator.generate_content(
    topic="The Future of Artificial Intelligence in Healthcare",
    content_type='blog_post',
    tone='professional',
    style='informative',
    length='medium',
    keywords=['AI healthcare', 'medical technology', 'patient care'],
    audience='healthcare professionals'
)

print("✓ Content generated!")
print(f"\nPreview:\n{content[:200]}...")

📊 SEO Analyzer

class SEOAnalyzer:
    """Analyze content for SEO and readability"""
    
    def __init__(self):
        self.metrics = {}
    
    def analyze(self, content, keywords=None):
        """
        Comprehensive SEO analysis
        
        Returns:
            Dict with readability scores, keyword density, suggestions
        """
        
        # Word count
        words = content.split()
        word_count = len(words)
        
        # Readability scores
        flesch_reading_ease = textstat.flesch_reading_ease(content)
        flesch_kincaid_grade = textstat.flesch_kincaid_grade(content)
        
        # Keyword analysis
        keyword_metrics = {}
        if keywords:
            content_lower = content.lower()
            for keyword in keywords:
                count = content_lower.count(keyword.lower())
                density = (count / word_count) * 100 if word_count > 0 else 0
                keyword_metrics[keyword] = {
                    'count': count,
                    'density': f'{density:.2f}%'
                }
        
        # Structure analysis
        sentences = content.split('.')
        sentence_count = len([s for s in sentences if s.strip()])
        avg_sentence_length = word_count / sentence_count if sentence_count > 0 else 0
        
        # Compile results
        analysis = {
            'word_count': word_count,
            'sentence_count': sentence_count,
            'avg_sentence_length': round(avg_sentence_length, 1),
            'readability': {
                'flesch_reading_ease': round(flesch_reading_ease, 1),
                'flesch_kincaid_grade': round(flesch_kincaid_grade, 1),
                'interpretation': self._interpret_readability(flesch_reading_ease)
            },
            'keyword_metrics': keyword_metrics,
            'suggestions': self._generate_suggestions(
                flesch_reading_ease,
                avg_sentence_length,
                keyword_metrics
            )
        }
        
        return analysis
    
    def _interpret_readability(self, score):
        """Interpret Flesch Reading Ease score"""
        if score >= 90:
            return "Very Easy (5th grade)"
        elif score >= 80:
            return "Easy (6th grade)"
        elif score >= 70:
            return "Fairly Easy (7th grade)"
        elif score >= 60:
            return "Standard (8th-9th grade)"
        elif score >= 50:
            return "Fairly Difficult (10th-12th grade)"
        elif score >= 30:
            return "Difficult (College)"
        else:
            return "Very Difficult (College graduate)"
    
    def _generate_suggestions(self, readability, avg_sentence_length, keywords):
        """Generate improvement suggestions"""
        suggestions = []
        
        if readability < 50:
            suggestions.append("Consider simplifying language for better readability")
        
        if avg_sentence_length > 25:
            suggestions.append("Try shorter sentences for better clarity")
        
        if keywords:
            low_density = [k for k, v in keywords.items() 
                          if float(v['density'].rstrip('%')) < 0.5]
            if low_density:
                suggestions.append(f"Increase usage of: {', '.join(low_density)}")
        
        if not suggestions:
            suggestions.append("Content looks good! No major issues detected.")
        
        return suggestions

# Example usage
analyzer = SEOAnalyzer()

sample_content = """
Artificial intelligence is revolutionizing healthcare in unprecedented ways.
From diagnostic assistance to personalized treatment plans, AI healthcare 
solutions are improving patient care and outcomes. Medical technology powered 
by machine learning can analyze vast amounts of data quickly and accurately.
"""

analysis = analyzer.analyze(
    sample_content,
    keywords=['AI healthcare', 'medical technology', 'patient care']
)

print("SEO Analysis:")
print(f"  Word Count: {analysis['word_count']}")
print(f"  Readability: {analysis['readability']['interpretation']}")
print(f"  Keyword Density:")
for kw, metrics in analysis['keyword_metrics'].items():
    print(f"    {kw}: {metrics['count']} times ({metrics['density']})")
print(f"\nSuggestions:")
for suggestion in analysis['suggestions']:
    print(f"  • {suggestion}")

🎨 Streamlit Interface

# app.py - Main Streamlit application

import streamlit as st

def main():
    st.set_page_config(
        page_title="AI Content Writer",
        page_icon="✍️",
        layout="wide"
    )
    
    st.title("✍️ AI Content Writing Assistant")
    st.markdown("Generate high-quality content with AI-powered assistance")
    
    # Sidebar configuration
    with st.sidebar:
        st.header("⚙️ Configuration")
        
        # API Key
        api_key = st.text_input("OpenAI API Key", type="password")
        
        # Content Type
        content_type = st.selectbox(
            "Content Type",
            ['blog_post', 'social_media', 'email', 'product_description', 
             'seo_article', 'ad_copy']
        )
        
        # Tone
        tone = st.select_slider(
            "Tone",
            options=['formal', 'professional', 'casual', 'enthusiastic']
        )
        
        # Style
        style = st.selectbox(
            "Style",
            ['informative', 'persuasive', 'creative', 'technical']
        )
        
        # Length
        length = st.radio(
            "Length",
            ['short', 'medium', 'long']
        )
        
        # Language
        language = st.selectbox(
            "Language",
            ['English', 'Spanish', 'French', 'German', 'Italian', 
             'Portuguese', 'Chinese', 'Japanese']
        )
    
    # Main content area
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.header("📝 Content Generation")
        
        # Topic input
        topic = st.text_input(
            "Topic",
            placeholder="Enter your content topic..."
        )
        
        # Keywords
        keywords_input = st.text_input(
            "SEO Keywords (comma-separated)",
            placeholder="keyword1, keyword2, keyword3"
        )
        keywords = [k.strip() for k in keywords_input.split(',') if k.strip()]
        
        # Target audience
        audience = st.text_input(
            "Target Audience",
            placeholder="e.g., marketing professionals, teenagers, business owners"
        )
        
        # Generate button
        if st.button("🚀 Generate Content", type="primary"):
            if not api_key:
                st.error("Please enter your OpenAI API key in the sidebar")
            elif not topic:
                st.error("Please enter a topic")
            else:
                with st.spinner("Generating content..."):
                    # Initialize generator
                    generator = ContentGenerator(api_key=api_key)
                    
                    # Generate content
                    content = generator.generate_content(
                        topic=topic,
                        content_type=content_type,
                        tone=tone,
                        style=style,
                        length=length,
                        keywords=keywords,
                        audience=audience or 'general',
                        language=language
                    )
                    
                    # Store in session state
                    st.session_state.generated_content = content
                    st.session_state.keywords = keywords
                    
                    st.success("✓ Content generated successfully!")
        
        # Display generated content
        if 'generated_content' in st.session_state:
            st.markdown("---")
            st.subheader("Generated Content")
            
            # Editable text area
            edited_content = st.text_area(
                "Edit content if needed:",
                value=st.session_state.generated_content,
                height=400
            )
            
            # Update if edited
            if edited_content != st.session_state.generated_content:
                st.session_state.generated_content = edited_content
            
            # Export options
            st.markdown("---")
            st.subheader("📥 Export")
            
            col_exp1, col_exp2, col_exp3 = st.columns(3)
            
            with col_exp1:
                st.download_button(
                    "Download as Text",
                    data=edited_content,
                    file_name=f"content_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
                    mime="text/plain"
                )
            
            with col_exp2:
                st.download_button(
                    "Download as Markdown",
                    data=edited_content,
                    file_name=f"content_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
                    mime="text/markdown"
                )
            
            with col_exp3:
                # Convert to HTML
                import markdown
                html_content = markdown.markdown(edited_content)
                st.download_button(
                    "Download as HTML",
                    data=html_content,
                    file_name=f"content_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html",
                    mime="text/html"
                )
    
    with col2:
        st.header("📊 Analysis")
        
        if 'generated_content' in st.session_state:
            # Analyze content
            analyzer = SEOAnalyzer()
            analysis = analyzer.analyze(
                st.session_state.generated_content,
                st.session_state.get('keywords')
            )
            
            # Display metrics
            st.metric("Word Count", analysis['word_count'])
            st.metric("Sentences", analysis['sentence_count'])
            st.metric("Avg Sentence Length", f"{analysis['avg_sentence_length']} words")
            
            st.markdown("---")
            st.subheader("📖 Readability")
            st.metric(
                "Flesch Reading Ease",
                analysis['readability']['flesch_reading_ease']
            )
            st.info(analysis['readability']['interpretation'])
            
            # Keyword metrics
            if analysis['keyword_metrics']:
                st.markdown("---")
                st.subheader("🔑 Keywords")
                for kw, metrics in analysis['keyword_metrics'].items():
                    st.write(f"**{kw}**")
                    st.write(f"  Count: {metrics['count']}")
                    st.write(f"  Density: {metrics['density']}")
            
            # Suggestions
            st.markdown("---")
            st.subheader("💡 Suggestions")
            for suggestion in analysis['suggestions']:
                st.write(f"• {suggestion}")
        else:
            st.info("Generate content to see analysis")

if __name__ == "__main__":
    main()

# Run with: streamlit run app.py

🎯 Content Templates

class ContentTemplates:
    """Pre-built content templates"""
    
    TEMPLATES = {
        'blog_intro': """Write an engaging blog post introduction about {topic}.
        
Guidelines:
- Hook the reader in the first sentence
- Introduce the main topic
- Preview what they'll learn
- Keep it under 150 words""",
        
        'product_description': """Write a compelling product description for {topic}.
        
Include:
- Key features and benefits
- Target customer
- Unique selling proposition
- Call to action
- 100-150 words""",
        
        'social_media_thread': """Create a Twitter/X thread about {topic}.
        
Requirements:
- 5-7 tweets
- Each tweet under 280 characters
- Engaging and informative
- Include relevant hashtags in last tweet""",
        
        'email_campaign': """Write a marketing email about {topic}.
        
Structure:
- Compelling subject line
- Personal greeting
- Value proposition
- Clear call to action
- Professional sign-off""",
        
        'listicle': """Create a listicle article: "{topic}"
        
Format:
- Catchy title with number
- Brief introduction
- 7-10 list items with explanations
- Conclusion with takeaway""",
        
        'how_to_guide': """Write a how-to guide: "How to {topic}"
        
Include:
- Introduction explaining the benefit
- Materials/prerequisites needed
- Step-by-step instructions
- Tips and common mistakes
- Conclusion""",
    }
    
    @classmethod
    def get_template(cls, template_name):
        """Get template by name"""
        return cls.TEMPLATES.get(template_name, "")
    
    @classmethod
    def list_templates(cls):
        """List all available templates"""
        return list(cls.TEMPLATES.keys())

# Use templates
templates = ContentTemplates()

print("Available Templates:")
for template in templates.list_templates():
    print(f"  • {template}")

# Generate using template
template_prompt = templates.get_template('product_description')
filled_prompt = template_prompt.format(topic="noise-cancelling headphones")

print(f"\nTemplate Example:\n{filled_prompt}")

🚀 Running the Application

# Project structure:
"""
content-writer/
├── app.py                 # Main Streamlit app
├── content_generator.py   # Content generation engine
├── seo_analyzer.py        # SEO analysis
├── templates.py           # Content templates
├── requirements.txt       # Dependencies
└── README.md             # Documentation
"""

# requirements.txt content:
"""
streamlit==1.29.0
openai==1.3.0
langchain==0.0.340
anthropic==0.7.0
textstat==0.7.3
markdown==3.5.1
python-docx==1.1.0
pypdf2==3.0.1
"""

# To run the application:
# 1. Install dependencies: pip install -r requirements.txt
# 2. Run Streamlit: streamlit run app.py
# 3. Open browser to http://localhost:8501

print("✓ Application ready to run!")
print("\nSteps to deploy:")
print("  1. Create requirements.txt with dependencies")
print("  2. Test locally: streamlit run app.py")
print("  3. Deploy to Streamlit Cloud, Heroku, or AWS")
print("  4. Set API keys as environment variables")
print("  5. Share with users!")

🎯 Key Features Summary

🔄 Enhancements