LinkedIn AI Writer features like carousel, video script, and comment response generator

This commit is contained in:
ajaysi
2025-04-14 22:34:10 +05:30
parent dd9a9e5f09
commit d4f1fc77a1
49 changed files with 7636 additions and 88 deletions

View File

@@ -38,7 +38,7 @@ from lib.alwrity_ui.display_google_serp_results import (
)
from lib.alwrity_ui.google_trends_ui import display_google_trends_data, process_trends_data
from .tavily_ai_search import get_tavilyai_results
from .tavily_ai_search import do_tavily_ai_search
from .metaphor_basic_neural_web_search import metaphor_search_articles, streamlit_display_metaphor_results
from .google_serp_search import google_search
from .google_trends_researcher import do_google_trends_analysis
@@ -148,8 +148,8 @@ def gpt_web_researcher(search_keywords, search_mode, **kwargs):
include_domains = kwargs.pop('include_domains', None)
search_depth = kwargs.pop('search_depth', 'advanced')
# Pass the parameters to get_tavilyai_results
t_results = get_tavilyai_results(
# Pass the parameters to do_tavily_ai_search
t_results = do_tavily_ai_search(
keywords=search_keywords,
max_results=kwargs.get('num_results', 10),
include_domains=include_domains,
@@ -343,8 +343,8 @@ def do_tavily_ai_search(search_keywords, max_results=10, **kwargs):
'include_domains': kwargs.get('include_domains', [""]) if kwargs.get('include_domains') else [""]
}
# Pass the parameters to get_tavilyai_results
t_results = get_tavilyai_results(
# Pass the parameters to do_tavily_ai_search
t_results = do_tavily_ai_search(
keywords=search_keywords,
**tavily_params
)

View File

@@ -16,7 +16,7 @@ Usage:
Modifications:
- To modify the script, update the environment variables in the .env file with the required API keys.
- Adjust the search parameters, such as keywords and search depth, in the `get_tavilyai_results` function as needed.
- Adjust the search parameters, such as keywords and search depth, in the `do_tavily_ai_search` function as needed.
- Customize logging configurations and table formatting according to preferences.
To-Do (TBD):
@@ -49,7 +49,7 @@ from tenacity import retry, stop_after_attempt, wait_random_exponential
@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def get_tavilyai_results(keywords, max_results=5, include_domains=None, search_depth="advanced", **kwargs):
def do_tavily_ai_search(keywords, max_results=5, include_domains=None, search_depth="advanced", **kwargs):
"""
Get Tavily AI search results based on specified keywords and options.
"""

View File

@@ -1,76 +0,0 @@
import time #Iwish
import os
import json
import requests
import streamlit as st
from ..gpt_providers.text_generation.main_text_generation import llm_text_gen
from ..ai_web_researcher.gpt_online_researcher import do_google_serp_search
def linked_post_writer():
# Title and description
st.title("✍️ Alwrity - AI Linkedin Blog Post Generator")
# Input section
with st.expander("**PRO-TIP** - Read the instructions below.", expanded=True):
input_blog_keywords = st.text_input('**Enter main keywords of your Post!** (2-3 words that defines your blog)')
col1, col2, space, col3 = st.columns([5, 5, 0.5, 5])
with col1:
input_linkedin_type = st.selectbox('Post Type', ('General', 'How-to Guides', 'Polls', 'Listicles',
'Reality check posts', 'Job Posts', 'FAQs', 'Checklists/Cheat Sheets'), index=0)
with col2:
input_linkedin_length = st.selectbox('Post Length', ('1000 words', 'Long Form', 'Short form'), index=0)
with col3:
input_linkedin_language = st.selectbox('Choose Language', ('English', 'Vietnamese',
'Chinese', 'Hindi', 'Spanish'), index=0)
# Generate Blog FAQ button
if st.button('**Get LinkedIn Post**'):
with st.spinner():
# Clicking without providing data, really ?
if not input_blog_keywords:
st.error('** 🫣Provide Inputs to generate Blinkedin Post. Keywords, required!**')
elif input_blog_keywords:
linkedin_post = generate_linkedin_post(input_blog_keywords, input_linkedin_type,
input_linkedin_length, input_linkedin_language)
if linkedin_post:
st.subheader('**🧕🔬👩 Go Rule LinkedIn with this Blog Post!**')
st.write(linkedin_post)
st.write("\n\n\n")
else:
st.error("💥**Failed to generate linkedin Post. Please try again!**")
# Function to generate blog metadesc
def generate_linkedin_post(input_blog_keywords, input_linkedin_type, input_linkedin_length, input_linkedin_language):
""" Function to call upon LLM to get the work done. """
# Fetch SERP results & PAA questions for FAQ.
serp_results, people_also_ask = do_google_serp_search(input_blog_keywords)
# If keywords and content both are given.
if serp_results:
prompt = f"""As an Experienced, industry veteran and experienced linkedin content writer,
I will provide you with my 'blog keywords' and 'google serp results' done for the keywords.
Your task is to write a detailed linkedin post, using given keywords and search results.
Follow below guidelines for generating the linkedin post:
1). Write a title, introduction, sections, faqs and a conclusion for the post.
2). Your FAQ should be based on 'People also ask' and 'Related Queries' from given serp results.
3). Maintain consistent voice of tone, keep the sentence short and simple.
4). Make sure to include important results from the given google serp results.
5). Optimise your response for blog type of {input_linkedin_type}.
6). Important to provide your response in {input_linkedin_language} language.\n
Your final response should demostrate Experience, Expertise, Authoritativeness, and Trustworthiness.
blog keywords: \'\'\'{input_blog_keywords}\'\'\'
google serp results: \'\'\'{serp_results}\'\'\'
"""
try:
response = llm_text_gen(prompt)
return response
except Exception as err:
st.error(f"Failed to generate Open Graph tags: {err}")
return None

View File

@@ -0,0 +1,20 @@
"""
LinkedIn AI Writer Module
This module provides a comprehensive suite of tools for generating LinkedIn content.
"""
from .linkedin_ai_writer import linkedin_main_menu, LinkedInAIWriter
from .modules.post_generator.linkedin_post_generator import linkedin_post_generator_ui, LinkedInPostGenerator
from .modules.article_generator.linkedin_article_generator import linkedin_article_generator_ui
from .modules.carousel_generator.linkedin_carousel_generator import linkedin_carousel_generator_ui, LinkedInCarouselGenerator
__all__ = [
'linkedin_main_menu',
'LinkedInAIWriter',
'linkedin_post_generator_ui',
'LinkedInPostGenerator',
'linkedin_article_generator_ui',
'linkedin_carousel_generator_ui',
'LinkedInCarouselGenerator'
]

View File

@@ -0,0 +1,544 @@
"""
LinkedIn AI Writer
This module provides a comprehensive suite of tools for generating LinkedIn content.
"""
import time
import os
import json
import requests
import streamlit as st
import importlib
import sys
from pathlib import Path
from typing import Dict, List, Optional, Union
from loguru import logger
# Import AI text generation
from ...gpt_providers.text_generation.main_text_generation import llm_text_gen
# Import web research tools
from ...ai_web_researcher.gpt_online_researcher import do_google_serp_search
from ...ai_web_researcher.metaphor_basic_neural_web_search import metaphor_search_articles, streamlit_display_metaphor_results
from ...ai_web_researcher.tavily_ai_search import do_tavily_ai_search, streamlit_display_results
# Import LinkedIn content generators
from .modules.post_generator.linkedin_post_generator import linkedin_post_generator_ui
from .modules.article_generator.linkedin_article_generator import linkedin_article_generator_ui
from .modules.carousel_generator.linkedin_carousel_generator import linkedin_carousel_generator_ui
from .modules.video_script_generator.linkedin_video_script_generator import linkedin_video_script_generator_ui
# Import image generation
from ...gpt_providers.text_to_image_generation.main_generate_image_from_prompt import generate_image
def linkedin_main_menu():
"""Main function for the LinkedIn AI Writer."""
# Initialize session state for selected tool if it doesn't exist
if "selected_tool" not in st.session_state:
st.session_state.selected_tool = None
# Define the LinkedIn tools with their details
linkedin_tools = [
# Content Creation Tools
{
"name": "LinkedIn Post Generator",
"icon": "📝",
"description": "Create engaging, professional posts that drive engagement and establish thought leadership.",
"color": "#0A66C2", # LinkedIn blue
"category": "Content Creation",
"function": linkedin_post_generator_ui,
"status": "active",
"features": [
"Professional tone customization",
"Industry-specific terminology",
"Hashtag optimization",
"Formatting options",
"Character count optimization",
"Call-to-action suggestions",
"Engagement prediction",
"Visual content recommendations",
"Poll creation",
"Best posting time suggestions",
"Research-backed content",
"Reference tracking"
]
},
{
"name": "LinkedIn Article Generator",
"icon": "📄",
"description": "Generate long-form professional articles that showcase expertise and drive traffic.",
"color": "#0A66C2",
"category": "Content Creation",
"function": linkedin_article_generator_ui,
"status": "active",
"features": [
"Topic research and outline generation",
"SEO optimization for LinkedIn articles",
"Professional writing style adaptation",
"Section structuring",
"Citation and reference formatting",
"Image placement suggestions",
"Headline optimization",
"Meta description generation",
"Reading time estimation",
"Internal linking suggestions",
"Multiple research sources (Metaphor, Google, Tavily)",
"AI-generated section images"
]
},
{
"name": "LinkedIn Carousel Post Generator",
"icon": "🔄",
"description": "Create engaging carousel posts that showcase information in a visually appealing way.",
"color": "#0A66C2",
"category": "Content Creation",
"function": linkedin_carousel_generator_ui,
"status": "active",
"features": [
"Slide content generation",
"Visual hierarchy optimization",
"Story arc development",
"Call-to-action placement",
"Brand consistency maintenance",
"Engagement element integration",
"Professional design suggestions",
"Content distribution strategy",
"Analytics integration",
"A/B testing variations"
]
},
{
"name": "LinkedIn Video Script Generator",
"icon": "🎥",
"description": "Create scripts for LinkedIn videos that drive engagement.",
"color": "#0A66C2",
"category": "Content Creation",
"function": linkedin_video_script_generator_ui,
"status": "active",
"features": [
"Hook generation",
"Story structure development",
"Professional speaking points",
"Visual cue suggestions",
"Call-to-action optimization",
"Engagement prompt integration",
"Caption generation",
"Thumbnail text suggestions",
"Video description optimization",
"Hashtag strategy"
]
},
# Profile & Personal Branding Tools
{
"name": "LinkedIn Profile Optimizer",
"icon": "👤",
"description": "Enhance LinkedIn profiles to improve visibility and professional appeal.",
"color": "#0A66C2",
"category": "Profile & Personal Branding",
"function": None,
"status": "coming_soon",
"features": [
"Headline optimization",
"About section generation",
"Experience description enhancement",
"Skills recommendation",
"Project highlight creation",
"Endorsement request generation",
"Profile strength analysis",
"Keyword optimization",
"Professional summary generation",
"Custom URL suggestions"
]
},
{
"name": "LinkedIn Poll Generator",
"icon": "📊",
"description": "Create engaging polls that drive interaction and gather insights.",
"color": "#0A66C2",
"category": "Profile & Personal Branding",
"function": None,
"status": "coming_soon",
"features": [
"Question formulation optimization",
"Option generation based on topic",
"Industry-specific poll templates",
"Engagement prediction",
"Result analysis suggestions",
"Follow-up content recommendations",
"Trending topic integration",
"Professional tone maintenance",
"Data visualization suggestions",
"Poll scheduling optimization"
]
},
# Business & Marketing Tools
{
"name": "LinkedIn Company Page Content Generator",
"icon": "🏢",
"description": "Create content for company pages that builds brand awareness and engagement.",
"color": "#0A66C2",
"category": "Business & Marketing",
"function": None,
"status": "coming_soon",
"features": [
"Company culture post generation",
"Product/service announcement templates",
"Employee spotlight content",
"Company milestone celebrations",
"Industry insights sharing",
"Event promotion content",
"Job posting templates",
"Company news updates",
"Brand voice consistency",
"Engagement metrics optimization"
]
},
{
"name": "LinkedIn Newsletter Generator",
"icon": "📰",
"description": "Create professional newsletters that establish thought leadership and drive engagement.",
"color": "#0A66C2",
"category": "Business & Marketing",
"function": None,
"status": "coming_soon",
"features": [
"Newsletter structure templates",
"Topic clustering and organization",
"Professional introduction and conclusion",
"Industry trend analysis integration",
"Expert quote suggestions",
"Visual content recommendations",
"Call-to-action optimization",
"Subscriber engagement prompts",
"Consistency maintenance",
"Analytics integration suggestions"
]
},
{
"name": "LinkedIn Job Description Generator",
"icon": "💼",
"description": "Create compelling job descriptions that attract qualified candidates.",
"color": "#0A66C2",
"category": "Business & Marketing",
"function": None,
"status": "coming_soon",
"features": [
"Role-specific templates",
"Skills and qualifications optimization",
"Company culture integration",
"Benefits and perks highlighting",
"Inclusive language checker",
"Keyword optimization",
"Application process clarity",
"Remote/hybrid work policy integration",
"Diversity and inclusion statements",
"A/B testing variations"
]
},
# Sales & Networking Tools
{
"name": "LinkedIn Sales Navigator Content Generator",
"icon": "💰",
"description": "Create personalized outreach content for sales professionals.",
"color": "#0A66C2",
"category": "Sales & Networking",
"function": None,
"status": "coming_soon",
"features": [
"Prospect research integration",
"Industry-specific messaging",
"Personalization tokens",
"Connection request templates",
"Follow-up message sequences",
"Value proposition highlighting",
"Objection handling responses",
"Meeting request templates",
"Industry pain point addressing",
"ROI demonstration content"
]
},
{
"name": "LinkedIn InMail Generator",
"icon": "✉️",
"description": "Create personalized and effective InMail messages.",
"color": "#0A66C2",
"category": "Sales & Networking",
"function": None,
"status": "coming_soon",
"features": [
"Prospect research integration",
"Personalization token usage",
"Value proposition highlighting",
"Call-to-action optimization",
"Follow-up sequence generation",
"Objection handling preparation",
"Industry-specific messaging",
"A/B testing variations",
"Compliance checking",
"Engagement tracking suggestions"
]
},
# Learning & Education Tools
{
"name": "LinkedIn Learning Course Description Generator",
"icon": "📚",
"description": "Create compelling descriptions for LinkedIn Learning courses.",
"color": "#0A66C2",
"category": "Learning & Education",
"function": None,
"status": "coming_soon",
"features": [
"Course objective optimization",
"Learning outcome generation",
"Prerequisite suggestions",
"Target audience definition",
"Skill tag recommendations",
"Course structure outline",
"Engagement element suggestions",
"Completion certificate highlighting",
"Industry relevance emphasis",
"Career path integration"
]
},
{
"name": "LinkedIn Event Description Generator",
"icon": "📅",
"description": "Create compelling event descriptions that drive attendance and engagement.",
"color": "#0A66C2",
"category": "Learning & Education",
"function": None,
"status": "coming_soon",
"features": [
"Event objective highlighting",
"Speaker bio generation",
"Agenda formatting",
"Registration incentive suggestions",
"Networking opportunity emphasis",
"Industry relevance integration",
"Visual content recommendations",
"Engagement element suggestions",
"Post-event follow-up content",
"Attendance tracking integration"
]
},
# Community & Engagement Tools
{
"name": "LinkedIn Group Post Generator",
"icon": "👥",
"description": "Create content specifically optimized for LinkedIn Groups.",
"color": "#0A66C2",
"category": "Community & Engagement",
"function": None,
"status": "coming_soon",
"features": [
"Group-specific content adaptation",
"Discussion prompt generation",
"Community guideline compliance",
"Engagement optimization",
"Moderation suggestion",
"Topic relevance checking",
"Member value highlighting",
"Cross-promotion opportunities",
"Group culture adaptation",
"Content scheduling"
]
},
{
"name": "LinkedIn Comment Response Generator",
"icon": "💬",
"description": "Create professional and engaging responses to comments on LinkedIn posts.",
"color": "#0A66C2",
"category": "Community & Engagement",
"function": None,
"status": "coming_soon",
"features": [
"Tone adaptation based on comment",
"Professional disagreement handling",
"Question answering optimization",
"Engagement continuation prompts",
"Value-add response generation",
"Community building suggestions",
"Moderation guidance",
"Follow-up question generation",
"Resource sharing suggestions",
"Relationship building strategies"
]
}
]
# Create a container for the dashboard
dashboard_container = st.container()
# Create a container for the tool input section
tool_container = st.container()
# If a tool is selected, show its input section
if st.session_state.selected_tool is not None:
with tool_container:
# Add a back button at the top
if st.button("← Back to Dashboard", key="back_to_dashboard"):
st.session_state.selected_tool = None
st.rerun()
# Display the tool header with card layout
st.markdown(f"""
<div style='
background: linear-gradient(145deg, #ffffff 0%, #f0f7ff 50%, #e6f0ff 100%);
padding: 2.5rem;
border-radius: 16px;
box-shadow: 0 10px 25px rgba(10, 102, 194, 0.08);
margin: 1rem 0 2.5rem 0;
border: 1px solid rgba(10, 102, 194, 0.1);
'>
<div style='
display: flex;
align-items: center;
margin-bottom: 1.2rem;
background: rgba(255, 255, 255, 0.8);
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 4px 15px rgba(10, 102, 194, 0.05);
'>
<div style='
font-size: 2.5rem;
margin-right: 1rem;
color: #0A66C2;
'>{st.session_state.selected_tool['icon']}</div>
<div>
<h1 style='
margin: 0;
color: #0A66C2;
font-size: 2.2rem;
font-weight: 600;
'>{st.session_state.selected_tool['name']}</h1>
<p style='
color: #666;
margin: 0.5rem 0 0 0;
font-size: 1.1rem;
line-height: 1.5;
'>{st.session_state.selected_tool['description']}</p>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Call the tool's function if it exists
if st.session_state.selected_tool["function"] is not None:
st.session_state.selected_tool["function"]()
else:
# Display coming soon information
st.info(f"**{st.session_state.selected_tool['status'].replace('_', ' ').title()}!**")
st.write(st.session_state.selected_tool["description"])
# Display features
st.subheader("Features")
for feature in st.session_state.selected_tool["features"]:
st.markdown(f"- {feature}")
# Display placeholder image
st.image(f"https://via.placeholder.com/600x300?text={st.session_state.selected_tool['name']}+Coming+Soon", use_container_width=True)
else:
with dashboard_container:
# Display the dashboard
# Header
st.markdown("""
<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px; margin-bottom: 10px;'>
<h1 style='color: #0A66C2; text-align: center;'>💼 LinkedIn AI Writer</h1>
<p style='text-align: center;'>Generate professional LinkedIn content with ALwrity's AI-powered tools</p>
</div>
""", unsafe_allow_html=True)
# Group tools by category
categories = {}
for tool in linkedin_tools:
category = tool["category"]
if category not in categories:
categories[category] = []
categories[category].append(tool)
# Display tools by category
for category, tools in categories.items():
st.markdown(f"## {category}")
# Create a 3-column layout for the tool cards
cols = st.columns(3)
# Display the tool cards
for i, tool in enumerate(tools):
# Determine which column to use
col = cols[i % 3]
with col:
# Create a card for each tool
status_badge = ""
if tool["status"] == "coming_soon":
status_badge = "<span style='background-color: #FFA500; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;'>Coming Soon</span>"
elif tool["status"] == "future":
status_badge = "<span style='background-color: #808080; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;'>Future</span>"
elif tool["status"] == "active":
status_badge = "<span style='background-color: #4CAF50; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;'>Active</span>"
st.markdown(f"""
<div style='background-color: {tool["color"]}; padding: 20px; border-radius: 10px; margin-bottom: 20px; color: white;'>
<h2 style='color: white;'>{tool["icon"]} {tool["name"]} {status_badge}</h2>
<p>{tool["description"]}</p>
</div>
""", unsafe_allow_html=True)
# Add a button to access the tool
if st.button(f"Use {tool['name']}", key=f"btn_{tool['name']}"):
# Store the selected tool in session state
st.session_state.selected_tool = tool
st.rerun()
class LinkedInAIWriter:
"""
AI-powered content generator for LinkedIn marketing and communication.
This class provides various tools for generating LinkedIn content including:
- Posts and articles
- Profile optimization
- Company page content
- Sales and networking content
- Learning and education content
- Community and engagement content
"""
def __init__(self):
"""Initialize the LinkedIn AI Writer."""
pass
# Methods will be implemented in future iterations
# Each method will correspond to a specific LinkedIn content generation tool
# List of available tools
AVAILABLE_TOOLS = [
'Post Generator',
'Article Generator',
'Carousel Post Generator',
'Video Script Generator',
'Profile Optimizer',
'Poll Generator',
'Company Page Content Generator',
'Newsletter Generator',
'Job Description Generator',
'Sales Navigator Content Generator',
'InMail Generator',
'Learning Course Description Generator',
'Event Description Generator',
'Group Post Generator',
'Comment Response Generator'
]
if __name__ == "__main__":
linkedin_main_menu()

View File

@@ -0,0 +1,17 @@
"""
LinkedIn AI Writer Modules
This package contains various modules for generating different types of LinkedIn content.
"""
from .post_generator.linkedin_post_generator import linkedin_post_generator_ui, LinkedInPostGenerator
from .article_generator.linkedin_article_generator import linkedin_article_generator_ui
from .carousel_generator.linkedin_carousel_generator import linkedin_carousel_generator_ui, LinkedInCarouselGenerator
__all__ = [
'linkedin_post_generator_ui',
'LinkedInPostGenerator',
'linkedin_article_generator_ui',
'linkedin_carousel_generator_ui',
'LinkedInCarouselGenerator'
]

View File

@@ -0,0 +1,253 @@
# LinkedIn Article Generator 📝
A powerful AI-powered tool designed specifically for LinkedIn content creators to generate professional, research-backed articles that engage and provide value to your professional network.
## 🌟 Key Features
### Content Generation
- **AI-Powered Research**: Integrates with multiple search engines (Metaphor, Google, Tavily) for up-to-date, accurate content
- **Professional Writing**: Generates industry-specific content with expert insights and statistics
- **Topic-Focused Content**: Ensures all content stays relevant to your chosen topic without AI explanations or meta-commentary
- **SEO Optimization**: Built-in SEO tools for maximum visibility
- **Image Generation**: AI-powered visuals for article header and sections
### Research Integration
- **Multi-Source Research**: Choose from Metaphor AI, Google Search, or Tavily AI
- **Real-Time Data**: Access current industry trends and statistics
- **Expert Insights**: Incorporate professional perspectives and quotes
- **Fact-Checking**: Web-researched context to prevent AI hallucinations
### Visual Enhancement
- **Topic Images**: Generate professional header images
- **Section Visuals**: Create relevant images for each section
- **Image Refinement**: Edit and regenerate images until perfect
- **Custom Prompts**: Write your own image generation prompts
## 🚀 Getting Started
### 1. Article Generation Process
#### Step 1: Topic Input
- Enter your article topic
- Select your industry
- Choose writing tone:
- Professional
- Analytical
- Conversational
- Technical
- Thought Leadership
#### Step 2: Research Selection
Choose your preferred research source:
- 🔍 Metaphor AI: For comprehensive industry insights
- 🌐 Google Search: For broad topic coverage
- 🤖 Tavily AI: For focused, AI-curated research
#### Step 3: Content Generation
The tool will:
1. Research your topic thoroughly
2. Create a detailed outline
3. Generate comprehensive content
4. Add relevant statistics and quotes
5. Generate professional images
6. Optimize for SEO
### 2. Article Preview and Editing
#### Content Tab
- View the complete article
- Edit content directly
- Download in HTML format
- Copy to clipboard
#### Images & Visuals Tab
- Preview and regenerate topic image
- Edit image prompts
- Generate section-specific images
- Choose from alternative image suggestions
#### SEO & Metadata Tab
- Review focus keywords
- Edit meta descriptions
- Optimize article tags
- Customize social sharing text
## 💡 Best Practices
### 1. Topic Selection
- Choose specific, industry-relevant topics
- Focus on your area of expertise
- Consider current trends in your field
- Target your professional audience's needs
### 2. Content Structure
- Strong, attention-grabbing headlines
- Professional introduction
- Well-organized sections
- Clear takeaways
- Compelling call-to-action
### 3. Visual Strategy
- Professional, topic-relevant images
- Consistent visual style
- High-quality graphics
- Mobile-friendly visuals
## 🎯 Content Types
### Industry Insights
- Market analysis
- Trend reports
- Expert perspectives
- Case studies
### How-to Articles
- Step-by-step guides
- Best practices
- Implementation strategies
- Professional tips
### Thought Leadership
- Industry predictions
- Expert opinions
- Strategy discussions
- Innovation insights
## 📊 SEO Optimization
### Automatic Optimization
- Focus keyword selection
- Secondary keywords
- Meta descriptions
- Article tags
- Social sharing text
### Content Enhancement
- Keyword placement
- Header optimization
- Link suggestions
- Readability improvements
## 🛠️ Advanced Features
### Research Integration
- Multiple search engines
- Real-time data gathering
- Expert quote integration
- Statistical data inclusion
### Image Generation
- Custom prompt creation
- Style customization
- Alternative suggestions
- Section-specific visuals
### Content Export
- HTML format
- Clipboard copy
- Social media optimized
- SEO-ready structure
## 📱 Mobile Optimization
- Responsive images
- Readable text
- Optimized layout
- Cross-device compatibility
## 💪 Success Tips
### 1. Content Strategy
- Regular posting schedule
- Consistent topic focus
- Industry relevance
- Audience engagement
### 2. Visual Impact
- Professional imagery
- Brand consistency
- Visual storytelling
- Quality graphics
### 3. Engagement
- Compelling headlines
- Interactive elements
- Clear call-to-action
- Professional tone
## 🔍 Technical Details
### System Requirements
- Modern web browser
- Internet connection
- API access (if using custom keys)
### Performance
- Fast generation times
- Real-time preview
- Instant updates
- Smooth editing
## 📈 Best Use Cases
1. **Industry Analysis**
- Market trends
- Technology updates
- Business insights
- Professional perspectives
2. **Professional Guides**
- Best practices
- Implementation strategies
- Career development
- Skill enhancement
3. **Thought Leadership**
- Industry predictions
- Expert opinions
- Innovation insights
- Strategic analysis
## 🎨 Design Guidelines
1. **Visual Consistency**
- Brand colors
- Professional fonts
- Clean layouts
- Quality images
2. **Content Format**
- Clear headers
- Organized sections
- Professional tone
- Engaging structure
3. **Mobile Design**
- Responsive layout
- Readable text
- Optimized images
- Cross-device testing
## 🔄 Workflow Integration
1. **Content Planning**
- Topic research
- Outline creation
- Content generation
- Visual design
2. **Quality Control**
- Content review
- Image refinement
- SEO verification
- Final checks
3. **Publishing**
- Format selection
- Preview verification
- LinkedIn optimization
- Engagement tracking
---
Start creating professional LinkedIn articles that engage your network and establish your expertise! 🚀

View File

@@ -0,0 +1,281 @@
# LinkedIn Carousel Generator 🎯
An AI-powered tool designed specifically for LinkedIn content creators to generate engaging, visually stunning carousel posts that drive engagement and showcase expertise.
## ✨ Key Features
### Content Creation
- **AI-Powered Research**: Multi-source research integration (Metaphor, Google, Tavily)
- **Dynamic Slide Generation**: Auto-generation of 3-10 cohesive slides
- **Smart Content Structure**: Optimized flow from hook to call-to-action
- **Visual Content**: AI-generated professional visuals for each slide
- **Content Types**: How-to Guides, Lists, Stories, Case Studies, Tips & Tricks
### Visual Excellence
- **Professional Imagery**: Custom AI-generated visuals per slide
- **Brand Consistency**: Cohesive visual style across slides
- **Visual Hierarchy**: Optimized layout for maximum impact
- **Custom Styling**: Flexible design options for each slide
### Research Integration
- **Triple-Engine Research**:
- 🔍 Metaphor AI: Deep industry insights
- 🌐 Google Search: Comprehensive coverage
- 🤖 Tavily AI: Focused research
- **Real-Time Data**: Current trends and statistics
- **Expert Insights**: Professional quotes and perspectives
## 🚀 Getting Started
### 1. Carousel Creation Process
#### Initial Setup
- Choose your topic
- Select your industry
- Pick your content style:
- Professional
- Educational
- Conversational
- Inspiring
- Technical
#### Content Type Selection
Choose from:
- How-to Guide: Step-by-step instructions
- List: Curated points or tips
- Story: Narrative-driven content
- Case Study: Real-world examples
- Tips & Tricks: Quick, actionable advice
#### Slide Configuration
- Select number of slides (3-10)
- Choose research source
- Enable/disable features:
- Custom visuals
- Content optimization
- Research integration
### 2. Carousel Preview and Editing
#### Slide Navigation
- Previous/Next navigation
- Slide overview
- Individual slide editing
- Real-time preview
#### Content Editing
- Edit headings
- Modify subheadings
- Update main content
- Customize visuals
- Optimize text
#### Visual Customization
- Edit image prompts
- Generate new visuals
- Adjust style settings
- Preview changes
## 💡 Best Practices
### 1. Content Strategy
- **First Slide**
- Strong hook
- Clear value proposition
- Attention-grabbing visual
- Topic introduction
- **Middle Slides**
- Logical progression
- Supporting evidence
- Engaging visuals
- Clear explanations
- **Last Slide**
- Strong call-to-action
- Next steps
- Contact information
- Engagement prompt
### 2. Visual Strategy
- **Consistency**
- Cohesive style
- Brand colors
- Font hierarchy
- Layout patterns
- **Image Quality**
- Professional aesthetics
- Clear messaging
- Relevant visuals
- Brand alignment
### 3. Content Flow
- **Progression**
- Logical sequence
- Clear transitions
- Building complexity
- Cohesive narrative
## 📊 Content Types Guide
### How-to Guide
- Clear steps
- Visual instructions
- Progress indicators
- Action items
### List Format
- Clear numbering
- Consistent structure
- Visual hierarchy
- Easy scanning
### Story Format
- Engaging narrative
- Character elements
- Visual journey
- Emotional connection
### Case Study
- Problem statement
- Solution process
- Results/outcomes
- Key learnings
### Tips & Tricks
- Quick insights
- Actionable advice
- Visual examples
- Implementation guidance
## 🎨 Design Guidelines
### Visual Hierarchy
- **Headlines**
- Clear visibility
- Consistent sizing
- Impactful fonts
- Color contrast
- **Content Layout**
- Balanced design
- White space
- Reading flow
- Visual anchors
### Brand Elements
- **Style Guide**
- Color palette
- Typography
- Logo placement
- Visual elements
## 📱 Optimization
### Mobile View
- Text readability
- Image scaling
- Touch-friendly
- Quick loading
### Platform Specs
- LinkedIn dimensions
- File size limits
- Format requirements
- Quality standards
## 💪 Engagement Tips
### 1. Content Hooks
- **First Slide**
- Compelling question
- Bold statement
- Surprising fact
- Clear benefit
### 2. Visual Impact
- **Each Slide**
- Professional quality
- Clear message
- Brand alignment
- Emotional appeal
### 3. Call-to-Action
- **Last Slide**
- Clear direction
- Value offer
- Next steps
- Engagement prompt
## 🛠️ Technical Features
### Performance
- Fast generation
- Real-time preview
- Smooth editing
- Quick exports
### Export Options
- Individual slides
- Complete carousel
- Various formats
- High resolution
## 📈 Success Tips
### Content Quality
- Research-backed
- Professional tone
- Clear messaging
- Valuable insights
### Visual Excellence
- Professional design
- Consistent branding
- Quality visuals
- Mobile optimization
### Engagement Focus
- Interactive elements
- Question prompts
- Discussion starters
- Clear CTAs
## 🔍 Quick Tips
1. **Optimal Length**
- 3-5 slides for simple topics
- 6-8 slides for detailed guides
- 8-10 slides for comprehensive content
2. **Visual Best Practices**
- One main point per slide
- Clear, readable text
- High-quality images
- Consistent branding
3. **Content Flow**
- Hook → Content → CTA
- Logical progression
- Clear transitions
- Strong ending
4. **Engagement Boosters**
- Ask questions
- Include statistics
- Share insights
- Prompt discussion
---
Transform your LinkedIn presence with professional, engaging carousel posts! 🚀
Remember:
- Keep each slide focused
- Maintain visual consistency
- Tell a compelling story
- End with clear action steps
- Test and optimize regularly
Start creating stunning LinkedIn carousels that showcase your expertise! 💫

View File

@@ -0,0 +1,10 @@
"""
LinkedIn Carousel Generator Package
This package provides functionality for generating LinkedIn carousel posts with
AI-powered content and visuals.
"""
from .linkedin_carousel_generator import linkedin_carousel_generator_ui, LinkedInCarouselGenerator, CarouselSlide
__all__ = ['linkedin_carousel_generator_ui', 'LinkedInCarouselGenerator', 'CarouselSlide']

View File

@@ -0,0 +1,409 @@
"""
LinkedIn Carousel Post Generator
This module provides functionality for generating LinkedIn carousel posts with
AI-powered content and visuals.
"""
import streamlit as st
from typing import Dict, List, Optional
from loguru import logger
import json
from .....gpt_providers.text_generation.main_text_generation import llm_text_gen
from .....gpt_providers.text_to_image_generation.main_generate_image_from_prompt import generate_image
from .....ai_web_researcher.gpt_online_researcher import do_google_serp_search
from .....ai_web_researcher.metaphor_basic_neural_web_search import metaphor_search_articles
from .....ai_web_researcher.tavily_ai_search import do_tavily_ai_search
class CarouselSlide:
"""Represents a single slide in the carousel."""
def __init__(self, index: int, slide_type: str = "text_and_image"):
self.index = index
self.slide_type = slide_type
self.content = ""
self.image_prompt = ""
self.image_path = None
self.heading = ""
self.subheading = ""
def to_dict(self) -> Dict:
"""Convert slide to dictionary format."""
return {
"index": self.index,
"type": self.slide_type,
"content": self.content,
"image_prompt": self.image_prompt,
"image_path": self.image_path,
"heading": self.heading,
"subheading": self.subheading
}
class LinkedInCarouselGenerator:
"""
Generator for LinkedIn carousel posts with AI-powered content and visuals.
"""
def __init__(self):
"""Initialize the carousel generator."""
self.slides: List[CarouselSlide] = []
self.topic = ""
self.industry = ""
self.tone = ""
self.content_type = ""
self.num_slides = 0
self.research_results = {}
def research_topic(self, topic: str, industry: str, search_engine: str = "metaphor") -> Dict:
"""Research the topic to gather content for carousel slides."""
try:
# Construct research query
search_query = f"""
Find detailed professional content about '{topic}' in {industry} industry
focusing on:
- Key concepts and main points
- Statistics and data
- Examples and case studies
- Best practices
- Expert insights
"""
# Perform research using selected engine
if search_engine == "metaphor":
results = metaphor_search_articles(search_query)
elif search_engine == "google":
results = do_google_serp_search(search_query)
elif search_engine == "tavily":
results = do_tavily_ai_search(search_query)
self.research_results = results
return results
except Exception as e:
logger.error(f"Error researching topic: {e}")
return {}
def generate_slide_content(self, topic: str, industry: str, tone: str, content_type: str, num_slides: int) -> List[CarouselSlide]:
"""Generate content for carousel slides."""
try:
# Store parameters
self.topic = topic
self.industry = industry
self.tone = tone
self.content_type = content_type
self.num_slides = num_slides
# Generate content structure
structure_prompt = f"""
Create a {num_slides}-slide carousel post about '{topic}' for {industry} industry.
Style: {content_type} (e.g., How-to, List, Story)
Tone: {tone}
For each slide, provide:
1. Heading (short, attention-grabbing)
2. Subheading (supporting context)
3. Main content (clear, concise points)
4. Image prompt (visual representation)
Format as JSON:
{{
"slides": [
{{
"index": 1,
"heading": "Attention-grabbing title",
"subheading": "Supporting context",
"content": "Main slide content",
"image_prompt": "Detailed image generation prompt"
}}
]
}}
Requirements:
- First slide should hook the audience
- Maintain clear progression of ideas
- Each slide should be self-contained but connected
- Last slide should have clear call-to-action
- Keep text concise and impactful
- Ensure all content is professional and LinkedIn-appropriate
"""
# Generate structure using LLM
carousel_structure = llm_text_gen(structure_prompt)
try:
structure_data = json.loads(carousel_structure)
# Create slides from structure
self.slides = []
for slide_data in structure_data["slides"]:
slide = CarouselSlide(slide_data["index"])
slide.heading = slide_data["heading"]
slide.subheading = slide_data["subheading"]
slide.content = slide_data["content"]
slide.image_prompt = slide_data["image_prompt"]
self.slides.append(slide)
return self.slides
except json.JSONDecodeError:
logger.error("Failed to parse carousel structure")
return []
except Exception as e:
logger.error(f"Error generating slide content: {e}")
return []
def generate_slide_image(self, slide: CarouselSlide) -> Optional[str]:
"""Generate an image for a carousel slide."""
try:
# Generate image using the slide's prompt
image_path = generate_image(slide.image_prompt)
slide.image_path = image_path
return image_path
except Exception as e:
logger.error(f"Error generating slide image: {e}")
return None
def optimize_content(self, slide: CarouselSlide) -> CarouselSlide:
"""Optimize slide content for engagement."""
try:
optimization_prompt = f"""
Optimize this carousel slide content for maximum LinkedIn engagement:
Current Content:
Heading: {slide.heading}
Subheading: {slide.subheading}
Content: {slide.content}
Requirements:
1. Make heading more attention-grabbing
2. Ensure content is concise and impactful
3. Add relevant emojis where appropriate
4. Optimize for readability
5. Keep professional tone
6. Maintain focus on {self.topic}
Return as JSON:
{{
"heading": "Optimized heading",
"subheading": "Optimized subheading",
"content": "Optimized content"
}}
"""
optimized = llm_text_gen(optimization_prompt)
try:
optimized_data = json.loads(optimized)
slide.heading = optimized_data["heading"]
slide.subheading = optimized_data["subheading"]
slide.content = optimized_data["content"]
except json.JSONDecodeError:
logger.error("Failed to parse optimized content")
return slide
except Exception as e:
logger.error(f"Error optimizing slide content: {e}")
return slide
def linkedin_carousel_generator_ui():
"""Streamlit UI for the LinkedIn Carousel Generator."""
st.title("🔄 LinkedIn Carousel Post Generator")
st.write("Create engaging carousel posts that showcase your content professionally")
# Initialize generator
generator = LinkedInCarouselGenerator()
# Initialize session state
if "carousel_data" not in st.session_state:
st.session_state.carousel_data = {
"slides": [],
"research_results": None,
"generated_images": {},
"current_slide": 0
}
# Input form
with st.form("carousel_form"):
topic = st.text_input("Topic", placeholder="Enter the main topic of your carousel")
industry = st.text_input("Industry", placeholder="e.g., Technology, Healthcare, Finance")
col1, col2, col3 = st.columns(3)
with col1:
tone = st.selectbox(
"Tone",
["Professional", "Educational", "Conversational", "Inspiring", "Technical"]
)
with col2:
content_type = st.selectbox(
"Content Type",
["How-to Guide", "List", "Story", "Case Study", "Tips & Tricks"]
)
with col3:
num_slides = st.slider("Number of Slides", min_value=3, max_value=10, value=5)
# Research source selection
search_engine = st.radio(
"Research Source",
["metaphor", "google", "tavily"],
format_func=lambda x: {
"metaphor": "🔍 Metaphor AI",
"google": "🌐 Google Search",
"tavily": "🤖 Tavily AI"
}[x]
)
submit = st.form_submit_button("Generate Carousel")
if submit and topic and industry:
# Create status container
status_container = st.empty()
with st.spinner("Researching and generating your carousel..."):
# Research phase
status_container.text("🔍 Phase 1: Researching topic...")
research_results = generator.research_topic(topic, industry, search_engine)
st.session_state.carousel_data["research_results"] = research_results
if research_results:
# Content generation phase
status_container.text("✍️ Phase 2: Creating carousel content...")
slides = generator.generate_slide_content(
topic, industry, tone.lower(), content_type.lower(), num_slides
)
st.session_state.carousel_data["slides"] = slides
# Image generation phase
status_container.text("🎨 Phase 3: Generating slide visuals...")
for slide in slides:
image_path = generator.generate_slide_image(slide)
if image_path:
st.session_state.carousel_data["generated_images"][slide.index] = image_path
status_container.text("✅ Carousel generation complete!")
else:
status_container.error("❌ No research results found. Please try a different topic or research source.")
# Display carousel if we have slides
if st.session_state.carousel_data["slides"]:
st.markdown("---")
# Create tabs for different views
tab1, tab2 = st.tabs(["🎯 Carousel Preview", "📊 Research Results"])
with tab1:
st.subheader("Carousel Preview")
# Slide navigation
col1, col2, col3 = st.columns([1, 3, 1])
with col1:
if st.button("⬅️ Previous") and st.session_state.carousel_data["current_slide"] > 0:
st.session_state.carousel_data["current_slide"] -= 1
with col3:
if st.button("Next ➡️") and st.session_state.carousel_data["current_slide"] < len(st.session_state.carousel_data["slides"]) - 1:
st.session_state.carousel_data["current_slide"] += 1
# Display current slide
current_slide = st.session_state.carousel_data["slides"][st.session_state.carousel_data["current_slide"]]
st.markdown(f"""
<div style='
background: white;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin: 1rem 0;
'>
<h1 style='
color: #0A66C2;
font-size: 1.8rem;
margin-bottom: 0.5rem;
'>{current_slide.heading}</h1>
<h2 style='
color: #666;
font-size: 1.2rem;
margin-bottom: 1.5rem;
'>{current_slide.subheading}</h2>
<p style='
font-size: 1.1rem;
line-height: 1.6;
color: #2f2f2f;
'>{current_slide.content}</p>
</div>
""", unsafe_allow_html=True)
# Display slide image if available
if current_slide.image_path:
st.image(current_slide.image_path,
caption=f"Slide {current_slide.index} Image",
use_container_width=True)
# Slide controls
st.markdown(f"**Slide {current_slide.index} of {len(st.session_state.carousel_data['slides'])}**")
# Edit options
with st.expander("✏️ Edit Slide"):
# Edit form for current slide
edited_heading = st.text_input("Heading", value=current_slide.heading)
edited_subheading = st.text_input("Subheading", value=current_slide.subheading)
edited_content = st.text_area("Content", value=current_slide.content)
if st.button("Update Slide"):
current_slide.heading = edited_heading
current_slide.subheading = edited_subheading
current_slide.content = edited_content
st.success("✅ Slide updated!")
if st.button("Optimize Content"):
optimized_slide = generator.optimize_content(current_slide)
st.success("✅ Content optimized!")
st.experimental_rerun()
# Export options
with st.expander("💾 Export Options"):
col1, col2 = st.columns(2)
with col1:
if st.button("Export Current Slide"):
st.success("Slide exported successfully!")
with col2:
if st.button("Export Full Carousel"):
st.success("Carousel exported successfully!")
with tab2:
st.subheader("Research Results")
research_results = st.session_state.carousel_data["research_results"]
if research_results:
# Display key insights
st.markdown("### Key Insights")
for insight in research_results.get("key_insights", []):
st.markdown(f"- {insight}")
# Display statistics
st.markdown("### Statistics & Data")
for stat in research_results.get("statistics", []):
st.markdown(f"- {stat}")
# Display sources
st.markdown("### Sources")
for source in research_results.get("sources", []):
st.markdown(f"- {source}")
else:
st.info("No research results available.")
if __name__ == "__main__":
linkedin_carousel_generator_ui()

View File

@@ -0,0 +1,261 @@
# LinkedIn Comment Response Generator
A powerful AI-powered tool for generating professional, engaging, and contextually appropriate responses to LinkedIn comments. This module helps maintain active engagement on LinkedIn by providing intelligent, well-crafted responses that build relationships and drive meaningful discussions.
## Features
### 1. Intelligent Comment Analysis
- Sentiment analysis of comments
- Identification of key discussion points
- Recognition of user intent and tone
- Context-aware interpretation
- Engagement opportunity detection
### 2. Response Generation
- Multiple response types:
- General professional responses
- Disagreement handling
- Value-add responses
- Resource suggestions
- Follow-up questions
- Brand voice customization
- Engagement goal targeting
- Context-aware responses
- Professional tone maintenance
### 3. Disagreement Handling
- Diplomatic response generation
- Evidence-based arguments
- Common ground identification
- Constructive dialogue promotion
- Relationship preservation
- Professional conflict resolution
### 4. Value-Add Responses
- Industry-specific insights
- Actionable recommendations
- Expert perspective sharing
- Resource linking
- Knowledge sharing
- Engagement hooks
### 5. Resource Suggestions
- Curated learning materials
- Progressive learning paths
- Practical application tips
- Follow-up support
- Expertise-level matching
- Topic-specific resources
### 6. Follow-up Questions
- Discussion deepening
- Multiple perspective exploration
- Experience sharing prompts
- Reflection encouragement
- Engagement maintenance
- Value exploration
### 7. Tone Optimization
- Multiple tone options:
- Professional
- Friendly
- Expert
- Supportive
- Diplomatic
- Appreciative
- Audience-specific adjustments
- Brand voice alignment
- Engagement optimization
- Relationship building focus
## Usage
### Basic Response Generation
```python
from lib.ai_writers.linkedin_writer.modules.comment_response_generator import LinkedInCommentResponseGenerator
# Initialize the generator
generator = LinkedInCommentResponseGenerator()
# Generate a response
response = await generator.generate_response(
comment="Your comment here",
post_context="Original post context",
brand_voice="professional",
engagement_goal="continue_discussion"
)
```
### Handling Disagreements
```python
# Generate a diplomatic response
response = await generator.handle_disagreement(
comment="Disagreeing comment",
post_context="Post context",
brand_voice="diplomatic"
)
```
### Value-Add Responses
```python
# Generate a value-adding response
response = await generator.generate_value_add_response(
comment="Comment to respond to",
industry="Technology",
expertise_areas=["AI", "Machine Learning", "Data Science"]
)
```
### Resource Suggestions
```python
# Suggest resources
response = await generator.suggest_resources(
comment="Comment requesting resources",
topic="Artificial Intelligence",
expertise_level="intermediate"
)
```
### Follow-up Questions
```python
# Generate follow-up questions
response = await generator.generate_follow_up_questions(
comment="Original comment",
discussion_context="Discussion context"
)
```
### Tone Optimization
```python
# Optimize response tone
optimized = await generator.optimize_response_tone(
response="Your response",
target_tone="professional",
audience="Tech professionals"
)
```
## UI Interface
The module includes a Streamlit-based user interface with the following sections:
1. **General Response Tab**
- Comment input
- Post context
- Brand voice selection
- Engagement goal selection
- Response generation
- Strategy display
2. **Handle Disagreement Tab**
- Disagreeing comment input
- Context input
- Brand voice selection
- Diplomatic response generation
- Strategy display
3. **Value-Add Response Tab**
- Comment input
- Industry specification
- Expertise areas input
- Value-adding response generation
- Component display
4. **Resource Suggestions Tab**
- Comment input
- Topic specification
- Expertise level selection
- Resource suggestion generation
- Resource details display
5. **Follow-up Questions Tab**
- Comment input
- Discussion context
- Question generation
- Strategy display
6. **Tone Optimization Section**
- Response input
- Target tone selection
- Audience specification
- Tone optimization
- Optimization details display
## Implementation Details
### Core Components
1. **LinkedInCommentResponseGenerator Class**
- Main generator class
- Response tone definitions
- Comment type definitions
- Core response generation methods
2. **Response Generation Methods**
- `analyze_comment`: Analyzes comment sentiment and intent
- `generate_response`: Creates contextually appropriate responses
- `handle_disagreement`: Generates diplomatic responses
- `generate_value_add_response`: Creates value-adding responses
- `suggest_resources`: Provides relevant resource suggestions
- `generate_follow_up_questions`: Creates engaging follow-up questions
- `optimize_response_tone`: Adjusts response tone for target audience
3. **UI Implementation**
- Streamlit-based interface
- Tab-based organization
- Interactive input fields
- Real-time response generation
- Detailed strategy displays
### Dependencies
- Streamlit
- AI text generation capabilities
- Web research tools
- JSON processing
- Async/await support
## Best Practices
1. **Response Generation**
- Always provide context
- Select appropriate brand voice
- Define clear engagement goals
- Review generated responses
- Optimize tone for audience
2. **Disagreement Handling**
- Maintain professionalism
- Focus on common ground
- Provide evidence
- Encourage dialogue
- Preserve relationships
3. **Value-Add Responses**
- Share relevant expertise
- Provide actionable insights
- Include supporting evidence
- Suggest practical applications
- Maintain engagement
4. **Resource Suggestions**
- Match expertise level
- Provide learning path
- Include application tips
- Offer follow-up support
- Ensure resource accessibility
5. **Follow-up Questions**
- Deepen discussion
- Explore new angles
- Encourage participation
- Maintain professionalism
- Drive engagement
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
This project is licensed under the MIT License - see the LICENSE file for details.

View File

@@ -0,0 +1,11 @@
"""
LinkedIn Comment Response Generator Module
This module provides AI-powered generation of professional and engaging responses
to comments on LinkedIn posts.
"""
from .linkedin_comment_response_generator import LinkedInCommentResponseGenerator
from .linkedin_comment_response_generator_ui import linkedin_comment_response_generator_ui
__all__ = ['LinkedInCommentResponseGenerator', 'linkedin_comment_response_generator_ui']

View File

@@ -0,0 +1,346 @@
"""
LinkedIn Comment Response Generator
This module provides AI-powered generation of professional and engaging responses
to comments on LinkedIn posts.
"""
import json
from typing import Dict, List, Optional
from loguru import logger
from .....gpt_providers.text_generation.main_text_generation import llm_text_gen
from .....ai_web_researcher.gpt_online_researcher import do_google_serp_search
from .....ai_web_researcher.metaphor_basic_neural_web_search import metaphor_search_articles
from .....ai_web_researcher.tavily_ai_search import do_tavily_ai_search
class LinkedInCommentResponseGenerator:
"""
AI-powered generator for professional and engaging LinkedIn comment responses.
"""
def __init__(self):
"""Initialize the LinkedIn Comment Response Generator."""
self.response_tones = [
"professional",
"friendly",
"expert",
"supportive",
"diplomatic",
"appreciative"
]
self.comment_types = [
"question",
"agreement",
"disagreement",
"appreciation",
"criticism",
"suggestion",
"experience_sharing"
]
async def analyze_comment(self, comment: str) -> Dict:
"""
Analyze the comment to determine its type, tone, and key points.
Args:
comment: The comment text to analyze
Returns:
Dict containing comment analysis
"""
prompt = f"""
As a LinkedIn engagement expert, analyze this comment:
Comment: {comment}
Provide a detailed analysis including:
- Comment type (question/agreement/disagreement/etc.)
- Emotional tone
- Key points or questions raised
- Intent and context
- Engagement potential
Return a JSON with:
- comment_type: The type of comment
- tone: Emotional tone
- key_points: List of main points
- questions: Any questions raised
- intent: Perceived intent
- engagement_potential: High/Medium/Low
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def generate_response(self,
comment: str,
post_context: str,
brand_voice: str,
engagement_goal: str
) -> Dict:
"""
Generate an appropriate response to the comment.
Args:
comment: The comment to respond to
post_context: The context of the original post
brand_voice: Desired brand voice/tone
engagement_goal: Goal for the response
Returns:
Dict containing response and strategy
"""
# First analyze the comment
analysis = await self.analyze_comment(comment)
prompt = f"""
As a LinkedIn engagement expert, generate a response to this comment:
Comment: {comment}
Post Context: {post_context}
Brand Voice: {brand_voice}
Engagement Goal: {engagement_goal}
Comment Analysis: {json.dumps(analysis)}
Generate a response that:
- Maintains professional tone
- Addresses key points/questions
- Aligns with brand voice
- Encourages further engagement
- Builds community
- Adds value
Return a JSON with:
- response: The generated response
- tone_used: Tone of the response
- key_points_addressed: Points addressed
- engagement_hooks: Elements to encourage interaction
- value_adds: Additional value provided
- follow_up_suggestions: Potential follow-up points
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def handle_disagreement(self,
comment: str,
post_context: str,
brand_voice: str
) -> Dict:
"""
Generate a professional response to a disagreement.
Args:
comment: The disagreeing comment
post_context: Original post context
brand_voice: Desired brand voice
Returns:
Dict containing diplomatic response
"""
prompt = f"""
As a LinkedIn communication expert, craft a diplomatic response to this disagreement:
Comment: {comment}
Post Context: {post_context}
Brand Voice: {brand_voice}
Generate a response that:
- Maintains professionalism
- Acknowledges the perspective
- Provides supporting evidence
- Finds common ground
- Keeps discussion constructive
- Invites further dialogue
Return a JSON with:
- response: The diplomatic response
- acknowledgment: How the perspective was acknowledged
- evidence: Supporting points provided
- common_ground: Areas of agreement
- dialogue_hooks: Elements to continue discussion
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def generate_value_add_response(self,
comment: str,
industry: str,
expertise_areas: List[str]
) -> Dict:
"""
Generate a response that adds significant value.
Args:
comment: The comment to respond to
industry: Relevant industry
expertise_areas: Areas of expertise
Returns:
Dict containing value-adding response
"""
# Research relevant insights
research = await do_tavily_ai_search(
f"latest insights trends {industry} {' '.join(expertise_areas)}"
)
prompt = f"""
As a LinkedIn thought leader, generate a value-adding response:
Comment: {comment}
Industry: {industry}
Expertise Areas: {expertise_areas}
Research Insights: {json.dumps(research)}
Create a response that:
- Shares relevant insights
- Provides actionable advice
- References credible sources
- Demonstrates expertise
- Encourages implementation
- Invites questions
Return a JSON with:
- response: The value-adding response
- insights_shared: Key insights provided
- action_items: Actionable takeaways
- sources: Referenced sources
- expertise_demonstrated: How expertise was shown
- engagement_hooks: Questions or prompts
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def suggest_resources(self,
comment: str,
topic: str,
expertise_level: str
) -> Dict:
"""
Suggest relevant resources in response to a comment.
Args:
comment: The comment requesting/needing resources
topic: The topic of discussion
expertise_level: User's expertise level
Returns:
Dict containing resource suggestions
"""
# Research relevant resources
resources = await metaphor_search_articles(
f"best resources tutorials guides {topic} {expertise_level}"
)
prompt = f"""
As a LinkedIn learning facilitator, suggest helpful resources:
Comment: {comment}
Topic: {topic}
Expertise Level: {expertise_level}
Found Resources: {json.dumps(resources)}
Provide suggestions that:
- Match expertise level
- Cover key aspects
- Include various formats
- Are readily accessible
- Support learning goals
- Encourage application
Return a JSON with:
- response: Resource suggestion response
- recommended_resources: List of resources
- learning_path: Suggested learning sequence
- application_tips: How to apply resources
- follow_up_support: Additional support offered
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def generate_follow_up_questions(self,
comment: str,
discussion_context: str
) -> Dict:
"""
Generate engaging follow-up questions to continue the discussion.
Args:
comment: The comment to generate questions for
discussion_context: Context of the discussion
Returns:
Dict containing follow-up questions
"""
prompt = f"""
As a LinkedIn engagement expert, generate follow-up questions:
Comment: {comment}
Discussion Context: {discussion_context}
Generate questions that:
- Deepen the discussion
- Explore different angles
- Draw out experiences
- Encourage reflection
- Maintain professionalism
- Drive engagement
Return a JSON with:
- primary_question: Main follow-up question
- secondary_questions: Additional questions
- discussion_angles: New perspectives to explore
- engagement_prompts: Ways to encourage participation
- value_exploration: Areas to uncover value
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def optimize_response_tone(self,
response: str,
target_tone: str,
audience: str
) -> Dict:
"""
Optimize the tone of a response for the target audience.
Args:
response: The response to optimize
target_tone: Desired tone
audience: Target audience
Returns:
Dict containing tone-optimized response
"""
prompt = f"""
As a LinkedIn communication expert, optimize this response's tone:
Response: {response}
Target Tone: {target_tone}
Audience: {audience}
Optimize the response to:
- Match desired tone
- Resonate with audience
- Maintain professionalism
- Enhance engagement
- Build rapport
- Reflect brand voice
Return a JSON with:
- optimized_response: Tone-adjusted response
- tone_adjustments: Changes made
- audience_alignment: How it matches audience
- engagement_potential: Expected engagement
- relationship_building: How it builds connection
"""
response = await llm_text_gen(prompt)
return json.loads(response)

View File

@@ -0,0 +1,283 @@
"""
LinkedIn Comment Response Generator UI
This module provides the Streamlit UI for the LinkedIn Comment Response Generator.
"""
import streamlit as st
import json
from typing import Dict, List
from .linkedin_comment_response_generator import LinkedInCommentResponseGenerator
async def linkedin_comment_response_generator_ui():
"""
Streamlit UI for the LinkedIn Comment Response Generator.
"""
# Initialize the generator
generator = LinkedInCommentResponseGenerator()
st.title("LinkedIn Comment Response Generator")
# Create tabs for different response scenarios
tabs = st.tabs([
"General Response",
"Handle Disagreement",
"Value-Add Response",
"Resource Suggestions",
"Follow-up Questions"
])
# General Response Tab
with tabs[0]:
st.header("Generate Professional Response")
st.info("Generate an engaging and professional response to a LinkedIn comment")
comment = st.text_area("Comment to Respond to", height=100)
post_context = st.text_area("Original Post Context", height=100)
col1, col2 = st.columns(2)
with col1:
brand_voice = st.selectbox(
"Brand Voice",
["Professional", "Friendly", "Expert", "Supportive", "Diplomatic", "Appreciative"]
)
with col2:
engagement_goal = st.selectbox(
"Engagement Goal",
["Continue Discussion", "Share Knowledge", "Build Relationship", "Address Concern", "Encourage Action"]
)
if st.button("Generate Response", key="general_response"):
with st.spinner("Generating response..."):
# First analyze the comment
analysis = await generator.analyze_comment(comment)
# Display analysis
with st.expander("Comment Analysis", expanded=True):
st.json(analysis)
# Generate response
response = await generator.generate_response(
comment,
post_context,
brand_voice.lower(),
engagement_goal
)
# Display response
st.subheader("Generated Response")
st.success(response['response'])
# Display strategy
with st.expander("Response Strategy"):
st.write("**Tone Used:**", response['tone_used'])
st.write("**Key Points Addressed:**")
for point in response['key_points_addressed']:
st.write(f"- {point}")
st.write("**Engagement Hooks:**")
for hook in response['engagement_hooks']:
st.write(f"- {hook}")
st.write("**Value Adds:**")
for value in response['value_adds']:
st.write(f"- {value}")
st.write("**Follow-up Suggestions:**")
for suggestion in response['follow_up_suggestions']:
st.write(f"- {suggestion}")
# Handle Disagreement Tab
with tabs[1]:
st.header("Handle Disagreement")
st.info("Generate a diplomatic response to a disagreeing comment")
disagreement_comment = st.text_area("Disagreeing Comment", height=100, key="disagreement_comment")
disagreement_context = st.text_area("Post Context", height=100, key="disagreement_context")
disagreement_voice = st.selectbox(
"Brand Voice",
["Diplomatic", "Professional", "Expert", "Supportive"],
key="disagreement_voice"
)
if st.button("Generate Diplomatic Response"):
with st.spinner("Generating diplomatic response..."):
response = await generator.handle_disagreement(
disagreement_comment,
disagreement_context,
disagreement_voice.lower()
)
st.subheader("Diplomatic Response")
st.success(response['response'])
with st.expander("Response Strategy"):
st.write("**Acknowledgment:**", response['acknowledgment'])
st.write("**Supporting Evidence:**")
for point in response['evidence']:
st.write(f"- {point}")
st.write("**Common Ground:**")
for point in response['common_ground']:
st.write(f"- {point}")
st.write("**Dialogue Continuation:**")
for hook in response['dialogue_hooks']:
st.write(f"- {hook}")
# Value-Add Response Tab
with tabs[2]:
st.header("Value-Add Response")
st.info("Generate a response that provides significant value")
value_comment = st.text_area("Comment", height=100, key="value_comment")
industry = st.text_input("Industry")
expertise_areas = st.text_area(
"Areas of Expertise (one per line)",
height=100
).split("\n")
if st.button("Generate Value-Add Response"):
with st.spinner("Researching and generating response..."):
response = await generator.generate_value_add_response(
value_comment,
industry,
expertise_areas
)
st.subheader("Value-Adding Response")
st.success(response['response'])
with st.expander("Value Components"):
st.write("**Key Insights:**")
for insight in response['insights_shared']:
st.write(f"- {insight}")
st.write("**Action Items:**")
for item in response['action_items']:
st.write(f"- {item}")
st.write("**Sources:**")
for source in response['sources']:
st.write(f"- {source}")
st.write("**Expertise Demonstrated:**")
st.write(response['expertise_demonstrated'])
st.write("**Engagement Hooks:**")
for hook in response['engagement_hooks']:
st.write(f"- {hook}")
# Resource Suggestions Tab
with tabs[3]:
st.header("Resource Suggestions")
st.info("Suggest helpful resources in response to a comment")
resource_comment = st.text_area("Comment", height=100, key="resource_comment")
topic = st.text_input("Topic")
expertise_level = st.select_slider(
"Expertise Level",
options=["Beginner", "Intermediate", "Advanced", "Expert"]
)
if st.button("Generate Resource Suggestions"):
with st.spinner("Researching and compiling resources..."):
response = await generator.suggest_resources(
resource_comment,
topic,
expertise_level.lower()
)
st.subheader("Resource Suggestion Response")
st.success(response['response'])
with st.expander("Resource Details"):
st.write("**Recommended Resources:**")
for resource in response['recommended_resources']:
st.write(f"- {resource}")
st.write("**Learning Path:**")
for step in response['learning_path']:
st.write(f"- {step}")
st.write("**Application Tips:**")
for tip in response['application_tips']:
st.write(f"- {tip}")
st.write("**Follow-up Support:**")
st.write(response['follow_up_support'])
# Follow-up Questions Tab
with tabs[4]:
st.header("Follow-up Questions")
st.info("Generate engaging follow-up questions to continue the discussion")
question_comment = st.text_area("Comment", height=100, key="question_comment")
discussion_context = st.text_area("Discussion Context", height=100, key="question_context")
if st.button("Generate Follow-up Questions"):
with st.spinner("Generating questions..."):
response = await generator.generate_follow_up_questions(
question_comment,
discussion_context
)
st.subheader("Primary Follow-up Question")
st.success(response['primary_question'])
st.subheader("Secondary Questions")
for question in response['secondary_questions']:
st.info(question)
with st.expander("Discussion Strategy"):
st.write("**Discussion Angles:**")
for angle in response['discussion_angles']:
st.write(f"- {angle}")
st.write("**Engagement Prompts:**")
for prompt in response['engagement_prompts']:
st.write(f"- {prompt}")
st.write("**Value Exploration:**")
for area in response['value_exploration']:
st.write(f"- {area}")
# Add tone optimization section at the bottom
st.divider()
st.subheader("Response Tone Optimization")
st.info("Optimize the tone of any generated response")
response_to_optimize = st.text_area("Response to Optimize", height=100)
col1, col2 = st.columns(2)
with col1:
target_tone = st.selectbox(
"Target Tone",
generator.response_tones
)
with col2:
audience = st.text_input("Target Audience")
if st.button("Optimize Tone"):
with st.spinner("Optimizing response tone..."):
optimized = await generator.optimize_response_tone(
response_to_optimize,
target_tone,
audience
)
st.subheader("Tone-Optimized Response")
st.success(optimized['optimized_response'])
with st.expander("Optimization Details"):
st.write("**Tone Adjustments:**")
for adjustment in optimized['tone_adjustments']:
st.write(f"- {adjustment}")
st.write("**Audience Alignment:**", optimized['audience_alignment'])
st.write("**Engagement Potential:**", optimized['engagement_potential'])
st.write("**Relationship Building:**", optimized['relationship_building'])

View File

@@ -0,0 +1,216 @@
# LinkedIn Poll Generator
## Overview
The LinkedIn Poll Generator is an AI-powered tool designed to help professionals create engaging, data-driven polls for LinkedIn. This tool leverages advanced AI to generate poll questions, options, and engagement predictions, helping users gather valuable insights from their professional network.
## Features
### 1. Poll Creation
- **Multiple Poll Types**: Create various types of polls including:
- Multiple Choice (2-4 options)
- Yes/No
- Rating Scale (1-5)
- Ranking (order items by preference)
- Open-ended (with suggested responses)
- **Customizable Tone**: Generate polls with different tones (professional, casual, authoritative, conversational, thoughtful)
- **Industry-Specific Content**: Tailor polls to specific industries and professional contexts
### 2. Research Integration
- **Multi-Source Research**: Gather insights from multiple search engines:
- Metaphor (neural search)
- Google SERP
- Tavily AI
- **Insight Extraction**: Automatically extract key insights and trends from research
- **Question Generation**: Generate potential poll questions based on research findings
### 3. Engagement Prediction
- **Response Prediction**: Forecast expected engagement levels (low, medium, high, viral)
- **Comment & Share Likelihood**: Predict the likelihood of comments and shares
- **Response Distribution**: Estimate the expected distribution of responses across options
- **Insight Generation**: Identify potential insights that could be gained from the poll
### 4. Optimization
- **Question Improvements**: Get suggestions for improving poll question wording and clarity
- **Option Improvements**: Receive recommendations for enhancing poll options
- **Timing Suggestions**: Learn the optimal days and times to post your poll
- **Audience Targeting**: Identify the most relevant audience segments for your poll
- **Hashtag Recommendations**: Get industry-specific hashtag suggestions
### 5. Follow-up Content
- **Post Templates**: Receive templates for sharing poll results
- **Visual Suggestions**: Get recommendations for visualizing poll results
- **Next Poll Ideas**: Discover ideas for follow-up polls that build on previous insights
- **Data Visualization**: Receive suggestions for effective data visualization of poll results
## Usage
### Basic Workflow
1. **Select Topic and Industry**: Enter your poll topic and target industry
2. **Choose Poll Type**: Select the type of poll you want to create
3. **Set Tone**: Choose the tone for your poll (professional, casual, etc.)
4. **Research Topic**: Gather insights about your topic (optional)
5. **Generate Poll**: Create your poll with AI-generated questions and options
6. **Review Predictions**: See engagement predictions and response distribution
7. **Optimize**: Get suggestions for improving your poll
8. **Plan Follow-up**: Receive templates and ideas for sharing results
### Advanced Features
#### Research Integration
- Use the "Research Topic" button to gather insights before creating your poll
- View key insights, emerging trends, and potential questions based on research
- Use research findings to inform your poll creation
#### Engagement Prediction
- View predicted engagement levels before posting
- See expected response distribution across options
- Identify potential insights that could be gained
#### Optimization
- Get suggestions for improving your poll question and options
- Learn the best times to post for maximum engagement
- Identify the most relevant audience segments
- Receive hashtag recommendations
#### Follow-up Content
- Get templates for sharing poll results
- Receive visual content suggestions
- Discover ideas for follow-up polls
- Get data visualization recommendations
## Best Practices
### Creating Effective Polls
1. **Be Specific**: Ask clear, specific questions that your audience can answer confidently
2. **Keep it Concise**: Use concise language for both questions and options
3. **Avoid Bias**: Ensure your poll doesn't lead respondents toward a particular answer
4. **Use Appropriate Options**: Make sure options are mutually exclusive and collectively exhaustive
5. **Consider Timing**: Post polls at times when your audience is most active
6. **Follow Up**: Share results and insights after the poll closes
### Maximizing Engagement
1. **Target Your Audience**: Ensure your poll is relevant to your specific audience
2. **Use Visuals**: Include relevant images or graphics with your poll
3. **Add Context**: Provide brief context or explanation for your poll
4. **Engage with Comments**: Respond to comments to encourage discussion
5. **Share Results**: Follow up with a post sharing the results and insights
6. **Use Hashtags**: Include relevant hashtags to increase visibility
### Industry-Specific Tips
#### Technology
- Focus on emerging trends and technologies
- Ask about adoption rates and preferences
- Include technical and non-technical options
#### Healthcare
- Address current healthcare challenges
- Ask about patient experiences and preferences
- Include options that reflect different stakeholder perspectives
#### Finance
- Focus on investment preferences and strategies
- Ask about financial planning and management
- Include options that reflect different risk tolerances
#### Marketing
- Address current marketing trends and challenges
- Ask about content preferences and consumption habits
- Include options that reflect different marketing approaches
#### Education
- Focus on learning preferences and methods
- Ask about educational technology and tools
- Include options that reflect different learning styles
## Technical Details
### Dependencies
- Streamlit: For the user interface
- Plotly: For data visualization
- Loguru: For logging
- GPT Providers: For AI text generation
- Web Research Tools: For gathering insights
### Architecture
The LinkedIn Poll Generator consists of:
- `LinkedInPollGenerator` class: Core functionality for poll generation
- `linkedin_poll_generator_ui` function: Streamlit UI implementation
### Integration
The Poll Generator is integrated into the LinkedIn AI Writer suite and can be accessed through the main LinkedIn AI Writer interface.
## Examples
### Example 1: Technology Industry Poll
**Question**: "What emerging technology will have the biggest impact on business in 2023?"
**Options**:
1. Artificial Intelligence
2. Blockchain
3. Quantum Computing
4. Extended Reality (XR)
### Example 2: Healthcare Industry Poll
**Question**: "What is the most significant barrier to telehealth adoption?"
**Options**:
1. Technical issues
2. Privacy concerns
3. Lack of insurance coverage
4. Patient preference for in-person care
### Example 3: Finance Industry Poll
**Question**: "What investment strategy are you most likely to pursue in a volatile market?"
**Options**:
1. Increase cash reserves
2. Focus on dividend stocks
3. Invest in defensive sectors
4. Look for opportunistic buys
## Troubleshooting
### Common Issues
1. **Research Not Returning Results**
- Try a different search engine
- Use more specific search terms
- Check your internet connection
2. **Low Engagement Predictions**
- Review question wording for clarity
- Ensure options are relevant and distinct
- Consider targeting a more specific audience
3. **JSON Parsing Errors**
- This is typically handled automatically by the system
- If persistent, try regenerating the poll
## Future Enhancements
- **A/B Testing**: Compare different poll versions
- **Historical Data Analysis**: Learn from past poll performance
- **Competitor Poll Analysis**: Analyze successful polls in your industry
- **Advanced Visualization**: More sophisticated data visualization options
- **Integration with LinkedIn API**: Direct posting to LinkedIn
- **Poll Templates**: Pre-built templates for common use cases
- **Multi-language Support**: Generate polls in multiple languages
## Contributing
Contributions to the LinkedIn Poll Generator are welcome! Please follow these steps:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Contact
For questions or feedback about the LinkedIn Poll Generator, please contact the development team.

View File

@@ -0,0 +1,10 @@
"""
LinkedIn Poll Generator Module
This module provides functionality for generating LinkedIn polls with
AI-powered content and engagement optimization.
"""
from .linkedin_poll_generator import LinkedInPollGenerator, linkedin_poll_generator_ui
__all__ = ["LinkedInPollGenerator", "linkedin_poll_generator_ui"]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,291 @@
# LinkedIn Post Generator 🚀
An AI-powered tool designed for LinkedIn professionals to create engaging, research-backed posts that drive engagement and establish thought leadership.
## ✨ Key Features
### Content Creation
- **AI-Powered Research**: Multi-source research integration (Metaphor, Google, Tavily)
- **Smart Content Generation**: Industry-specific, engagement-optimized content
- **Hashtag Optimization**: Data-driven hashtag suggestions
- **Visual Content**: AI-generated images with professional aesthetics
- **Engagement Predictions**: AI-powered performance analytics
- **Poll Creation**: Interactive audience engagement tools
- **Posting Time Optimization**: Industry-specific timing recommendations
### Research Excellence
- **Triple-Engine Research**:
- 🔍 Metaphor AI: Deep industry insights
- 🌐 Google Search: Comprehensive coverage
- 🤖 Tavily AI: Focused research
- **Real-Time Data**: Current trends and statistics
- **Expert Insights**: Professional quotes and perspectives
- **Fact Verification**: Web-researched authenticity
### Visual Enhancement
- **Professional Imagery**: AI-generated visuals
- **Custom Prompts**: Tailored image generation
- **Style Customization**: Brand-aligned visuals
- **Multiple Formats**: Various visual content options
## 🎯 Getting Started
### 1. Post Creation Process
#### Initial Setup
- Choose your topic
- Select your industry
- Pick your writing tone:
- Professional
- Casual
- Informative
- Inspirational
#### Research Configuration
Select your preferred research source:
- Metaphor AI: Comprehensive insights
- Google Search: Wide coverage
- Tavily AI: Focused research
#### Content Options
Customize your post with:
- ✅ Hashtags
- 🖼️ Visual content
- 📊 Polls
- ⏰ Posting time recommendations
### 2. Post Generation and Preview
#### Content Tab
- View generated post
- Edit content directly
- Copy to clipboard
- Download as text
#### Analytics Tab
- Engagement predictions
- Optimal posting times
- Performance metrics
- Audience insights
#### Visual Content Tab
- Preview generated images
- Edit image prompts
- Generate alternatives
- Download visuals
## 💡 Best Practices
### 1. Content Strategy
- **Topic Selection**
- Industry relevance
- Current trends
- Audience interest
- Professional expertise
- **Content Structure**
- Strong hook
- Value proposition
- Supporting points
- Clear CTA
### 2. Engagement Optimization
- **Hashtag Strategy**
- Industry-specific tags
- Trending topics
- Balanced visibility
- Professional relevance
- **Visual Impact**
- Professional imagery
- Brand consistency
- Clear messaging
- Mobile optimization
### 3. Timing and Frequency
- **Posting Schedule**
- Industry peak times
- Audience activity
- Time zone consideration
- Consistency
## 📊 Content Types
### 1. Thought Leadership
- Industry insights
- Expert opinions
- Trend analysis
- Future predictions
### 2. Professional Tips
- Best practices
- How-to guides
- Career advice
- Industry hacks
### 3. Success Stories
- Case studies
- Achievements
- Lessons learned
- Professional growth
### 4. Industry Updates
- Market trends
- News analysis
- Technology updates
- Professional developments
## 🎨 Visual Guidelines
### Image Generation
- **Style Options**
- Professional photography
- Abstract concepts
- Data visualization
- Brand elements
- **Customization**
- Color schemes
- Text overlays
- Visual hierarchy
- Professional aesthetics
### Brand Alignment
- **Visual Identity**
- Consistent style
- Professional tone
- Brand colors
- Quality standards
## 📱 Platform Optimization
### Mobile Experience
- Text readability
- Image scaling
- Content preview
- Performance check
### Cross-Platform
- LinkedIn app compatibility
- Web version optimization
- Image resolution
- Loading speed
## 💪 Engagement Strategies
### 1. Interactive Elements
- **Polls**
- Topic relevance
- Response options
- Duration setting
- Follow-up strategy
- **Call-to-Action**
- Clear direction
- Value proposition
- Professional tone
- Measurable goals
### 2. Hashtag Optimization
- **Selection Criteria**
- Relevance
- Reach
- Professional context
- Trending topics
### 3. Timing Strategy
- **Post Scheduling**
- Peak engagement times
- Industry patterns
- Audience availability
- Global considerations
## 🛠️ Technical Features
### Performance
- Fast generation
- Real-time preview
- Smooth editing
- Quick updates
### Integration
- Browser compatibility
- API connections
- Data security
- Regular updates
## 📈 Analytics and Insights
### Engagement Metrics
- Like predictions
- Comment estimates
- Share potential
- Profile visit forecasts
### Performance Tracking
- Engagement rates
- Reach estimates
- Audience response
- Content effectiveness
## 🔄 Workflow Integration
### 1. Content Planning
- Topic research
- Content creation
- Visual design
- Optimization
### 2. Quality Assurance
- Content review
- Image verification
- Hashtag check
- Timing optimization
### 3. Publication
- Final preview
- Platform check
- Scheduling
- Performance monitoring
## 🎯 Success Metrics
### Engagement Goals
- Professional visibility
- Audience growth
- Industry authority
- Network expansion
### Content Quality
- Professional standards
- Industry relevance
- Value delivery
- Brand alignment
## 🔍 Support and Resources
### Help Center
- User guides
- Best practices
- FAQs
- Technical support
### Updates
- Feature releases
- Performance improvements
- Platform updates
- Content tips
---
Transform your LinkedIn presence with professional, engaging posts that drive results! 🚀
### Quick Tips
- Keep posts between 800-1200 characters
- Include 3-5 relevant hashtags
- Add professional visuals
- Engage with comments
- Monitor performance
- Stay consistent
Start creating impactful LinkedIn posts that establish your professional authority! 💫

View File

@@ -0,0 +1,10 @@
"""
LinkedIn Post Generator Package
This package provides functionality for generating LinkedIn posts with research-backed content,
optimized hashtags, and engagement predictions.
"""
from .linkedin_post_generator import linkedin_post_generator_ui, LinkedInPostGenerator
__all__ = ['linkedin_post_generator_ui', 'LinkedInPostGenerator']

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,184 @@
# LinkedIn Profile Optimizer
## Overview
The LinkedIn Profile Optimizer is an AI-powered tool designed to help content creators maximize their LinkedIn presence and professional appeal. This tool analyzes and enhances every aspect of your LinkedIn profile to increase visibility, engagement, and professional opportunities.
## Key Features
### 1. Profile Strength Analysis 📊
- Comprehensive profile audit with section-by-section scoring
- SEO optimization recommendations
- Missing elements identification
- Prioritized improvement suggestions
- Engagement potential assessment
- Overall profile strength score
### 2. Headline Optimizer 🎯
- Industry-specific keyword optimization
- Value proposition enhancement
- Achievement integration
- Character count optimization
- Professional title recommendations
- SEO-friendly formatting
### 3. About Section Generator 📝
- Compelling narrative creation
- Professional journey storytelling
- Achievement showcase
- Industry expertise highlighting
- Call-to-action optimization
- Target audience alignment
- Proper formatting and structure
### 4. Experience Description Enhancer 💼
- Action verb optimization
- Quantifiable achievement integration
- Key responsibility highlighting
- Industry-relevant keyword incorporation
- Professional formatting
- Impact measurement metrics
- Role-specific enhancements
### 5. Skills Recommender 🎓
- Industry-trending skills analysis
- Role-specific recommendations
- Technical and soft skills balance
- Skill categorization
- Obsolete skill identification
- Endorsement strategy suggestions
## Getting Started
### Prerequisites
- Python 3.8 or higher
- Streamlit
- Access to ALwrity's AI services
### Usage
1. **Profile Analysis**
```python
# Initialize the optimizer
optimizer = LinkedInProfileOptimizer()
# Analyze profile
analysis = await optimizer.analyze_profile_strength(profile_data)
```
2. **Headline Optimization**
```python
# Optimize your headline
headline_result = await optimizer.optimize_headline(
current_headline="Your current headline",
industry="Your industry",
role="Your role"
)
```
3. **About Section Generation**
```python
# Generate optimized About section
about_section = await optimizer.generate_about_section(
current_about="Your current about",
experience=experience_list,
achievements=achievements_list,
target_audience="Your target audience"
)
```
## Best Practices for Content Creators
### 1. Profile Optimization Strategy
- Start with the Profile Analysis to identify key improvement areas
- Focus on your headline first - it's your first impression
- Craft your About section to showcase your content creation expertise
- Highlight your content creation achievements with metrics
- Include multimedia samples of your work
### 2. Content Creator Specific Tips
- Emphasize your content creation specialties in your headline
- Showcase engagement metrics in your experience descriptions
- Include platform-specific expertise (LinkedIn, YouTube, etc.)
- Highlight collaboration experiences with brands
- Demonstrate thought leadership in your niche
### 3. SEO Optimization
- Use industry-standard content creation terms
- Include platform-specific keywords
- Incorporate trending industry hashtags
- Balance creative and professional terminology
- Optimize for both human readers and search algorithms
### 4. Skills Strategy
- Balance technical content creation skills with soft skills
- Include platform-specific skills (LinkedIn content creation, etc.)
- Add emerging content formats (Shorts, Lives, etc.)
- Include analytics and measurement skills
- Showcase collaboration and community management abilities
## Advanced Features
### Custom URL Optimization
- Professional URL structure recommendations
- Brand alignment suggestions
- SEO-friendly formatting
- Consistency with other social profiles
### Project Highlights
- Content campaign showcases
- Viral content examples
- Brand collaboration features
- Impact metrics display
- Portfolio integration
### Endorsement Strategy
- Skill endorsement prioritization
- Network engagement tactics
- Reciprocal endorsement approaches
- Expertise validation methods
## Performance Metrics
The Profile Optimizer evaluates profiles based on:
- Profile Completeness Score
- Keyword Optimization Level
- Content Quality Metrics
- Engagement Potential
- Network Growth Indicators
- Professional Appeal Score
## Tips for Maximum Impact
1. **Regular Updates**
- Review and update your profile monthly
- Add new content creation achievements regularly
- Keep skills current with industry trends
- Update metrics and performance statistics
2. **Content Strategy Integration**
- Align profile messaging with your content
- Cross-reference your content platforms
- Showcase your content creation process
- Highlight your unique value proposition
3. **Network Growth**
- Optimize for your target audience
- Use industry-specific terminology
- Showcase collaboration opportunities
- Highlight your community engagement
## Support and Resources
For additional support:
- Check the [ALwrity Documentation](https://docs.alwrity.com)
- Join our [Content Creator Community](https://community.alwrity.com)
- Follow our [LinkedIn Page](https://linkedin.com/company/alwrity)
- Contact support at support@alwrity.com
## Contributing
We welcome contributions from the content creator community! Please read our [Contributing Guidelines](CONTRIBUTING.md) for details on submitting pull requests.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

View File

@@ -0,0 +1,11 @@
"""
LinkedIn Profile Optimizer Module
This module provides AI-powered optimization for LinkedIn profiles to improve visibility
and professional appeal.
"""
from .linkedin_profile_optimizer import LinkedInProfileOptimizer
from .linkedin_profile_optimizer_ui import linkedin_profile_optimizer_ui
__all__ = ['LinkedInProfileOptimizer', 'linkedin_profile_optimizer_ui']

View File

@@ -0,0 +1,240 @@
"""
LinkedIn Profile Optimizer
This module provides AI-powered optimization for LinkedIn profiles to improve visibility
and professional appeal.
"""
import json
from typing import Dict, List, Optional
from loguru import logger
from .....gpt_providers.text_generation.main_text_generation import llm_text_gen
from .....ai_web_researcher.gpt_online_researcher import do_google_serp_search
from .....ai_web_researcher.metaphor_basic_neural_web_search import metaphor_search_articles
from .....ai_web_researcher.tavily_ai_search import do_tavily_ai_search
class LinkedInProfileOptimizer:
"""
AI-powered LinkedIn Profile Optimizer that enhances profiles for better visibility
and professional appeal.
"""
def __init__(self):
"""Initialize the LinkedIn Profile Optimizer."""
self.industry_keywords = {}
self.seo_patterns = {}
self.profile_sections = [
"headline",
"about",
"experience",
"skills",
"projects",
"endorsements",
"summary",
"custom_url"
]
async def optimize_headline(self, current_headline: str, industry: str, role: str) -> Dict:
"""
Optimize the LinkedIn headline for better visibility and impact.
Args:
current_headline: Current LinkedIn headline
industry: User's industry
role: User's current or target role
Returns:
Dict containing optimized headline and explanation
"""
prompt = f"""
As an expert LinkedIn profile optimizer, enhance this headline for maximum impact and visibility:
Current Headline: {current_headline}
Industry: {industry}
Role: {role}
Consider:
- Including relevant keywords for {industry}
- Highlighting unique value proposition
- Using industry-standard titles
- Incorporating achievements or specialties
- Keeping it under LinkedIn's character limit
Return a JSON with:
- optimized_headline: The enhanced headline
- explanation: Why changes were made
- keywords_used: Key terms included
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def generate_about_section(self,
current_about: str,
experience: List[Dict],
achievements: List[str],
target_audience: str
) -> Dict:
"""
Generate an optimized About section.
Args:
current_about: Current About section content
experience: List of work experiences
achievements: List of key achievements
target_audience: Intended profile visitors
Returns:
Dict containing new About section and explanation
"""
prompt = f"""
As an expert LinkedIn profile writer, create an engaging About section that showcases professional value:
Current About: {current_about}
Key Experiences: {json.dumps(experience)}
Achievements: {json.dumps(achievements)}
Target Audience: {target_audience}
Consider:
- Strong opening hook
- Professional journey narrative
- Key achievements and impact
- Industry expertise
- Call to action
- Proper formatting and structure
Return a JSON with:
- about_section: The optimized content
- structure_explanation: Section breakdown
- impact_factors: Key elements that drive engagement
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def enhance_experience_descriptions(self,
experiences: List[Dict]
) -> List[Dict]:
"""
Enhance work experience descriptions for better impact.
Args:
experiences: List of work experiences with roles and descriptions
Returns:
List of enhanced experience descriptions
"""
enhanced_experiences = []
for exp in experiences:
prompt = f"""
As an expert LinkedIn profile writer, enhance this work experience description:
Role: {exp.get('role')}
Company: {exp.get('company')}
Current Description: {exp.get('description')}
Enhance the description to:
- Lead with strong action verbs
- Include quantifiable achievements
- Highlight key responsibilities
- Incorporate relevant keywords
- Use proper formatting
Return a JSON with:
- enhanced_description: The improved description
- achievements_highlighted: Key accomplishments
- keywords_used: Industry terms included
"""
response = await llm_text_gen(prompt)
enhanced_exp = json.loads(response)
enhanced_experiences.append({
**exp,
'enhanced_description': enhanced_exp['enhanced_description'],
'achievements': enhanced_exp['achievements_highlighted'],
'keywords': enhanced_exp['keywords_used']
})
return enhanced_experiences
async def recommend_skills(self,
current_skills: List[str],
industry: str,
role: str
) -> Dict:
"""
Recommend relevant skills based on industry and role.
Args:
current_skills: List of current skills
industry: User's industry
role: User's role
Returns:
Dict containing skill recommendations
"""
# Research trending skills in the industry
industry_research = await do_tavily_ai_search(
f"most in-demand skills for {role} in {industry} LinkedIn 2024"
)
prompt = f"""
As a LinkedIn profile optimization expert, recommend skills based on:
Current Skills: {json.dumps(current_skills)}
Industry: {industry}
Role: {role}
Industry Research: {json.dumps(industry_research)}
Provide:
- Must-have technical skills
- Important soft skills
- Trending skills in the industry
- Skills to remove (if any)
Return a JSON with:
- recommended_skills: New skills to add
- skills_to_remove: Skills to consider removing
- skill_categories: Grouping of skills by category
- trending_skills: Currently popular skills
"""
response = await llm_text_gen(prompt)
return json.loads(response)
async def analyze_profile_strength(self,
profile_data: Dict
) -> Dict:
"""
Analyze overall profile strength and provide improvement recommendations.
Args:
profile_data: Complete profile information
Returns:
Dict containing analysis and recommendations
"""
prompt = f"""
As a LinkedIn profile optimization expert, analyze this profile:
Profile Data: {json.dumps(profile_data)}
Provide a comprehensive analysis including:
- Overall profile strength score
- Section-by-section analysis
- Missing elements
- Improvement opportunities
- SEO optimization suggestions
- Engagement potential
Return a JSON with:
- strength_score: 0-100 rating
- section_scores: Individual section ratings
- missing_elements: Key missing components
- priority_improvements: Ordered list of suggestions
- seo_recommendations: Keyword and optimization tips
"""
response = await llm_text_gen(prompt)
return json.loads(response)

View File

@@ -0,0 +1,209 @@
"""
LinkedIn Profile Optimizer UI
This module provides the Streamlit UI for the LinkedIn Profile Optimizer.
"""
import streamlit as st
import json
from typing import Dict, List
from .linkedin_profile_optimizer import LinkedInProfileOptimizer
async def linkedin_profile_optimizer_ui():
"""
Streamlit UI for the LinkedIn Profile Optimizer.
"""
# Initialize the profile optimizer
optimizer = LinkedInProfileOptimizer()
# Create tabs for different optimization sections
tabs = st.tabs([
"Profile Analysis",
"Headline Optimizer",
"About Section",
"Experience Enhancer",
"Skills Recommender"
])
# Profile Analysis Tab
with tabs[0]:
st.header("Profile Strength Analysis")
st.info("Upload your profile information for a comprehensive analysis")
# Profile Data Input
with st.expander("Enter Profile Information", expanded=True):
profile_data = {
"headline": st.text_input("Current Headline"),
"about": st.text_area("About Section"),
"industry": st.text_input("Industry"),
"current_role": st.text_input("Current Role"),
"experience": [],
"skills": st.text_area("Current Skills (one per line)").split("\n"),
"education": st.text_area("Education (one per line)").split("\n")
}
# Experience Input
st.subheader("Work Experience")
num_experiences = st.number_input("Number of experiences to add", min_value=0, max_value=10, value=1)
for i in range(num_experiences):
with st.expander(f"Experience {i+1}"):
exp = {
"role": st.text_input(f"Role {i+1}"),
"company": st.text_input(f"Company {i+1}"),
"description": st.text_area(f"Description {i+1}")
}
profile_data["experience"].append(exp)
if st.button("Analyze Profile"):
with st.spinner("Analyzing your profile..."):
analysis = await optimizer.analyze_profile_strength(profile_data)
# Display Analysis Results
col1, col2 = st.columns(2)
with col1:
st.metric("Profile Strength Score", f"{analysis['strength_score']}/100")
st.subheader("Section Scores")
for section, score in analysis['section_scores'].items():
st.progress(score/100, text=f"{section}: {score}%")
with col2:
st.subheader("Priority Improvements")
for improvement in analysis['priority_improvements']:
st.warning(improvement)
st.subheader("SEO Recommendations")
for rec in analysis['seo_recommendations']:
st.info(rec)
# Headline Optimizer Tab
with tabs[1]:
st.header("Headline Optimizer")
st.info("Optimize your headline for better visibility and impact")
current_headline = st.text_input("Current Headline")
industry = st.text_input("Industry")
role = st.text_input("Current/Target Role")
if st.button("Optimize Headline"):
with st.spinner("Generating optimized headline..."):
headline_optimization = await optimizer.optimize_headline(
current_headline,
industry,
role
)
st.subheader("Optimized Headline")
st.success(headline_optimization['optimized_headline'])
st.subheader("Optimization Explanation")
st.write(headline_optimization['explanation'])
st.subheader("Keywords Used")
for keyword in headline_optimization['keywords_used']:
st.info(keyword)
# About Section Tab
with tabs[2]:
st.header("About Section Generator")
st.info("Create an engaging and professional About section")
current_about = st.text_area("Current About Section")
achievements = st.text_area("Key Achievements (one per line)").split("\n")
target_audience = st.text_input("Target Audience")
if st.button("Generate About Section"):
with st.spinner("Generating optimized About section..."):
about_optimization = await optimizer.generate_about_section(
current_about,
profile_data.get("experience", []),
achievements,
target_audience
)
st.subheader("Optimized About Section")
st.markdown(about_optimization['about_section'])
st.subheader("Section Structure")
for section, explanation in about_optimization['structure_explanation'].items():
with st.expander(section):
st.write(explanation)
st.subheader("Impact Factors")
for factor in about_optimization['impact_factors']:
st.success(factor)
# Experience Enhancer Tab
with tabs[3]:
st.header("Experience Description Enhancer")
st.info("Enhance your work experience descriptions for maximum impact")
experiences = []
num_exp = st.number_input("Number of experiences to enhance", min_value=1, max_value=10, value=1)
for i in range(num_exp):
with st.expander(f"Experience {i+1}"):
exp = {
"role": st.text_input(f"Role {i+1}"),
"company": st.text_input(f"Company {i+1}"),
"description": st.text_area(f"Current Description {i+1}")
}
experiences.append(exp)
if st.button("Enhance Experiences"):
with st.spinner("Enhancing experience descriptions..."):
enhanced_experiences = await optimizer.enhance_experience_descriptions(experiences)
for i, exp in enumerate(enhanced_experiences):
with st.expander(f"Enhanced Experience {i+1}"):
st.subheader(f"{exp['role']} at {exp['company']}")
st.markdown(exp['enhanced_description'])
st.subheader("Key Achievements")
for achievement in exp['achievements']:
st.success(achievement)
st.subheader("Keywords Used")
for keyword in exp['keywords']:
st.info(keyword)
# Skills Recommender Tab
with tabs[4]:
st.header("Skills Recommender")
st.info("Get personalized skill recommendations for your profile")
current_skills = st.text_area("Current Skills (one per line)").split("\n")
industry = st.text_input("Industry (for skills)")
role = st.text_input("Role (for skills)")
if st.button("Get Skill Recommendations"):
with st.spinner("Analyzing and recommending skills..."):
skill_recommendations = await optimizer.recommend_skills(
current_skills,
industry,
role
)
col1, col2 = st.columns(2)
with col1:
st.subheader("Recommended Skills to Add")
for skill in skill_recommendations['recommended_skills']:
st.success(skill)
st.subheader("Consider Removing")
for skill in skill_recommendations['skills_to_remove']:
st.warning(skill)
with col2:
st.subheader("Trending Skills")
for skill in skill_recommendations['trending_skills']:
st.info(skill)
st.subheader("Skill Categories")
for category, skills in skill_recommendations['skill_categories'].items():
with st.expander(category):
for skill in skills:
st.write(f"- {skill}")

View File

@@ -0,0 +1,207 @@
# LinkedIn Video Script Generator
## Overview
The LinkedIn Video Script Generator is an AI-powered tool designed to help professionals create engaging and effective video scripts for LinkedIn content. This tool combines research-driven insights with professional scriptwriting techniques to generate compelling video content that resonates with your target audience.
## Features
### 1. Script Generation
- **Hook Creation**: Generate attention-grabbing openings that capture viewer interest
- **Story Structure**: Create well-organized scripts with clear sections and transitions
- **Professional Speaking Points**: Generate key talking points and emphasis areas
- **Multiple Video Types**:
- Thought Leadership
- Tutorial/How-to
- Product Demo
- Company Culture
- Industry Insights
- Event Highlights
- Customer Story
- Behind the Scenes
### 2. Research Integration
- **Multi-Source Research**: Gather insights from:
- Metaphor (neural search)
- Google SERP
- Tavily AI
- **Insight Extraction**: Automatically extract key insights and trends
- **Topic Analysis**: Research current trends and best practices
### 3. Visual Elements
- **Visual Cue Suggestions**: Get recommendations for:
- B-roll footage
- Graphics and animations
- Text overlays
- Visual transitions
- **Timing Guidance**: Precise timing suggestions for each visual element
- **Visual Hierarchy**: Optimize visual flow and emphasis
### 4. Engagement Optimization
- **Call-to-Action Generation**: Create compelling CTAs
- **Engagement Prompts**: Generate discussion questions and interaction points
- **Audience Targeting**: Tailor content to specific professional audiences
- **Tone Customization**: Multiple tone options:
- Professional & Authoritative
- Conversational & Friendly
- Educational & Informative
- Inspirational & Motivational
- Storytelling & Narrative
### 5. Length Options
- Short (< 1 minute)
- Medium (1-3 minutes)
- Long (3-5 minutes)
- Extended (5+ minutes)
## Usage
### Basic Workflow
1. **Enter Basic Details**
- Choose your topic
- Select your industry
- Pick a video type
- Set desired length
2. **Configure Advanced Options**
- Select target audience
- Choose tone
- Set additional preferences
3. **Research Your Topic**
- Choose research source
- Review insights and trends
- Incorporate key findings
4. **Generate Script**
- Get complete script with sections
- Review visual suggestions
- Check engagement elements
### Best Practices
#### Script Structure
1. **Strong Hook (0-15 seconds)**
- Capture attention immediately
- Present clear value proposition
- Use professional tone
2. **Content Flow (Main Body)**
- Clear section transitions
- Logical progression
- Engaging visuals
3. **Effective Closing**
- Strong call-to-action
- Engagement prompts
- Next steps
#### Visual Elements
1. **Professional Quality**
- High-quality visuals
- Consistent branding
- Clear text overlays
2. **Engagement Focus**
- Strategic visual pacing
- Attention-holding elements
- Professional transitions
3. **Brand Consistency**
- Aligned with brand guidelines
- Professional appearance
- Consistent style
#### Content Tips by Video Type
##### Thought Leadership
- Focus on unique insights
- Share expert perspective
- Include industry trends
##### Tutorial/How-to
- Clear step-by-step structure
- Visual demonstrations
- Practical examples
##### Product Demo
- Feature highlights
- Use cases
- Value proposition
##### Company Culture
- Authentic representation
- Team involvement
- Behind-the-scenes elements
## Technical Details
### Dependencies
- Streamlit: For the user interface
- GPT Providers: For AI text generation
- Web Research Tools: For gathering insights
### Integration
The Video Script Generator is fully integrated into the LinkedIn AI Writer suite and can be accessed through the main interface.
## Examples
### Example 1: Tech Industry Thought Leadership
**Topic**: "The Future of AI in Business"
**Length**: 2-3 minutes
**Target**: Decision Makers
### Example 2: Healthcare Tutorial
**Topic**: "Implementing Telehealth Solutions"
**Length**: 3-5 minutes
**Target**: Healthcare Professionals
### Example 3: Product Demo
**Topic**: "New CRM Features Overview"
**Length**: 1-2 minutes
**Target**: Business Users
## Troubleshooting
### Common Issues
1. **Research Not Returning Results**
- Try different search terms
- Switch research sources
- Check connection
2. **Script Generation Issues**
- Verify all fields are filled
- Try different topic phrasing
- Check length settings
3. **Visual Suggestions**
- Ensure script sections are clear
- Check timing specifications
- Review section content
## Future Enhancements
- **AI Voice Generation**: Add AI voiceover capabilities
- **Template Library**: Pre-built script templates
- **Analytics Integration**: Performance tracking
- **Multi-language Support**: Generate scripts in multiple languages
- **Direct Publishing**: Integration with LinkedIn video upload
## Contributing
Contributions to the LinkedIn Video Script Generator are welcome! Please follow these steps:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Contact
For questions or feedback about the LinkedIn Video Script Generator, please contact the development team.

View File

@@ -0,0 +1,10 @@
"""
LinkedIn Video Script Generator Module
This module provides functionality for generating professional video scripts
for LinkedIn content with AI-powered optimization and engagement features.
"""
from .linkedin_video_script_generator import LinkedInVideoScriptGenerator, linkedin_video_script_generator_ui
__all__ = ["LinkedInVideoScriptGenerator", "linkedin_video_script_generator_ui"]

View File

@@ -0,0 +1,462 @@
"""
LinkedIn Video Script Generator
This module provides functionality for generating professional video scripts
for LinkedIn content with AI-powered optimization and engagement features.
"""
import streamlit as st
import json
from typing import Dict, List, Optional, Union
from loguru import logger
from .....gpt_providers.text_generation.main_text_generation import llm_text_gen
from .....ai_web_researcher.gpt_online_researcher import do_google_serp_search
from .....ai_web_researcher.metaphor_basic_neural_web_search import metaphor_search_articles
from .....ai_web_researcher.tavily_ai_search import do_tavily_ai_search
class LinkedInVideoScriptGenerator:
"""
AI-powered LinkedIn video script generator that creates engaging scripts with
hooks, story structure, and visual suggestions.
"""
def __init__(self):
"""Initialize the LinkedIn Video Script Generator."""
self.video_types = {
"thought_leadership": "Thought Leadership",
"tutorial": "Tutorial/How-to",
"product_demo": "Product Demo",
"company_culture": "Company Culture",
"industry_insights": "Industry Insights",
"event_highlights": "Event Highlights",
"customer_story": "Customer Story",
"behind_scenes": "Behind the Scenes"
}
self.video_lengths = {
"short": "Short (< 1 minute)",
"medium": "Medium (1-3 minutes)",
"long": "Long (3-5 minutes)",
"extended": "Extended (5+ minutes)"
}
self.tone_options = {
"professional": "Professional & Authoritative",
"conversational": "Conversational & Friendly",
"educational": "Educational & Informative",
"inspirational": "Inspirational & Motivational",
"storytelling": "Storytelling & Narrative"
}
self.target_audiences = {
"professionals": "Industry Professionals",
"decision_makers": "Decision Makers",
"job_seekers": "Job Seekers",
"students": "Students & Early Career",
"entrepreneurs": "Entrepreneurs & Business Owners",
"general": "General Professional Network"
}
def research_topic(self, topic: str, industry: str, search_engine: str = "metaphor") -> Dict:
"""
Research a topic to gather insights for video content.
Args:
topic: The main topic for the video
industry: The target industry
search_engine: The search engine to use (metaphor, google, tavily)
Returns:
Dict containing research results and insights
"""
try:
search_query = f"{topic} {industry} trends insights best practices"
if search_engine == "metaphor":
articles = metaphor_search_articles(search_query)
elif search_engine == "google":
articles = do_google_serp_search(search_query)
elif search_engine == "tavily":
articles = do_tavily_ai_search(search_query)
else:
raise ValueError(f"Unsupported search engine: {search_engine}")
insights, trends = self._extract_insights_and_trends(articles)
return {
"articles": articles,
"insights": insights,
"trends": trends
}
except Exception as e:
logger.error(f"Error researching topic: {str(e)}")
return {
"articles": [],
"insights": [],
"trends": []
}
def _extract_insights_and_trends(self, articles: List[Dict]) -> tuple[List[str], List[str]]:
"""Extract key insights and trends from research articles."""
try:
prompt = f"""
Based on the following articles, extract:
1. Key insights relevant for a video script
2. Current trends in the industry
Articles:
{json.dumps(articles, indent=2)}
Return a JSON with two lists: 'insights' and 'trends'
"""
response = llm_text_gen(prompt)
result = json.loads(response)
return result.get("insights", []), result.get("trends", [])
except Exception as e:
logger.error(f"Error extracting insights and trends: {str(e)}")
return [], []
def generate_hook(self, topic: str, video_type: str, target_audience: str, tone: str) -> str:
"""
Generate an attention-grabbing hook for the video.
Args:
topic: The main topic of the video
video_type: Type of video content
target_audience: Target audience for the video
tone: Desired tone of the hook
Returns:
str: The generated hook
"""
try:
prompt = f"""
Create an attention-grabbing hook for a LinkedIn video with:
- Topic: {topic}
- Video Type: {self.video_types[video_type]}
- Target Audience: {self.target_audiences[target_audience]}
- Tone: {self.tone_options[tone]}
The hook should be:
1. Under 15 seconds when spoken
2. Immediately capture attention
3. Clear value proposition
4. Professional and engaging
Return only the hook text.
"""
return llm_text_gen(prompt)
except Exception as e:
logger.error(f"Error generating hook: {str(e)}")
return ""
def generate_story_structure(self, topic: str, video_type: str, length: str, insights: List[str]) -> Dict:
"""
Generate a structured outline for the video.
Args:
topic: Main topic of the video
video_type: Type of video content
length: Target video length
insights: Research insights to incorporate
Returns:
Dict containing the story structure
"""
try:
prompt = f"""
Create a professional video script structure for LinkedIn with:
- Topic: {topic}
- Video Type: {self.video_types[video_type]}
- Length: {self.video_lengths[length]}
- Key Insights: {json.dumps(insights)}
Return a JSON with:
1. sections: List of sections with timing and content
2. transitions: List of smooth transitions
3. key_points: Main points to emphasize
4. pacing_notes: Guidance on pacing and delivery
"""
response = llm_text_gen(prompt)
return json.loads(response)
except Exception as e:
logger.error(f"Error generating story structure: {str(e)}")
return {
"sections": [],
"transitions": [],
"key_points": [],
"pacing_notes": []
}
def generate_visual_cues(self, script_sections: List[Dict]) -> List[Dict]:
"""
Generate visual suggestions for each section of the script.
Args:
script_sections: List of script sections
Returns:
List of visual cue suggestions
"""
try:
prompt = f"""
For each section of the LinkedIn video script, suggest visual elements:
Script Sections:
{json.dumps(script_sections, indent=2)}
For each section, provide:
1. Visual type (b-roll, graphics, text overlay, etc.)
2. Description of visual content
3. Timing and duration
4. Visual transitions
Return a JSON array of visual suggestions.
"""
response = llm_text_gen(prompt)
return json.loads(response)
except Exception as e:
logger.error(f"Error generating visual cues: {str(e)}")
return []
def generate_full_script(self, topic: str, video_type: str, length: str,
target_audience: str, tone: str, insights: List[str]) -> Dict:
"""
Generate a complete video script with all components.
Args:
topic: Main topic of the video
video_type: Type of video content
length: Target video length
target_audience: Target audience
tone: Desired tone
insights: Research insights
Returns:
Dict containing the complete script
"""
try:
# Generate hook
hook = self.generate_hook(topic, video_type, target_audience, tone)
# Generate story structure
structure = self.generate_story_structure(topic, video_type, length, insights)
# Generate visual cues
visuals = self.generate_visual_cues(structure["sections"])
# Generate call-to-action
cta = self.generate_cta(topic, video_type, target_audience)
# Combine all components
script = {
"metadata": {
"topic": topic,
"video_type": video_type,
"length": length,
"target_audience": target_audience,
"tone": tone
},
"hook": hook,
"structure": structure,
"visuals": visuals,
"cta": cta
}
return script
except Exception as e:
logger.error(f"Error generating full script: {str(e)}")
return {}
def generate_cta(self, topic: str, video_type: str, target_audience: str) -> Dict:
"""Generate an effective call-to-action."""
try:
prompt = f"""
Create an effective call-to-action for a LinkedIn video:
- Topic: {topic}
- Video Type: {self.video_types[video_type]}
- Target Audience: {self.target_audiences[target_audience]}
Return a JSON with:
1. primary_cta: Main call-to-action text
2. secondary_cta: Optional follow-up action
3. engagement_prompts: Questions or prompts for comments
"""
response = llm_text_gen(prompt)
return json.loads(response)
except Exception as e:
logger.error(f"Error generating CTA: {str(e)}")
return {}
def linkedin_video_script_generator_ui():
"""Streamlit UI for the LinkedIn Video Script Generator."""
st.title("LinkedIn Video Script Generator")
st.markdown("""
Create professional video scripts for LinkedIn that drive engagement and showcase your expertise.
""")
# Initialize the video script generator
generator = LinkedInVideoScriptGenerator()
# Create tabs for different sections
tab1, tab2, tab3 = st.tabs(["Script Details", "Research & Insights", "Generated Script"])
with tab1:
st.header("Video Script Details")
# Basic information
col1, col2 = st.columns(2)
with col1:
topic = st.text_input("Topic", placeholder="e.g., AI in Healthcare, Remote Work Best Practices")
industry = st.text_input("Industry", placeholder="e.g., Technology, Healthcare, Finance")
with col2:
video_type = st.selectbox(
"Video Type",
options=list(generator.video_types.keys()),
format_func=lambda x: generator.video_types[x]
)
length = st.selectbox(
"Video Length",
options=list(generator.video_lengths.keys()),
format_func=lambda x: generator.video_lengths[x]
)
# Advanced options
with st.expander("Advanced Options"):
col3, col4 = st.columns(2)
with col3:
target_audience = st.selectbox(
"Target Audience",
options=list(generator.target_audiences.keys()),
format_func=lambda x: generator.target_audiences[x]
)
with col4:
tone = st.selectbox(
"Tone",
options=list(generator.tone_options.keys()),
format_func=lambda x: generator.tone_options[x]
)
with tab2:
st.header("Research & Insights")
if topic and industry:
# Research options
search_engine = st.selectbox(
"Research Source",
options=["metaphor", "google", "tavily"],
format_func=lambda x: x.title()
)
if st.button("Research Topic"):
with st.spinner("Researching topic..."):
research_results = generator.research_topic(topic, industry, search_engine)
if research_results["insights"] or research_results["trends"]:
# Store results in session state
st.session_state.research_results = research_results
# Display insights
st.subheader("Key Insights")
for insight in research_results["insights"]:
st.markdown(f"- {insight}")
# Display trends
st.subheader("Current Trends")
for trend in research_results["trends"]:
st.markdown(f"- {trend}")
else:
st.warning("No insights found. Try adjusting your topic or using a different research source.")
else:
st.info("Please enter a topic and industry in the Script Details tab to research insights.")
with tab3:
st.header("Generated Script")
if all([topic, industry, video_type, length, target_audience, tone]):
if st.button("Generate Script"):
with st.spinner("Generating video script..."):
# Get insights from research if available
insights = []
if hasattr(st.session_state, 'research_results'):
insights = st.session_state.research_results.get("insights", [])
# Generate full script
script = generator.generate_full_script(
topic=topic,
video_type=video_type,
length=length,
target_audience=target_audience,
tone=tone,
insights=insights
)
if script:
# Display hook
st.subheader("Hook")
st.write(script["hook"])
# Display structure
st.subheader("Script Structure")
for i, section in enumerate(script["structure"]["sections"], 1):
with st.expander(f"Section {i}"):
st.write(f"**Timing:** {section.get('timing', 'N/A')}")
st.write(f"**Content:** {section.get('content', 'N/A')}")
# Display visual cues for this section
if script["visuals"]:
visual = next((v for v in script["visuals"] if v.get("section") == i), None)
if visual:
st.write("**Visual Elements:**")
st.write(f"- Type: {visual.get('type', 'N/A')}")
st.write(f"- Description: {visual.get('description', 'N/A')}")
st.write(f"- Duration: {visual.get('duration', 'N/A')}")
# Display transitions
st.subheader("Transitions")
for transition in script["structure"]["transitions"]:
st.markdown(f"- {transition}")
# Display key points
st.subheader("Key Points to Emphasize")
for point in script["structure"]["key_points"]:
st.markdown(f"- {point}")
# Display CTA
st.subheader("Call-to-Action")
st.write(f"**Primary CTA:** {script['cta'].get('primary_cta', 'N/A')}")
if script['cta'].get('secondary_cta'):
st.write(f"**Secondary CTA:** {script['cta']['secondary_cta']}")
# Display engagement prompts
if script['cta'].get('engagement_prompts'):
st.subheader("Engagement Prompts")
for prompt in script['cta']['engagement_prompts']:
st.markdown(f"- {prompt}")
# Display pacing notes
st.subheader("Pacing & Delivery Notes")
for note in script["structure"]["pacing_notes"]:
st.markdown(f"- {note}")
else:
st.error("Failed to generate script. Please try again.")
else:
st.info("Please fill in all required fields in the Script Details tab to generate a script.")

View File

@@ -55,7 +55,6 @@ def generate_image(user_prompt):
image_stored_at = generate_dalle3_images(img_prompt)
elif 'Stability-AI' in image_engine:
logger.info(f"Calling Stable diffusion text-to-image with prompt: \n{img_prompt}")
print("\n\n")
image_stored_at = generate_stable_diffusion_image(img_prompt)
elif 'Gemini-AI' in image_engine:
logger.info(f"Calling Gemini text-to-image with prompt: \n{img_prompt}")

View File

@@ -15,8 +15,8 @@ from lib.ai_writers.ai_news_article_writer import ai_news_generation
#from lib.ai_writers.ai_agents_crew_writer import ai_agents_writers
from lib.ai_writers.ai_financial_writer import write_basic_ta_report
from lib.ai_writers.ai_facebook_writer.facebook_ai_writer import facebook_main_menu
from lib.ai_writers.linkedin_ai_writer import linked_post_writer
from lib.ai_writers.twitter_ai_writer import tweet_writer
from lib.ai_writers.linkedin_writer.linkedin_ai_writer import linkedin_main_menu
from lib.ai_writers.twitter_ai_writer import tweet_writer
from lib.ai_writers.insta_ai_writer import insta_writer
from lib.ai_writers.youtube_writers.youtube_ai_writer import youtube_main_menu
from lib.ai_writers.web_url_ai_writer import blog_from_url

View File

@@ -8,6 +8,7 @@ from lib.alwrity_ui.keyword_web_researcher import do_web_research
from lib.ai_writers.ai_story_writer.story_writer import story_input_section
from lib.ai_writers.ai_product_description_writer import write_ai_prod_desc
from lib.ai_writers.ai_copywriter.copywriter_dashboard import copywriter_dashboard
from lib.ai_writers.linkedin_writer import LinkedInAIWriter
#from lib.content_planning_calender.content_planning_agents_alwrity_crew import ai_agents_content_planner
@@ -20,6 +21,7 @@ def ai_writers():
"Write Financial TA report",
"AI Product Description Writer",
"AI Copywriter",
"LinkedIn AI Writer",
"Quit"
]
choice = st.selectbox("**👇Select a content creation type:**", options, index=0, format_func=lambda x: f"📝 {x}")
@@ -39,6 +41,10 @@ def ai_writers():
elif choice == "AI Copywriter":
# Initialize the copywriter dashboard
copywriter_dashboard()
elif choice == "LinkedIn AI Writer":
# Initialize the LinkedIn AI Writer
linkedin_writer = LinkedInAIWriter()
linkedin_writer.run()
elif choice == "Quit":
st.info("Thank you for using Alwrity. Goodbye!")
st.stop()

View File

@@ -8,7 +8,7 @@ from lib.utils.settings_page import render_settings_page
# Import social media writer functions
from lib.ai_writers.ai_facebook_writer.facebook_ai_writer import facebook_main_menu
from lib.ai_writers.linkedin_ai_writer import linked_post_writer
from lib.ai_writers.linkedin_writer.linkedin_ai_writer import linkedin_main_menu
from lib.ai_writers.twitter_ai_writer import tweet_writer
from lib.ai_writers.insta_ai_writer import insta_writer
from lib.ai_writers.youtube_writers.youtube_ai_writer import youtube_main_menu
@@ -321,7 +321,7 @@ def setup_alwrity_ui():
# Define sub-menu items for AI Social Tools
social_tools_submenu = {
"Facebook": ("📘", lambda: facebook_main_menu()),
"LinkedIn": ("💼", lambda: linked_post_writer()),
"LinkedIn": ("💼", lambda: linkedin_main_menu()),
"Twitter": ("🐦", lambda: tweet_writer()),
"Instagram": ("📸", lambda: insta_writer()),
"YouTube": ("🎥", lambda: youtube_main_menu())

Binary file not shown.

After

Width:  |  Height:  |  Size: 742 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 838 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 662 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 831 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 668 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 880 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 877 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 789 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 692 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 856 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 805 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 824 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 898 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 698 KiB