Added new features to the project
This commit is contained in:
488
lib/competitive_intelligence/README.md
Normal file
488
lib/competitive_intelligence/README.md
Normal file
@@ -0,0 +1,488 @@
|
||||
# 🥷 AI-Powered Competitive Intelligence
|
||||
|
||||
**AI Competitive Intelligence Suite for Entrepreneurs**
|
||||
|
||||
Transform your competitive analysis with AI-powered intelligence gathering, content strategy insights, and market opportunity identification. Perfect for entrepreneurs and small teams who need enterprise-level competitive intelligence without the enterprise budget.
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Features](#features)
|
||||
- [Installation](#installation)
|
||||
- [Usage](#usage)
|
||||
- [Architecture](#architecture)
|
||||
- [AI Analysis Capabilities](#ai-analysis-capabilities)
|
||||
- [API Reference](#api-reference)
|
||||
- [File Structure](#file-structure)
|
||||
- [Configuration](#configuration)
|
||||
- [Development](#development)
|
||||
- [Use Cases](#use-cases)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Contributing](#contributing)
|
||||
|
||||
## 🔍 Overview
|
||||
|
||||
The AI-Powered Competitive Intelligence suite provides comprehensive competitor analysis and market insights using advanced AI capabilities:
|
||||
|
||||
- **AI Competitive Intelligence**: Advanced competitive analysis with AI insights
|
||||
- **AI Content Strategy Analysis**: Understand what content works for competitors
|
||||
- **Market Opportunity Detection**: Identify gaps and opportunities in your market
|
||||
- **Strategic Recommendations**: AI-powered actionable insights
|
||||
|
||||
### Key Benefits
|
||||
|
||||
- **🧠 AI-Powered Analysis**: Leverages LLM intelligence for deep competitive insights
|
||||
- **⚡ Quick Setup**: Get started with competitor intelligence in minutes
|
||||
- **💰 Cost-Effective**: Enterprise-level insights without enterprise costs
|
||||
- **🎯 Actionable Insights**: Clear recommendations for competitive advantage
|
||||
- **📊 Strategic Intelligence**: Market gaps, opportunities, and positioning insights
|
||||
|
||||
## ✨ Features
|
||||
|
||||
### Core Intelligence Capabilities
|
||||
|
||||
#### 1. **AI Competitor Analysis**
|
||||
- Rapid competitive landscape assessment
|
||||
- Competitor strength/weakness analysis
|
||||
- Market positioning insights
|
||||
- Content strategy evaluation
|
||||
|
||||
#### 2. **AI Content Intelligence**
|
||||
- Competitor content performance analysis
|
||||
- Content gap identification
|
||||
- Strategic content recommendations
|
||||
- Optimal content strategy insights
|
||||
|
||||
#### 3. **Market Opportunity Detection**
|
||||
- Underserved market segment identification
|
||||
- Content opportunity mapping
|
||||
- Competitive advantage discovery
|
||||
- Strategic positioning recommendations
|
||||
|
||||
#### 4. **Strategic Recommendations**
|
||||
- Competitive differentiation strategies
|
||||
- Market entry recommendations
|
||||
- Content strategy optimization
|
||||
- Positioning improvements
|
||||
|
||||
### Analysis Categories
|
||||
|
||||
1. **🎯 Competitive Positioning**: Where you stand vs competitors
|
||||
2. **📈 Content Performance**: What content works in your space
|
||||
3. **🔍 Market Gaps**: Opportunities competitors are missing
|
||||
4. **💡 Strategic Insights**: AI-powered competitive recommendations
|
||||
5. **⚡ Quick Wins**: Immediate actions for competitive advantage
|
||||
6. **🚀 Growth Opportunities**: Long-term strategic opportunities
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
### Prerequisites
|
||||
|
||||
```bash
|
||||
# Already included in Alwrity - no additional installation required!
|
||||
# Uses existing dependencies: streamlit, llm_text_gen, requests
|
||||
```
|
||||
|
||||
### Setup
|
||||
|
||||
1. **Auto-Integration** (already included):
|
||||
```python
|
||||
# Available in AI Writer Dashboard
|
||||
# Access via: "Bootstrap AI Competitive Suite"
|
||||
```
|
||||
|
||||
2. **Direct Usage**:
|
||||
```python
|
||||
from lib.competitive_intelligence.ai_competitive_intelligence import AICompetitiveIntelligence
|
||||
```
|
||||
|
||||
3. **Full Suite Access**:
|
||||
```python
|
||||
from lib.ai_competitive_suite.bootstrap_ai_suite import BootstrapAISuite
|
||||
```
|
||||
|
||||
4. **UI Components**:
|
||||
```python
|
||||
from lib.competitive_intelligence.ai_competitive_intelligence import render_ai_competitive_intelligence_ui
|
||||
from lib.ai_competitive_suite.bootstrap_ai_suite import render_bootstrap_ai_suite
|
||||
```
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
### Through AI Writer Dashboard
|
||||
|
||||
1. Open Alwrity
|
||||
2. Navigate to "AI Writer Dashboard"
|
||||
3. Select "🚀 Bootstrap AI Competitive Suite"
|
||||
4. Enter competitor information or industry
|
||||
5. Get comprehensive competitive intelligence!
|
||||
|
||||
### AI Competitor Analysis
|
||||
|
||||
```python
|
||||
from lib.competitive_intelligence.ai_competitive_intelligence import AICompetitiveIntelligence
|
||||
|
||||
# Initialize AI analyzer
|
||||
intel = AICompetitiveIntelligence()
|
||||
|
||||
# Quick competitor analysis
|
||||
result = await intel.analyze_competitors(
|
||||
competitor_urls=["https://jasper.ai", "https://copy.ai"],
|
||||
industry="AI writing tools",
|
||||
your_strengths=["AI-first approach", "Solo entrepreneur focus"]
|
||||
)
|
||||
|
||||
print(f"Key Insights: {result['competitor_insights']}")
|
||||
print(f"Opportunities: {result['strategic_opportunities']}")
|
||||
```
|
||||
|
||||
### Full AI Competitive Suite
|
||||
|
||||
```python
|
||||
from lib.ai_competitive_suite.bootstrap_ai_suite import BootstrapAISuite
|
||||
|
||||
# Initialize full suite
|
||||
suite = BootstrapAISuite()
|
||||
|
||||
# Comprehensive analysis
|
||||
analysis = await suite.get_competitive_content_strategy(
|
||||
content="Your content here",
|
||||
target_platform="twitter",
|
||||
competitor_urls=["https://competitor1.com", "https://competitor2.com"],
|
||||
industry="content creation",
|
||||
your_strengths=["AI expertise", "Bootstrap approach"]
|
||||
)
|
||||
|
||||
print(f"Integrated Strategy: {analysis['integrated_strategy']}")
|
||||
print(f"Action Plan: {analysis['action_plan']}")
|
||||
```
|
||||
|
||||
### Programmatic Usage
|
||||
|
||||
```python
|
||||
import streamlit as st
|
||||
from lib.competitive_intelligence.ai_competitive_intelligence import render_ai_competitive_intelligence_ui
|
||||
|
||||
# Add to your Streamlit app
|
||||
st.title("AI Competitive Intelligence")
|
||||
render_ai_competitive_intelligence_ui()
|
||||
```
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
### System Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ STREAMLIT UI │
|
||||
│ (render_bootstrap_ai_suite / render_ai_intelligence_ui) │
|
||||
└─────────────────┬───────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────────┴───────────────────────────────────────────┐
|
||||
│ BOOTSTRAP AI COMPETITIVE SUITE │
|
||||
│ (BootstrapAISuite) │
|
||||
│ ┌─────────────────┐ ┌─────────────────────────────────┐ │
|
||||
│ │ Competitor │ │ Market Intelligence │ │
|
||||
│ │ Analysis │ │ (Opportunities & Gaps) │ │
|
||||
│ └─────────────────┘ └─────────────────────────────────┘ │
|
||||
└─────────────────┬───────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────────┴───────────────────────────────────────────┐
|
||||
│ BOOTSTRAP COMPETITOR INTEL │
|
||||
│ (BootstrapCompetitorIntel) │
|
||||
│ ┌─────────────────┐ ┌─────────────────────────────────┐ │
|
||||
│ │ Industry │ │ Competitive Positioning │ │
|
||||
│ │ Analysis │ │ & Strategic Insights │ │
|
||||
│ └─────────────────┘ └─────────────────────────────────┘ │
|
||||
└─────────────────┬───────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────────┴───────────────────────────────────────────┐
|
||||
│ ALWRITY LLM ENGINE │
|
||||
│ (llm_text_gen) │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Component Details
|
||||
|
||||
1. **BootstrapAISuite**: Complete competitive intelligence platform
|
||||
2. **BootstrapCompetitorIntel**: Core competitor analysis engine
|
||||
3. **Market Intelligence**: Opportunity detection and gap analysis
|
||||
4. **Strategic Insights**: AI-powered recommendations and positioning
|
||||
5. **UI Components**: Interactive analysis interfaces
|
||||
|
||||
## 🧠 AI Analysis Capabilities
|
||||
|
||||
### Competitive Intelligence Analysis
|
||||
|
||||
The suite uses sophisticated AI prompts to analyze:
|
||||
|
||||
- **Competitor Strengths**: What makes competitors successful
|
||||
- **Market Weaknesses**: Where competitors are failing
|
||||
- **Content Strategies**: What content approaches work best
|
||||
- **Positioning Opportunities**: How to differentiate effectively
|
||||
|
||||
### Market Intelligence Features
|
||||
|
||||
#### Industry Landscape Analysis
|
||||
- Market size and growth trends
|
||||
- Key player identification
|
||||
- Competitive dynamics assessment
|
||||
- Market maturity evaluation
|
||||
|
||||
#### Competitive Positioning
|
||||
- Strength/weakness matrix
|
||||
- Differentiation opportunities
|
||||
- Market positioning gaps
|
||||
- Value proposition analysis
|
||||
|
||||
#### Content Strategy Intelligence
|
||||
- High-performing content identification
|
||||
- Content gap analysis
|
||||
- Viral content pattern recognition
|
||||
- Platform-specific strategies
|
||||
|
||||
#### Strategic Recommendations
|
||||
- Competitive advantage opportunities
|
||||
- Market entry strategies
|
||||
- Product positioning advice
|
||||
- Growth opportunity identification
|
||||
|
||||
## 🚀 Bootstrap Features
|
||||
|
||||
### Quick Setup Intelligence
|
||||
|
||||
#### 1. **Rapid Competitor Analysis**
|
||||
- Input: Industry + Competitors
|
||||
- Output: Comprehensive competitive landscape
|
||||
- Time: 2-3 minutes
|
||||
- Insight: Market positioning and opportunities
|
||||
|
||||
#### 2. **Industry Assessment**
|
||||
- Input: Industry description
|
||||
- Output: Market dynamics and key players
|
||||
- Time: 1-2 minutes
|
||||
- Insight: Market opportunities and threats
|
||||
|
||||
#### 3. **Strategic Positioning**
|
||||
- Input: Your product + competitors
|
||||
- Output: Differentiation strategy
|
||||
- Time: 2-3 minutes
|
||||
- Insight: Competitive advantages and positioning
|
||||
|
||||
#### 4. **Content Intelligence**
|
||||
- Input: Industry + content focus
|
||||
- Output: Content strategy recommendations
|
||||
- Time: 2-3 minutes
|
||||
- Insight: What content works and content gaps
|
||||
|
||||
### Bootstrap Configurations
|
||||
|
||||
Located in the intelligence modules:
|
||||
|
||||
```python
|
||||
ANALYSIS_TEMPLATES = {
|
||||
"competitor_analysis": {
|
||||
"focus_areas": ["strengths", "weaknesses", "positioning"],
|
||||
"output_format": "strategic_insights",
|
||||
"depth": "comprehensive"
|
||||
},
|
||||
"market_intelligence": {
|
||||
"analysis_type": "opportunity_detection",
|
||||
"scope": "industry_wide",
|
||||
"recommendations": "actionable"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📊 Analysis Output
|
||||
|
||||
### Competitive Analysis Report
|
||||
|
||||
```python
|
||||
{
|
||||
"executive_summary": "Key findings and strategic recommendations",
|
||||
"competitor_analysis": {
|
||||
"direct_competitors": [...],
|
||||
"indirect_competitors": [...],
|
||||
"competitive_advantages": [...],
|
||||
"competitive_threats": [...]
|
||||
},
|
||||
"market_intelligence": {
|
||||
"market_size": "Large/Medium/Small",
|
||||
"growth_rate": "High/Medium/Low",
|
||||
"key_trends": [...],
|
||||
"opportunities": [...]
|
||||
},
|
||||
"strategic_recommendations": {
|
||||
"positioning": "How to position your product",
|
||||
"differentiation": "Key differentiators to focus on",
|
||||
"content_strategy": "What content to create",
|
||||
"quick_wins": "Immediate actions to take"
|
||||
},
|
||||
"content_opportunities": {
|
||||
"content_gaps": [...],
|
||||
"viral_patterns": [...],
|
||||
"platform_strategies": {...}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Intelligence Categories
|
||||
|
||||
1. **Market Position**: Where you stand competitively
|
||||
2. **Opportunities**: Gaps competitors haven't filled
|
||||
3. **Threats**: Competitive risks to monitor
|
||||
4. **Strategy**: Recommended competitive approach
|
||||
5. **Content**: What content strategy to pursue
|
||||
6. **Quick Wins**: Immediate competitive advantages
|
||||
|
||||
## 🔧 Configuration
|
||||
|
||||
### Analysis Settings
|
||||
|
||||
Customize analysis depth and focus:
|
||||
|
||||
```python
|
||||
# Configure analysis parameters
|
||||
analysis_config = {
|
||||
"depth": "comprehensive", # quick, standard, comprehensive
|
||||
"focus": "content_strategy", # market_position, content_strategy, opportunities
|
||||
"industry": "your_industry",
|
||||
"competitive_scope": "direct_competitors" # direct, indirect, all
|
||||
}
|
||||
```
|
||||
|
||||
### Customization Options
|
||||
|
||||
- **Analysis Depth**: Quick overview vs comprehensive analysis
|
||||
- **Focus Areas**: Market positioning, content strategy, opportunities
|
||||
- **Industry Scope**: Narrow niche vs broad market analysis
|
||||
- **Output Format**: Executive summary, detailed report, action items
|
||||
|
||||
## 🚀 Development
|
||||
|
||||
### Adding New Analysis Types
|
||||
|
||||
1. Extend analysis templates in configuration
|
||||
2. Add new AI prompts for specific analysis
|
||||
3. Update UI to support new analysis types
|
||||
|
||||
### Enhancing Intelligence Gathering
|
||||
|
||||
1. Add new data sources for competitive information
|
||||
2. Implement automated monitoring capabilities
|
||||
3. Enhance AI analysis with additional insights
|
||||
|
||||
## 📈 Use Cases
|
||||
|
||||
### Solo Entrepreneurs
|
||||
|
||||
- **Quick Market Assessment**: Understand competitive landscape fast
|
||||
- **Content Strategy**: Identify what content works in your niche
|
||||
- **Positioning**: Find your unique market position
|
||||
- **Opportunities**: Discover gaps competitors are missing
|
||||
|
||||
### Small Teams
|
||||
|
||||
- **Competitive Strategy**: Develop comprehensive competitive approach
|
||||
- **Market Intelligence**: Ongoing competitive monitoring
|
||||
- **Strategic Planning**: AI-powered strategic recommendations
|
||||
- **Content Planning**: Content strategy based on competitive analysis
|
||||
|
||||
### Growing Businesses
|
||||
|
||||
- **Market Expansion**: Identify new market opportunities
|
||||
- **Competitive Advantage**: Maintain edge over competitors
|
||||
- **Strategic Positioning**: Refine market positioning strategy
|
||||
- **Growth Planning**: AI-powered growth recommendations
|
||||
|
||||
## 🔍 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**No Analysis Generated**:
|
||||
- Check LLM service availability
|
||||
- Verify competitor/industry information is provided
|
||||
- Ensure sufficient detail in input
|
||||
|
||||
**Generic Insights**:
|
||||
- Provide more specific industry information
|
||||
- Include specific competitor names
|
||||
- Add context about your product/service
|
||||
|
||||
**UI Not Loading**:
|
||||
- Check Streamlit dependencies
|
||||
- Verify import paths
|
||||
- Ensure LLM service is configured
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable detailed logging:
|
||||
```python
|
||||
import logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
```
|
||||
|
||||
## 📈 Performance Tips
|
||||
|
||||
1. **Specific Industries**: Provide detailed industry information for better analysis
|
||||
2. **Competitor Details**: Include specific competitor names and details
|
||||
3. **Context**: Add context about your business for relevant insights
|
||||
4. **Iterate**: Use insights to refine your competitive strategy
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch
|
||||
3. Add new analysis capabilities or improve existing ones
|
||||
4. Test with different industries and competitors
|
||||
5. Submit a pull request
|
||||
|
||||
### Development Setup
|
||||
|
||||
```bash
|
||||
# No additional setup required!
|
||||
# Uses existing Alwrity infrastructure
|
||||
```
|
||||
|
||||
## 📝 License
|
||||
|
||||
Part of the Alwrity AI Content Creation Suite.
|
||||
|
||||
---
|
||||
|
||||
**Ready to gain competitive intelligence? Access the Bootstrap AI Competitive Suite through the AI Writer Dashboard now!**
|
||||
|
||||
## 🎯 Quick Start Examples
|
||||
|
||||
### Example 1: SaaS Competitive Analysis
|
||||
```python
|
||||
# Analyze SaaS competitive landscape
|
||||
result = await intel.analyze_competitor_landscape(
|
||||
industry="AI writing software",
|
||||
competitors=["Jasper", "Copy.ai", "Writesonic"],
|
||||
your_product="Alwrity - AI writer for solo developers"
|
||||
)
|
||||
```
|
||||
|
||||
### Example 2: Content Strategy Intelligence
|
||||
```python
|
||||
# Get content strategy insights
|
||||
content_intel = await suite.analyze_content_opportunities(
|
||||
industry="digital marketing",
|
||||
content_focus="social media content creation"
|
||||
)
|
||||
```
|
||||
|
||||
### Example 3: Market Opportunity Detection
|
||||
```python
|
||||
# Find market gaps
|
||||
opportunities = await intel.identify_market_opportunities(
|
||||
industry="productivity software",
|
||||
target_audience="small business owners"
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Transform your competitive strategy with AI-powered intelligence! 🥷**
|
||||
725
lib/competitive_intelligence/ai_competitive_intelligence.py
Normal file
725
lib/competitive_intelligence/ai_competitive_intelligence.py
Normal file
@@ -0,0 +1,725 @@
|
||||
"""
|
||||
AI-Powered Competitive Intelligence
|
||||
|
||||
Advanced competitive intelligence for entrepreneurs using AI.
|
||||
Provides strategic insights, competitor analysis, and market opportunities.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List, Optional
|
||||
from loguru import logger
|
||||
import streamlit as st
|
||||
from urllib.parse import urlparse
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
# Import existing Alwrity modules
|
||||
from lib.ai_seo_tools.content_gap_analysis.competitor_analyzer import CompetitorAnalyzer
|
||||
from lib.ai_web_researcher.gpt_online_researcher import do_google_pytrends_analysis
|
||||
from lib.gpt_providers.text_generation.main_text_generation import llm_text_gen
|
||||
|
||||
|
||||
class AICompetitiveIntelligence:
|
||||
"""
|
||||
AI-powered competitive intelligence for entrepreneurs and startups.
|
||||
Uses existing AI capabilities to provide strategic insights.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the AI competitive intelligence."""
|
||||
self.competitor_analyzer = CompetitorAnalyzer()
|
||||
self.analysis_history = []
|
||||
|
||||
logger.info("AI Competitive Intelligence initialized")
|
||||
|
||||
async def analyze_competitors(
|
||||
self,
|
||||
competitor_urls: List[str],
|
||||
industry: str,
|
||||
your_strengths: List[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Analyze competitors using AI-powered insights.
|
||||
|
||||
Args:
|
||||
competitor_urls: List of competitor URLs
|
||||
industry: Your industry/niche
|
||||
your_strengths: Your current strengths (optional)
|
||||
|
||||
Returns:
|
||||
AI-powered competitive analysis
|
||||
"""
|
||||
logger.info(f"Starting AI competitive analysis for {len(competitor_urls)} competitors")
|
||||
|
||||
try:
|
||||
analysis_report = {
|
||||
'analysis_metadata': {
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'competitors_analyzed': len(competitor_urls),
|
||||
'industry': industry,
|
||||
'your_strengths': your_strengths or []
|
||||
},
|
||||
'competitor_insights': {},
|
||||
'strategic_opportunities': [],
|
||||
'content_gap_analysis': {},
|
||||
'ai_recommendations': [],
|
||||
'quick_wins': [],
|
||||
'competitive_positioning': {}
|
||||
}
|
||||
|
||||
# Step 1: Basic competitor analysis using existing tools
|
||||
st.info("🔍 Analyzing competitor basics...")
|
||||
basic_analysis = self.competitor_analyzer.analyze(competitor_urls, industry)
|
||||
|
||||
# Step 2: AI-powered deep analysis
|
||||
st.info("🧠 AI is analyzing competitive landscape...")
|
||||
ai_insights = await self._get_ai_competitive_insights(
|
||||
competitor_urls, industry, basic_analysis, your_strengths
|
||||
)
|
||||
|
||||
# Step 3: Content gap opportunities
|
||||
st.info("🎯 Identifying content opportunities...")
|
||||
content_opportunities = await self._find_content_opportunities(
|
||||
competitor_urls, industry, basic_analysis
|
||||
)
|
||||
|
||||
# Step 4: Strategic recommendations
|
||||
st.info("💡 Generating strategic recommendations...")
|
||||
strategic_recommendations = await self._generate_strategic_recommendations(
|
||||
competitor_urls, industry, ai_insights, content_opportunities, your_strengths
|
||||
)
|
||||
|
||||
# Compile results
|
||||
analysis_report.update({
|
||||
'competitor_insights': ai_insights,
|
||||
'content_gap_analysis': content_opportunities,
|
||||
'ai_recommendations': strategic_recommendations,
|
||||
'quick_wins': self._extract_quick_wins(strategic_recommendations),
|
||||
'competitive_positioning': self._analyze_positioning(ai_insights, your_strengths)
|
||||
})
|
||||
|
||||
# Save to history
|
||||
self.analysis_history.append({
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'industry': industry,
|
||||
'competitors_count': len(competitor_urls),
|
||||
'report_id': f"{industry}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
||||
})
|
||||
|
||||
logger.info("AI competitive analysis completed successfully")
|
||||
return analysis_report
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error in competitive analysis: {str(e)}"
|
||||
logger.error(error_msg, exc_info=True)
|
||||
return {'error': error_msg}
|
||||
|
||||
async def _get_ai_competitive_insights(
|
||||
self,
|
||||
competitor_urls: List[str],
|
||||
industry: str,
|
||||
basic_analysis: Dict[str, Any],
|
||||
your_strengths: List[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get AI-powered competitive insights."""
|
||||
|
||||
competitors_list = [urlparse(url).netloc for url in competitor_urls]
|
||||
your_strengths_str = ', '.join(your_strengths) if your_strengths else "Not specified"
|
||||
|
||||
insights_prompt = f"""
|
||||
You are a competitive intelligence expert analyzing the {industry} market.
|
||||
|
||||
COMPETITORS TO ANALYZE:
|
||||
{', '.join(competitors_list)}
|
||||
|
||||
BASIC COMPETITIVE ANALYSIS DATA:
|
||||
{json.dumps(basic_analysis, indent=2)[:3000]}
|
||||
|
||||
YOUR CURRENT STRENGTHS:
|
||||
{your_strengths_str}
|
||||
|
||||
Please provide a comprehensive competitive analysis with these insights:
|
||||
|
||||
1. MARKET LANDSCAPE OVERVIEW:
|
||||
- Who are the dominant players?
|
||||
- What's the competitive intensity like?
|
||||
- What are the key market trends?
|
||||
- Where are the market gaps?
|
||||
|
||||
2. COMPETITOR STRENGTHS & WEAKNESSES:
|
||||
For each major competitor, identify:
|
||||
- Their main competitive advantages
|
||||
- Their key weaknesses or blind spots
|
||||
- Their content strategy approach
|
||||
- Their target audience focus
|
||||
|
||||
3. DIFFERENTIATION OPPORTUNITIES:
|
||||
- How can you position differently?
|
||||
- What unique value can you offer?
|
||||
- Which competitor weaknesses can you exploit?
|
||||
- What underserved market segments exist?
|
||||
|
||||
4. THREAT ASSESSMENT:
|
||||
- Which competitors pose the biggest threat to you?
|
||||
- What are they doing better than you?
|
||||
- Where are they vulnerable?
|
||||
- How quickly are they evolving?
|
||||
|
||||
5. STRATEGIC INSIGHTS:
|
||||
- What patterns do you see across all competitors?
|
||||
- What are they all missing that you could provide?
|
||||
- Where is the market heading?
|
||||
- What first-mover opportunities exist?
|
||||
|
||||
Provide specific, actionable insights that a solo entrepreneur can use to compete effectively.
|
||||
Focus on realistic strategies that don't require massive resources.
|
||||
"""
|
||||
|
||||
try:
|
||||
ai_insights = llm_text_gen(
|
||||
insights_prompt,
|
||||
system_prompt="You are a strategic business consultant specializing in competitive analysis for startups and small businesses. Provide practical, actionable insights."
|
||||
)
|
||||
|
||||
return {
|
||||
'full_analysis': ai_insights,
|
||||
'key_insights': self._extract_key_insights(ai_insights),
|
||||
'threat_levels': self._assess_threat_levels(ai_insights, competitors_list),
|
||||
'opportunities': self._extract_opportunities(ai_insights)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting AI insights: {str(e)}")
|
||||
return {
|
||||
'full_analysis': f"Error generating insights: {str(e)}",
|
||||
'key_insights': ["Unable to generate AI insights"],
|
||||
'threat_levels': {},
|
||||
'opportunities': []
|
||||
}
|
||||
|
||||
async def _find_content_opportunities(
|
||||
self,
|
||||
competitor_urls: List[str],
|
||||
industry: str,
|
||||
basic_analysis: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
"""Find content opportunities using AI analysis."""
|
||||
|
||||
content_gaps = basic_analysis.get('content_gaps', [])
|
||||
advantages = basic_analysis.get('advantages', [])
|
||||
|
||||
content_prompt = f"""
|
||||
Analyze content opportunities in the {industry} space based on competitor analysis:
|
||||
|
||||
COMPETITOR CONTENT GAPS IDENTIFIED:
|
||||
{json.dumps(content_gaps[:10], indent=2)}
|
||||
|
||||
COMPETITOR ADVANTAGES:
|
||||
{json.dumps(advantages[:10], indent=2)}
|
||||
|
||||
INDUSTRY: {industry}
|
||||
|
||||
Provide specific content opportunities analysis:
|
||||
|
||||
1. HIGH-PRIORITY CONTENT GAPS:
|
||||
- What topics are competitors not covering well?
|
||||
- What questions are audiences asking that aren't being answered?
|
||||
- What content formats are underutilized?
|
||||
- What pain points are being ignored?
|
||||
|
||||
2. CONTENT DIFFERENTIATION OPPORTUNITIES:
|
||||
- How can you approach common topics differently?
|
||||
- What unique perspective can you bring?
|
||||
- What content formats can you innovate with?
|
||||
- How can you provide more value than competitors?
|
||||
|
||||
3. TRENDING CONTENT OPPORTUNITIES:
|
||||
- What emerging topics should you cover first?
|
||||
- What seasonal content opportunities exist?
|
||||
- What industry changes create content needs?
|
||||
- What tools/technologies need better content coverage?
|
||||
|
||||
4. AUDIENCE-SPECIFIC CONTENT GAPS:
|
||||
- Which audience segments are underserved?
|
||||
- What skill levels need better content?
|
||||
- What use cases are poorly addressed?
|
||||
- What demographics are being ignored?
|
||||
|
||||
5. QUICK CONTENT WINS:
|
||||
- What content can you create quickly that competitors lack?
|
||||
- What simple explanations are missing from the market?
|
||||
- What FAQ content is needed but not provided?
|
||||
- What beginner content opportunities exist?
|
||||
|
||||
Prioritize opportunities that a solo creator can realistically execute.
|
||||
"""
|
||||
|
||||
try:
|
||||
content_analysis = llm_text_gen(
|
||||
content_prompt,
|
||||
system_prompt="You are a content strategist specializing in competitive content analysis. Provide specific, actionable content opportunities."
|
||||
)
|
||||
|
||||
return {
|
||||
'full_analysis': content_analysis,
|
||||
'priority_gaps': self._extract_priority_gaps(content_analysis),
|
||||
'quick_wins': self._extract_content_quick_wins(content_analysis),
|
||||
'differentiation_opportunities': self._extract_differentiation_opps(content_analysis)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error finding content opportunities: {str(e)}")
|
||||
return {
|
||||
'full_analysis': f"Error analyzing content opportunities: {str(e)}",
|
||||
'priority_gaps': content_gaps[:5],
|
||||
'quick_wins': [],
|
||||
'differentiation_opportunities': []
|
||||
}
|
||||
|
||||
async def _generate_strategic_recommendations(
|
||||
self,
|
||||
competitor_urls: List[str],
|
||||
industry: str,
|
||||
ai_insights: Dict[str, Any],
|
||||
content_opportunities: Dict[str, Any],
|
||||
your_strengths: List[str] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Generate strategic recommendations using AI."""
|
||||
|
||||
your_strengths_str = ', '.join(your_strengths) if your_strengths else "Not specified"
|
||||
|
||||
strategy_prompt = f"""
|
||||
Based on the competitive analysis, provide strategic recommendations for competing in {industry}:
|
||||
|
||||
AI COMPETITIVE INSIGHTS:
|
||||
{ai_insights.get('full_analysis', '')[:2000]}
|
||||
|
||||
CONTENT OPPORTUNITIES:
|
||||
{content_opportunities.get('full_analysis', '')[:2000]}
|
||||
|
||||
YOUR CURRENT STRENGTHS:
|
||||
{your_strengths_str}
|
||||
|
||||
BUDGET CONSTRAINT: Solo entrepreneur with limited resources
|
||||
|
||||
Provide specific, actionable recommendations in these categories:
|
||||
|
||||
1. IMMEDIATE ACTIONS (0-30 days):
|
||||
- What can you implement this week?
|
||||
- Which competitor weaknesses can you exploit quickly?
|
||||
- What low-cost marketing tactics should you try?
|
||||
- Which content should you create first?
|
||||
|
||||
2. SHORT-TERM STRATEGY (1-3 months):
|
||||
- How should you position against competitors?
|
||||
- What features/content should you prioritize?
|
||||
- Which partnerships should you pursue?
|
||||
- How should you differentiate your messaging?
|
||||
|
||||
3. MEDIUM-TERM POSITIONING (3-6 months):
|
||||
- How can you build sustainable competitive advantages?
|
||||
- Which market segments should you focus on?
|
||||
- What unique value proposition should you develop?
|
||||
- How can you build barriers to competition?
|
||||
|
||||
4. RESOURCE ALLOCATION:
|
||||
- Where should you spend your limited time?
|
||||
- Which marketing channels offer best ROI?
|
||||
- What tools/software investments are worthwhile?
|
||||
- How should you prioritize feature development?
|
||||
|
||||
5. COMPETITIVE DEFENSE:
|
||||
- How can you protect against competitor moves?
|
||||
- What should you do if competitors copy you?
|
||||
- How can you build customer loyalty?
|
||||
- What contingency plans should you have?
|
||||
|
||||
For each recommendation:
|
||||
- Specify the exact action to take
|
||||
- Estimate time/resource requirements
|
||||
- Explain expected impact
|
||||
- Rate priority (High/Medium/Low)
|
||||
- Provide success metrics
|
||||
|
||||
Focus on David vs Goliath strategies that work for solo entrepreneurs.
|
||||
"""
|
||||
|
||||
try:
|
||||
strategic_recommendations = llm_text_gen(
|
||||
strategy_prompt,
|
||||
system_prompt="You are a startup strategist specializing in helping solo entrepreneurs compete against established players. Provide practical, executable strategies."
|
||||
)
|
||||
|
||||
return self._parse_strategic_recommendations(strategic_recommendations)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating strategic recommendations: {str(e)}")
|
||||
return [
|
||||
{
|
||||
'category': 'Content Strategy',
|
||||
'priority': 'High',
|
||||
'timeframe': '0-30 days',
|
||||
'action': 'Create content addressing competitor blind spots',
|
||||
'expected_impact': 'Attract underserved audience segments',
|
||||
'resources_needed': 'Time for content creation',
|
||||
'success_metrics': 'Website traffic, engagement rates'
|
||||
}
|
||||
]
|
||||
|
||||
def _extract_key_insights(self, ai_analysis: str) -> List[str]:
|
||||
"""Extract key insights from AI analysis."""
|
||||
insights = []
|
||||
|
||||
# Simple parsing to extract key points
|
||||
lines = ai_analysis.split('\n')
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line and (line.startswith('•') or line.startswith('-') or line.startswith('*')):
|
||||
insight = line.lstrip('•-* ').strip()
|
||||
if len(insight) > 20: # Only substantial insights
|
||||
insights.append(insight)
|
||||
|
||||
return insights[:8] # Return top 8 insights
|
||||
|
||||
def _assess_threat_levels(self, ai_analysis: str, competitors: List[str]) -> Dict[str, str]:
|
||||
"""Assess threat levels for each competitor."""
|
||||
threat_levels = {}
|
||||
|
||||
# Simple heuristic based on AI analysis content
|
||||
for competitor in competitors:
|
||||
if competitor.lower() in ai_analysis.lower():
|
||||
if any(word in ai_analysis.lower() for word in ['dominant', 'leader', 'strong', 'established']):
|
||||
threat_levels[competitor] = 'High'
|
||||
elif any(word in ai_analysis.lower() for word in ['weak', 'vulnerable', 'gaps', 'opportunity']):
|
||||
threat_levels[competitor] = 'Low'
|
||||
else:
|
||||
threat_levels[competitor] = 'Medium'
|
||||
else:
|
||||
threat_levels[competitor] = 'Medium' # Default
|
||||
|
||||
return threat_levels
|
||||
|
||||
def _extract_opportunities(self, ai_analysis: str) -> List[str]:
|
||||
"""Extract opportunities from AI analysis."""
|
||||
opportunities = []
|
||||
|
||||
# Look for opportunity-related keywords
|
||||
opportunity_keywords = ['opportunity', 'gap', 'underserved', 'missing', 'lack', 'could', 'should']
|
||||
|
||||
lines = ai_analysis.split('\n')
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if any(keyword in line.lower() for keyword in opportunity_keywords) and len(line) > 30:
|
||||
opportunities.append(line.lstrip('•-* ').strip())
|
||||
|
||||
return opportunities[:6] # Return top 6 opportunities
|
||||
|
||||
def _extract_priority_gaps(self, content_analysis: str) -> List[str]:
|
||||
"""Extract priority content gaps."""
|
||||
gaps = []
|
||||
|
||||
# Look for gaps in the analysis
|
||||
gap_keywords = ['gap', 'missing', 'lack', 'absent', 'underserved', 'neglected']
|
||||
|
||||
lines = content_analysis.split('\n')
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if any(keyword in line.lower() for keyword in gap_keywords) and len(line) > 20:
|
||||
gaps.append(line.lstrip('•-* ').strip())
|
||||
|
||||
return gaps[:5] # Top 5 priority gaps
|
||||
|
||||
def _extract_content_quick_wins(self, content_analysis: str) -> List[str]:
|
||||
"""Extract content quick wins."""
|
||||
quick_wins = []
|
||||
|
||||
# Look for quick win indicators
|
||||
quick_keywords = ['quick', 'easy', 'simple', 'immediately', 'now', 'today']
|
||||
|
||||
lines = content_analysis.split('\n')
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if any(keyword in line.lower() for keyword in quick_keywords) and len(line) > 15:
|
||||
quick_wins.append(line.lstrip('•-* ').strip())
|
||||
|
||||
return quick_wins[:4] # Top 4 quick wins
|
||||
|
||||
def _extract_differentiation_opps(self, content_analysis: str) -> List[str]:
|
||||
"""Extract differentiation opportunities."""
|
||||
diff_opps = []
|
||||
|
||||
# Look for differentiation keywords
|
||||
diff_keywords = ['different', 'unique', 'innovative', 'better', 'superior', 'distinct']
|
||||
|
||||
lines = content_analysis.split('\n')
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if any(keyword in line.lower() for keyword in diff_keywords) and len(line) > 20:
|
||||
diff_opps.append(line.lstrip('•-* ').strip())
|
||||
|
||||
return diff_opps[:4] # Top 4 differentiation opportunities
|
||||
|
||||
def _parse_strategic_recommendations(self, recommendations: str) -> List[Dict[str, Any]]:
|
||||
"""Parse strategic recommendations into structured format."""
|
||||
structured_recs = []
|
||||
|
||||
# Split by sections and parse
|
||||
sections = recommendations.split('\n\n')
|
||||
|
||||
for section in sections:
|
||||
lines = section.split('\n')
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line and len(line) > 30: # Substantial recommendations
|
||||
structured_recs.append({
|
||||
'category': 'Strategic Recommendation',
|
||||
'priority': 'Medium', # Default
|
||||
'timeframe': 'Short-term',
|
||||
'action': line.lstrip('•-* ').strip()[:300], # Limit length
|
||||
'expected_impact': 'Competitive advantage',
|
||||
'resources_needed': 'Time and effort',
|
||||
'success_metrics': 'Market position improvement'
|
||||
})
|
||||
|
||||
return structured_recs[:10] # Return top 10 recommendations
|
||||
|
||||
def _extract_quick_wins(self, recommendations: List[Dict[str, Any]]) -> List[Dict[str, str]]:
|
||||
"""Extract quick wins from recommendations."""
|
||||
quick_wins = []
|
||||
|
||||
for rec in recommendations:
|
||||
action = rec.get('action', '').lower()
|
||||
if any(word in action for word in ['quick', 'immediate', 'now', 'today', 'easy', 'simple']):
|
||||
quick_wins.append({
|
||||
'action': rec.get('action', ''),
|
||||
'timeframe': rec.get('timeframe', '0-30 days'),
|
||||
'impact': rec.get('expected_impact', 'Quick improvement')
|
||||
})
|
||||
|
||||
# Add some default quick wins if none found
|
||||
if len(quick_wins) < 3:
|
||||
quick_wins.extend([
|
||||
{
|
||||
'action': 'Create content addressing competitor blind spots',
|
||||
'timeframe': '1-2 weeks',
|
||||
'impact': 'Immediate traffic from underserved topics'
|
||||
},
|
||||
{
|
||||
'action': 'Optimize social media with competitor hashtag gaps',
|
||||
'timeframe': '1 week',
|
||||
'impact': 'Better discoverability'
|
||||
},
|
||||
{
|
||||
'action': 'Set up Google Alerts for competitor mentions',
|
||||
'timeframe': '1 day',
|
||||
'impact': 'Real-time competitive intelligence'
|
||||
}
|
||||
])
|
||||
|
||||
return quick_wins[:5] # Top 5 quick wins
|
||||
|
||||
def _analyze_positioning(self, ai_insights: Dict[str, Any], your_strengths: List[str]) -> Dict[str, Any]:
|
||||
"""Analyze competitive positioning."""
|
||||
return {
|
||||
'your_advantages': your_strengths or ['Agility', 'Personal touch', 'Niche focus'],
|
||||
'competitor_weaknesses': ai_insights.get('opportunities', [])[:3],
|
||||
'positioning_strategy': 'Focus on agility and personal service vs big competitors',
|
||||
'unique_value_prop': 'Personalized solutions that big players can\'t match'
|
||||
}
|
||||
|
||||
def get_analysis_summary(self) -> Dict[str, Any]:
|
||||
"""Get summary of analysis activities."""
|
||||
return {
|
||||
'total_analyses': len(self.analysis_history),
|
||||
'recent_analyses': self.analysis_history[-3:] if self.analysis_history else [],
|
||||
'capabilities': [
|
||||
'AI-powered competitive insights',
|
||||
'Content gap analysis',
|
||||
'Strategic recommendations',
|
||||
'Quick win identification',
|
||||
'Positioning strategy'
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
# Streamlit interface for AI competitive intelligence
|
||||
def render_ai_competitive_intelligence_ui():
|
||||
"""Render the AI competitive intelligence interface."""
|
||||
st.title("🥷 AI Competitive Intelligence")
|
||||
st.markdown("AI-powered competitive analysis for solo entrepreneurs and bootstrapped startups")
|
||||
|
||||
# Initialize intelligence engine
|
||||
if 'ai_intel' not in st.session_state:
|
||||
st.session_state.ai_intel = AICompetitiveIntelligence()
|
||||
|
||||
intel_engine = st.session_state.ai_intel
|
||||
|
||||
# Input section
|
||||
st.header("🎯 Competitor Analysis Setup")
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
|
||||
with col1:
|
||||
industry = st.text_input(
|
||||
"Your Industry/Niche",
|
||||
value="AI Content Creation",
|
||||
help="What industry are you competing in?"
|
||||
)
|
||||
|
||||
competitor_urls = st.text_area(
|
||||
"Competitor URLs (one per line)",
|
||||
value="https://jasper.ai\nhttps://copy.ai\nhttps://writesonic.com",
|
||||
height=100,
|
||||
help="Enter competitor websites to analyze"
|
||||
)
|
||||
|
||||
with col2:
|
||||
your_strengths = st.text_area(
|
||||
"Your Current Strengths (optional)",
|
||||
value="Personal touch, Agility, Niche expertise",
|
||||
height=100,
|
||||
help="What are your competitive advantages?"
|
||||
)
|
||||
|
||||
# Process inputs
|
||||
urls = [url.strip() for url in competitor_urls.split('\n') if url.strip()]
|
||||
strengths = [s.strip() for s in your_strengths.split(',') if s.strip()] if your_strengths else []
|
||||
|
||||
if st.button("🧠 Analyze Competitors", type="primary"):
|
||||
if urls and industry:
|
||||
with st.spinner("🕵️ AI is analyzing your competition..."):
|
||||
results = asyncio.run(
|
||||
intel_engine.analyze_competitors(urls, industry, strengths)
|
||||
)
|
||||
|
||||
if 'error' not in results:
|
||||
st.success("✅ Competitive analysis complete!")
|
||||
|
||||
# Analysis overview
|
||||
metadata = results.get('analysis_metadata', {})
|
||||
st.header("📊 Analysis Overview")
|
||||
|
||||
col1, col2, col3 = st.columns(3)
|
||||
with col1:
|
||||
st.metric("Competitors Analyzed", metadata.get('competitors_analyzed', 0))
|
||||
with col2:
|
||||
st.metric("Industry", metadata.get('industry', 'N/A'))
|
||||
with col3:
|
||||
st.metric("Your Strengths", len(metadata.get('your_strengths', [])))
|
||||
|
||||
# Quick wins first (most important for bootstrapped entrepreneurs)
|
||||
quick_wins = results.get('quick_wins', [])
|
||||
if quick_wins:
|
||||
st.header("🚀 Quick Wins (Do These First!)")
|
||||
|
||||
for i, win in enumerate(quick_wins):
|
||||
with st.expander(f"Quick Win #{i+1}: {win.get('timeframe', 'N/A')}"):
|
||||
st.write(f"**Action:** {win.get('action', 'N/A')}")
|
||||
st.write(f"**Expected Impact:** {win.get('impact', 'N/A')}")
|
||||
st.write(f"**Timeframe:** {win.get('timeframe', 'N/A')}")
|
||||
|
||||
# Key competitive insights
|
||||
insights = results.get('competitor_insights', {})
|
||||
if insights:
|
||||
st.header("🧠 AI Competitive Insights")
|
||||
|
||||
key_insights = insights.get('key_insights', [])
|
||||
for insight in key_insights[:5]:
|
||||
st.info(f"💡 {insight}")
|
||||
|
||||
# Threat levels
|
||||
threat_levels = insights.get('threat_levels', {})
|
||||
if threat_levels:
|
||||
st.subheader("⚠️ Competitor Threat Assessment")
|
||||
|
||||
for competitor, threat in threat_levels.items():
|
||||
color = {'High': '🔴', 'Medium': '🟡', 'Low': '🟢'}.get(threat, '⚪')
|
||||
st.write(f"{color} **{competitor}**: {threat} threat level")
|
||||
|
||||
# Content opportunities
|
||||
content_opps = results.get('content_gap_analysis', {})
|
||||
if content_opps:
|
||||
st.header("✍️ Content Opportunities")
|
||||
|
||||
priority_gaps = content_opps.get('priority_gaps', [])
|
||||
if priority_gaps:
|
||||
st.subheader("🎯 Priority Content Gaps")
|
||||
for gap in priority_gaps[:4]:
|
||||
st.write(f"• {gap}")
|
||||
|
||||
quick_content_wins = content_opps.get('quick_wins', [])
|
||||
if quick_content_wins:
|
||||
st.subheader("⚡ Quick Content Wins")
|
||||
for win in quick_content_wins[:3]:
|
||||
st.write(f"• {win}")
|
||||
|
||||
# Strategic recommendations
|
||||
recommendations = results.get('ai_recommendations', [])
|
||||
if recommendations:
|
||||
st.header("🎯 Strategic Recommendations")
|
||||
|
||||
for i, rec in enumerate(recommendations[:6]):
|
||||
with st.expander(f"Strategy #{i+1}: {rec.get('category', 'Strategic Move')}"):
|
||||
st.write(f"**Action:** {rec.get('action', 'N/A')}")
|
||||
st.write(f"**Timeframe:** {rec.get('timeframe', 'N/A')}")
|
||||
st.write(f"**Expected Impact:** {rec.get('expected_impact', 'N/A')}")
|
||||
st.write(f"**Priority:** {rec.get('priority', 'Medium')}")
|
||||
|
||||
# Competitive positioning
|
||||
positioning = results.get('competitive_positioning', {})
|
||||
if positioning:
|
||||
st.header("🏆 Your Competitive Position")
|
||||
|
||||
st.subheader("Your Key Advantages:")
|
||||
for advantage in positioning.get('your_advantages', []):
|
||||
st.write(f"✅ {advantage}")
|
||||
|
||||
st.subheader("Competitor Weaknesses to Exploit:")
|
||||
for weakness in positioning.get('competitor_weaknesses', []):
|
||||
st.write(f"🎯 {weakness}")
|
||||
|
||||
# Full AI analysis
|
||||
with st.expander("🤖 Complete AI Analysis"):
|
||||
ai_analysis = insights.get('full_analysis', 'No detailed analysis available')
|
||||
st.write(ai_analysis)
|
||||
|
||||
# Export functionality
|
||||
st.subheader("📥 Export Analysis")
|
||||
if st.button("Download Report"):
|
||||
report_json = json.dumps(results, indent=2, default=str)
|
||||
st.download_button(
|
||||
label="Download JSON Report",
|
||||
data=report_json,
|
||||
file_name=f"competitor_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
||||
mime="application/json"
|
||||
)
|
||||
|
||||
else:
|
||||
st.error(f"❌ Analysis failed: {results.get('error')}")
|
||||
else:
|
||||
st.warning("⚠️ Please provide competitor URLs and industry information")
|
||||
|
||||
# Sidebar with tips
|
||||
st.sidebar.header("💡 AI Competition Tips")
|
||||
st.sidebar.info("""
|
||||
**David vs Goliath Strategies:**
|
||||
|
||||
• Focus on what big competitors can't do
|
||||
• Be more personal and responsive
|
||||
• Serve niche audiences they ignore
|
||||
• Move faster than they can
|
||||
• Provide better customer service
|
||||
• Build deeper relationships
|
||||
• Innovate in areas they neglect
|
||||
""")
|
||||
|
||||
# Analysis history
|
||||
summary = intel_engine.get_analysis_summary()
|
||||
st.sidebar.metric("Total Analyses", summary.get('total_analyses', 0))
|
||||
|
||||
|
||||
# Main execution
|
||||
if __name__ == "__main__":
|
||||
render_ai_competitive_intelligence_ui()
|
||||
Reference in New Issue
Block a user