import streamlit as st import requests import json import time import os from dotenv import load_dotenv import openai from typing import List, Dict, Any # Load environment variables load_dotenv() # Set OpenAI API key openai.api_key = os.getenv('OPENAI_API_KEY') # Configure page st.set_page_config( page_title="SEO Content Writer", page_icon="✨", layout="wide", initial_sidebar_state="expanded" ) # Simple CSS styling st.markdown(""" """, unsafe_allow_html=True) class SEOContentWriter: def __init__(self): self.openai_client = openai def generate_keywords(self, seed_keyword: str) -> List[str]: """Generate related keywords using OpenAI""" try: response = self.openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are an SEO expert. Generate related keywords for content optimization."}, {"role": "user", "content": f"Generate 8 related keywords for '{seed_keyword}' that would be useful for SEO content creation. Return only the keywords, one per line, without numbers or bullet points."} ], max_tokens=200, temperature=0.7 ) keywords = [line.strip() for line in response.choices[0].message.content.strip().split('\n') if line.strip()] return keywords[:8] except Exception as e: st.error(f"Error generating keywords: {str(e)}") return [] def generate_titles(self, keyword: str, tone: str = "professional") -> List[str]: """Generate SEO-optimized titles""" try: response = self.openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": f"You are an SEO expert. Generate compelling, SEO-optimized titles with a {tone} tone."}, {"role": "user", "content": f"Generate 6 SEO-optimized titles for the keyword '{keyword}'. Each title should be 30-60 characters, include the keyword naturally, and have a {tone} tone. Return only the titles, one per line."} ], max_tokens=300, temperature=0.8 ) titles = [line.strip() for line in response.choices[0].message.content.strip().split('\n') if line.strip()] return titles[:6] except Exception as e: st.error(f"Error generating titles: {str(e)}") return [] def generate_topics(self, title: str, keyword: str) -> List[Dict[str, Any]]: """Generate topic outlines""" try: response = self.openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a content strategist. Create detailed topic outlines for articles."}, {"role": "user", "content": f"Create 3 different topic outlines for an article with title '{title}' targeting keyword '{keyword}'. Each outline should have 4-6 main sections with brief descriptions. Format as JSON with structure: [{{\"title\": \"outline_name\", \"sections\": [{{\"heading\": \"section_title\", \"description\": \"brief_desc\"}}]}}]"} ], max_tokens=800, temperature=0.7 ) try: topics = json.loads(response.choices[0].message.content.strip()) return topics except json.JSONDecodeError: # Fallback if JSON parsing fails return [{"title": "Standard Article Outline", "sections": [ {"heading": "Introduction", "description": "Overview of the topic"}, {"heading": "Main Content", "description": "Core information"}, {"heading": "Benefits/Examples", "description": "Practical applications"}, {"heading": "Conclusion", "description": "Summary and takeaways"} ]}] except Exception as e: st.error(f"Error generating topics: {str(e)}") return [] def generate_content(self, title: str, keyword: str, outline: Dict[str, Any], content_type: str = "blog_intro", word_count: int = 150) -> str: """Generate SEO-optimized content""" try: outline_text = "\n".join([f"- {section['heading']}: {section['description']}" for section in outline.get('sections', [])]) response = self.openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": f"You are an expert content writer specializing in SEO-optimized {content_type} content."}, {"role": "user", "content": f"""Write SEO-optimized content for: Title: {title} Target Keyword: {keyword} Content Type: {content_type} Word Count: ~{word_count} words Outline: {outline_text} Requirements: - Natural keyword integration (1-3% density) - Engaging and informative - Proper formatting with headers if needed - High readability - SEO best practices"""} ], max_tokens=word_count * 2, temperature=0.7 ) return response.choices[0].message.content.strip() except Exception as e: st.error(f"Error generating content: {str(e)}") return "" def analyze_seo(self, content: str, title: str, keyword: str) -> Dict[str, Any]: """Analyze SEO score of content""" if not all([content, title, keyword]): return {} # Calculate metrics word_count = len(content.split()) keyword_count = content.lower().count(keyword.lower()) keyword_density = (keyword_count / word_count * 100) if word_count > 0 else 0 title_length = len(title) keyword_in_title = keyword.lower() in title.lower() sentences = content.split('.') avg_sentence_length = sum(len(s.split()) for s in sentences) / len(sentences) if sentences else 0 # Calculate scores (0-100) keyword_density_score = min(100, max(0, 100 - abs(keyword_density - 2) * 20)) # Optimal: 2% title_length_score = min(100, max(0, 100 - abs(title_length - 45) * 2)) # Optimal: 45 chars keyword_in_title_score = 100 if keyword_in_title else 0 content_length_score = min(100, word_count / 3) # Optimal: 300+ words readability_score = min(100, max(0, 100 - abs(avg_sentence_length - 17) * 3)) # Optimal: 17 words/sentence # Calculate overall score with weights overall_score = ( keyword_density_score * 0.3 + title_length_score * 0.25 + keyword_in_title_score * 0.2 + content_length_score * 0.15 + readability_score * 0.1 ) # Generate recommendations recommendations = [] if keyword_density < 1: recommendations.append("Increase keyword density (aim for 1-3%)") elif keyword_density > 3: recommendations.append("Reduce keyword density to avoid over-optimization") if title_length < 30: recommendations.append("Consider making your title longer (30-60 characters)") elif title_length > 60: recommendations.append("Consider shortening your title (30-60 characters)") if not keyword_in_title: recommendations.append("Include your target keyword in the title") if word_count < 150: recommendations.append("Add more content (aim for 300+ words)") if avg_sentence_length > 25: recommendations.append("Use shorter sentences for better readability") return { "overall_score": round(overall_score), "scores": { "keyword_density": {"score": round(keyword_density_score), "value": f"{keyword_density:.1f}%"}, "title_length": {"score": round(title_length_score), "value": f"{title_length} chars"}, "keyword_in_title": {"score": round(keyword_in_title_score), "value": "Yes" if keyword_in_title else "No"}, "content_length": {"score": round(content_length_score), "value": f"{word_count} words"}, "readability": {"score": round(readability_score), "value": f"{avg_sentence_length:.1f} words/sentence"} }, "recommendations": recommendations[:3] # Limit to top 3 } def get_score_color_class(score: int) -> str: """Get CSS class based on score""" if score >= 80: return "seo-score-excellent" elif score >= 60: return "seo-score-good" else: return "seo-score-poor" def get_score_emoji(score: int) -> str: """Get emoji based on score""" if score >= 80: return "⚫" # Black circle for excellent elif score >= 60: return "⚪" # White circle for good else: return "◯" # Empty circle for poor def main(): # Initialize the SEO Content Writer if 'seo_writer' not in st.session_state: st.session_state.seo_writer = SEOContentWriter() # Initialize session state if 'current_step' not in st.session_state: st.session_state.current_step = 0 if 'seed_keyword' not in st.session_state: st.session_state.seed_keyword = "" if 'keywords' not in st.session_state: st.session_state.keywords = [] if 'selected_keyword' not in st.session_state: st.session_state.selected_keyword = "" if 'titles' not in st.session_state: st.session_state.titles = [] if 'selected_title' not in st.session_state: st.session_state.selected_title = "" if 'topics' not in st.session_state: st.session_state.topics = [] if 'selected_topic' not in st.session_state: st.session_state.selected_topic = None if 'generated_content' not in st.session_state: st.session_state.generated_content = "" if 'seo_analysis' not in st.session_state: st.session_state.seo_analysis = {} # Header st.title("SEO Content Writer") st.write("AI-powered content creation with real-time SEO optimization") # Sidebar with workflow progress with st.sidebar: st.subheader("Workflow Progress") steps = [ "Keyword Research", "Title Generation", "Topic Selection", "Content Creation" ] for i, step in enumerate(steps): if i < st.session_state.current_step: st.write(f"✓ {step}") elif i == st.session_state.current_step: st.write(f"→ **{step}**") else: st.write(f"○ {step}") progress = (st.session_state.current_step + 1) / len(steps) st.progress(progress) st.write(f"**{int(progress * 100)}% Complete**") # Reset workflow button if st.button("Start New Project"): for key in ['current_step', 'seed_keyword', 'keywords', 'selected_keyword', 'titles', 'selected_title', 'topics', 'selected_topic', 'generated_content', 'seo_analysis']: if key in st.session_state: if key == 'current_step': st.session_state[key] = 0 elif key in ['keywords', 'titles', 'topics']: st.session_state[key] = [] elif key == 'selected_topic': st.session_state[key] = None elif key == 'seo_analysis': st.session_state[key] = {} else: st.session_state[key] = "" st.rerun() # Project info st.markdown("---") st.write("**Project Info**") st.write("[Full Project Repository](https://github.com/akshayram1/AI_Content_Writer_Prototype)") st.caption("Originally attempted deployment on Vercel and Railway, but free tier limitations prevented deploying the full LLM service stack.") st.caption("Built with Streamlit and OpenAI") # Main content area with tabs tab1, tab2, tab3, tab4, tab5 = st.tabs(["Keywords", "Titles", "Topics", "Content", "SEO Test"]) # Tab 1: Keyword Research with tab1: st.subheader("Keyword Research") st.write("Discover high-impact keywords to boost your content's SEO potential") col1, col2 = st.columns([2, 1]) with col1: seed_keyword = st.text_input( "Enter your seed keyword", value=st.session_state.seed_keyword, placeholder="e.g., digital marketing, web development, content strategy" ) with col2: research_button = st.button("Research Keywords", type="primary") if research_button and seed_keyword: with st.spinner("Analyzing your keyword and finding related suggestions..."): keywords = st.session_state.seo_writer.generate_keywords(seed_keyword) if keywords: st.session_state.keywords = keywords st.session_state.seed_keyword = seed_keyword st.session_state.current_step = max(st.session_state.current_step, 1) if st.session_state.keywords: st.write("**Suggested Keywords**") st.markdown(f'
Based on: "{st.session_state.seed_keyword}"
', unsafe_allow_html=True) cols = st.columns(2) for i, keyword in enumerate(st.session_state.keywords): with cols[i % 2]: if st.button(f"{keyword}", key=f"keyword_{i}", use_container_width=True): st.session_state.selected_keyword = keyword st.session_state.current_step = max(st.session_state.current_step, 1) st.success(f"Selected keyword: **{keyword}**") time.sleep(1) st.rerun() if st.session_state.selected_keyword: st.markdown('
', unsafe_allow_html=True) st.write(f"**Great choice!** Keyword selected: **{st.session_state.selected_keyword}**") st.write("Ready to generate titles! The workflow will continue automatically.") st.markdown('
', unsafe_allow_html=True) # Tab 2: Title Generation with tab2: st.markdown("## 📝 Title Generation") st.markdown("Generate SEO-optimized titles for your selected keyword") if not st.session_state.selected_keyword: st.warning("⚠️ Please select a keyword first in the Keywords tab.") else: st.markdown('
', unsafe_allow_html=True) st.markdown(f"**Selected Keyword:** {st.session_state.selected_keyword}") st.markdown('
', unsafe_allow_html=True) col1, col2, col3 = st.columns([2, 1, 1]) with col1: tone = st.selectbox("Select tone", ["professional", "casual", "authoritative", "friendly", "technical"]) with col2: generate_titles_button = st.button("📝 Generate Titles", type="primary") with col3: if st.button("🔙 Change Keyword"): st.session_state.current_step = 0 st.rerun() if generate_titles_button: with st.spinner("Creating SEO-optimized titles for your keyword..."): titles = st.session_state.seo_writer.generate_titles(st.session_state.selected_keyword, tone) if titles: st.session_state.titles = titles st.session_state.current_step = max(st.session_state.current_step, 2) if st.session_state.titles: st.markdown("### 🏷️ Generated Titles") for i, title in enumerate(st.session_state.titles): col1, col2 = st.columns([4, 1]) with col1: st.markdown(f"**{title}**") st.caption(f"{len(title)} characters") with col2: if st.button("Select", key=f"title_{i}"): st.session_state.selected_title = title st.session_state.current_step = max(st.session_state.current_step, 2) st.success(f"✅ Selected title: **{title}**") time.sleep(1) st.rerun() if st.session_state.selected_title: st.markdown('
', unsafe_allow_html=True) st.markdown(f"✅ **Selected title:** {st.session_state.selected_title}") st.markdown("Ready to generate topic outline! The workflow will continue automatically.") st.markdown('
', unsafe_allow_html=True) # Tab 3: Topic Selection with tab3: st.markdown("## 📋 Topic Selection & Outline") st.markdown("Choose a content structure and outline for your article") if not st.session_state.selected_title: st.warning("⚠️ Please select a title first in the Titles tab.") else: st.markdown('
', unsafe_allow_html=True) st.markdown(f"**Keyword:** {st.session_state.selected_keyword}") st.markdown(f"**Title:** {st.session_state.selected_title}") st.markdown('
', unsafe_allow_html=True) col1, col2 = st.columns([1, 1]) with col1: generate_topics_button = st.button("📋 Generate Topic Outlines", type="primary") with col2: if st.button("🔙 Change Title"): st.session_state.current_step = 1 st.rerun() if generate_topics_button: with st.spinner("Creating topic outlines and content structure..."): topics = st.session_state.seo_writer.generate_topics(st.session_state.selected_title, st.session_state.selected_keyword) if topics: st.session_state.topics = topics st.session_state.current_step = max(st.session_state.current_step, 3) if st.session_state.topics: st.markdown("### 📄 Content Outlines") for i, topic in enumerate(st.session_state.topics): with st.expander(f"📝 {topic.get('title', f'Outline {i+1}')}"): if 'sections' in topic: for section in topic['sections']: st.markdown(f"**{section.get('heading', 'Section')}**") st.markdown(f"*{section.get('description', 'Description not available')}*") st.markdown("---") if st.button(f"Select This Outline", key=f"topic_{i}"): st.session_state.selected_topic = topic st.session_state.current_step = max(st.session_state.current_step, 3) st.success("✅ Topic outline selected! Ready to generate your content.") time.sleep(1) st.rerun() if st.session_state.selected_topic: st.markdown('
', unsafe_allow_html=True) st.markdown("✅ **Topic outline selected!** Ready to generate your content.") st.markdown('
', unsafe_allow_html=True) # Tab 4: Content Creation with tab4: st.markdown("## ✍️ Content Creation") st.markdown("Generate your final SEO-optimized content based on your selections") if not st.session_state.selected_topic: st.warning("⚠️ Please select a topic outline first in the Topics tab.") else: st.markdown('
', unsafe_allow_html=True) st.markdown(f"**Keyword:** {st.session_state.selected_keyword}") st.markdown(f"**Title:** {st.session_state.selected_title}") st.markdown("**Outline:** Selected") st.markdown('
', unsafe_allow_html=True) col1, col2, col3, col4 = st.columns([2, 1, 1, 1]) with col1: content_type = st.selectbox("Content Type", [ "blog_intro", "meta_description", "product_description", "landing_page", "social_media" ]) with col2: word_count = st.selectbox("Word Count", [100, 150, 200, 300, 500]) with col3: generate_content_button = st.button("✍️ Generate Content", type="primary") with col4: if st.button("🔙 Change Outline"): st.session_state.current_step = 2 st.rerun() if generate_content_button: with st.spinner("Creating your SEO-optimized content..."): content = st.session_state.seo_writer.generate_content( st.session_state.selected_title, st.session_state.selected_keyword, st.session_state.selected_topic, content_type, word_count ) if content: st.session_state.generated_content = content # Analyze SEO seo_analysis = st.session_state.seo_writer.analyze_seo( content, st.session_state.selected_title, st.session_state.selected_keyword ) st.session_state.seo_analysis = seo_analysis if st.session_state.generated_content: st.markdown("### 📄 Generated Content") # Display content in a nice box st.markdown('
', unsafe_allow_html=True) st.markdown(st.session_state.generated_content) st.markdown('
', unsafe_allow_html=True) # SEO Analysis if st.session_state.seo_analysis: seo = st.session_state.seo_analysis overall_score = seo.get('overall_score', 0) st.markdown("### 📊 SEO Analysis") score_class = get_score_color_class(overall_score) score_emoji = get_score_emoji(overall_score) st.markdown(f'
', unsafe_allow_html=True) st.markdown(f"## {score_emoji} Overall SEO Score: {overall_score}/100") st.markdown('
', unsafe_allow_html=True) # Detailed metrics st.markdown("#### 📋 Detailed Metrics") metrics_cols = st.columns(2) scores = seo.get('scores', {}) metric_names = { 'keyword_density': '🎯 Keyword Density', 'title_length': '📏 Title Length', 'keyword_in_title': '🏷️ Keyword in Title', 'content_length': '📝 Content Length', 'readability': '📖 Readability' } for i, (metric, data) in enumerate(scores.items()): with metrics_cols[i % 2]: score = data.get('score', 0) value = data.get('value', 'N/A') emoji = get_score_emoji(score) st.markdown(f"**{metric_names.get(metric, metric)}**") st.markdown(f"{emoji} {score}/100 - {value}") # Recommendations recommendations = seo.get('recommendations', []) if recommendations: st.markdown("#### 💡 Recommendations") for rec in recommendations: st.markdown(f"• {rec}") # Export options st.markdown("### 📤 Export Options") col1, col2, col3 = st.columns(3) with col1: if st.button("📋 Copy to Clipboard"): st.code(st.session_state.generated_content, language=None) st.success("✅ Content ready to copy!") with col2: st.download_button( label="💾 Download as Text", data=st.session_state.generated_content, file_name=f"seo-content-{int(time.time())}.txt", mime="text/plain" ) with col3: if st.button("🔄 Start New Project"): # Reset everything for key in ['current_step', 'seed_keyword', 'keywords', 'selected_keyword', 'titles', 'selected_title', 'topics', 'selected_topic', 'generated_content', 'seo_analysis']: if key in st.session_state: if key == 'current_step': st.session_state[key] = 0 elif key in ['keywords', 'titles', 'topics']: st.session_state[key] = [] elif key == 'selected_topic': st.session_state[key] = None elif key == 'seo_analysis': st.session_state[key] = {} else: st.session_state[key] = "" st.rerun() # Tab 5: SEO Test Page with tab5: st.markdown("## 🧪 SEO Scoring Test Page") st.markdown("Test the real-time SEO scoring feature with your own content") col1, col2 = st.columns([1, 1]) with col1: st.markdown("### Content Input") if st.button("📝 Load Demo Content"): st.session_state.test_keyword = "digital marketing" st.session_state.test_title = "The Complete Guide to Digital Marketing in 2024" st.session_state.test_content = """Digital marketing has become an essential component of modern business strategy. In today's competitive landscape, digital marketing techniques help businesses reach their target audience effectively. This comprehensive guide covers all aspects of digital marketing, from social media marketing to search engine optimization. Digital marketing strategies have evolved significantly, and businesses must adapt to stay competitive. Whether you're new to digital marketing or looking to enhance your existing digital marketing skills, this guide provides valuable insights. We'll explore various digital marketing channels and how they can boost your business growth.""" st.rerun() test_keyword = st.text_input( "Keyword", value=st.session_state.get('test_keyword', ''), placeholder="e.g., digital marketing" ) test_title = st.text_input( "Title", value=st.session_state.get('test_title', ''), placeholder="e.g., The Complete Guide to Digital Marketing" ) test_content = st.text_area( "Content", value=st.session_state.get('test_content', ''), height=300, placeholder="Enter your content here to see real-time SEO scoring..." ) # Store in session state st.session_state.test_keyword = test_keyword st.session_state.test_title = test_title st.session_state.test_content = test_content with col2: st.markdown("### Instructions & SEO Analysis") st.markdown(""" **How to use:** 1. Enter a keyword, title, and content in the form 2. Click "Load Demo Content" for sample data 3. The SEO analysis will update automatically 4. Modify the content to see scores update **SEO Metrics Analyzed:** - **Keyword Density:** 1-3% is optimal - **Title Length:** 30-60 characters ideal - **Content Length:** Longer content ranks better - **Keyword in Title:** Should include target keyword - **Readability:** Average sentence length analysis """) # Real-time SEO analysis if test_keyword and test_title and test_content: test_seo = st.session_state.seo_writer.analyze_seo(test_content, test_title, test_keyword) if test_seo: overall_score = test_seo.get('overall_score', 0) score_class = get_score_color_class(overall_score) score_emoji = get_score_emoji(overall_score) st.markdown(f'
', unsafe_allow_html=True) st.markdown(f"### {score_emoji} SEO Score: {overall_score}/100") st.markdown('
', unsafe_allow_html=True) # Quick metrics scores = test_seo.get('scores', {}) for metric, data in scores.items(): score = data.get('score', 0) value = data.get('value', 'N/A') emoji = get_score_emoji(score) metric_name = metric.replace('_', ' ').title() st.markdown(f"**{metric_name}:** {emoji} {score}/100 ({value})") # Recommendations recommendations = test_seo.get('recommendations', []) if recommendations: st.markdown("**💡 Recommendations:**") for rec in recommendations: st.markdown(f"• {rec}") if __name__ == "__main__": main()