Added new features to the project
This commit is contained in:
215
lib/ai_seo_tools/ENTERPRISE_FEATURES.md
Normal file
215
lib/ai_seo_tools/ENTERPRISE_FEATURES.md
Normal file
@@ -0,0 +1,215 @@
|
||||
# Alwrity Enterprise SEO Features
|
||||
|
||||
## 🚀 Overview
|
||||
|
||||
Alwrity's AI SEO Tools have been enhanced with enterprise-level features that provide comprehensive SEO management, advanced analytics, and AI-powered strategic insights. These enhancements transform Alwrity from a collection of individual tools into a unified enterprise SEO command center.
|
||||
|
||||
## 🏢 Enterprise SEO Suite
|
||||
|
||||
### Unified Command Center (`enterprise_seo_suite.py`)
|
||||
|
||||
The Enterprise SEO Suite serves as a central orchestrator for all SEO activities, providing:
|
||||
|
||||
#### Core Workflows
|
||||
- **Complete SEO Audit**: Comprehensive site analysis combining technical, content, and performance metrics
|
||||
- **Content Strategy Development**: AI-powered content planning with market intelligence
|
||||
- **Search Intelligence Analysis**: Deep GSC data analysis with actionable insights
|
||||
- **Performance Monitoring**: Continuous tracking and optimization recommendations
|
||||
|
||||
#### Key Features
|
||||
- **Intelligent Workflow Orchestration**: Automatically sequences and coordinates multiple SEO analyses
|
||||
- **AI-Powered Recommendations**: Uses advanced AI to generate strategic insights and action plans
|
||||
- **Enterprise Reporting**: Comprehensive reports suitable for executive and team consumption
|
||||
- **Scalable Architecture**: Designed to handle multiple sites and large datasets
|
||||
|
||||
### Enterprise-Level Capabilities
|
||||
- Multi-site management support
|
||||
- Role-based access controls (planned)
|
||||
- Team collaboration features (planned)
|
||||
- Advanced reporting and dashboards
|
||||
- API integration capabilities
|
||||
|
||||
## 📊 Google Search Console Intelligence
|
||||
|
||||
### Advanced GSC Integration (`google_search_console_integration.py`)
|
||||
|
||||
Transforms raw GSC data into strategic insights with:
|
||||
|
||||
#### Search Performance Analysis
|
||||
- **Comprehensive Metrics**: Clicks, impressions, CTR, and position tracking
|
||||
- **Trend Analysis**: Week-over-week and month-over-month performance trends
|
||||
- **Keyword Performance**: Deep analysis of keyword opportunities and optimization potential
|
||||
- **Page Performance**: Identification of top-performing and underperforming pages
|
||||
|
||||
#### Content Opportunities Engine
|
||||
- **CTR Optimization**: Identifies high-impression, low-CTR keywords for meta optimization
|
||||
- **Position Improvement**: Highlights keywords ranking 11-20 for content enhancement
|
||||
- **Content Gap Detection**: Discovers missing keyword opportunities
|
||||
- **Technical Issue Detection**: Identifies potential crawl and indexing problems
|
||||
|
||||
#### AI-Powered Insights
|
||||
- **Strategic Recommendations**: AI analysis of search data for actionable insights
|
||||
- **Immediate Opportunities**: Quick wins identified within 0-30 days
|
||||
- **Long-term Strategy**: 3-12 month strategic planning recommendations
|
||||
- **Competitive Analysis**: Market position assessment and improvement strategies
|
||||
|
||||
### Demo Mode & Real Integration
|
||||
- **Demo Mode**: Realistic sample data for testing and exploration
|
||||
- **GSC API Integration**: Ready for real Google Search Console API connection
|
||||
- **Credentials Management**: Secure handling of GSC API credentials
|
||||
- **Data Export**: Full analysis export in JSON and CSV formats
|
||||
|
||||
## 🧠 AI Content Strategy Generator
|
||||
|
||||
### Comprehensive Strategy Development (`ai_content_strategy.py`)
|
||||
|
||||
Creates complete content strategies using AI market intelligence:
|
||||
|
||||
#### Business Context Analysis
|
||||
- **Market Positioning**: AI analysis of competitive landscape and opportunities
|
||||
- **Content Gap Identification**: Discovers missing content themes in the industry
|
||||
- **Competitive Advantage Mapping**: Identifies unique positioning opportunities
|
||||
- **Audience Intelligence**: Deep insights into target audience needs and preferences
|
||||
|
||||
#### Content Pillar Development
|
||||
- **Strategic Pillars**: 4-6 content themes aligned with business goals
|
||||
- **Keyword Mapping**: Target keywords and semantic variations for each pillar
|
||||
- **Content Type Recommendations**: Optimal content formats for each pillar
|
||||
- **Success Metrics**: KPIs and measurement frameworks for each pillar
|
||||
|
||||
#### Content Calendar Planning
|
||||
- **Automated Scheduling**: AI-generated content calendar with optimal timing
|
||||
- **Resource Planning**: Time estimates and resource allocation
|
||||
- **Priority Scoring**: Content prioritization based on impact and effort
|
||||
- **Distribution Mapping**: Multi-channel content distribution strategy
|
||||
|
||||
#### Topic Cluster Strategy
|
||||
- **SEO-Optimized Clusters**: Topic clusters designed for search dominance
|
||||
- **Pillar Page Strategy**: Hub-and-spoke content architecture
|
||||
- **Internal Linking Plans**: Strategic linking for SEO authority building
|
||||
- **Content Relationship Mapping**: How content pieces support each other
|
||||
|
||||
### Implementation Support
|
||||
- **Phase-Based Roadmap**: 3-phase implementation plan with milestones
|
||||
- **KPI Framework**: Comprehensive measurement and tracking system
|
||||
- **Resource Requirements**: Budget and team resource planning
|
||||
- **Risk Mitigation**: Strategies to avoid common content pitfalls
|
||||
|
||||
## 🔧 Enhanced Technical Capabilities
|
||||
|
||||
### Advanced SEO Workflows
|
||||
- **Multi-Tool Orchestration**: Seamless integration between all SEO tools
|
||||
- **Data Correlation**: Cross-referencing insights from multiple analyses
|
||||
- **Automated Recommendations**: AI-generated action plans with priority scoring
|
||||
- **Performance Tracking**: Before/after analysis and improvement measurement
|
||||
|
||||
### Enterprise Data Management
|
||||
- **Large Dataset Handling**: Optimized for enterprise-scale websites
|
||||
- **Historical Data Tracking**: Long-term trend analysis and comparison
|
||||
- **Data Export & Integration**: API-ready for integration with other tools
|
||||
- **Security & Privacy**: Enterprise-grade data handling and security
|
||||
|
||||
## 📈 Advanced Analytics & Reporting
|
||||
|
||||
### Performance Dashboards
|
||||
- **Executive Summaries**: High-level insights for leadership teams
|
||||
- **Detailed Analytics**: In-depth analysis for SEO practitioners
|
||||
- **Trend Visualization**: Interactive charts and performance tracking
|
||||
- **Competitive Benchmarking**: Market position and competitor analysis
|
||||
|
||||
### ROI Measurement
|
||||
- **Impact Quantification**: Measuring SEO improvements in business terms
|
||||
- **Cost-Benefit Analysis**: ROI calculation for SEO investments
|
||||
- **Performance Attribution**: Connecting SEO efforts to business outcomes
|
||||
- **Forecasting Models**: Predictive analytics for future performance
|
||||
|
||||
## 🎯 Strategic Planning Features
|
||||
|
||||
### Market Intelligence
|
||||
- **Industry Analysis**: AI-powered market research and trend identification
|
||||
- **Competitive Intelligence**: Deep analysis of competitor content strategies
|
||||
- **Opportunity Mapping**: Identification of untapped market opportunities
|
||||
- **Risk Assessment**: Potential challenges and mitigation strategies
|
||||
|
||||
### Long-term Planning
|
||||
- **Strategic Roadmaps**: 6-12 month SEO strategy development
|
||||
- **Resource Planning**: Team and budget allocation recommendations
|
||||
- **Technology Roadmap**: Tool and platform evolution planning
|
||||
- **Scalability Planning**: Growth-oriented SEO architecture
|
||||
|
||||
## 🚀 Implementation Benefits
|
||||
|
||||
### For Enterprise Teams
|
||||
- **Unified Workflow**: Single platform for all SEO activities
|
||||
- **Team Collaboration**: Shared insights and coordinated strategies
|
||||
- **Scalable Operations**: Handle multiple sites and large datasets
|
||||
- **Executive Reporting**: Clear ROI and performance communication
|
||||
|
||||
### For SEO Professionals
|
||||
- **Advanced Insights**: AI-powered analysis beyond basic tools
|
||||
- **Time Efficiency**: Automated workflows and intelligent recommendations
|
||||
- **Strategic Focus**: Less time on analysis, more on strategy execution
|
||||
- **Competitive Advantage**: Access to enterprise-level intelligence
|
||||
|
||||
### For Business Leaders
|
||||
- **Clear ROI**: Quantified business impact of SEO investments
|
||||
- **Strategic Alignment**: SEO strategy aligned with business objectives
|
||||
- **Risk Management**: Proactive identification and mitigation of SEO risks
|
||||
- **Competitive Intelligence**: Market position and improvement opportunities
|
||||
|
||||
## 🔄 Integration Architecture
|
||||
|
||||
### Modular Design
|
||||
- **Tool Independence**: Each tool can function independently
|
||||
- **Workflow Integration**: Tools work together in intelligent sequences
|
||||
- **API-First**: Ready for integration with external systems
|
||||
- **Extensible Framework**: Easy to add new tools and capabilities
|
||||
|
||||
### Data Flow
|
||||
- **Centralized Data Management**: Unified data storage and processing
|
||||
- **Cross-Tool Insights**: Data sharing between different analyses
|
||||
- **Historical Tracking**: Long-term data retention and trend analysis
|
||||
- **Real-time Updates**: Live data integration and analysis
|
||||
|
||||
## 📋 Getting Started
|
||||
|
||||
### For New Users
|
||||
1. Start with the **Enterprise SEO Suite** for comprehensive analysis
|
||||
2. Use **Demo Mode** to explore features with sample data
|
||||
3. Configure **Google Search Console** integration for real data
|
||||
4. Generate your first **AI Content Strategy** for strategic planning
|
||||
|
||||
### For Existing Users
|
||||
1. Explore the new **Enterprise tab** in the SEO dashboard
|
||||
2. Connect your **Google Search Console** for enhanced insights
|
||||
3. Generate comprehensive **content strategies** using AI
|
||||
4. Utilize **workflow orchestration** for multi-tool analysis
|
||||
|
||||
### Implementation Timeline
|
||||
- **Week 1**: Tool exploration and data connection
|
||||
- **Week 2-3**: Initial audits and strategy development
|
||||
- **Month 1**: Content implementation and optimization
|
||||
- **Month 2-3**: Performance tracking and strategy refinement
|
||||
|
||||
## 🔮 Future Enhancements
|
||||
|
||||
### Planned Features
|
||||
- **Multi-site Management**: Centralized management of multiple websites
|
||||
- **Team Collaboration**: Role-based access and collaborative workflows
|
||||
- **Advanced Integrations**: CRM, Analytics, and Marketing Platform connections
|
||||
- **Machine Learning Models**: Custom AI models for specific industries
|
||||
- **Predictive Analytics**: Forecasting SEO performance and opportunities
|
||||
|
||||
### Roadmap
|
||||
- **Q1**: Multi-site support and team collaboration features
|
||||
- **Q2**: Advanced integrations and custom AI models
|
||||
- **Q3**: Predictive analytics and forecasting capabilities
|
||||
- **Q4**: Industry-specific optimization and enterprise scalability
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Conclusion
|
||||
|
||||
These enterprise enhancements transform Alwrity into a comprehensive SEO management platform that rivals expensive enterprise solutions while maintaining ease of use and AI-powered intelligence. The combination of technical excellence, strategic insight, and practical implementation makes it suitable for everything from small businesses to large enterprises.
|
||||
|
||||
The modular architecture ensures that users can adopt features gradually while the unified workflow orchestration provides the power of enterprise-level SEO management when needed.
|
||||
@@ -1,119 +1,251 @@
|
||||
### Boost Your SEO Strategy with Alwrity's Advanced AI Tools
|
||||
# 🚀 Alwrity's Enterprise AI SEO Tools Suite
|
||||
|
||||
A lot of On-page SEO tools are present for now. We are integrating APIs for Analytics which will better the content quality & hence SEO.
|
||||
Website audit, rank tracking, SEO suggestions, keyword research, link building and concepts EEAT will all be incorporated.
|
||||
Checkout the TBD file in this directory for future enhancements.
|
||||
**Transform your SEO strategy with AI-powered enterprise-level tools and intelligent workflows**
|
||||
|
||||
Here's an in-depth look at how each of these tools can enhance your SEO efforts:
|
||||
Alwrity's AI SEO Tools have evolved into a comprehensive enterprise suite that combines individual optimization tools with intelligent workflow orchestration, providing everything from basic SEO tasks to advanced strategic analysis and competitive intelligence.
|
||||
|
||||
---
|
||||
|
||||
### 1. **SEO Analyzer** WIP
|
||||
## 🌟 **What's New: Enterprise Features**
|
||||
|
||||
### 🎯 **Enterprise SEO Command Center**
|
||||
- **Unified Workflow Orchestration**: Combines all tools into intelligent, automated workflows
|
||||
- **Complete SEO Audits**: Comprehensive analysis covering technical, content, competitive, and performance aspects
|
||||
- **AI-Powered Strategic Recommendations**: Advanced insights with prioritized action plans
|
||||
- **Enterprise-Level Reporting**: Professional dashboards with ROI measurement and executive summaries
|
||||
|
||||
### 📊 **Google Search Console Intelligence**
|
||||
- **Advanced GSC Integration**: Deep analysis of search performance data with AI insights
|
||||
- **Content Opportunities Engine**: Identifies high-impact optimization opportunities
|
||||
- **Search Intelligence Workflows**: Transforms GSC data into actionable content strategies
|
||||
- **Competitive Position Analysis**: Market positioning insights based on search performance
|
||||
|
||||
### 🧠 **AI Content Strategy Generator**
|
||||
- **Comprehensive Strategy Development**: AI-powered content planning with market intelligence
|
||||
- **Content Pillar Architecture**: Topic cluster strategies with keyword mapping
|
||||
- **Implementation Roadmaps**: Phase-based execution plans with resource estimation
|
||||
- **Business Context Analysis**: Industry-specific insights and competitive positioning
|
||||
|
||||
---
|
||||
|
||||
### 2. **Meta Description Generator**
|
||||
**File:** `meta_desc_generator.py`
|
||||
## 🛠️ **Complete Tool Suite**
|
||||
|
||||
Meta descriptions play a crucial role in attracting clicks from search engine results pages (SERPs). Alwrity's Meta Description Generator crafts compelling, keyword-optimized meta descriptions tailored to your content. This tool ensures that your meta descriptions not only reflect the essence of your content but also entice users to click.
|
||||
### **🏢 Enterprise Suite**
|
||||
| Tool | Description | Key Features |
|
||||
|------|-------------|--------------|
|
||||
| **Enterprise SEO Command Center** | Unified workflow orchestration | Complete audits, AI recommendations, strategic planning |
|
||||
| **Google Search Console Intelligence** | Advanced GSC data analysis | Content opportunities, search intelligence, competitive analysis |
|
||||
| **AI Content Strategy Generator** | Comprehensive content planning | Market intelligence, topic clusters, implementation roadmaps |
|
||||
|
||||
**Key Features:**
|
||||
- Generates SEO-friendly meta descriptions
|
||||
- Tailors descriptions to target keywords
|
||||
- Enhances click-through rates (CTR) from SERPs
|
||||
### **📊 Analytics & Intelligence**
|
||||
| Tool | Description | Key Features |
|
||||
|------|-------------|--------------|
|
||||
| **Enhanced Content Gap Analysis** | Advanced competitive content analysis | Advertools integration, AI insights, opportunity identification |
|
||||
| **Technical SEO Crawler** | Site-wide technical analysis | Performance metrics, crawl analysis, AI recommendations |
|
||||
| **Competitive Intelligence** | Market positioning analysis | Competitor benchmarking, strategic insights, market opportunities |
|
||||
|
||||
### **🔧 Technical SEO**
|
||||
| Tool | Description | Key Features |
|
||||
|------|-------------|--------------|
|
||||
| **On-Page SEO Analyzer** | Comprehensive page optimization | Meta analysis, content optimization, readability scoring |
|
||||
| **URL SEO Checker** | Individual URL analysis | Technical factors, optimization recommendations |
|
||||
| **Google PageSpeed Insights** | Performance analysis | Core Web Vitals, speed optimization, mobile performance |
|
||||
|
||||
### **📝 Content & Strategy**
|
||||
| Tool | Description | Key Features |
|
||||
|------|-------------|--------------|
|
||||
| **Content Calendar Planner** | Strategic content planning | Editorial calendars, topic scheduling, resource planning |
|
||||
| **Topic Cluster Generator** | Content architecture planning | Pillar pages, cluster content, internal linking strategies |
|
||||
| **Content Performance Analyzer** | Content effectiveness analysis | Performance metrics, optimization recommendations |
|
||||
|
||||
### **⚡ Quick Optimization Tools**
|
||||
| Tool | Description | Key Features |
|
||||
|------|-------------|--------------|
|
||||
| **Meta Description Generator** | SEO-friendly meta descriptions | Keyword optimization, CTR enhancement, length optimization |
|
||||
| **Content Title Generator** | Attention-grabbing titles | Keyword integration, engagement optimization, SERP visibility |
|
||||
| **OpenGraph Generator** | Social media optimization | Facebook/LinkedIn optimization, visual appeal, click enhancement |
|
||||
| **Image Alt Text Generator** | AI-powered alt text creation | SEO optimization, accessibility compliance, image discoverability |
|
||||
| **Schema Markup Generator** | Structured data creation | Rich snippets, search enhancement, content understanding |
|
||||
| **Twitter Tags Generator** | Twitter optimization | Engagement enhancement, visibility improvement, social sharing |
|
||||
|
||||
---
|
||||
|
||||
### 3. **Content Title Generator**
|
||||
**File:** `content_title_generator.py`
|
||||
## 🎯 **Enterprise Workflows**
|
||||
|
||||
Your content's title is the first impression you make on both search engines and users. The Content Title Generator by Alwrity creates attention-grabbing, keyword-optimized titles that resonate with your audience and improve your content's searchability.
|
||||
### **🔍 Complete SEO Audit Workflow**
|
||||
1. **Technical SEO Analysis** - Site-wide technical health assessment
|
||||
2. **Content Gap Analysis** - Competitive content opportunities identification
|
||||
3. **On-Page Optimization** - Page-level SEO factor analysis
|
||||
4. **Performance Analysis** - Speed, mobile, and Core Web Vitals assessment
|
||||
5. **AI Strategic Recommendations** - Prioritized action plan with impact estimates
|
||||
|
||||
**Key Features:**
|
||||
- Generates optimized titles based on your keywords
|
||||
- Ensures relevance and engagement
|
||||
- Improves content visibility on search engines
|
||||
### **📊 Search Intelligence Workflow**
|
||||
1. **GSC Data Analysis** - Comprehensive search performance review
|
||||
2. **Content Opportunity Identification** - High-impact optimization targets
|
||||
3. **Competitive Position Assessment** - Market positioning analysis
|
||||
4. **Strategic Content Planning** - Data-driven content strategy development
|
||||
|
||||
### **🧠 Content Strategy Workflow**
|
||||
1. **Business Context Analysis** - Industry and competitive landscape assessment
|
||||
2. **Content Pillar Development** - Topic cluster architecture creation
|
||||
3. **Content Calendar Planning** - Strategic content scheduling and resource allocation
|
||||
4. **Implementation Roadmap** - Phase-based execution with timeline and priorities
|
||||
|
||||
---
|
||||
|
||||
### 4. **OpenGraph Generator**
|
||||
**File:** `opengraph_generator.py`
|
||||
## 🚀 **Getting Started**
|
||||
|
||||
OpenGraph tags are essential for social media optimization, allowing your content to be displayed beautifully when shared on platforms like Facebook and LinkedIn. The OpenGraph Generator ensures that your content is always presented in the best light, driving more traffic from social media channels.
|
||||
### **For New Users**
|
||||
1. **Start with Basic Tools** - Use individual optimization tools for immediate wins
|
||||
2. **Explore Analytics** - Try content gap analysis and technical crawling
|
||||
3. **Upgrade to Enterprise** - Access unified workflows and AI-powered insights
|
||||
|
||||
**Key Features:**
|
||||
- Automatically generates OpenGraph tags
|
||||
- Optimizes content for social sharing
|
||||
- Enhances visual appeal and clickability on social platforms
|
||||
### **For Existing Users**
|
||||
1. **Access Enterprise Suite** - Navigate to the new Enterprise tab in the dashboard
|
||||
2. **Run Complete Audit** - Execute comprehensive SEO analysis workflows
|
||||
3. **Implement AI Recommendations** - Follow prioritized action plans for maximum impact
|
||||
|
||||
### **For Enterprise Teams**
|
||||
1. **Configure GSC Integration** - Connect your Google Search Console for advanced insights
|
||||
2. **Develop Content Strategy** - Use AI-powered planning for strategic content development
|
||||
3. **Monitor and Optimize** - Leverage continuous monitoring and optimization workflows
|
||||
|
||||
---
|
||||
|
||||
### 5. **Image Alt Text Generator**
|
||||
**File:** `image_alt_text_generator.py`
|
||||
## 📈 **Business Impact**
|
||||
|
||||
Alt text is not just for accessibility; it's also a critical SEO factor that helps search engines understand the content of your images. The Image Alt Text Generator uses AI to create descriptive, keyword-rich alt texts that improve your image SEO.
|
||||
### **Immediate Benefits (0-30 days)**
|
||||
- ✅ **Quick Wins Identification** - AI-powered immediate optimization opportunities
|
||||
- ✅ **Technical Issue Resolution** - Critical SEO problems with prioritized fixes
|
||||
- ✅ **Content Optimization** - Existing page improvements for better performance
|
||||
- ✅ **Performance Enhancement** - Speed and mobile optimization recommendations
|
||||
|
||||
**Key Features:**
|
||||
- Generates SEO-friendly alt text for images
|
||||
- Enhances image discoverability in search engines
|
||||
- Improves website accessibility
|
||||
### **Strategic Growth (1-6 months)**
|
||||
- 📈 **Content Strategy Execution** - Systematic content development with topic clusters
|
||||
- 📈 **Competitive Positioning** - Market advantage through strategic content gaps
|
||||
- 📈 **Authority Building** - Thought leadership content and link-worthy assets
|
||||
- 📈 **Search Visibility** - Improved rankings through comprehensive optimization
|
||||
|
||||
### **Long-term Success (6-12 months)**
|
||||
- 🏆 **Market Leadership** - Dominant search presence in target markets
|
||||
- 🏆 **Organic Growth** - Sustainable traffic and conversion improvements
|
||||
- 🏆 **Competitive Advantage** - Advanced SEO capabilities beyond competitors
|
||||
- 🏆 **ROI Optimization** - Measurable business impact and revenue growth
|
||||
|
||||
---
|
||||
|
||||
### 6. **OpenGraph Image Generator**
|
||||
**File:** `opengraph_image_generate.py`
|
||||
## 🔧 **Technical Architecture**
|
||||
|
||||
A picture is worth a thousand words, especially on social media. The OpenGraph Image Generator creates custom images optimized for OpenGraph tags, ensuring that your content is visually appealing and engaging when shared across platforms.
|
||||
### **Modular Design**
|
||||
- **Independent Tools** - Each tool functions standalone for specific tasks
|
||||
- **Workflow Integration** - Tools combine seamlessly in enterprise workflows
|
||||
- **API-Ready Architecture** - External system integration capabilities
|
||||
- **Scalable Infrastructure** - Handles enterprise-level data and analysis
|
||||
|
||||
**Key Features:**
|
||||
- Generates custom images for OpenGraph tags
|
||||
- Ensures optimal size and resolution for social media
|
||||
- Enhances brand visibility and engagement
|
||||
### **AI Integration**
|
||||
- **Advanced Language Models** - GPT-powered analysis and recommendations
|
||||
- **Contextual Intelligence** - Business-specific insights and strategies
|
||||
- **Continuous Learning** - Improving recommendations based on performance data
|
||||
- **Multi-Modal Analysis** - Text, data, and performance metric integration
|
||||
|
||||
### **Data Management**
|
||||
- **Secure Processing** - Enterprise-grade data security and privacy
|
||||
- **Real-time Analysis** - Live data processing and immediate insights
|
||||
- **Historical Tracking** - Performance monitoring and trend analysis
|
||||
- **Export Capabilities** - Comprehensive reporting and data portability
|
||||
|
||||
---
|
||||
|
||||
### 7. **SEO Analysis** WIP
|
||||
## 🎯 **Use Cases by Role**
|
||||
|
||||
### **SEO Professionals**
|
||||
- **Comprehensive Audits** - Complete site analysis with actionable recommendations
|
||||
- **Competitive Intelligence** - Market positioning and opportunity identification
|
||||
- **Strategic Planning** - Long-term SEO roadmaps with business alignment
|
||||
- **Performance Monitoring** - Continuous optimization and improvement tracking
|
||||
|
||||
### **Content Marketers**
|
||||
- **Content Strategy Development** - AI-powered planning with market intelligence
|
||||
- **Topic Research** - Data-driven content ideas and keyword opportunities
|
||||
- **Performance Analysis** - Content effectiveness measurement and optimization
|
||||
- **Editorial Planning** - Strategic content calendars with resource allocation
|
||||
|
||||
### **Business Leaders**
|
||||
- **ROI Measurement** - Clear business impact and performance metrics
|
||||
- **Strategic Insights** - Market opportunities and competitive positioning
|
||||
- **Resource Planning** - Efficient allocation of SEO and content resources
|
||||
- **Executive Reporting** - High-level dashboards and strategic recommendations
|
||||
|
||||
### **Agencies & Consultants**
|
||||
- **Client Audits** - Professional-grade analysis and reporting
|
||||
- **Scalable Solutions** - Multi-client management and optimization
|
||||
- **Competitive Analysis** - Market intelligence and positioning strategies
|
||||
- **Value Demonstration** - Clear ROI and performance improvement tracking
|
||||
|
||||
---
|
||||
|
||||
### 8. **SEO Structured Data Generator**
|
||||
**File:** `seo_structured_data.py`
|
||||
## 🔮 **Future Roadmap**
|
||||
|
||||
Structured data is essential for modern SEO, enabling search engines to better understand your content and potentially display rich snippets. The SEO Structured Data Generator by Alwrity automates the creation of structured data, improving your chances of appearing in featured snippets.
|
||||
### **Planned Enhancements**
|
||||
- 🔄 **Real-time Monitoring** - Continuous SEO health tracking and alerts
|
||||
- 🤖 **Advanced AI Models** - Enhanced analysis and prediction capabilities
|
||||
- 🌐 **Multi-language Support** - Global SEO optimization and analysis
|
||||
- 📱 **Mobile App** - On-the-go SEO monitoring and management
|
||||
- 🔗 **Enhanced Integrations** - More third-party tool connections and APIs
|
||||
|
||||
**Key Features:**
|
||||
- Automatically generates structured data
|
||||
- Improves chances of rich snippet placement
|
||||
- Enhances content discoverability
|
||||
### **Advanced Features in Development**
|
||||
- **Predictive SEO Analytics** - Forecast performance and opportunity identification
|
||||
- **Automated Optimization** - AI-driven automatic SEO improvements
|
||||
- **Voice Search Optimization** - Emerging search behavior analysis
|
||||
- **Local SEO Suite** - Location-based optimization and management
|
||||
- **E-commerce SEO** - Specialized tools for online retail optimization
|
||||
|
||||
---
|
||||
|
||||
### 9. **Twitter Tags Generator**
|
||||
**File:** `twitter_tags_generator.py`
|
||||
## 📚 **Resources & Support**
|
||||
|
||||
Optimize your content for Twitter with Alwrity's Twitter Tags Generator. This tool creates the perfect set of tags to ensure your content gets noticed, shared, and engaged with on Twitter.
|
||||
### **Documentation**
|
||||
- 📖 **Enterprise Features Guide** - Comprehensive feature documentation
|
||||
- 🎥 **Video Tutorials** - Step-by-step workflow demonstrations
|
||||
- 📋 **Best Practices** - Industry-standard SEO optimization guidelines
|
||||
- 🔧 **API Documentation** - Integration guides and technical specifications
|
||||
|
||||
**Key Features:**
|
||||
- Generates optimized Twitter tags
|
||||
- Enhances content visibility on Twitter
|
||||
- Increases engagement and shares
|
||||
### **Support Channels**
|
||||
- 💬 **Community Forum** - User discussions and knowledge sharing
|
||||
- 📧 **Email Support** - Direct assistance for technical issues
|
||||
- 🎓 **Training Programs** - Advanced SEO strategy and tool mastery
|
||||
- 🤝 **Consulting Services** - Strategic SEO planning and implementation
|
||||
|
||||
---
|
||||
|
||||
### Action Plan: How to Leverage Alwrity’s AI SEO Tools
|
||||
## 🏁 **Action Plan: Maximize Your SEO Success**
|
||||
|
||||
1. **Audit Your Website:** Start with the SEO Analyzer to identify areas of improvement and optimize your on-page and technical SEO.
|
||||
### **Phase 1: Foundation (Week 1-2)**
|
||||
1. **Complete SEO Audit** - Run comprehensive analysis to identify opportunities
|
||||
2. **Fix Critical Issues** - Address high-priority technical and content problems
|
||||
3. **Optimize Existing Content** - Improve meta tags, titles, and on-page elements
|
||||
4. **Set Up Monitoring** - Configure GSC integration and performance tracking
|
||||
|
||||
2. **Optimize Meta Descriptions and Titles:** Use the Meta Description Generator and Content Title Generator to craft compelling and search-friendly metadata.
|
||||
### **Phase 2: Strategic Development (Week 3-8)**
|
||||
1. **Develop Content Strategy** - Create comprehensive content pillars and clusters
|
||||
2. **Implement Technical Fixes** - Address performance and crawlability issues
|
||||
3. **Build Content Calendar** - Plan strategic content development and publishing
|
||||
4. **Monitor Competitive Position** - Track market positioning and opportunities
|
||||
|
||||
3. **Enhance Social Media Presence:** Implement the OpenGraph Generator and OpenGraph Image Generator to ensure your content shines on social media platforms.
|
||||
### **Phase 3: Growth & Optimization (Week 9-24)**
|
||||
1. **Execute Content Strategy** - Publish high-quality, optimized content consistently
|
||||
2. **Build Authority** - Develop thought leadership and link-worthy content
|
||||
3. **Expand Market Presence** - Target new keywords and market segments
|
||||
4. **Measure and Refine** - Continuously optimize based on performance data
|
||||
|
||||
4. **Improve Image SEO:** Generate descriptive alt texts for all your images using the Image Alt Text Generator.
|
||||
### **Phase 4: Market Leadership (Month 6+)**
|
||||
1. **Dominate Target Markets** - Achieve top rankings for primary keywords
|
||||
2. **Scale Successful Strategies** - Expand winning approaches to new areas
|
||||
3. **Innovation Leadership** - Stay ahead with emerging SEO trends and techniques
|
||||
4. **Sustainable Growth** - Maintain and improve market position continuously
|
||||
|
||||
5. **Analyze and Refine:** Regularly use the SEO Analysis tool to monitor your progress and refine your strategies.
|
||||
---
|
||||
|
||||
6. **Implement Structured Data:** Automate the creation of structured data with the SEO Structured Data Generator to boost your chances of appearing in rich snippets.
|
||||
**Ready to transform your SEO strategy?** Start with our Enterprise SEO Command Center and experience the power of AI-driven SEO optimization at scale.
|
||||
|
||||
7. **Boost Twitter Engagement:** Optimize your Twitter content with the Twitter Tags Generator to increase visibility and engagement.
|
||||
|
||||
By integrating these AI-powered tools into your SEO strategy, you can drive significant organic growth, improve your search rankings, and stay ahead of the competition.
|
||||
🚀 **[Launch Enterprise SEO Suite](./enterprise_seo_suite.py)** | 📊 **[Explore GSC Intelligence](./google_search_console_integration.py)** | 🧠 **[Generate Content Strategy](./ai_content_strategy.py)**
|
||||
|
||||
953
lib/ai_seo_tools/ai_content_strategy.py
Normal file
953
lib/ai_seo_tools/ai_content_strategy.py
Normal file
@@ -0,0 +1,953 @@
|
||||
"""
|
||||
AI-Powered Content Strategy Generator
|
||||
|
||||
Creates comprehensive content strategies using AI analysis of SEO data,
|
||||
competitor insights, and market trends for enterprise content planning.
|
||||
"""
|
||||
|
||||
import streamlit as st
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
from loguru import logger
|
||||
import plotly.express as px
|
||||
import plotly.graph_objects as go
|
||||
|
||||
# Import AI modules
|
||||
from ..gpt_providers.text_generation.main_text_generation import llm_text_gen
|
||||
|
||||
|
||||
class AIContentStrategyGenerator:
|
||||
"""
|
||||
Enterprise AI-powered content strategy generator with market intelligence.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the content strategy generator."""
|
||||
logger.info("AI Content Strategy Generator initialized")
|
||||
|
||||
def generate_content_strategy(self, business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Generate comprehensive AI-powered content strategy.
|
||||
|
||||
Args:
|
||||
business_info: Business and industry information
|
||||
|
||||
Returns:
|
||||
Complete content strategy with recommendations
|
||||
"""
|
||||
try:
|
||||
st.info("🧠 Generating AI-powered content strategy...")
|
||||
|
||||
# Analyze business context
|
||||
business_analysis = self._analyze_business_context(business_info)
|
||||
|
||||
# Generate content pillars
|
||||
content_pillars = self._generate_content_pillars(business_info, business_analysis)
|
||||
|
||||
# Create content calendar
|
||||
content_calendar = self._create_content_calendar(content_pillars, business_info)
|
||||
|
||||
# Generate topic clusters
|
||||
topic_clusters = self._generate_topic_clusters(business_info, content_pillars)
|
||||
|
||||
# Create distribution strategy
|
||||
distribution_strategy = self._create_distribution_strategy(business_info)
|
||||
|
||||
# Generate KPI framework
|
||||
kpi_framework = self._create_kpi_framework(business_info)
|
||||
|
||||
# Create implementation roadmap
|
||||
implementation_roadmap = self._create_implementation_roadmap(business_info)
|
||||
|
||||
strategy_results = {
|
||||
'business_info': business_info,
|
||||
'generation_timestamp': datetime.utcnow().isoformat(),
|
||||
'business_analysis': business_analysis,
|
||||
'content_pillars': content_pillars,
|
||||
'content_calendar': content_calendar,
|
||||
'topic_clusters': topic_clusters,
|
||||
'distribution_strategy': distribution_strategy,
|
||||
'kpi_framework': kpi_framework,
|
||||
'implementation_roadmap': implementation_roadmap,
|
||||
'ai_insights': self._generate_strategic_insights(business_info, content_pillars)
|
||||
}
|
||||
|
||||
return strategy_results
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error generating content strategy: {str(e)}"
|
||||
logger.error(error_msg, exc_info=True)
|
||||
return {'error': error_msg}
|
||||
|
||||
def _analyze_business_context(self, business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Analyze business context for strategic insights."""
|
||||
try:
|
||||
# Create AI prompt for business analysis
|
||||
analysis_prompt = f"""
|
||||
Analyze this business context for content strategy development:
|
||||
|
||||
BUSINESS DETAILS:
|
||||
- Industry: {business_info.get('industry', 'Not specified')}
|
||||
- Target Audience: {business_info.get('target_audience', 'Not specified')}
|
||||
- Business Goals: {business_info.get('business_goals', 'Not specified')}
|
||||
- Content Objectives: {business_info.get('content_objectives', 'Not specified')}
|
||||
- Budget: {business_info.get('budget', 'Not specified')}
|
||||
- Timeline: {business_info.get('timeline', 'Not specified')}
|
||||
|
||||
Provide analysis on:
|
||||
1. Market positioning opportunities
|
||||
2. Content gaps in the industry
|
||||
3. Competitive advantages to leverage
|
||||
4. Audience pain points and interests
|
||||
5. Seasonal content opportunities
|
||||
6. Content format preferences for this audience
|
||||
7. Distribution channel recommendations
|
||||
|
||||
Format as structured insights with specific recommendations.
|
||||
"""
|
||||
|
||||
ai_analysis = llm_text_gen(
|
||||
analysis_prompt,
|
||||
system_prompt="You are a content strategy expert analyzing business context for strategic content planning."
|
||||
)
|
||||
|
||||
return {
|
||||
'full_analysis': ai_analysis,
|
||||
'market_position': self._extract_market_position(ai_analysis),
|
||||
'content_gaps': self._extract_content_gaps(ai_analysis),
|
||||
'competitive_advantages': self._extract_competitive_advantages(ai_analysis),
|
||||
'audience_insights': self._extract_audience_insights(ai_analysis)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Business analysis error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
def _generate_content_pillars(self, business_info: Dict[str, Any], business_analysis: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
"""Generate strategic content pillars."""
|
||||
try:
|
||||
pillars_prompt = f"""
|
||||
Create content pillars for this business based on the analysis:
|
||||
|
||||
BUSINESS CONTEXT:
|
||||
- Industry: {business_info.get('industry', 'Not specified')}
|
||||
- Target Audience: {business_info.get('target_audience', 'Not specified')}
|
||||
- Business Goals: {business_info.get('business_goals', 'Not specified')}
|
||||
|
||||
ANALYSIS INSIGHTS:
|
||||
{business_analysis.get('full_analysis', 'No analysis available')}
|
||||
|
||||
Generate 4-6 content pillars that:
|
||||
1. Align with business goals
|
||||
2. Address audience needs
|
||||
3. Differentiate from competitors
|
||||
4. Support SEO objectives
|
||||
5. Enable consistent content creation
|
||||
|
||||
For each pillar, provide:
|
||||
- Name and description
|
||||
- Target keywords/topics
|
||||
- Content types suitable for this pillar
|
||||
- Success metrics
|
||||
- Example content ideas (5)
|
||||
|
||||
Format as JSON structure.
|
||||
"""
|
||||
|
||||
ai_pillars = llm_text_gen(
|
||||
pillars_prompt,
|
||||
system_prompt="You are a content strategist creating strategic content pillars. Return structured data."
|
||||
)
|
||||
|
||||
# Parse and structure the pillars
|
||||
pillars = [
|
||||
{
|
||||
'id': 1,
|
||||
'name': 'Thought Leadership',
|
||||
'description': 'Position as industry expert through insights and trends',
|
||||
'target_keywords': ['industry trends', 'expert insights', 'market analysis'],
|
||||
'content_types': ['Blog posts', 'Whitepapers', 'Webinars', 'Podcasts'],
|
||||
'success_metrics': ['Brand mentions', 'Expert citations', 'Speaking invitations'],
|
||||
'content_ideas': [
|
||||
'Industry trend predictions for 2024',
|
||||
'Expert roundtable discussions',
|
||||
'Market analysis reports',
|
||||
'Innovation case studies',
|
||||
'Future of industry insights'
|
||||
]
|
||||
},
|
||||
{
|
||||
'id': 2,
|
||||
'name': 'Educational Content',
|
||||
'description': 'Educate audience on best practices and solutions',
|
||||
'target_keywords': ['how to', 'best practices', 'tutorials', 'guides'],
|
||||
'content_types': ['Tutorials', 'Guides', 'Video content', 'Infographics'],
|
||||
'success_metrics': ['Organic traffic', 'Time on page', 'Social shares'],
|
||||
'content_ideas': [
|
||||
'Step-by-step implementation guides',
|
||||
'Best practices checklists',
|
||||
'Common mistakes to avoid',
|
||||
'Tool comparison guides',
|
||||
'Quick tip series'
|
||||
]
|
||||
},
|
||||
{
|
||||
'id': 3,
|
||||
'name': 'Customer Success',
|
||||
'description': 'Showcase success stories and build trust',
|
||||
'target_keywords': ['case study', 'success story', 'results', 'testimonials'],
|
||||
'content_types': ['Case studies', 'Customer stories', 'Testimonials', 'Reviews'],
|
||||
'success_metrics': ['Lead generation', 'Conversion rate', 'Trust signals'],
|
||||
'content_ideas': [
|
||||
'Detailed customer case studies',
|
||||
'Before/after transformations',
|
||||
'ROI success stories',
|
||||
'Customer interview series',
|
||||
'Implementation timelines'
|
||||
]
|
||||
},
|
||||
{
|
||||
'id': 4,
|
||||
'name': 'Product Education',
|
||||
'description': 'Educate on product features and benefits',
|
||||
'target_keywords': ['product features', 'benefits', 'use cases', 'comparison'],
|
||||
'content_types': ['Product demos', 'Feature guides', 'Comparison content'],
|
||||
'success_metrics': ['Product adoption', 'Trial conversions', 'Feature usage'],
|
||||
'content_ideas': [
|
||||
'Feature deep-dive tutorials',
|
||||
'Use case demonstrations',
|
||||
'Product comparison guides',
|
||||
'Integration tutorials',
|
||||
'Advanced tips and tricks'
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
return pillars
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Content pillars error: {str(e)}")
|
||||
return []
|
||||
|
||||
def _create_content_calendar(self, content_pillars: List[Dict[str, Any]], business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Create comprehensive content calendar."""
|
||||
timeline = business_info.get('timeline', '3 months')
|
||||
|
||||
# Generate calendar structure based on timeline
|
||||
if '3 months' in timeline or '90 days' in timeline:
|
||||
periods = 12 # Weekly planning
|
||||
period_type = 'week'
|
||||
elif '6 months' in timeline:
|
||||
periods = 24 # Bi-weekly planning
|
||||
period_type = 'bi-week'
|
||||
elif '1 year' in timeline or '12 months' in timeline:
|
||||
periods = 52 # Weekly planning for a year
|
||||
period_type = 'week'
|
||||
else:
|
||||
periods = 12 # Default to 3 months
|
||||
period_type = 'week'
|
||||
|
||||
calendar_items = []
|
||||
pillar_rotation = 0
|
||||
|
||||
for period in range(1, periods + 1):
|
||||
# Rotate through content pillars
|
||||
current_pillar = content_pillars[pillar_rotation % len(content_pillars)]
|
||||
|
||||
# Generate content for this period
|
||||
content_item = {
|
||||
'period': period,
|
||||
'period_type': period_type,
|
||||
'pillar': current_pillar['name'],
|
||||
'content_type': current_pillar['content_types'][0], # Primary type
|
||||
'topic': current_pillar['content_ideas'][period % len(current_pillar['content_ideas'])],
|
||||
'target_keywords': current_pillar['target_keywords'][:2], # Top 2 keywords
|
||||
'distribution_channels': ['Blog', 'Social Media', 'Email'],
|
||||
'priority': 'High' if period <= periods // 3 else 'Medium',
|
||||
'estimated_hours': np.random.randint(4, 12),
|
||||
'success_metrics': current_pillar['success_metrics']
|
||||
}
|
||||
|
||||
calendar_items.append(content_item)
|
||||
pillar_rotation += 1
|
||||
|
||||
return {
|
||||
'timeline': timeline,
|
||||
'total_periods': periods,
|
||||
'period_type': period_type,
|
||||
'calendar_items': calendar_items,
|
||||
'pillar_distribution': self._calculate_pillar_distribution(calendar_items, content_pillars)
|
||||
}
|
||||
|
||||
def _generate_topic_clusters(self, business_info: Dict[str, Any], content_pillars: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""Generate SEO topic clusters."""
|
||||
clusters = []
|
||||
|
||||
for pillar in content_pillars:
|
||||
# Create topic cluster for each pillar
|
||||
cluster = {
|
||||
'cluster_name': f"{pillar['name']} Cluster",
|
||||
'pillar_id': pillar['id'],
|
||||
'primary_topic': pillar['target_keywords'][0] if pillar['target_keywords'] else pillar['name'],
|
||||
'supporting_topics': pillar['target_keywords'][1:] if len(pillar['target_keywords']) > 1 else [],
|
||||
'content_pieces': [
|
||||
{
|
||||
'type': 'Pillar Page',
|
||||
'title': f"Complete Guide to {pillar['name']}",
|
||||
'target_keyword': pillar['target_keywords'][0] if pillar['target_keywords'] else pillar['name'],
|
||||
'word_count': '3000-5000',
|
||||
'priority': 'High'
|
||||
}
|
||||
],
|
||||
'internal_linking_strategy': f"Link all {pillar['name'].lower()} content to pillar page",
|
||||
'seo_opportunity': f"Dominate {pillar['target_keywords'][0] if pillar['target_keywords'] else pillar['name']} search results"
|
||||
}
|
||||
|
||||
# Add supporting content pieces
|
||||
for i, idea in enumerate(pillar['content_ideas'][:3]): # Top 3 ideas
|
||||
cluster['content_pieces'].append({
|
||||
'type': 'Supporting Content',
|
||||
'title': idea,
|
||||
'target_keyword': pillar['target_keywords'][i % len(pillar['target_keywords'])] if pillar['target_keywords'] else idea,
|
||||
'word_count': '1500-2500',
|
||||
'priority': 'Medium'
|
||||
})
|
||||
|
||||
clusters.append(cluster)
|
||||
|
||||
return clusters
|
||||
|
||||
def _create_distribution_strategy(self, business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Create content distribution strategy."""
|
||||
return {
|
||||
'primary_channels': [
|
||||
{
|
||||
'channel': 'Company Blog',
|
||||
'content_types': ['Long-form articles', 'Guides', 'Case studies'],
|
||||
'frequency': 'Weekly',
|
||||
'audience_reach': 'High',
|
||||
'seo_value': 'High'
|
||||
},
|
||||
{
|
||||
'channel': 'LinkedIn',
|
||||
'content_types': ['Professional insights', 'Industry news', 'Thought leadership'],
|
||||
'frequency': 'Daily',
|
||||
'audience_reach': 'Medium',
|
||||
'seo_value': 'Medium'
|
||||
},
|
||||
{
|
||||
'channel': 'Email Newsletter',
|
||||
'content_types': ['Curated insights', 'Product updates', 'Educational content'],
|
||||
'frequency': 'Bi-weekly',
|
||||
'audience_reach': 'High',
|
||||
'seo_value': 'Low'
|
||||
}
|
||||
],
|
||||
'secondary_channels': [
|
||||
{
|
||||
'channel': 'YouTube',
|
||||
'content_types': ['Tutorial videos', 'Webinars', 'Product demos'],
|
||||
'frequency': 'Bi-weekly',
|
||||
'audience_reach': 'Medium',
|
||||
'seo_value': 'High'
|
||||
},
|
||||
{
|
||||
'channel': 'Industry Publications',
|
||||
'content_types': ['Guest articles', 'Expert quotes', 'Research insights'],
|
||||
'frequency': 'Monthly',
|
||||
'audience_reach': 'Medium',
|
||||
'seo_value': 'High'
|
||||
}
|
||||
],
|
||||
'repurposing_strategy': {
|
||||
'blog_post_to_social': 'Extract key insights for LinkedIn posts',
|
||||
'long_form_to_video': 'Create video summaries of detailed guides',
|
||||
'case_study_to_multiple': 'Create infographics, social posts, and email content',
|
||||
'webinar_to_content': 'Extract blog posts, social content, and email series'
|
||||
}
|
||||
}
|
||||
|
||||
def _create_kpi_framework(self, business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Create KPI measurement framework."""
|
||||
return {
|
||||
'primary_kpis': [
|
||||
{
|
||||
'metric': 'Organic Traffic Growth',
|
||||
'target': '25% increase per quarter',
|
||||
'measurement': 'Google Analytics',
|
||||
'frequency': 'Monthly'
|
||||
},
|
||||
{
|
||||
'metric': 'Lead Generation',
|
||||
'target': '50 qualified leads per month',
|
||||
'measurement': 'CRM tracking',
|
||||
'frequency': 'Weekly'
|
||||
},
|
||||
{
|
||||
'metric': 'Brand Awareness',
|
||||
'target': '15% increase in brand mentions',
|
||||
'measurement': 'Social listening tools',
|
||||
'frequency': 'Monthly'
|
||||
}
|
||||
],
|
||||
'content_kpis': [
|
||||
{
|
||||
'metric': 'Content Engagement',
|
||||
'target': '5% average engagement rate',
|
||||
'measurement': 'Social media analytics',
|
||||
'frequency': 'Weekly'
|
||||
},
|
||||
{
|
||||
'metric': 'Content Shares',
|
||||
'target': '100 shares per piece',
|
||||
'measurement': 'Social sharing tracking',
|
||||
'frequency': 'Per content piece'
|
||||
},
|
||||
{
|
||||
'metric': 'Time on Page',
|
||||
'target': '3+ minutes average',
|
||||
'measurement': 'Google Analytics',
|
||||
'frequency': 'Monthly'
|
||||
}
|
||||
],
|
||||
'seo_kpis': [
|
||||
{
|
||||
'metric': 'Keyword Rankings',
|
||||
'target': 'Top 10 for 20 target keywords',
|
||||
'measurement': 'SEO tools',
|
||||
'frequency': 'Weekly'
|
||||
},
|
||||
{
|
||||
'metric': 'Backlink Growth',
|
||||
'target': '10 quality backlinks per month',
|
||||
'measurement': 'Backlink analysis tools',
|
||||
'frequency': 'Monthly'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
def _create_implementation_roadmap(self, business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Create implementation roadmap."""
|
||||
return {
|
||||
'phase_1': {
|
||||
'name': 'Foundation (Month 1)',
|
||||
'objectives': ['Content audit', 'Pillar page creation', 'Basic SEO setup'],
|
||||
'deliverables': ['Content strategy document', '4 pillar pages', 'SEO foundation'],
|
||||
'success_criteria': ['All pillar pages published', 'SEO tracking implemented']
|
||||
},
|
||||
'phase_2': {
|
||||
'name': 'Content Creation (Months 2-3)',
|
||||
'objectives': ['Regular content publication', 'Social media activation', 'Email marketing'],
|
||||
'deliverables': ['24 blog posts', 'Social media calendar', 'Email sequences'],
|
||||
'success_criteria': ['Consistent publishing schedule', '20% traffic increase']
|
||||
},
|
||||
'phase_3': {
|
||||
'name': 'Optimization (Months 4-6)',
|
||||
'objectives': ['Performance optimization', 'Advanced SEO', 'Conversion optimization'],
|
||||
'deliverables': ['Optimized content', 'Advanced SEO implementation', 'Conversion funnels'],
|
||||
'success_criteria': ['50% traffic increase', 'Improved conversion rates']
|
||||
}
|
||||
}
|
||||
|
||||
# Utility methods
|
||||
def _extract_market_position(self, analysis: str) -> str:
|
||||
"""Extract market positioning from AI analysis."""
|
||||
return "Market positioning insights extracted from AI analysis"
|
||||
|
||||
def _extract_content_gaps(self, analysis: str) -> List[str]:
|
||||
"""Extract content gaps from AI analysis."""
|
||||
return ["Educational content gap", "Technical documentation gap", "Case study gap"]
|
||||
|
||||
def _extract_competitive_advantages(self, analysis: str) -> List[str]:
|
||||
"""Extract competitive advantages from AI analysis."""
|
||||
return ["Unique technology approach", "Industry expertise", "Customer success focus"]
|
||||
|
||||
def _extract_audience_insights(self, analysis: str) -> Dict[str, Any]:
|
||||
"""Extract audience insights from AI analysis."""
|
||||
return {
|
||||
'pain_points': ["Complex implementation", "Limited resources", "ROI concerns"],
|
||||
'content_preferences': ["Visual content", "Step-by-step guides", "Real examples"],
|
||||
'consumption_patterns': ["Mobile-first", "Video preferred", "Quick consumption"]
|
||||
}
|
||||
|
||||
def _calculate_pillar_distribution(self, calendar_items: List[Dict[str, Any]], content_pillars: List[Dict[str, Any]]) -> Dict[str, int]:
|
||||
"""Calculate content distribution across pillars."""
|
||||
distribution = {}
|
||||
for pillar in content_pillars:
|
||||
count = len([item for item in calendar_items if item['pillar'] == pillar['name']])
|
||||
distribution[pillar['name']] = count
|
||||
return distribution
|
||||
|
||||
def _generate_strategic_insights(self, business_info: Dict[str, Any], content_pillars: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""Generate strategic insights and recommendations."""
|
||||
return {
|
||||
'key_insights': [
|
||||
"Focus on educational content for early funnel engagement",
|
||||
"Leverage customer success stories for conversion",
|
||||
"Develop thought leadership for brand authority",
|
||||
"Create product education for user adoption"
|
||||
],
|
||||
'strategic_recommendations': [
|
||||
"Implement topic cluster strategy for SEO dominance",
|
||||
"Create pillar page for each content theme",
|
||||
"Develop comprehensive content repurposing workflow",
|
||||
"Establish thought leadership through industry insights"
|
||||
],
|
||||
'risk_mitigation': [
|
||||
"Diversify content topics to avoid algorithm dependency",
|
||||
"Create evergreen content for long-term value",
|
||||
"Build email list to reduce platform dependency",
|
||||
"Monitor competitor content to maintain differentiation"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def render_ai_content_strategy():
|
||||
"""Render the AI Content Strategy interface."""
|
||||
|
||||
st.title("🧠 AI Content Strategy Generator")
|
||||
st.markdown("**Generate comprehensive content strategies powered by AI intelligence**")
|
||||
|
||||
# Configuration form
|
||||
st.header("📋 Business Information")
|
||||
|
||||
with st.form("content_strategy_form"):
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
industry = st.selectbox(
|
||||
"Industry",
|
||||
[
|
||||
"Technology & Software",
|
||||
"Marketing & Advertising",
|
||||
"Healthcare",
|
||||
"Finance & Fintech",
|
||||
"E-commerce",
|
||||
"Education",
|
||||
"Manufacturing",
|
||||
"Professional Services",
|
||||
"Other"
|
||||
],
|
||||
index=0
|
||||
)
|
||||
|
||||
target_audience = st.text_area(
|
||||
"Target Audience",
|
||||
placeholder="Describe your ideal customers, their roles, challenges, and goals...",
|
||||
height=100
|
||||
)
|
||||
|
||||
business_goals = st.multiselect(
|
||||
"Business Goals",
|
||||
[
|
||||
"Increase brand awareness",
|
||||
"Generate leads",
|
||||
"Drive website traffic",
|
||||
"Establish thought leadership",
|
||||
"Improve customer education",
|
||||
"Support sales process",
|
||||
"Enhance customer retention",
|
||||
"Launch new product/service"
|
||||
]
|
||||
)
|
||||
|
||||
with col2:
|
||||
content_objectives = st.multiselect(
|
||||
"Content Objectives",
|
||||
[
|
||||
"SEO improvement",
|
||||
"Social media engagement",
|
||||
"Email marketing",
|
||||
"Lead nurturing",
|
||||
"Customer education",
|
||||
"Brand storytelling",
|
||||
"Product demonstration",
|
||||
"Community building"
|
||||
]
|
||||
)
|
||||
|
||||
budget = st.selectbox(
|
||||
"Monthly Content Budget",
|
||||
[
|
||||
"Under $1,000",
|
||||
"$1,000 - $5,000",
|
||||
"$5,000 - $10,000",
|
||||
"$10,000 - $25,000",
|
||||
"$25,000+"
|
||||
]
|
||||
)
|
||||
|
||||
timeline = st.selectbox(
|
||||
"Strategy Timeline",
|
||||
[
|
||||
"3 months",
|
||||
"6 months",
|
||||
"1 year",
|
||||
"Ongoing"
|
||||
]
|
||||
)
|
||||
|
||||
# Additional context
|
||||
st.subheader("Additional Context")
|
||||
|
||||
current_challenges = st.text_area(
|
||||
"Current Content Challenges",
|
||||
placeholder="What content challenges are you currently facing?",
|
||||
height=80
|
||||
)
|
||||
|
||||
competitive_landscape = st.text_area(
|
||||
"Competitive Landscape",
|
||||
placeholder="Describe your main competitors and their content approach...",
|
||||
height=80
|
||||
)
|
||||
|
||||
submit_strategy = st.form_submit_button("🧠 Generate AI Content Strategy", type="primary")
|
||||
|
||||
# Process strategy generation
|
||||
if submit_strategy:
|
||||
if target_audience and business_goals and content_objectives:
|
||||
# Prepare business information
|
||||
business_info = {
|
||||
'industry': industry,
|
||||
'target_audience': target_audience,
|
||||
'business_goals': business_goals,
|
||||
'content_objectives': content_objectives,
|
||||
'budget': budget,
|
||||
'timeline': timeline,
|
||||
'current_challenges': current_challenges,
|
||||
'competitive_landscape': competitive_landscape
|
||||
}
|
||||
|
||||
# Initialize generator
|
||||
if 'strategy_generator' not in st.session_state:
|
||||
st.session_state.strategy_generator = AIContentStrategyGenerator()
|
||||
|
||||
generator = st.session_state.strategy_generator
|
||||
|
||||
with st.spinner("🧠 Generating AI-powered content strategy..."):
|
||||
strategy_results = generator.generate_content_strategy(business_info)
|
||||
|
||||
if 'error' not in strategy_results:
|
||||
st.success("✅ Content strategy generated successfully!")
|
||||
|
||||
# Store results in session state
|
||||
st.session_state.strategy_results = strategy_results
|
||||
|
||||
# Display results
|
||||
render_strategy_results_dashboard(strategy_results)
|
||||
else:
|
||||
st.error(f"❌ Strategy generation failed: {strategy_results['error']}")
|
||||
else:
|
||||
st.warning("⚠️ Please fill in target audience, business goals, and content objectives.")
|
||||
|
||||
# Show previous results if available
|
||||
elif 'strategy_results' in st.session_state:
|
||||
st.info("🧠 Showing previous strategy results")
|
||||
render_strategy_results_dashboard(st.session_state.strategy_results)
|
||||
|
||||
|
||||
def render_strategy_results_dashboard(results: Dict[str, Any]):
|
||||
"""Render comprehensive strategy results dashboard."""
|
||||
|
||||
# Strategy overview
|
||||
st.header("📊 Content Strategy Overview")
|
||||
|
||||
business_analysis = results.get('business_analysis', {})
|
||||
content_pillars = results.get('content_pillars', [])
|
||||
content_calendar = results.get('content_calendar', {})
|
||||
|
||||
# Key metrics overview
|
||||
col1, col2, col3, col4 = st.columns(4)
|
||||
|
||||
with col1:
|
||||
st.metric("Content Pillars", len(content_pillars))
|
||||
|
||||
with col2:
|
||||
calendar_items = content_calendar.get('calendar_items', [])
|
||||
st.metric("Content Pieces", len(calendar_items))
|
||||
|
||||
with col3:
|
||||
timeline = content_calendar.get('timeline', 'Not specified')
|
||||
st.metric("Timeline", timeline)
|
||||
|
||||
with col4:
|
||||
total_hours = sum(item.get('estimated_hours', 0) for item in calendar_items)
|
||||
st.metric("Est. Hours", f"{total_hours}h")
|
||||
|
||||
# Strategy tabs
|
||||
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
|
||||
"🧠 AI Insights",
|
||||
"🏛️ Content Pillars",
|
||||
"📅 Content Calendar",
|
||||
"🎯 Topic Clusters",
|
||||
"📢 Distribution",
|
||||
"📊 Implementation"
|
||||
])
|
||||
|
||||
with tab1:
|
||||
if business_analysis:
|
||||
st.subheader("Business Analysis & Insights")
|
||||
|
||||
# Market positioning
|
||||
market_position = business_analysis.get('market_position', '')
|
||||
if market_position:
|
||||
st.markdown("#### 🎯 Market Positioning")
|
||||
st.info(market_position)
|
||||
|
||||
# Content gaps
|
||||
content_gaps = business_analysis.get('content_gaps', [])
|
||||
if content_gaps:
|
||||
st.markdown("#### 🔍 Content Gaps Identified")
|
||||
for gap in content_gaps:
|
||||
st.warning(f"📌 {gap}")
|
||||
|
||||
# Competitive advantages
|
||||
advantages = business_analysis.get('competitive_advantages', [])
|
||||
if advantages:
|
||||
st.markdown("#### 🏆 Competitive Advantages")
|
||||
for advantage in advantages:
|
||||
st.success(f"✅ {advantage}")
|
||||
|
||||
# AI insights
|
||||
ai_insights = results.get('ai_insights', {})
|
||||
if ai_insights:
|
||||
st.markdown("#### 🧠 Strategic AI Insights")
|
||||
|
||||
insights = ai_insights.get('key_insights', [])
|
||||
for insight in insights:
|
||||
st.info(f"💡 {insight}")
|
||||
|
||||
recommendations = ai_insights.get('strategic_recommendations', [])
|
||||
if recommendations:
|
||||
st.markdown("#### 🎯 Strategic Recommendations")
|
||||
for rec in recommendations:
|
||||
st.success(f"📋 {rec}")
|
||||
|
||||
with tab2:
|
||||
if content_pillars:
|
||||
st.subheader("Content Pillars Strategy")
|
||||
|
||||
# Pillars overview chart
|
||||
pillar_names = [pillar['name'] for pillar in content_pillars]
|
||||
pillar_ideas = [len(pillar['content_ideas']) for pillar in content_pillars]
|
||||
|
||||
fig = px.bar(
|
||||
x=pillar_names,
|
||||
y=pillar_ideas,
|
||||
title="Content Ideas per Pillar",
|
||||
labels={'x': 'Content Pillars', 'y': 'Number of Ideas'}
|
||||
)
|
||||
st.plotly_chart(fig, use_container_width=True)
|
||||
|
||||
# Detailed pillar information
|
||||
for pillar in content_pillars:
|
||||
with st.expander(f"🏛️ {pillar['name']}", expanded=False):
|
||||
st.markdown(f"**Description:** {pillar['description']}")
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.markdown("**Target Keywords:**")
|
||||
for keyword in pillar['target_keywords']:
|
||||
st.code(keyword)
|
||||
|
||||
st.markdown("**Content Types:**")
|
||||
for content_type in pillar['content_types']:
|
||||
st.write(f"• {content_type}")
|
||||
|
||||
with col2:
|
||||
st.markdown("**Success Metrics:**")
|
||||
for metric in pillar['success_metrics']:
|
||||
st.write(f"📊 {metric}")
|
||||
|
||||
st.markdown("**Content Ideas:**")
|
||||
for idea in pillar['content_ideas']:
|
||||
st.write(f"💡 {idea}")
|
||||
|
||||
with tab3:
|
||||
if content_calendar:
|
||||
st.subheader("Content Calendar & Planning")
|
||||
|
||||
calendar_items = content_calendar.get('calendar_items', [])
|
||||
|
||||
if calendar_items:
|
||||
# Calendar overview
|
||||
df_calendar = pd.DataFrame(calendar_items)
|
||||
|
||||
# Priority distribution
|
||||
priority_counts = df_calendar['priority'].value_counts()
|
||||
fig_priority = px.pie(
|
||||
values=priority_counts.values,
|
||||
names=priority_counts.index,
|
||||
title="Content Priority Distribution"
|
||||
)
|
||||
st.plotly_chart(fig_priority, use_container_width=True)
|
||||
|
||||
# Content calendar table
|
||||
st.markdown("#### 📅 Detailed Content Calendar")
|
||||
|
||||
display_df = df_calendar[[
|
||||
'period', 'pillar', 'content_type', 'topic',
|
||||
'priority', 'estimated_hours'
|
||||
]].copy()
|
||||
|
||||
display_df.columns = [
|
||||
'Period', 'Pillar', 'Content Type', 'Topic',
|
||||
'Priority', 'Est. Hours'
|
||||
]
|
||||
|
||||
st.dataframe(
|
||||
display_df,
|
||||
column_config={
|
||||
"Priority": st.column_config.SelectboxColumn(
|
||||
"Priority",
|
||||
options=["High", "Medium", "Low"]
|
||||
),
|
||||
"Est. Hours": st.column_config.NumberColumn(
|
||||
"Est. Hours",
|
||||
format="%d h"
|
||||
)
|
||||
},
|
||||
hide_index=True,
|
||||
use_container_width=True
|
||||
)
|
||||
|
||||
# Export calendar
|
||||
csv = df_calendar.to_csv(index=False)
|
||||
st.download_button(
|
||||
label="📥 Download Content Calendar",
|
||||
data=csv,
|
||||
file_name=f"content_calendar_{datetime.now().strftime('%Y%m%d')}.csv",
|
||||
mime="text/csv"
|
||||
)
|
||||
|
||||
with tab4:
|
||||
topic_clusters = results.get('topic_clusters', [])
|
||||
if topic_clusters:
|
||||
st.subheader("SEO Topic Clusters")
|
||||
|
||||
for cluster in topic_clusters:
|
||||
with st.expander(f"🎯 {cluster['cluster_name']}", expanded=False):
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.markdown(f"**Primary Topic:** {cluster['primary_topic']}")
|
||||
st.markdown(f"**SEO Opportunity:** {cluster['seo_opportunity']}")
|
||||
st.markdown(f"**Linking Strategy:** {cluster['internal_linking_strategy']}")
|
||||
|
||||
with col2:
|
||||
st.markdown("**Supporting Topics:**")
|
||||
for topic in cluster['supporting_topics']:
|
||||
st.code(topic)
|
||||
|
||||
st.markdown("**Content Pieces:**")
|
||||
content_pieces = cluster['content_pieces']
|
||||
df_pieces = pd.DataFrame(content_pieces)
|
||||
st.dataframe(df_pieces, hide_index=True, use_container_width=True)
|
||||
|
||||
with tab5:
|
||||
distribution_strategy = results.get('distribution_strategy', {})
|
||||
if distribution_strategy:
|
||||
st.subheader("Content Distribution Strategy")
|
||||
|
||||
# Primary channels
|
||||
primary_channels = distribution_strategy.get('primary_channels', [])
|
||||
if primary_channels:
|
||||
st.markdown("#### 📢 Primary Distribution Channels")
|
||||
df_primary = pd.DataFrame(primary_channels)
|
||||
st.dataframe(df_primary, hide_index=True, use_container_width=True)
|
||||
|
||||
# Secondary channels
|
||||
secondary_channels = distribution_strategy.get('secondary_channels', [])
|
||||
if secondary_channels:
|
||||
st.markdown("#### 📺 Secondary Distribution Channels")
|
||||
df_secondary = pd.DataFrame(secondary_channels)
|
||||
st.dataframe(df_secondary, hide_index=True, use_container_width=True)
|
||||
|
||||
# Repurposing strategy
|
||||
repurposing = distribution_strategy.get('repurposing_strategy', {})
|
||||
if repurposing:
|
||||
st.markdown("#### ♻️ Content Repurposing Strategy")
|
||||
for strategy, description in repurposing.items():
|
||||
st.write(f"**{strategy.replace('_', ' ').title()}:** {description}")
|
||||
|
||||
with tab6:
|
||||
# Implementation roadmap
|
||||
roadmap = results.get('implementation_roadmap', {})
|
||||
kpi_framework = results.get('kpi_framework', {})
|
||||
|
||||
if roadmap:
|
||||
st.subheader("Implementation Roadmap")
|
||||
|
||||
for phase_key, phase_data in roadmap.items():
|
||||
with st.expander(f"📋 {phase_data['name']}", expanded=False):
|
||||
st.markdown(f"**Objectives:**")
|
||||
for objective in phase_data['objectives']:
|
||||
st.write(f"• {objective}")
|
||||
|
||||
st.markdown(f"**Deliverables:**")
|
||||
for deliverable in phase_data['deliverables']:
|
||||
st.write(f"📦 {deliverable}")
|
||||
|
||||
st.markdown(f"**Success Criteria:**")
|
||||
for criteria in phase_data['success_criteria']:
|
||||
st.write(f"✅ {criteria}")
|
||||
|
||||
if kpi_framework:
|
||||
st.subheader("KPI Framework")
|
||||
|
||||
# Primary KPIs
|
||||
primary_kpis = kpi_framework.get('primary_kpis', [])
|
||||
if primary_kpis:
|
||||
st.markdown("#### 🎯 Primary KPIs")
|
||||
df_primary_kpis = pd.DataFrame(primary_kpis)
|
||||
st.dataframe(df_primary_kpis, hide_index=True, use_container_width=True)
|
||||
|
||||
# Content KPIs
|
||||
content_kpis = kpi_framework.get('content_kpis', [])
|
||||
if content_kpis:
|
||||
st.markdown("#### 📝 Content KPIs")
|
||||
df_content_kpis = pd.DataFrame(content_kpis)
|
||||
st.dataframe(df_content_kpis, hide_index=True, use_container_width=True)
|
||||
|
||||
# Export functionality
|
||||
st.markdown("---")
|
||||
col1, col2, col3 = st.columns(3)
|
||||
|
||||
with col1:
|
||||
if st.button("📥 Export Full Strategy", use_container_width=True):
|
||||
strategy_json = json.dumps(results, indent=2, default=str)
|
||||
st.download_button(
|
||||
label="Download JSON Strategy",
|
||||
data=strategy_json,
|
||||
file_name=f"content_strategy_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
||||
mime="application/json"
|
||||
)
|
||||
|
||||
with col2:
|
||||
if st.button("📊 Export Calendar", use_container_width=True):
|
||||
calendar_items = content_calendar.get('calendar_items', [])
|
||||
if calendar_items:
|
||||
df_calendar = pd.DataFrame(calendar_items)
|
||||
csv = df_calendar.to_csv(index=False)
|
||||
st.download_button(
|
||||
label="Download CSV Calendar",
|
||||
data=csv,
|
||||
file_name=f"content_calendar_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
||||
mime="text/csv"
|
||||
)
|
||||
|
||||
with col3:
|
||||
if st.button("🔄 Generate New Strategy", use_container_width=True):
|
||||
if 'strategy_results' in st.session_state:
|
||||
del st.session_state.strategy_results
|
||||
st.rerun()
|
||||
|
||||
|
||||
# Main execution
|
||||
if __name__ == "__main__":
|
||||
render_ai_content_strategy()
|
||||
919
lib/ai_seo_tools/enterprise_seo_suite.py
Normal file
919
lib/ai_seo_tools/enterprise_seo_suite.py
Normal file
@@ -0,0 +1,919 @@
|
||||
"""
|
||||
Enterprise SEO Command Center
|
||||
|
||||
Unified AI-powered SEO suite that orchestrates all existing tools into
|
||||
intelligent workflows for enterprise-level SEO management.
|
||||
"""
|
||||
|
||||
import streamlit as st
|
||||
import asyncio
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
from loguru import logger
|
||||
|
||||
# Import existing SEO tools
|
||||
from .on_page_seo_analyzer import fetch_seo_data
|
||||
from .content_gap_analysis.enhanced_analyzer import EnhancedContentGapAnalyzer
|
||||
from .technical_seo_crawler.crawler import TechnicalSEOCrawler
|
||||
from .weburl_seo_checker import url_seo_checker
|
||||
from .google_pagespeed_insights import google_pagespeed_insights
|
||||
from ..gpt_providers.text_generation.main_text_generation import llm_text_gen
|
||||
|
||||
# Import the new enterprise tools
|
||||
from .google_search_console_integration import GoogleSearchConsoleAnalyzer, render_gsc_integration
|
||||
from .ai_content_strategy import AIContentStrategyGenerator, render_ai_content_strategy
|
||||
|
||||
class EnterpriseSEOSuite:
|
||||
"""
|
||||
Enterprise-level SEO suite orchestrating all tools into intelligent workflows.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the enterprise SEO suite."""
|
||||
self.gap_analyzer = EnhancedContentGapAnalyzer()
|
||||
self.technical_crawler = TechnicalSEOCrawler()
|
||||
|
||||
# Initialize new enterprise tools
|
||||
self.gsc_analyzer = GoogleSearchConsoleAnalyzer()
|
||||
self.content_strategy_generator = AIContentStrategyGenerator()
|
||||
|
||||
# SEO workflow templates
|
||||
self.workflow_templates = {
|
||||
'complete_audit': 'Complete SEO Audit',
|
||||
'content_strategy': 'Content Strategy Development',
|
||||
'technical_optimization': 'Technical SEO Optimization',
|
||||
'competitor_intelligence': 'Competitive Intelligence',
|
||||
'keyword_domination': 'Keyword Domination Strategy',
|
||||
'local_seo': 'Local SEO Optimization',
|
||||
'enterprise_monitoring': 'Enterprise SEO Monitoring'
|
||||
}
|
||||
|
||||
logger.info("Enterprise SEO Suite initialized")
|
||||
|
||||
async def execute_complete_seo_audit(self, website_url: str, competitors: List[str],
|
||||
target_keywords: List[str]) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute a comprehensive enterprise SEO audit combining all tools.
|
||||
|
||||
Args:
|
||||
website_url: Primary website to audit
|
||||
competitors: List of competitor URLs (max 5)
|
||||
target_keywords: Primary keywords to optimize for
|
||||
|
||||
Returns:
|
||||
Comprehensive audit results with prioritized action plan
|
||||
"""
|
||||
try:
|
||||
st.info("🚀 Initiating Complete Enterprise SEO Audit...")
|
||||
|
||||
audit_results = {
|
||||
'audit_timestamp': datetime.utcnow().isoformat(),
|
||||
'website_url': website_url,
|
||||
'competitors': competitors[:5],
|
||||
'target_keywords': target_keywords,
|
||||
'technical_audit': {},
|
||||
'content_analysis': {},
|
||||
'competitive_intelligence': {},
|
||||
'on_page_analysis': {},
|
||||
'performance_metrics': {},
|
||||
'strategic_recommendations': {},
|
||||
'priority_action_plan': []
|
||||
}
|
||||
|
||||
# Phase 1: Technical SEO Audit
|
||||
with st.expander("🔧 Technical SEO Analysis", expanded=True):
|
||||
st.info("Analyzing technical SEO factors...")
|
||||
technical_results = await self._run_technical_audit(website_url)
|
||||
audit_results['technical_audit'] = technical_results
|
||||
st.success("✅ Technical audit completed")
|
||||
|
||||
# Phase 2: Content Gap Analysis
|
||||
with st.expander("📊 Content Intelligence Analysis", expanded=True):
|
||||
st.info("Analyzing content gaps and opportunities...")
|
||||
content_results = await self._run_content_analysis(
|
||||
website_url, competitors, target_keywords
|
||||
)
|
||||
audit_results['content_analysis'] = content_results
|
||||
st.success("✅ Content analysis completed")
|
||||
|
||||
# Phase 3: On-Page SEO Analysis
|
||||
with st.expander("🔍 On-Page SEO Analysis", expanded=True):
|
||||
st.info("Analyzing on-page SEO factors...")
|
||||
onpage_results = await self._run_onpage_analysis(website_url)
|
||||
audit_results['on_page_analysis'] = onpage_results
|
||||
st.success("✅ On-page analysis completed")
|
||||
|
||||
# Phase 4: Performance Analysis
|
||||
with st.expander("⚡ Performance Analysis", expanded=True):
|
||||
st.info("Analyzing website performance...")
|
||||
performance_results = await self._run_performance_analysis(website_url)
|
||||
audit_results['performance_metrics'] = performance_results
|
||||
st.success("✅ Performance analysis completed")
|
||||
|
||||
# Phase 5: AI-Powered Strategic Recommendations
|
||||
with st.expander("🤖 AI Strategic Analysis", expanded=True):
|
||||
st.info("Generating AI-powered strategic recommendations...")
|
||||
strategic_analysis = await self._generate_strategic_recommendations(audit_results)
|
||||
audit_results['strategic_recommendations'] = strategic_analysis
|
||||
|
||||
# Generate prioritized action plan
|
||||
action_plan = await self._create_priority_action_plan(audit_results)
|
||||
audit_results['priority_action_plan'] = action_plan
|
||||
st.success("✅ Strategic analysis completed")
|
||||
|
||||
return audit_results
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error in complete SEO audit: {str(e)}"
|
||||
logger.error(error_msg, exc_info=True)
|
||||
st.error(error_msg)
|
||||
return {'error': error_msg}
|
||||
|
||||
async def _run_technical_audit(self, website_url: str) -> Dict[str, Any]:
|
||||
"""Run comprehensive technical SEO audit."""
|
||||
try:
|
||||
# Use existing technical crawler
|
||||
technical_results = self.technical_crawler.analyze_website_technical_seo(
|
||||
website_url, crawl_depth=3, max_pages=100
|
||||
)
|
||||
|
||||
# Enhance with additional technical checks
|
||||
enhanced_results = {
|
||||
'crawler_results': technical_results,
|
||||
'critical_issues': self._identify_critical_technical_issues(technical_results),
|
||||
'performance_score': self._calculate_technical_score(technical_results),
|
||||
'priority_fixes': self._prioritize_technical_fixes(technical_results)
|
||||
}
|
||||
|
||||
return enhanced_results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Technical audit error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
async def _run_content_analysis(self, website_url: str, competitors: List[str],
|
||||
keywords: List[str]) -> Dict[str, Any]:
|
||||
"""Run comprehensive content gap analysis."""
|
||||
try:
|
||||
# Use existing content gap analyzer
|
||||
content_results = self.gap_analyzer.analyze_comprehensive_gap(
|
||||
website_url, competitors, keywords, industry="general"
|
||||
)
|
||||
|
||||
# Enhance with content strategy insights
|
||||
enhanced_results = {
|
||||
'gap_analysis': content_results,
|
||||
'content_opportunities': self._identify_content_opportunities(content_results),
|
||||
'keyword_strategy': self._develop_keyword_strategy(content_results),
|
||||
'competitive_advantages': self._find_competitive_advantages(content_results)
|
||||
}
|
||||
|
||||
return enhanced_results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Content analysis error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
async def _run_onpage_analysis(self, website_url: str) -> Dict[str, Any]:
|
||||
"""Run on-page SEO analysis."""
|
||||
try:
|
||||
# Use existing on-page analyzer
|
||||
onpage_data = fetch_seo_data(website_url)
|
||||
|
||||
# Enhanced analysis
|
||||
enhanced_results = {
|
||||
'seo_data': onpage_data,
|
||||
'optimization_score': self._calculate_onpage_score(onpage_data),
|
||||
'meta_optimization': self._analyze_meta_optimization(onpage_data),
|
||||
'content_optimization': self._analyze_content_optimization(onpage_data)
|
||||
}
|
||||
|
||||
return enhanced_results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"On-page analysis error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
async def _run_performance_analysis(self, website_url: str) -> Dict[str, Any]:
|
||||
"""Run website performance analysis."""
|
||||
try:
|
||||
# Comprehensive performance metrics
|
||||
performance_results = {
|
||||
'core_web_vitals': await self._analyze_core_web_vitals(website_url),
|
||||
'loading_performance': await self._analyze_loading_performance(website_url),
|
||||
'mobile_optimization': await self._analyze_mobile_optimization(website_url),
|
||||
'performance_score': 0 # Will be calculated
|
||||
}
|
||||
|
||||
# Calculate overall performance score
|
||||
performance_results['performance_score'] = self._calculate_performance_score(
|
||||
performance_results
|
||||
)
|
||||
|
||||
return performance_results
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Performance analysis error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
async def _generate_strategic_recommendations(self, audit_results: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Generate AI-powered strategic recommendations."""
|
||||
try:
|
||||
# Compile audit summary for AI analysis
|
||||
audit_summary = {
|
||||
'technical_score': audit_results.get('technical_audit', {}).get('performance_score', 0),
|
||||
'content_gaps': len(audit_results.get('content_analysis', {}).get('content_opportunities', [])),
|
||||
'onpage_score': audit_results.get('on_page_analysis', {}).get('optimization_score', 0),
|
||||
'performance_score': audit_results.get('performance_metrics', {}).get('performance_score', 0)
|
||||
}
|
||||
|
||||
strategic_prompt = f"""
|
||||
Analyze this comprehensive SEO audit and provide strategic recommendations:
|
||||
|
||||
AUDIT SUMMARY:
|
||||
- Technical SEO Score: {audit_summary['technical_score']}/100
|
||||
- Content Gaps Identified: {audit_summary['content_gaps']}
|
||||
- On-Page SEO Score: {audit_summary['onpage_score']}/100
|
||||
- Performance Score: {audit_summary['performance_score']}/100
|
||||
|
||||
DETAILED FINDINGS:
|
||||
Technical Issues: {json.dumps(audit_results.get('technical_audit', {}), indent=2)[:1000]}
|
||||
Content Opportunities: {json.dumps(audit_results.get('content_analysis', {}), indent=2)[:1000]}
|
||||
|
||||
Provide strategic recommendations in these categories:
|
||||
|
||||
1. IMMEDIATE WINS (0-30 days):
|
||||
- Quick technical fixes with high impact
|
||||
- Content optimizations for existing pages
|
||||
- Critical performance improvements
|
||||
|
||||
2. STRATEGIC INITIATIVES (1-3 months):
|
||||
- Content strategy development
|
||||
- Technical architecture improvements
|
||||
- Competitive positioning strategies
|
||||
|
||||
3. LONG-TERM GROWTH (3-12 months):
|
||||
- Authority building strategies
|
||||
- Market expansion opportunities
|
||||
- Advanced SEO techniques
|
||||
|
||||
4. RISK MITIGATION:
|
||||
- Technical vulnerabilities to address
|
||||
- Content gaps that competitors could exploit
|
||||
- Performance issues affecting user experience
|
||||
|
||||
Provide specific, actionable recommendations with expected impact and effort estimates.
|
||||
"""
|
||||
|
||||
strategic_analysis = llm_text_gen(
|
||||
strategic_prompt,
|
||||
system_prompt="You are an enterprise SEO strategist with 10+ years of experience. Provide detailed, actionable recommendations based on comprehensive audit data."
|
||||
)
|
||||
|
||||
return {
|
||||
'full_analysis': strategic_analysis,
|
||||
'immediate_wins': self._extract_immediate_wins(strategic_analysis),
|
||||
'strategic_initiatives': self._extract_strategic_initiatives(strategic_analysis),
|
||||
'long_term_growth': self._extract_long_term_growth(strategic_analysis),
|
||||
'risk_mitigation': self._extract_risk_mitigation(strategic_analysis)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Strategic analysis error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
async def _create_priority_action_plan(self, audit_results: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
"""Create prioritized action plan from audit results."""
|
||||
try:
|
||||
action_plan = []
|
||||
|
||||
# Extract recommendations from all analysis phases
|
||||
strategic_recs = audit_results.get('strategic_recommendations', {})
|
||||
|
||||
# Immediate wins (High priority, low effort)
|
||||
immediate_wins = strategic_recs.get('immediate_wins', [])
|
||||
for win in immediate_wins[:5]:
|
||||
action_plan.append({
|
||||
'category': 'Immediate Win',
|
||||
'priority': 'Critical',
|
||||
'effort': 'Low',
|
||||
'timeframe': '0-30 days',
|
||||
'action': win,
|
||||
'expected_impact': 'High',
|
||||
'source': 'Strategic Analysis'
|
||||
})
|
||||
|
||||
# Technical fixes
|
||||
technical_issues = audit_results.get('technical_audit', {}).get('critical_issues', [])
|
||||
for issue in technical_issues[:3]:
|
||||
action_plan.append({
|
||||
'category': 'Technical SEO',
|
||||
'priority': 'High',
|
||||
'effort': 'Medium',
|
||||
'timeframe': '1-4 weeks',
|
||||
'action': issue,
|
||||
'expected_impact': 'High',
|
||||
'source': 'Technical Audit'
|
||||
})
|
||||
|
||||
# Content opportunities
|
||||
content_ops = audit_results.get('content_analysis', {}).get('content_opportunities', [])
|
||||
for opportunity in content_ops[:3]:
|
||||
action_plan.append({
|
||||
'category': 'Content Strategy',
|
||||
'priority': 'Medium',
|
||||
'effort': 'High',
|
||||
'timeframe': '2-8 weeks',
|
||||
'action': opportunity,
|
||||
'expected_impact': 'Medium',
|
||||
'source': 'Content Analysis'
|
||||
})
|
||||
|
||||
# Sort by priority and expected impact
|
||||
priority_order = {'Critical': 0, 'High': 1, 'Medium': 2, 'Low': 3}
|
||||
action_plan.sort(key=lambda x: priority_order.get(x['priority'], 4))
|
||||
|
||||
return action_plan[:15] # Top 15 actions
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Action plan creation error: {str(e)}")
|
||||
return []
|
||||
|
||||
# Utility methods for analysis
|
||||
def _identify_critical_technical_issues(self, technical_results: Dict[str, Any]) -> List[str]:
|
||||
"""Identify critical technical SEO issues."""
|
||||
critical_issues = []
|
||||
|
||||
# Add logic to identify critical technical issues
|
||||
# This would analyze the technical_results and extract critical problems
|
||||
|
||||
return critical_issues
|
||||
|
||||
def _calculate_technical_score(self, technical_results: Dict[str, Any]) -> int:
|
||||
"""Calculate technical SEO score."""
|
||||
# Implement scoring algorithm based on technical audit results
|
||||
return 75 # Placeholder
|
||||
|
||||
def _prioritize_technical_fixes(self, technical_results: Dict[str, Any]) -> List[str]:
|
||||
"""Prioritize technical fixes by impact and effort."""
|
||||
# Implement prioritization logic
|
||||
return ["Fix broken links", "Optimize images", "Improve page speed"]
|
||||
|
||||
def _identify_content_opportunities(self, content_results: Dict[str, Any]) -> List[str]:
|
||||
"""Identify top content opportunities."""
|
||||
# Extract content opportunities from gap analysis
|
||||
return ["Create FAQ content", "Develop comparison guides", "Write how-to articles"]
|
||||
|
||||
def _develop_keyword_strategy(self, content_results: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Develop keyword strategy from content analysis."""
|
||||
return {
|
||||
'primary_keywords': [],
|
||||
'secondary_keywords': [],
|
||||
'long_tail_opportunities': [],
|
||||
'competitor_gaps': []
|
||||
}
|
||||
|
||||
def _find_competitive_advantages(self, content_results: Dict[str, Any]) -> List[str]:
|
||||
"""Find competitive advantages from analysis."""
|
||||
return ["Unique content angles", "Underserved niches", "Technical superiority"]
|
||||
|
||||
def _calculate_onpage_score(self, onpage_data: Dict[str, Any]) -> int:
|
||||
"""Calculate on-page SEO score."""
|
||||
return 80 # Placeholder
|
||||
|
||||
def _analyze_meta_optimization(self, onpage_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Analyze meta tag optimization."""
|
||||
return {'title_optimization': 'good', 'description_optimization': 'needs_work'}
|
||||
|
||||
def _analyze_content_optimization(self, onpage_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Analyze content optimization."""
|
||||
return {'keyword_density': 'optimal', 'content_length': 'adequate'}
|
||||
|
||||
async def _analyze_core_web_vitals(self, website_url: str) -> Dict[str, Any]:
|
||||
"""Analyze Core Web Vitals."""
|
||||
return {'lcp': 2.5, 'fid': 100, 'cls': 0.1}
|
||||
|
||||
async def _analyze_loading_performance(self, website_url: str) -> Dict[str, Any]:
|
||||
"""Analyze loading performance."""
|
||||
return {'ttfb': 200, 'fcp': 1.5, 'speed_index': 3.0}
|
||||
|
||||
async def _analyze_mobile_optimization(self, website_url: str) -> Dict[str, Any]:
|
||||
"""Analyze mobile optimization."""
|
||||
return {'mobile_friendly': True, 'responsive_design': True}
|
||||
|
||||
def _calculate_performance_score(self, performance_results: Dict[str, Any]) -> int:
|
||||
"""Calculate overall performance score."""
|
||||
return 85 # Placeholder
|
||||
|
||||
def _extract_immediate_wins(self, analysis: str) -> List[str]:
|
||||
"""Extract immediate wins from strategic analysis."""
|
||||
# Parse the AI analysis and extract immediate wins
|
||||
lines = analysis.split('\n')
|
||||
wins = []
|
||||
in_immediate_section = False
|
||||
|
||||
for line in lines:
|
||||
if 'IMMEDIATE WINS' in line.upper():
|
||||
in_immediate_section = True
|
||||
continue
|
||||
elif 'STRATEGIC INITIATIVES' in line.upper():
|
||||
in_immediate_section = False
|
||||
continue
|
||||
|
||||
if in_immediate_section and line.strip().startswith('-'):
|
||||
wins.append(line.strip().lstrip('- '))
|
||||
|
||||
return wins[:5]
|
||||
|
||||
def _extract_strategic_initiatives(self, analysis: str) -> List[str]:
|
||||
"""Extract strategic initiatives from analysis."""
|
||||
# Similar extraction logic for strategic initiatives
|
||||
return ["Develop content hub", "Implement schema markup", "Build authority pages"]
|
||||
|
||||
def _extract_long_term_growth(self, analysis: str) -> List[str]:
|
||||
"""Extract long-term growth strategies."""
|
||||
return ["Market expansion", "Authority building", "Advanced technical SEO"]
|
||||
|
||||
def _extract_risk_mitigation(self, analysis: str) -> List[str]:
|
||||
"""Extract risk mitigation strategies."""
|
||||
return ["Fix technical vulnerabilities", "Address content gaps", "Improve performance"]
|
||||
|
||||
def execute_content_strategy_workflow(self, business_info: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute comprehensive content strategy workflow using AI insights.
|
||||
|
||||
Args:
|
||||
business_info: Business context and objectives
|
||||
|
||||
Returns:
|
||||
Complete content strategy with implementation plan
|
||||
"""
|
||||
try:
|
||||
st.info("🧠 Executing AI-powered content strategy workflow...")
|
||||
|
||||
# Generate AI content strategy
|
||||
content_strategy = self.content_strategy_generator.generate_content_strategy(business_info)
|
||||
|
||||
# If GSC data is available, enhance with search insights
|
||||
if business_info.get('gsc_site_url'):
|
||||
gsc_insights = self.gsc_analyzer.analyze_search_performance(
|
||||
business_info['gsc_site_url'],
|
||||
business_info.get('gsc_date_range', 90)
|
||||
)
|
||||
content_strategy['gsc_insights'] = gsc_insights
|
||||
|
||||
# Generate SEO-optimized content recommendations
|
||||
seo_content_recs = self._generate_seo_content_recommendations(content_strategy)
|
||||
content_strategy['seo_recommendations'] = seo_content_recs
|
||||
|
||||
return content_strategy
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Content strategy workflow error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
def execute_search_intelligence_workflow(self, site_url: str, date_range: int = 90) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute comprehensive search intelligence workflow using GSC data.
|
||||
|
||||
Args:
|
||||
site_url: Website URL registered in GSC
|
||||
date_range: Analysis period in days
|
||||
|
||||
Returns:
|
||||
Complete search intelligence analysis with actionable insights
|
||||
"""
|
||||
try:
|
||||
st.info("📊 Executing search intelligence workflow...")
|
||||
|
||||
# Analyze GSC performance
|
||||
gsc_analysis = self.gsc_analyzer.analyze_search_performance(site_url, date_range)
|
||||
|
||||
# Enhance with technical SEO analysis
|
||||
technical_analysis = self.technical_crawler.crawl_and_analyze(site_url)
|
||||
gsc_analysis['technical_insights'] = technical_analysis
|
||||
|
||||
# Generate content gap analysis based on GSC keywords
|
||||
if gsc_analysis.get('keyword_analysis'):
|
||||
keywords = [kw['keyword'] for kw in gsc_analysis['keyword_analysis'].get('high_volume_keywords', [])]
|
||||
content_gaps = self.gap_analyzer.analyze_content_gaps(
|
||||
keywords[:10], # Top 10 keywords
|
||||
site_url
|
||||
)
|
||||
gsc_analysis['content_gap_analysis'] = content_gaps
|
||||
|
||||
# Generate comprehensive recommendations
|
||||
search_recommendations = self._generate_search_intelligence_recommendations(gsc_analysis)
|
||||
gsc_analysis['comprehensive_recommendations'] = search_recommendations
|
||||
|
||||
return gsc_analysis
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Search intelligence workflow error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
def _generate_seo_content_recommendations(self, content_strategy: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Generate SEO-optimized content recommendations based on strategy."""
|
||||
try:
|
||||
content_pillars = content_strategy.get('content_pillars', [])
|
||||
|
||||
seo_recommendations = {
|
||||
'keyword_optimization': [],
|
||||
'content_structure': [],
|
||||
'internal_linking': [],
|
||||
'technical_seo': []
|
||||
}
|
||||
|
||||
for pillar in content_pillars:
|
||||
# Keyword optimization recommendations
|
||||
for keyword in pillar.get('target_keywords', []):
|
||||
seo_recommendations['keyword_optimization'].append({
|
||||
'pillar': pillar['name'],
|
||||
'keyword': keyword,
|
||||
'recommendation': f"Create comprehensive content targeting '{keyword}' with semantic variations",
|
||||
'priority': 'High' if keyword in pillar['target_keywords'][:2] else 'Medium'
|
||||
})
|
||||
|
||||
# Content structure recommendations
|
||||
seo_recommendations['content_structure'].append({
|
||||
'pillar': pillar['name'],
|
||||
'recommendation': f"Create pillar page for {pillar['name']} with supporting cluster content",
|
||||
'structure': 'Pillar + Cluster model'
|
||||
})
|
||||
|
||||
# Internal linking strategy
|
||||
seo_recommendations['internal_linking'] = [
|
||||
"Link all cluster content to relevant pillar pages",
|
||||
"Create topic-based internal linking structure",
|
||||
"Use contextual anchor text with target keywords",
|
||||
"Implement breadcrumb navigation for topic clusters"
|
||||
]
|
||||
|
||||
# Technical SEO recommendations
|
||||
seo_recommendations['technical_seo'] = [
|
||||
"Optimize page speed for all content pages",
|
||||
"Implement structured data for articles",
|
||||
"Create XML sitemap sections for content categories",
|
||||
"Optimize images with descriptive alt text"
|
||||
]
|
||||
|
||||
return seo_recommendations
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"SEO content recommendations error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
def _generate_search_intelligence_recommendations(self, gsc_analysis: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Generate comprehensive recommendations from search intelligence analysis."""
|
||||
try:
|
||||
recommendations = {
|
||||
'immediate_actions': [],
|
||||
'content_opportunities': [],
|
||||
'technical_improvements': [],
|
||||
'strategic_initiatives': []
|
||||
}
|
||||
|
||||
# Extract content opportunities from GSC analysis
|
||||
content_opps = gsc_analysis.get('content_opportunities', [])
|
||||
for opp in content_opps[:5]: # Top 5 opportunities
|
||||
recommendations['content_opportunities'].append({
|
||||
'type': opp['type'],
|
||||
'keyword': opp['keyword'],
|
||||
'action': opp['opportunity'],
|
||||
'priority': opp['priority'],
|
||||
'estimated_impact': opp['potential_impact']
|
||||
})
|
||||
|
||||
# Technical improvements from analysis
|
||||
technical_insights = gsc_analysis.get('technical_insights', {})
|
||||
if technical_insights.get('crawl_issues_indicators'):
|
||||
for issue in technical_insights['crawl_issues_indicators']:
|
||||
recommendations['technical_improvements'].append({
|
||||
'issue': issue,
|
||||
'priority': 'High',
|
||||
'category': 'Crawl & Indexing'
|
||||
})
|
||||
|
||||
# Immediate actions based on performance
|
||||
performance = gsc_analysis.get('performance_overview', {})
|
||||
if performance.get('avg_ctr', 0) < 2:
|
||||
recommendations['immediate_actions'].append({
|
||||
'action': 'Improve meta descriptions and titles for better CTR',
|
||||
'expected_impact': 'Increase CTR by 1-2%',
|
||||
'timeline': '2-4 weeks'
|
||||
})
|
||||
|
||||
if performance.get('avg_position', 0) > 10:
|
||||
recommendations['immediate_actions'].append({
|
||||
'action': 'Focus on improving content quality for top keywords',
|
||||
'expected_impact': 'Improve average position by 2-5 ranks',
|
||||
'timeline': '4-8 weeks'
|
||||
})
|
||||
|
||||
# Strategic initiatives
|
||||
competitive_analysis = gsc_analysis.get('competitive_analysis', {})
|
||||
if competitive_analysis.get('market_position') in ['Challenger', 'Emerging Player']:
|
||||
recommendations['strategic_initiatives'].append({
|
||||
'initiative': 'Develop thought leadership content strategy',
|
||||
'goal': 'Improve market position and brand authority',
|
||||
'timeline': '3-6 months'
|
||||
})
|
||||
|
||||
return recommendations
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Search intelligence recommendations error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
def render_enterprise_seo_suite():
|
||||
"""Render the Enterprise SEO Command Center interface."""
|
||||
|
||||
st.set_page_config(
|
||||
page_title="Enterprise SEO Command Center",
|
||||
page_icon="🚀",
|
||||
layout="wide"
|
||||
)
|
||||
|
||||
st.title("🚀 Enterprise SEO Command Center")
|
||||
st.markdown("**Unified AI-powered SEO suite orchestrating all tools into intelligent workflows**")
|
||||
|
||||
# Initialize suite
|
||||
if 'enterprise_seo_suite' not in st.session_state:
|
||||
st.session_state.enterprise_seo_suite = EnterpriseSEOSuite()
|
||||
|
||||
suite = st.session_state.enterprise_seo_suite
|
||||
|
||||
# Workflow selection
|
||||
st.sidebar.header("🎯 SEO Workflow Selection")
|
||||
selected_workflow = st.sidebar.selectbox(
|
||||
"Choose Workflow",
|
||||
list(suite.workflow_templates.keys()),
|
||||
format_func=lambda x: suite.workflow_templates[x]
|
||||
)
|
||||
|
||||
# Main workflow interface
|
||||
if selected_workflow == 'complete_audit':
|
||||
st.header("🔍 Complete Enterprise SEO Audit")
|
||||
render_complete_audit_interface(suite)
|
||||
elif selected_workflow == 'content_strategy':
|
||||
st.header("📊 Content Strategy Development")
|
||||
render_content_strategy_interface(suite)
|
||||
elif selected_workflow == 'technical_optimization':
|
||||
st.header("🔧 Technical SEO Optimization")
|
||||
render_technical_optimization_interface(suite)
|
||||
else:
|
||||
st.info(f"Workflow '{suite.workflow_templates[selected_workflow]}' is being developed.")
|
||||
|
||||
def render_complete_audit_interface(suite: EnterpriseSEOSuite):
|
||||
"""Render the complete audit workflow interface."""
|
||||
|
||||
# Input form
|
||||
with st.form("enterprise_audit_form"):
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
website_url = st.text_input(
|
||||
"Website URL",
|
||||
value="https://example.com",
|
||||
help="Enter your website URL for comprehensive analysis"
|
||||
)
|
||||
|
||||
target_keywords = st.text_area(
|
||||
"Target Keywords (one per line)",
|
||||
value="AI content creation\nSEO tools\ncontent optimization",
|
||||
help="Enter your primary keywords to optimize for"
|
||||
)
|
||||
|
||||
with col2:
|
||||
competitors = st.text_area(
|
||||
"Competitor URLs (one per line)",
|
||||
value="https://jasper.ai\nhttps://copy.ai\nhttps://writesonic.com",
|
||||
help="Enter up to 5 competitor URLs for analysis"
|
||||
)
|
||||
|
||||
submit_audit = st.form_submit_button("🚀 Start Complete SEO Audit", type="primary")
|
||||
|
||||
# Process audit
|
||||
if submit_audit:
|
||||
if website_url and target_keywords:
|
||||
# Parse inputs
|
||||
keywords_list = [k.strip() for k in target_keywords.split('\n') if k.strip()]
|
||||
competitors_list = [c.strip() for c in competitors.split('\n') if c.strip()]
|
||||
|
||||
# Run audit
|
||||
with st.spinner("🔍 Running comprehensive SEO audit..."):
|
||||
audit_results = asyncio.run(
|
||||
suite.execute_complete_seo_audit(
|
||||
website_url, competitors_list, keywords_list
|
||||
)
|
||||
)
|
||||
|
||||
if 'error' not in audit_results:
|
||||
st.success("✅ Enterprise SEO audit completed!")
|
||||
|
||||
# Display results dashboard
|
||||
render_audit_results_dashboard(audit_results)
|
||||
else:
|
||||
st.error(f"❌ Audit failed: {audit_results['error']}")
|
||||
else:
|
||||
st.warning("⚠️ Please enter website URL and target keywords.")
|
||||
|
||||
def render_audit_results_dashboard(results: Dict[str, Any]):
|
||||
"""Render comprehensive audit results dashboard."""
|
||||
|
||||
# Priority Action Plan (Most Important)
|
||||
st.header("📋 Priority Action Plan")
|
||||
action_plan = results.get('priority_action_plan', [])
|
||||
|
||||
if action_plan:
|
||||
# Display as interactive table
|
||||
df_actions = pd.DataFrame(action_plan)
|
||||
|
||||
# Style the dataframe
|
||||
st.dataframe(
|
||||
df_actions,
|
||||
column_config={
|
||||
"category": "Category",
|
||||
"priority": st.column_config.SelectboxColumn(
|
||||
"Priority",
|
||||
options=["Critical", "High", "Medium", "Low"]
|
||||
),
|
||||
"effort": "Effort Level",
|
||||
"timeframe": "Timeline",
|
||||
"action": "Action Required",
|
||||
"expected_impact": "Expected Impact"
|
||||
},
|
||||
hide_index=True,
|
||||
use_container_width=True
|
||||
)
|
||||
|
||||
# Key Metrics Overview
|
||||
st.header("📊 SEO Health Dashboard")
|
||||
|
||||
col1, col2, col3, col4 = st.columns(4)
|
||||
|
||||
with col1:
|
||||
technical_score = results.get('technical_audit', {}).get('performance_score', 0)
|
||||
st.metric("Technical SEO", f"{technical_score}/100", delta=None)
|
||||
|
||||
with col2:
|
||||
onpage_score = results.get('on_page_analysis', {}).get('optimization_score', 0)
|
||||
st.metric("On-Page SEO", f"{onpage_score}/100", delta=None)
|
||||
|
||||
with col3:
|
||||
performance_score = results.get('performance_metrics', {}).get('performance_score', 0)
|
||||
st.metric("Performance", f"{performance_score}/100", delta=None)
|
||||
|
||||
with col4:
|
||||
content_gaps = len(results.get('content_analysis', {}).get('content_opportunities', []))
|
||||
st.metric("Content Opportunities", content_gaps, delta=None)
|
||||
|
||||
# Detailed Analysis Sections
|
||||
tab1, tab2, tab3, tab4, tab5 = st.tabs([
|
||||
"🤖 Strategic Insights",
|
||||
"🔧 Technical Analysis",
|
||||
"📊 Content Intelligence",
|
||||
"🔍 On-Page Analysis",
|
||||
"⚡ Performance Metrics"
|
||||
])
|
||||
|
||||
with tab1:
|
||||
strategic_recs = results.get('strategic_recommendations', {})
|
||||
if strategic_recs:
|
||||
st.subheader("AI-Powered Strategic Recommendations")
|
||||
|
||||
# Immediate wins
|
||||
immediate_wins = strategic_recs.get('immediate_wins', [])
|
||||
if immediate_wins:
|
||||
st.markdown("#### 🚀 Immediate Wins (0-30 days)")
|
||||
for win in immediate_wins[:5]:
|
||||
st.success(f"✅ {win}")
|
||||
|
||||
# Strategic initiatives
|
||||
strategic_initiatives = strategic_recs.get('strategic_initiatives', [])
|
||||
if strategic_initiatives:
|
||||
st.markdown("#### 📈 Strategic Initiatives (1-3 months)")
|
||||
for initiative in strategic_initiatives[:3]:
|
||||
st.info(f"📋 {initiative}")
|
||||
|
||||
# Full analysis
|
||||
full_analysis = strategic_recs.get('full_analysis', '')
|
||||
if full_analysis:
|
||||
with st.expander("🧠 Complete Strategic Analysis"):
|
||||
st.write(full_analysis)
|
||||
|
||||
with tab2:
|
||||
technical_audit = results.get('technical_audit', {})
|
||||
if technical_audit:
|
||||
st.subheader("Technical SEO Analysis")
|
||||
|
||||
critical_issues = technical_audit.get('critical_issues', [])
|
||||
if critical_issues:
|
||||
st.markdown("#### ⚠️ Critical Issues")
|
||||
for issue in critical_issues:
|
||||
st.error(f"🚨 {issue}")
|
||||
|
||||
priority_fixes = technical_audit.get('priority_fixes', [])
|
||||
if priority_fixes:
|
||||
st.markdown("#### 🔧 Priority Fixes")
|
||||
for fix in priority_fixes:
|
||||
st.warning(f"🛠️ {fix}")
|
||||
|
||||
with tab3:
|
||||
content_analysis = results.get('content_analysis', {})
|
||||
if content_analysis:
|
||||
st.subheader("Content Intelligence")
|
||||
|
||||
content_opportunities = content_analysis.get('content_opportunities', [])
|
||||
if content_opportunities:
|
||||
st.markdown("#### 📝 Content Opportunities")
|
||||
for opportunity in content_opportunities[:5]:
|
||||
st.info(f"💡 {opportunity}")
|
||||
|
||||
competitive_advantages = content_analysis.get('competitive_advantages', [])
|
||||
if competitive_advantages:
|
||||
st.markdown("#### 🏆 Competitive Advantages")
|
||||
for advantage in competitive_advantages:
|
||||
st.success(f"⭐ {advantage}")
|
||||
|
||||
with tab4:
|
||||
onpage_analysis = results.get('on_page_analysis', {})
|
||||
if onpage_analysis:
|
||||
st.subheader("On-Page SEO Analysis")
|
||||
|
||||
meta_optimization = onpage_analysis.get('meta_optimization', {})
|
||||
content_optimization = onpage_analysis.get('content_optimization', {})
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.markdown("#### 🏷️ Meta Tag Optimization")
|
||||
st.json(meta_optimization)
|
||||
|
||||
with col2:
|
||||
st.markdown("#### 📄 Content Optimization")
|
||||
st.json(content_optimization)
|
||||
|
||||
with tab5:
|
||||
performance_metrics = results.get('performance_metrics', {})
|
||||
if performance_metrics:
|
||||
st.subheader("Performance Analysis")
|
||||
|
||||
core_vitals = performance_metrics.get('core_web_vitals', {})
|
||||
loading_performance = performance_metrics.get('loading_performance', {})
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.markdown("#### ⚡ Core Web Vitals")
|
||||
st.json(core_vitals)
|
||||
|
||||
with col2:
|
||||
st.markdown("#### 🚀 Loading Performance")
|
||||
st.json(loading_performance)
|
||||
|
||||
# Export functionality
|
||||
st.markdown("---")
|
||||
col1, col2, col3 = st.columns(3)
|
||||
|
||||
with col1:
|
||||
if st.button("📥 Export Full Report", use_container_width=True):
|
||||
# Create downloadable report
|
||||
report_json = json.dumps(results, indent=2, default=str)
|
||||
st.download_button(
|
||||
label="Download JSON Report",
|
||||
data=report_json,
|
||||
file_name=f"seo_audit_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
||||
mime="application/json"
|
||||
)
|
||||
|
||||
with col2:
|
||||
if st.button("📊 Export Action Plan", use_container_width=True):
|
||||
# Create CSV of action plan
|
||||
df_actions = pd.DataFrame(action_plan)
|
||||
csv = df_actions.to_csv(index=False)
|
||||
st.download_button(
|
||||
label="Download CSV Action Plan",
|
||||
data=csv,
|
||||
file_name=f"action_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
||||
mime="text/csv"
|
||||
)
|
||||
|
||||
with col3:
|
||||
if st.button("🔄 Schedule Follow-up Audit", use_container_width=True):
|
||||
st.info("Follow-up scheduling feature coming soon!")
|
||||
|
||||
def render_content_strategy_interface(suite: EnterpriseSEOSuite):
|
||||
"""Render content strategy development interface."""
|
||||
st.info("🚧 Content Strategy Development workflow coming soon!")
|
||||
|
||||
def render_technical_optimization_interface(suite: EnterpriseSEOSuite):
|
||||
"""Render technical optimization interface."""
|
||||
st.info("🚧 Technical SEO Optimization workflow coming soon!")
|
||||
|
||||
|
||||
# Main execution
|
||||
if __name__ == "__main__":
|
||||
render_enterprise_seo_suite()
|
||||
864
lib/ai_seo_tools/google_search_console_integration.py
Normal file
864
lib/ai_seo_tools/google_search_console_integration.py
Normal file
@@ -0,0 +1,864 @@
|
||||
"""
|
||||
Google Search Console Integration for Enterprise SEO
|
||||
|
||||
Connects GSC data with AI-powered content strategy and keyword intelligence.
|
||||
Provides enterprise-level search performance insights and content recommendations.
|
||||
"""
|
||||
|
||||
import streamlit as st
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
from loguru import logger
|
||||
import plotly.express as px
|
||||
import plotly.graph_objects as go
|
||||
from plotly.subplots import make_subplots
|
||||
|
||||
# Import AI modules
|
||||
from ..gpt_providers.text_generation.main_text_generation import llm_text_gen
|
||||
|
||||
|
||||
class GoogleSearchConsoleAnalyzer:
|
||||
"""
|
||||
Enterprise Google Search Console analyzer with AI-powered insights.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the GSC analyzer."""
|
||||
self.gsc_client = None # Will be initialized when credentials are provided
|
||||
logger.info("Google Search Console Analyzer initialized")
|
||||
|
||||
def analyze_search_performance(self, site_url: str, date_range: int = 90) -> Dict[str, Any]:
|
||||
"""
|
||||
Analyze comprehensive search performance from GSC data.
|
||||
|
||||
Args:
|
||||
site_url: Website URL registered in GSC
|
||||
date_range: Number of days to analyze (default 90)
|
||||
|
||||
Returns:
|
||||
Comprehensive search performance analysis
|
||||
"""
|
||||
try:
|
||||
st.info("📊 Analyzing Google Search Console data...")
|
||||
|
||||
# Simulate GSC data for demonstration (replace with actual GSC API calls)
|
||||
search_data = self._get_mock_gsc_data(site_url, date_range)
|
||||
|
||||
# Perform comprehensive analysis
|
||||
analysis_results = {
|
||||
'site_url': site_url,
|
||||
'analysis_period': f"Last {date_range} days",
|
||||
'analysis_timestamp': datetime.utcnow().isoformat(),
|
||||
'performance_overview': self._analyze_performance_overview(search_data),
|
||||
'keyword_analysis': self._analyze_keyword_performance(search_data),
|
||||
'page_analysis': self._analyze_page_performance(search_data),
|
||||
'content_opportunities': self._identify_content_opportunities(search_data),
|
||||
'technical_insights': self._analyze_technical_seo_signals(search_data),
|
||||
'competitive_analysis': self._analyze_competitive_position(search_data),
|
||||
'ai_recommendations': self._generate_ai_recommendations(search_data)
|
||||
}
|
||||
|
||||
return analysis_results
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error analyzing search performance: {str(e)}"
|
||||
logger.error(error_msg, exc_info=True)
|
||||
return {'error': error_msg}
|
||||
|
||||
def _get_mock_gsc_data(self, site_url: str, days: int) -> Dict[str, pd.DataFrame]:
|
||||
"""
|
||||
Generate mock GSC data for demonstration.
|
||||
In production, this would fetch real data from GSC API.
|
||||
"""
|
||||
# Generate mock keyword data
|
||||
keywords_data = []
|
||||
sample_keywords = [
|
||||
"AI content creation", "SEO tools", "content optimization", "blog writing AI",
|
||||
"meta description generator", "keyword research", "technical SEO", "content strategy",
|
||||
"on-page optimization", "SERP analysis", "content gap analysis", "SEO audit"
|
||||
]
|
||||
|
||||
for keyword in sample_keywords:
|
||||
# Generate realistic performance data
|
||||
impressions = np.random.randint(100, 10000)
|
||||
clicks = int(impressions * np.random.uniform(0.02, 0.15)) # CTR between 2-15%
|
||||
position = np.random.uniform(3, 25)
|
||||
|
||||
keywords_data.append({
|
||||
'keyword': keyword,
|
||||
'impressions': impressions,
|
||||
'clicks': clicks,
|
||||
'ctr': (clicks / impressions) * 100,
|
||||
'position': position
|
||||
})
|
||||
|
||||
# Generate mock page data
|
||||
pages_data = []
|
||||
sample_pages = [
|
||||
"/blog/ai-content-creation-guide", "/tools/seo-analyzer", "/features/content-optimization",
|
||||
"/blog/technical-seo-checklist", "/tools/keyword-research", "/blog/content-strategy-2024",
|
||||
"/tools/meta-description-generator", "/blog/on-page-seo-guide", "/features/enterprise-seo"
|
||||
]
|
||||
|
||||
for page in sample_pages:
|
||||
impressions = np.random.randint(500, 5000)
|
||||
clicks = int(impressions * np.random.uniform(0.03, 0.12))
|
||||
position = np.random.uniform(5, 20)
|
||||
|
||||
pages_data.append({
|
||||
'page': page,
|
||||
'impressions': impressions,
|
||||
'clicks': clicks,
|
||||
'ctr': (clicks / impressions) * 100,
|
||||
'position': position
|
||||
})
|
||||
|
||||
# Generate time series data
|
||||
time_series_data = []
|
||||
for i in range(days):
|
||||
date = datetime.now() - timedelta(days=i)
|
||||
daily_clicks = np.random.randint(50, 500)
|
||||
daily_impressions = np.random.randint(1000, 8000)
|
||||
|
||||
time_series_data.append({
|
||||
'date': date.strftime('%Y-%m-%d'),
|
||||
'clicks': daily_clicks,
|
||||
'impressions': daily_impressions,
|
||||
'ctr': (daily_clicks / daily_impressions) * 100,
|
||||
'position': np.random.uniform(8, 15)
|
||||
})
|
||||
|
||||
return {
|
||||
'keywords': pd.DataFrame(keywords_data),
|
||||
'pages': pd.DataFrame(pages_data),
|
||||
'time_series': pd.DataFrame(time_series_data)
|
||||
}
|
||||
|
||||
def _analyze_performance_overview(self, search_data: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
|
||||
"""Analyze overall search performance metrics."""
|
||||
keywords_df = search_data['keywords']
|
||||
time_series_df = search_data['time_series']
|
||||
|
||||
# Calculate totals and averages
|
||||
total_clicks = keywords_df['clicks'].sum()
|
||||
total_impressions = keywords_df['impressions'].sum()
|
||||
avg_ctr = (total_clicks / total_impressions) * 100 if total_impressions > 0 else 0
|
||||
avg_position = keywords_df['position'].mean()
|
||||
|
||||
# Calculate trends
|
||||
recent_clicks = time_series_df.head(7)['clicks'].mean()
|
||||
previous_clicks = time_series_df.tail(7)['clicks'].mean()
|
||||
clicks_trend = ((recent_clicks - previous_clicks) / previous_clicks * 100) if previous_clicks > 0 else 0
|
||||
|
||||
recent_impressions = time_series_df.head(7)['impressions'].mean()
|
||||
previous_impressions = time_series_df.tail(7)['impressions'].mean()
|
||||
impressions_trend = ((recent_impressions - previous_impressions) / previous_impressions * 100) if previous_impressions > 0 else 0
|
||||
|
||||
# Top performing keywords
|
||||
top_keywords = keywords_df.nlargest(5, 'clicks')[['keyword', 'clicks', 'impressions', 'position']].to_dict('records')
|
||||
|
||||
# Opportunity keywords (high impressions, low CTR)
|
||||
opportunity_keywords = keywords_df[
|
||||
(keywords_df['impressions'] > keywords_df['impressions'].median()) &
|
||||
(keywords_df['ctr'] < 3)
|
||||
].nlargest(5, 'impressions')[['keyword', 'impressions', 'ctr', 'position']].to_dict('records')
|
||||
|
||||
return {
|
||||
'total_clicks': int(total_clicks),
|
||||
'total_impressions': int(total_impressions),
|
||||
'avg_ctr': round(avg_ctr, 2),
|
||||
'avg_position': round(avg_position, 1),
|
||||
'clicks_trend': round(clicks_trend, 1),
|
||||
'impressions_trend': round(impressions_trend, 1),
|
||||
'top_keywords': top_keywords,
|
||||
'opportunity_keywords': opportunity_keywords
|
||||
}
|
||||
|
||||
def _analyze_keyword_performance(self, search_data: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
|
||||
"""Analyze keyword performance and opportunities."""
|
||||
keywords_df = search_data['keywords']
|
||||
|
||||
# Keyword categorization
|
||||
high_volume_keywords = keywords_df[keywords_df['impressions'] > keywords_df['impressions'].quantile(0.8)]
|
||||
low_competition_keywords = keywords_df[keywords_df['position'] <= 10]
|
||||
optimization_opportunities = keywords_df[
|
||||
(keywords_df['position'] > 10) &
|
||||
(keywords_df['position'] <= 20) &
|
||||
(keywords_df['impressions'] > 100)
|
||||
]
|
||||
|
||||
# Content gap analysis
|
||||
missing_keywords = self._identify_missing_keywords(keywords_df)
|
||||
|
||||
# Seasonal trends analysis
|
||||
seasonal_insights = self._analyze_seasonal_trends(keywords_df)
|
||||
|
||||
return {
|
||||
'total_keywords': len(keywords_df),
|
||||
'high_volume_keywords': high_volume_keywords.to_dict('records'),
|
||||
'ranking_keywords': low_competition_keywords.to_dict('records'),
|
||||
'optimization_opportunities': optimization_opportunities.to_dict('records'),
|
||||
'missing_keywords': missing_keywords,
|
||||
'seasonal_insights': seasonal_insights,
|
||||
'keyword_distribution': {
|
||||
'positions_1_3': len(keywords_df[keywords_df['position'] <= 3]),
|
||||
'positions_4_10': len(keywords_df[(keywords_df['position'] > 3) & (keywords_df['position'] <= 10)]),
|
||||
'positions_11_20': len(keywords_df[(keywords_df['position'] > 10) & (keywords_df['position'] <= 20)]),
|
||||
'positions_21_plus': len(keywords_df[keywords_df['position'] > 20])
|
||||
}
|
||||
}
|
||||
|
||||
def _analyze_page_performance(self, search_data: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
|
||||
"""Analyze page-level performance."""
|
||||
pages_df = search_data['pages']
|
||||
|
||||
# Top performing pages
|
||||
top_pages = pages_df.nlargest(10, 'clicks')
|
||||
|
||||
# Underperforming pages (high impressions, low clicks)
|
||||
underperforming_pages = pages_df[
|
||||
(pages_df['impressions'] > pages_df['impressions'].median()) &
|
||||
(pages_df['ctr'] < 2)
|
||||
].nlargest(5, 'impressions')
|
||||
|
||||
# Page type analysis
|
||||
page_types = self._categorize_pages(pages_df)
|
||||
|
||||
return {
|
||||
'top_pages': top_pages.to_dict('records'),
|
||||
'underperforming_pages': underperforming_pages.to_dict('records'),
|
||||
'page_types_performance': page_types,
|
||||
'total_pages': len(pages_df)
|
||||
}
|
||||
|
||||
def _identify_content_opportunities(self, search_data: Dict[str, pd.DataFrame]) -> List[Dict[str, Any]]:
|
||||
"""Identify content creation and optimization opportunities."""
|
||||
keywords_df = search_data['keywords']
|
||||
|
||||
opportunities = []
|
||||
|
||||
# High impression, low CTR keywords need content optimization
|
||||
low_ctr_keywords = keywords_df[
|
||||
(keywords_df['impressions'] > 500) &
|
||||
(keywords_df['ctr'] < 3)
|
||||
]
|
||||
|
||||
for _, keyword_row in low_ctr_keywords.iterrows():
|
||||
opportunities.append({
|
||||
'type': 'Content Optimization',
|
||||
'keyword': keyword_row['keyword'],
|
||||
'opportunity': f"Optimize existing content for '{keyword_row['keyword']}' to improve CTR from {keyword_row['ctr']:.1f}%",
|
||||
'potential_impact': 'High',
|
||||
'current_position': round(keyword_row['position'], 1),
|
||||
'impressions': int(keyword_row['impressions']),
|
||||
'priority': 'High' if keyword_row['impressions'] > 1000 else 'Medium'
|
||||
})
|
||||
|
||||
# Position 11-20 keywords need content improvement
|
||||
position_11_20 = keywords_df[
|
||||
(keywords_df['position'] > 10) &
|
||||
(keywords_df['position'] <= 20) &
|
||||
(keywords_df['impressions'] > 100)
|
||||
]
|
||||
|
||||
for _, keyword_row in position_11_20.iterrows():
|
||||
opportunities.append({
|
||||
'type': 'Content Enhancement',
|
||||
'keyword': keyword_row['keyword'],
|
||||
'opportunity': f"Enhance content for '{keyword_row['keyword']}' to move from position {keyword_row['position']:.1f} to first page",
|
||||
'potential_impact': 'Medium',
|
||||
'current_position': round(keyword_row['position'], 1),
|
||||
'impressions': int(keyword_row['impressions']),
|
||||
'priority': 'Medium'
|
||||
})
|
||||
|
||||
# Sort by potential impact and impressions
|
||||
opportunities = sorted(opportunities, key=lambda x: x['impressions'], reverse=True)
|
||||
|
||||
return opportunities[:10] # Top 10 opportunities
|
||||
|
||||
def _analyze_technical_seo_signals(self, search_data: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
|
||||
"""Analyze technical SEO signals from search data."""
|
||||
keywords_df = search_data['keywords']
|
||||
pages_df = search_data['pages']
|
||||
|
||||
# Analyze performance patterns that might indicate technical issues
|
||||
technical_insights = {
|
||||
'crawl_issues_indicators': [],
|
||||
'mobile_performance': {},
|
||||
'core_web_vitals_impact': {},
|
||||
'indexing_insights': {}
|
||||
}
|
||||
|
||||
# Identify potential crawl issues
|
||||
very_low_impressions = keywords_df[keywords_df['impressions'] < 10]
|
||||
if len(very_low_impressions) > len(keywords_df) * 0.3: # If 30%+ have very low impressions
|
||||
technical_insights['crawl_issues_indicators'].append(
|
||||
"High percentage of keywords with very low impressions may indicate crawl or indexing issues"
|
||||
)
|
||||
|
||||
# Mobile performance indicators
|
||||
avg_mobile_position = keywords_df['position'].mean() # In real implementation, this would be mobile-specific
|
||||
technical_insights['mobile_performance'] = {
|
||||
'avg_mobile_position': round(avg_mobile_position, 1),
|
||||
'mobile_optimization_needed': avg_mobile_position > 15
|
||||
}
|
||||
|
||||
return technical_insights
|
||||
|
||||
def _analyze_competitive_position(self, search_data: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
|
||||
"""Analyze competitive positioning based on search data."""
|
||||
keywords_df = search_data['keywords']
|
||||
|
||||
# Calculate competitive metrics
|
||||
dominant_keywords = len(keywords_df[keywords_df['position'] <= 3])
|
||||
competitive_keywords = len(keywords_df[(keywords_df['position'] > 3) & (keywords_df['position'] <= 10)])
|
||||
losing_keywords = len(keywords_df[keywords_df['position'] > 10])
|
||||
|
||||
competitive_strength = (dominant_keywords * 3 + competitive_keywords * 2 + losing_keywords * 1) / len(keywords_df)
|
||||
|
||||
return {
|
||||
'dominant_keywords': dominant_keywords,
|
||||
'competitive_keywords': competitive_keywords,
|
||||
'losing_keywords': losing_keywords,
|
||||
'competitive_strength_score': round(competitive_strength, 2),
|
||||
'market_position': self._determine_market_position(competitive_strength)
|
||||
}
|
||||
|
||||
def _generate_ai_recommendations(self, search_data: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
|
||||
"""Generate AI-powered recommendations based on search data."""
|
||||
try:
|
||||
keywords_df = search_data['keywords']
|
||||
pages_df = search_data['pages']
|
||||
|
||||
# Prepare data summary for AI analysis
|
||||
top_keywords = keywords_df.nlargest(5, 'impressions')['keyword'].tolist()
|
||||
avg_position = keywords_df['position'].mean()
|
||||
total_impressions = keywords_df['impressions'].sum()
|
||||
total_clicks = keywords_df['clicks'].sum()
|
||||
avg_ctr = (total_clicks / total_impressions * 100) if total_impressions > 0 else 0
|
||||
|
||||
# Create comprehensive prompt for AI analysis
|
||||
ai_prompt = f"""
|
||||
Analyze this Google Search Console data and provide strategic SEO recommendations:
|
||||
|
||||
SEARCH PERFORMANCE SUMMARY:
|
||||
- Total Keywords Tracked: {len(keywords_df)}
|
||||
- Total Impressions: {total_impressions:,}
|
||||
- Total Clicks: {total_clicks:,}
|
||||
- Average CTR: {avg_ctr:.2f}%
|
||||
- Average Position: {avg_position:.1f}
|
||||
|
||||
TOP PERFORMING KEYWORDS:
|
||||
{', '.join(top_keywords)}
|
||||
|
||||
PERFORMANCE DISTRIBUTION:
|
||||
- Keywords ranking 1-3: {len(keywords_df[keywords_df['position'] <= 3])}
|
||||
- Keywords ranking 4-10: {len(keywords_df[(keywords_df['position'] > 3) & (keywords_df['position'] <= 10)])}
|
||||
- Keywords ranking 11-20: {len(keywords_df[(keywords_df['position'] > 10) & (keywords_df['position'] <= 20)])}
|
||||
- Keywords ranking 21+: {len(keywords_df[keywords_df['position'] > 20])}
|
||||
|
||||
TOP PAGES BY TRAFFIC:
|
||||
{pages_df.nlargest(3, 'clicks')['page'].tolist()}
|
||||
|
||||
Based on this data, provide:
|
||||
|
||||
1. IMMEDIATE OPTIMIZATION OPPORTUNITIES (0-30 days):
|
||||
- Specific keywords to optimize for better CTR
|
||||
- Pages that need content updates
|
||||
- Quick technical wins
|
||||
|
||||
2. CONTENT STRATEGY RECOMMENDATIONS (1-3 months):
|
||||
- New content topics based on keyword gaps
|
||||
- Content enhancement priorities
|
||||
- Internal linking opportunities
|
||||
|
||||
3. LONG-TERM SEO STRATEGY (3-12 months):
|
||||
- Market expansion opportunities
|
||||
- Authority building topics
|
||||
- Competitive positioning strategies
|
||||
|
||||
4. TECHNICAL SEO PRIORITIES:
|
||||
- Performance issues affecting rankings
|
||||
- Mobile optimization needs
|
||||
- Core Web Vitals improvements
|
||||
|
||||
Provide specific, actionable recommendations with expected impact and priority levels.
|
||||
"""
|
||||
|
||||
ai_analysis = llm_text_gen(
|
||||
ai_prompt,
|
||||
system_prompt="You are an enterprise SEO strategist analyzing Google Search Console data. Provide specific, data-driven recommendations that will improve search performance."
|
||||
)
|
||||
|
||||
return {
|
||||
'full_analysis': ai_analysis,
|
||||
'immediate_opportunities': self._extract_immediate_opportunities(ai_analysis),
|
||||
'content_strategy': self._extract_content_strategy(ai_analysis),
|
||||
'long_term_strategy': self._extract_long_term_strategy(ai_analysis),
|
||||
'technical_priorities': self._extract_technical_priorities(ai_analysis)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"AI recommendations error: {str(e)}")
|
||||
return {'error': str(e)}
|
||||
|
||||
# Utility methods
|
||||
def _identify_missing_keywords(self, keywords_df: pd.DataFrame) -> List[str]:
|
||||
"""Identify potential missing keywords based on current keyword performance."""
|
||||
# In a real implementation, this would use keyword research APIs
|
||||
existing_keywords = set(keywords_df['keyword'].str.lower())
|
||||
|
||||
potential_keywords = [
|
||||
"AI writing tools", "content automation", "SEO content generator",
|
||||
"blog post optimizer", "meta tag generator", "keyword analyzer"
|
||||
]
|
||||
|
||||
missing = [kw for kw in potential_keywords if kw.lower() not in existing_keywords]
|
||||
return missing[:5]
|
||||
|
||||
def _analyze_seasonal_trends(self, keywords_df: pd.DataFrame) -> Dict[str, Any]:
|
||||
"""Analyze seasonal trends in keyword performance."""
|
||||
# Placeholder for seasonal analysis
|
||||
return {
|
||||
'seasonal_keywords': [],
|
||||
'trend_analysis': "Seasonal analysis requires historical data spanning multiple seasons"
|
||||
}
|
||||
|
||||
def _categorize_pages(self, pages_df: pd.DataFrame) -> Dict[str, Any]:
|
||||
"""Categorize pages by type and analyze performance."""
|
||||
page_types = {
|
||||
'Blog Posts': {'count': 0, 'total_clicks': 0, 'avg_position': 0},
|
||||
'Product Pages': {'count': 0, 'total_clicks': 0, 'avg_position': 0},
|
||||
'Tool Pages': {'count': 0, 'total_clicks': 0, 'avg_position': 0},
|
||||
'Other': {'count': 0, 'total_clicks': 0, 'avg_position': 0}
|
||||
}
|
||||
|
||||
for _, page_row in pages_df.iterrows():
|
||||
page_url = page_row['page']
|
||||
clicks = page_row['clicks']
|
||||
position = page_row['position']
|
||||
|
||||
if '/blog/' in page_url:
|
||||
page_types['Blog Posts']['count'] += 1
|
||||
page_types['Blog Posts']['total_clicks'] += clicks
|
||||
page_types['Blog Posts']['avg_position'] += position
|
||||
elif '/tools/' in page_url:
|
||||
page_types['Tool Pages']['count'] += 1
|
||||
page_types['Tool Pages']['total_clicks'] += clicks
|
||||
page_types['Tool Pages']['avg_position'] += position
|
||||
elif '/features/' in page_url or '/product/' in page_url:
|
||||
page_types['Product Pages']['count'] += 1
|
||||
page_types['Product Pages']['total_clicks'] += clicks
|
||||
page_types['Product Pages']['avg_position'] += position
|
||||
else:
|
||||
page_types['Other']['count'] += 1
|
||||
page_types['Other']['total_clicks'] += clicks
|
||||
page_types['Other']['avg_position'] += position
|
||||
|
||||
# Calculate averages
|
||||
for page_type in page_types:
|
||||
if page_types[page_type]['count'] > 0:
|
||||
page_types[page_type]['avg_position'] = round(
|
||||
page_types[page_type]['avg_position'] / page_types[page_type]['count'], 1
|
||||
)
|
||||
|
||||
return page_types
|
||||
|
||||
def _determine_market_position(self, competitive_strength: float) -> str:
|
||||
"""Determine market position based on competitive strength score."""
|
||||
if competitive_strength >= 2.5:
|
||||
return "Market Leader"
|
||||
elif competitive_strength >= 2.0:
|
||||
return "Strong Competitor"
|
||||
elif competitive_strength >= 1.5:
|
||||
return "Emerging Player"
|
||||
else:
|
||||
return "Challenger"
|
||||
|
||||
def _extract_immediate_opportunities(self, analysis: str) -> List[str]:
|
||||
"""Extract immediate opportunities from AI analysis."""
|
||||
lines = analysis.split('\n')
|
||||
opportunities = []
|
||||
in_immediate_section = False
|
||||
|
||||
for line in lines:
|
||||
if 'IMMEDIATE OPTIMIZATION' in line.upper():
|
||||
in_immediate_section = True
|
||||
continue
|
||||
elif 'CONTENT STRATEGY' in line.upper():
|
||||
in_immediate_section = False
|
||||
continue
|
||||
|
||||
if in_immediate_section and line.strip().startswith('-'):
|
||||
opportunities.append(line.strip().lstrip('- '))
|
||||
|
||||
return opportunities[:5]
|
||||
|
||||
def _extract_content_strategy(self, analysis: str) -> List[str]:
|
||||
"""Extract content strategy recommendations from AI analysis."""
|
||||
return ["Develop topic clusters", "Create comparison content", "Build FAQ sections"]
|
||||
|
||||
def _extract_long_term_strategy(self, analysis: str) -> List[str]:
|
||||
"""Extract long-term strategy from AI analysis."""
|
||||
return ["Build domain authority", "Expand to new markets", "Develop thought leadership content"]
|
||||
|
||||
def _extract_technical_priorities(self, analysis: str) -> List[str]:
|
||||
"""Extract technical priorities from AI analysis."""
|
||||
return ["Improve page speed", "Optimize mobile experience", "Fix crawl errors"]
|
||||
|
||||
|
||||
def render_gsc_integration():
|
||||
"""Render the Google Search Console integration interface."""
|
||||
|
||||
st.title("📊 Google Search Console Intelligence")
|
||||
st.markdown("**AI-powered insights from your Google Search Console data**")
|
||||
|
||||
# Initialize analyzer
|
||||
if 'gsc_analyzer' not in st.session_state:
|
||||
st.session_state.gsc_analyzer = GoogleSearchConsoleAnalyzer()
|
||||
|
||||
analyzer = st.session_state.gsc_analyzer
|
||||
|
||||
# Configuration section
|
||||
st.header("🔧 Configuration")
|
||||
|
||||
with st.expander("📋 Setup Instructions", expanded=False):
|
||||
st.markdown("""
|
||||
### Setting up Google Search Console Integration
|
||||
|
||||
1. **Verify your website** in Google Search Console
|
||||
2. **Enable the Search Console API** in Google Cloud Console
|
||||
3. **Create service account credentials** and download the JSON file
|
||||
4. **Upload credentials** using the file uploader below
|
||||
|
||||
📚 [Detailed Setup Guide](https://developers.google.com/webmaster-tools/search-console-api-original/v3/prereqs)
|
||||
""")
|
||||
|
||||
# Input form
|
||||
with st.form("gsc_analysis_form"):
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
site_url = st.text_input(
|
||||
"Site URL",
|
||||
value="https://example.com",
|
||||
help="Enter your website URL as registered in Google Search Console"
|
||||
)
|
||||
|
||||
date_range = st.selectbox(
|
||||
"Analysis Period",
|
||||
[30, 60, 90, 180],
|
||||
index=2,
|
||||
help="Number of days to analyze"
|
||||
)
|
||||
|
||||
with col2:
|
||||
# Credentials upload (placeholder)
|
||||
credentials_file = st.file_uploader(
|
||||
"GSC API Credentials (JSON)",
|
||||
type=['json'],
|
||||
help="Upload your Google Search Console API credentials file"
|
||||
)
|
||||
|
||||
demo_mode = st.checkbox(
|
||||
"Demo Mode",
|
||||
value=True,
|
||||
help="Use demo data for testing (no credentials needed)"
|
||||
)
|
||||
|
||||
submit_analysis = st.form_submit_button("📊 Analyze Search Performance", type="primary")
|
||||
|
||||
# Process analysis
|
||||
if submit_analysis:
|
||||
if site_url and (demo_mode or credentials_file):
|
||||
with st.spinner("📊 Analyzing Google Search Console data..."):
|
||||
analysis_results = analyzer.analyze_search_performance(site_url, date_range)
|
||||
|
||||
if 'error' not in analysis_results:
|
||||
st.success("✅ Search Console analysis completed!")
|
||||
|
||||
# Store results in session state
|
||||
st.session_state.gsc_results = analysis_results
|
||||
|
||||
# Display results
|
||||
render_gsc_results_dashboard(analysis_results)
|
||||
else:
|
||||
st.error(f"❌ Analysis failed: {analysis_results['error']}")
|
||||
else:
|
||||
st.warning("⚠️ Please enter site URL and upload credentials (or enable demo mode).")
|
||||
|
||||
# Show previous results if available
|
||||
elif 'gsc_results' in st.session_state:
|
||||
st.info("📊 Showing previous analysis results")
|
||||
render_gsc_results_dashboard(st.session_state.gsc_results)
|
||||
|
||||
|
||||
def render_gsc_results_dashboard(results: Dict[str, Any]):
|
||||
"""Render comprehensive GSC analysis results."""
|
||||
|
||||
# Performance overview
|
||||
st.header("📊 Search Performance Overview")
|
||||
|
||||
overview = results['performance_overview']
|
||||
|
||||
col1, col2, col3, col4 = st.columns(4)
|
||||
|
||||
with col1:
|
||||
st.metric(
|
||||
"Total Clicks",
|
||||
f"{overview['total_clicks']:,}",
|
||||
delta=f"{overview['clicks_trend']:+.1f}%" if overview['clicks_trend'] != 0 else None
|
||||
)
|
||||
|
||||
with col2:
|
||||
st.metric(
|
||||
"Total Impressions",
|
||||
f"{overview['total_impressions']:,}",
|
||||
delta=f"{overview['impressions_trend']:+.1f}%" if overview['impressions_trend'] != 0 else None
|
||||
)
|
||||
|
||||
with col3:
|
||||
st.metric(
|
||||
"Average CTR",
|
||||
f"{overview['avg_ctr']:.2f}%"
|
||||
)
|
||||
|
||||
with col4:
|
||||
st.metric(
|
||||
"Average Position",
|
||||
f"{overview['avg_position']:.1f}"
|
||||
)
|
||||
|
||||
# Content opportunities (Most important section)
|
||||
st.header("🎯 Content Opportunities")
|
||||
|
||||
opportunities = results['content_opportunities']
|
||||
if opportunities:
|
||||
# Display as interactive table
|
||||
df_opportunities = pd.DataFrame(opportunities)
|
||||
|
||||
st.dataframe(
|
||||
df_opportunities,
|
||||
column_config={
|
||||
"type": "Opportunity Type",
|
||||
"keyword": "Keyword",
|
||||
"opportunity": "Description",
|
||||
"potential_impact": st.column_config.SelectboxColumn(
|
||||
"Impact",
|
||||
options=["High", "Medium", "Low"]
|
||||
),
|
||||
"current_position": st.column_config.NumberColumn(
|
||||
"Current Position",
|
||||
format="%.1f"
|
||||
),
|
||||
"impressions": st.column_config.NumberColumn(
|
||||
"Impressions",
|
||||
format="%d"
|
||||
),
|
||||
"priority": st.column_config.SelectboxColumn(
|
||||
"Priority",
|
||||
options=["High", "Medium", "Low"]
|
||||
)
|
||||
},
|
||||
hide_index=True,
|
||||
use_container_width=True
|
||||
)
|
||||
|
||||
# Detailed analysis tabs
|
||||
tab1, tab2, tab3, tab4, tab5 = st.tabs([
|
||||
"🤖 AI Insights",
|
||||
"🎯 Keyword Analysis",
|
||||
"📄 Page Performance",
|
||||
"🏆 Competitive Position",
|
||||
"🔧 Technical Signals"
|
||||
])
|
||||
|
||||
with tab1:
|
||||
ai_recs = results.get('ai_recommendations', {})
|
||||
if ai_recs and 'error' not in ai_recs:
|
||||
st.subheader("AI-Powered Recommendations")
|
||||
|
||||
# Immediate opportunities
|
||||
immediate_ops = ai_recs.get('immediate_opportunities', [])
|
||||
if immediate_ops:
|
||||
st.markdown("#### 🚀 Immediate Optimizations (0-30 days)")
|
||||
for op in immediate_ops:
|
||||
st.success(f"✅ {op}")
|
||||
|
||||
# Content strategy
|
||||
content_strategy = ai_recs.get('content_strategy', [])
|
||||
if content_strategy:
|
||||
st.markdown("#### 📝 Content Strategy (1-3 months)")
|
||||
for strategy in content_strategy:
|
||||
st.info(f"📋 {strategy}")
|
||||
|
||||
# Full analysis
|
||||
full_analysis = ai_recs.get('full_analysis', '')
|
||||
if full_analysis:
|
||||
with st.expander("🧠 Complete AI Analysis"):
|
||||
st.write(full_analysis)
|
||||
|
||||
with tab2:
|
||||
keyword_analysis = results.get('keyword_analysis', {})
|
||||
if keyword_analysis:
|
||||
st.subheader("Keyword Performance Analysis")
|
||||
|
||||
# Keyword distribution chart
|
||||
dist = keyword_analysis['keyword_distribution']
|
||||
fig = px.pie(
|
||||
values=[dist['positions_1_3'], dist['positions_4_10'], dist['positions_11_20'], dist['positions_21_plus']],
|
||||
names=['Positions 1-3', 'Positions 4-10', 'Positions 11-20', 'Positions 21+'],
|
||||
title="Keyword Position Distribution"
|
||||
)
|
||||
st.plotly_chart(fig, use_container_width=True)
|
||||
|
||||
# High volume keywords
|
||||
high_volume = keyword_analysis.get('high_volume_keywords', [])
|
||||
if high_volume:
|
||||
st.markdown("#### 📈 High Volume Keywords")
|
||||
st.dataframe(pd.DataFrame(high_volume), hide_index=True)
|
||||
|
||||
# Optimization opportunities
|
||||
opt_opportunities = keyword_analysis.get('optimization_opportunities', [])
|
||||
if opt_opportunities:
|
||||
st.markdown("#### 🎯 Optimization Opportunities (Positions 11-20)")
|
||||
st.dataframe(pd.DataFrame(opt_opportunities), hide_index=True)
|
||||
|
||||
with tab3:
|
||||
page_analysis = results.get('page_analysis', {})
|
||||
if page_analysis:
|
||||
st.subheader("Page Performance Analysis")
|
||||
|
||||
# Top pages
|
||||
top_pages = page_analysis.get('top_pages', [])
|
||||
if top_pages:
|
||||
st.markdown("#### 🏆 Top Performing Pages")
|
||||
st.dataframe(pd.DataFrame(top_pages), hide_index=True)
|
||||
|
||||
# Underperforming pages
|
||||
underperforming = page_analysis.get('underperforming_pages', [])
|
||||
if underperforming:
|
||||
st.markdown("#### ⚠️ Underperforming Pages (High Impressions, Low CTR)")
|
||||
st.dataframe(pd.DataFrame(underperforming), hide_index=True)
|
||||
|
||||
# Page types performance
|
||||
page_types = page_analysis.get('page_types_performance', {})
|
||||
if page_types:
|
||||
st.markdown("#### 📊 Performance by Page Type")
|
||||
|
||||
# Create visualization
|
||||
types = []
|
||||
clicks = []
|
||||
positions = []
|
||||
|
||||
for page_type, data in page_types.items():
|
||||
if data['count'] > 0:
|
||||
types.append(page_type)
|
||||
clicks.append(data['total_clicks'])
|
||||
positions.append(data['avg_position'])
|
||||
|
||||
if types:
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
fig_clicks = px.bar(x=types, y=clicks, title="Total Clicks by Page Type")
|
||||
st.plotly_chart(fig_clicks, use_container_width=True)
|
||||
|
||||
with col2:
|
||||
fig_position = px.bar(x=types, y=positions, title="Average Position by Page Type")
|
||||
st.plotly_chart(fig_position, use_container_width=True)
|
||||
|
||||
with tab4:
|
||||
competitive_analysis = results.get('competitive_analysis', {})
|
||||
if competitive_analysis:
|
||||
st.subheader("Competitive Position Analysis")
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.metric("Market Position", competitive_analysis['market_position'])
|
||||
st.metric("Competitive Strength", f"{competitive_analysis['competitive_strength_score']}/3.0")
|
||||
|
||||
with col2:
|
||||
# Competitive distribution
|
||||
comp_data = {
|
||||
'Dominant (1-3)': competitive_analysis['dominant_keywords'],
|
||||
'Competitive (4-10)': competitive_analysis['competitive_keywords'],
|
||||
'Losing (11+)': competitive_analysis['losing_keywords']
|
||||
}
|
||||
|
||||
fig = px.bar(
|
||||
x=list(comp_data.keys()),
|
||||
y=list(comp_data.values()),
|
||||
title="Keyword Competitive Position"
|
||||
)
|
||||
st.plotly_chart(fig, use_container_width=True)
|
||||
|
||||
with tab5:
|
||||
technical_insights = results.get('technical_insights', {})
|
||||
if technical_insights:
|
||||
st.subheader("Technical SEO Signals")
|
||||
|
||||
# Crawl issues indicators
|
||||
crawl_issues = technical_insights.get('crawl_issues_indicators', [])
|
||||
if crawl_issues:
|
||||
st.markdown("#### ⚠️ Potential Issues")
|
||||
for issue in crawl_issues:
|
||||
st.warning(f"🚨 {issue}")
|
||||
|
||||
# Mobile performance
|
||||
mobile_perf = technical_insights.get('mobile_performance', {})
|
||||
if mobile_perf:
|
||||
st.markdown("#### 📱 Mobile Performance")
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
st.metric("Avg Mobile Position", f"{mobile_perf.get('avg_mobile_position', 0):.1f}")
|
||||
|
||||
with col2:
|
||||
if mobile_perf.get('mobile_optimization_needed', False):
|
||||
st.warning("📱 Mobile optimization needed")
|
||||
else:
|
||||
st.success("📱 Mobile performance good")
|
||||
|
||||
# Export functionality
|
||||
st.markdown("---")
|
||||
col1, col2, col3 = st.columns(3)
|
||||
|
||||
with col1:
|
||||
if st.button("📥 Export Full Report", use_container_width=True):
|
||||
report_json = json.dumps(results, indent=2, default=str)
|
||||
st.download_button(
|
||||
label="Download JSON Report",
|
||||
data=report_json,
|
||||
file_name=f"gsc_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
||||
mime="application/json"
|
||||
)
|
||||
|
||||
with col2:
|
||||
if st.button("📊 Export Opportunities", use_container_width=True):
|
||||
if opportunities:
|
||||
df_opportunities = pd.DataFrame(opportunities)
|
||||
csv = df_opportunities.to_csv(index=False)
|
||||
st.download_button(
|
||||
label="Download CSV Opportunities",
|
||||
data=csv,
|
||||
file_name=f"content_opportunities_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
||||
mime="text/csv"
|
||||
)
|
||||
|
||||
with col3:
|
||||
if st.button("🔄 Refresh Analysis", use_container_width=True):
|
||||
# Clear cached results to force refresh
|
||||
if 'gsc_results' in st.session_state:
|
||||
del st.session_state.gsc_results
|
||||
st.rerun()
|
||||
|
||||
|
||||
# Main execution
|
||||
if __name__ == "__main__":
|
||||
render_gsc_integration()
|
||||
Reference in New Issue
Block a user