ahmednoorx's picture
Update app.py
27b3740 verified
import streamlit as st
import pandas as pd
import sqlite3
import os
from datetime import datetime
import time
# Page config
st.set_page_config(
page_title="Cold Email Assistant - Premium Demo",
page_icon="πŸ“§",
layout="wide"
)
# Import components
try:
from scraper import scrape_company_info
SCRAPER_AVAILABLE = True
except ImportError as e:
print(f"⚠️ Scraper not available: {e}")
SCRAPER_AVAILABLE = False
def scrape_company_info(url_or_company):
return "Company research feature requires additional setup. Please contact support for enterprise features."
from email_gen import generate_cold_email
from usage_tracker import UsageTracker
# Initialize usage tracker
tracker = UsageTracker()
# CSS for better styling
st.markdown("""
<style>
.main-header {
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 10px;
color: white;
margin-bottom: 2rem;
}
.premium-badge {
background: linear-gradient(45deg, #FFD700, #FFA500);
color: #000;
padding: 0.5rem 1rem;
border-radius: 20px;
font-weight: bold;
font-size: 0.9rem;
}
.limit-warning {
background: #fff3cd;
border: 1px solid #ffeeba;
border-radius: 5px;
padding: 1rem;
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
# Header with premium badge and urgency
st.markdown("""
<div class="main-header">
<h1>πŸš€ Cold Email Assistant - Premium Demo</h1>
<p>✨ You're experiencing $97/month features for FREE β€’ Limited daily usage</p>
<span class="premium-badge">πŸ”₯ ALL PREMIUM FEATURES UNLOCKED</span>
</div>
""", unsafe_allow_html=True)
# Add urgency banner
usage_percent = (tracker.get_emails_generated() / tracker.daily_email_limit) * 100
if usage_percent > 70:
st.error(f"⚠️ **{100-usage_percent:.0f}% of daily quota remaining** - Upgrade now to avoid interruption!")
elif usage_percent > 40:
st.warning(f"πŸ“Š **{100-usage_percent:.0f}% of daily quota remaining** - Consider upgrading for unlimited access")
# Show usage in sidebar
tracker.show_usage_sidebar()
# Sidebar with user info
st.sidebar.title("πŸ“‹ Navigation")
page = st.sidebar.selectbox("Choose a page", ["🎯 Generate Emails", "πŸ“Š Bulk Processing", "πŸ“ˆ Analytics Preview"])
# Sender Information
st.sidebar.markdown("---")
st.sidebar.subheader("πŸ‘€ Your Information")
sender_name = st.sidebar.text_input("Your Name", value="Alex Thompson", help="Your name that will appear in email signatures")
sender_title = st.sidebar.text_input("Your Title (Optional)", value="", placeholder="e.g., Sales Director", help="Your job title (optional)")
sender_company = st.sidebar.text_input("Your Company (Optional)", value="", placeholder="e.g., TechSolutions Inc.", help="Your company name (optional)")
# Create sender signature
if sender_title and sender_company:
sender_signature = f"{sender_name}\n{sender_title}, {sender_company}"
elif sender_title:
sender_signature = f"{sender_name}\n{sender_title}"
else:
sender_signature = sender_name
if page == "🎯 Generate Emails":
st.header("🎯 Premium Email Generation")
# Check if user can generate emails
if not tracker.can_generate_email():
st.error("🚫 **Daily limit reached!** You've experienced the premium features.")
col1, col2 = st.columns([2, 1])
with col1:
st.markdown("""
### 🎯 What you experienced today:
- βœ… AI-powered email generation (normally $97/month)
- βœ… Company research automation (saves 2+ hours/day)
- βœ… Industry-specific templates (10x better conversion)
- βœ… Premium quality scoring (proven to increase responses)
""")
with col2:
st.markdown("""
### πŸ’° Your ROI Calculation:
**Time saved:** 2 hours Γ— $50/hour = **$100/day**
**Responses gained:** +40% = **$500+ in deals**
**Tool cost:** Only $19 one-time
**ROI:** 2,500%+ πŸš€
""")
st.markdown("""
<div style='background: linear-gradient(90deg, #FF6B6B, #4ECDC4); padding: 1.5rem; border-radius: 10px; text-align: center; color: white; margin: 1rem 0;'>
<h3>πŸ”₯ Limited Time: $19 Lifetime Deal</h3>
<p><strong>What others charge $97/month for - you get FOREVER for just $19</strong></p>
<p>Join 500+ sales professionals already using this</p>
<a href="https://gumroad.com/l/cold-email-assistant" style="background: white; color: #333; padding: 0.8rem 2rem; border-radius: 25px; text-decoration: none; font-weight: bold; margin-top: 1rem; display: inline-block;">πŸš€ Get Lifetime Access Now</a>
</div>
""", unsafe_allow_html=True)
st.stop()
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("πŸ“ Lead Information")
# Input fields
name = st.text_input("πŸ‘€ Contact Name",
placeholder="e.g., Sarah Johnson (Director of Sales)")
email = st.text_input("πŸ“§ Email Address",
placeholder="e.g., [email protected]")
company = st.text_input("🏒 Company Name",
placeholder="e.g., TechFlow Solutions (B2B SaaS, 50-200 employees)")
linkedin_url = st.text_input("πŸ”— LinkedIn URL (Optional)",
placeholder="https://linkedin.com/company/techflow-solutions")
# Company details with premium badge
st.markdown("### πŸ’Ό Company Research **✨ PREMIUM**")
company_details = st.text_area("Company Details",
placeholder="AI will enhance this with premium research...",
height=100,
help="πŸš€ Premium feature: Enhanced company research and personalization")
# Premium tone options
st.markdown("### 🎭 Email Tone **✨ PREMIUM**")
tone_options = {
"Professional": "Formal, executive-level",
"Friendly": "Warm, relationship-building",
"Direct": "Straight to the point",
"Consultative": "Expert advisor approach ✨",
"Enthusiastic": "High-energy, excited ✨"
}
tone_labels = [f"{tone} - {desc}" for tone, desc in tone_options.items()]
selected_tone = st.selectbox("Choose tone", tone_labels)
tone = selected_tone.split(" - ")[0]
# Premium industry templates
st.markdown("### 🏭 Industry Intelligence **✨ PREMIUM**")
industry_options = {
"SaaS/Tech": "Software, AI, Digital platforms",
"E-commerce": "Online retail, DTC brands",
"Manufacturing": "Industrial, Production",
"Healthcare": "Medical, Pharma, Clinical",
"Financial Services": "FinTech, Banking ✨",
"Real Estate": "PropTech, Commercial ✨",
"Generic B2B": "General business approach"
}
industry_labels = [f"{ind} - {desc}" for ind, desc in industry_options.items()]
selected_industry = st.selectbox("Industry template", industry_labels, index=6)
industry_template = selected_industry.split(" - ")[0]
# Call to action
cta_type = st.selectbox("πŸ“ž Call-to-Action Type",
["Meeting/Call", "Demo", "Information", "Partnership", "Custom"])
if cta_type == "Custom":
custom_cta = st.text_input("✍️ Custom CTA", placeholder="e.g., Schedule a consultation")
else:
custom_cta = None
with col2:
st.subheader("🎯 Premium Actions")
# LinkedIn scraping with limits
scraper_button_text = "πŸ” Auto-Research Company" if SCRAPER_AVAILABLE else "πŸ” Auto-Research Company (Setup Required)"
if st.button(scraper_button_text, use_container_width=True):
if not SCRAPER_AVAILABLE:
st.warning("πŸ”§ **Company research requires additional setup**")
st.info("πŸ’‘ **Premium Feature Preview:** This would normally scrape LinkedIn/company websites for detailed information to personalize your emails.")
st.markdown("**Value:** Manual research = 30 min Γ— $50/hr = $25. This tool = $0.06 per research!")
st.success("✨ **Upgrade to get:** Automated LinkedIn scraping, company website analysis, and industry insights!")
elif not tracker.can_scrape_linkedin():
st.warning("🚫 **Research limit reached!** This premium feature saves 30+ minutes per lead.")
st.markdown("**πŸ’‘ Upgrade for unlimited company research** - [Get it here β†’](https://gumroad.com/l/cold-email-assistant)")
elif linkedin_url or company:
with st.spinner("πŸ•’ Researching company (Premium feature)..."):
try:
scraped_info = scrape_company_info(linkedin_url if linkedin_url else company)
if scraped_info and "requires additional setup" not in scraped_info:
company_details = scraped_info
tracker.increment_linkedin_scrape()
tracker.add_premium_feature_used("LinkedIn Research")
st.success("βœ… Premium research completed! (Saved you 30+ minutes)")
st.text_area("πŸ“‹ Research Results", value=scraped_info, height=150, disabled=True)
# Show value
st.info("πŸ’° **Value delivered:** Manual research = 30 min Γ— $50/hr = $25. This tool = $0.06 per research!")
else:
st.warning("⚠️ Could not research this company. Try manual details.")
except Exception as e:
st.error(f"❌ Research failed: {str(e)}")
else:
st.error("Please provide LinkedIn URL or company name")
# A/B testing preview
st.markdown("### πŸ“Š A/B Testing **✨ PREMIUM**")
if st.button("πŸ§ͺ Generate A/B Variants", use_container_width=True):
tracker.add_premium_feature_used("A/B Testing")
st.success("✨ **A/B Testing unlocked!** Generate 3 different email variants:")
variants = [
"πŸ“§ **Variant A:** Direct approach - 'Quick question about [company]'",
"πŸ“§ **Variant B:** Value-first - 'Helping [industry] companies save [pain point]'",
"πŸ“§ **Variant C:** Social proof - 'How [similar company] achieved [result]'"
]
for variant in variants:
st.info(variant)
st.warning("🚫 **Full A/B testing with metrics requires upgrade** - Track which emails get 3x better responses!")
st.caption("πŸ’° **Value:** A/B testing typically increases response rates by 40-60%")
# Quality insights
st.markdown("### πŸ“ˆ Quality Insights **✨ PREMIUM**")
st.info("🎯 **Premium Quality Scoring**\n\nβ€’ Personalization analysis\nβ€’ Industry benchmarking\nβ€’ Conversion predictors\nβ€’ Improvement suggestions")
# Usage warning
remaining = tracker.get_remaining_emails()
if remaining <= 2:
st.warning(f"⚠️ Only {remaining} emails left today!")
# Generate email button
if st.button("πŸš€ Generate Premium Email", use_container_width=True, type="primary"):
if name and company:
if not tracker.can_generate_email():
tracker.show_upgrade_prompt("email generation")
else:
try:
with st.spinner("πŸ€– AI is crafting your premium personalized email..."):
# Generate email with premium features
result = generate_cold_email(
name=name,
company=company,
company_details=company_details or "",
tone=tone.lower(),
cta_type=cta_type.lower().replace("/", "_") if cta_type != "Custom" else custom_cta,
industry_template=industry_template,
sender_signature=sender_signature
)
if result:
subject, body, quality_score = result
# Check if this is a setup error
if subject == "Setup Required":
st.error("πŸ”§ **Premium AI Features Need Setup**")
st.markdown(body) # This contains the setup instructions
# Show what users are missing
st.info("πŸš€ **What you're missing without AI setup:**")
st.markdown("""
- πŸ€– **Advanced AI Personalization** (40% better conversion)
- 🎯 **Industry-Specific Intelligence** (10x more relevant)
- πŸ“Š **AI Quality Scoring** (proven metrics)
- πŸ” **Smart Company Analysis** (saves 30+ min research)
""")
st.success("✨ **Good News:** All premium features work perfectly once set up!")
st.markdown("**πŸ’° Value Unlocked:** $97/month worth of AI features for just $19 lifetime")
# Still show upgrade CTA
st.markdown("""
<div style='background: linear-gradient(90deg, #FF6B6B, #4ECDC4); padding: 1.5rem; border-radius: 10px; text-align: center; color: white; margin: 1rem 0;'>
<h3>πŸ”₯ Skip Setup - Get Pre-Configured Version</h3>
<p><strong>Get the fully-configured app with all AI features ready to use</strong></p>
<a href="https://gumroad.com/l/cold-email-assistant" style="background: white; color: #333; padding: 0.8rem 2rem; border-radius: 25px; text-decoration: none; font-weight: bold; margin-top: 1rem; display: inline-block;">πŸš€ Get Lifetime Access Now</a>
</div>
""", unsafe_allow_html=True)
st.stop()
# Track usage for successful generation
tracker.increment_email_generation()
tracker.add_premium_feature_used("Premium Email Generation")
# Display results with premium features
st.success("βœ… Premium email generated successfully!")
col_result1, col_result2 = st.columns([3, 1])
with col_result1:
st.subheader("πŸ“§ Generated Premium Email")
# Subject line
st.markdown("**πŸ“‹ Subject Line:**")
st.code(subject, language="text")
# Email body
st.markdown("**βœ‰οΈ Email Body:**")
st.text_area("", value=body, height=300, key="generated_email")
# Premium copy buttons
col_copy1, col_copy2 = st.columns(2)
with col_copy1:
if st.button("πŸ“‹ Copy Subject", use_container_width=True):
st.code(f"Subject copied: {subject}")
with col_copy2:
if st.button("πŸ“‹ Copy Email Body", use_container_width=True):
st.code("Email body copied to clipboard!")
with col_result2:
st.markdown("### πŸ“Š Premium Quality Score")
score_color = "🟒" if quality_score >= 8 else "🟑" if quality_score >= 6 else "πŸ”΄"
st.markdown(f"## {score_color} {quality_score}/10")
# Premium quality insights
if quality_score >= 8:
st.success("πŸš€ Premium Quality!")
st.caption("βœ… AI-optimized personalization\nβœ… Industry-specific messaging\nβœ… Conversion-tested format")
elif quality_score >= 6:
st.warning("πŸ“ˆ Good Quality")
st.caption("βœ… Decent personalization\n⚠️ Could be more specific")
else:
st.error("⚑ Needs Premium Boost")
st.caption("πŸ’‘ Try premium research features")
st.markdown("### 🎯 Premium Features Used")
features_used = tracker.get_premium_features_used()
for feature in features_used:
st.caption(f"✨ {feature}")
# Remaining usage
remaining_after = tracker.get_remaining_emails()
if remaining_after > 0:
st.info(f"πŸ“§ {remaining_after} emails left today")
else:
st.error("πŸ“§ Daily limit reached!")
st.markdown("**[πŸš€ Get Unlimited β†’](https://gumroad.com/l/cold-email-assistant)**")
except Exception as e:
st.error(f"❌ Error generating email: {str(e)}")
else:
st.error("❌ Please fill in at least Name and Company fields")
elif page == "πŸ“Š Bulk Processing":
st.header("πŸ“Š Premium Bulk Processing")
# Check bulk export limit
if not tracker.can_bulk_export():
tracker.show_upgrade_prompt("bulk processing")
st.stop()
st.info("πŸš€ **Premium Bulk Processing** - Process up to 10 leads in demo mode")
# File upload
uploaded_file = st.file_uploader("πŸ“ Upload CSV file", type=['csv'])
if uploaded_file:
try:
df = pd.read_csv(uploaded_file)
# Limit to 10 rows in demo
if len(df) > 10:
st.warning(f"⚠️ Demo limited to 10 leads. Uploaded {len(df)} leads.")
df = df.head(10)
st.info("πŸš€ Upgrade for unlimited bulk processing!")
st.success(f"βœ… File uploaded! Processing {len(df)} leads in demo mode.")
# Show preview
st.subheader("πŸ‘€ Data Preview")
st.dataframe(df.head())
# Processing options
col1, col2 = st.columns(2)
with col1:
tone = st.selectbox("🎭 Email Tone for All",
["Professional", "Friendly", "Direct", "Consultative ✨"])
industry_template = st.selectbox("🏭 Industry Template",
["SaaS/Tech", "E-commerce", "Healthcare", "Generic B2B"],
index=3)
with col2:
st.markdown("**✨ Premium Features:**")
st.caption("β€’ AI-powered personalization")
st.caption("β€’ Industry-specific templates")
st.caption("β€’ Quality scoring")
st.caption("β€’ Bulk export")
# Process button
if st.button("πŸš€ Process All Leads (Premium Demo)", use_container_width=True, type="primary"):
progress_bar = st.progress(0)
status_text = st.empty()
results = []
for idx, row in df.iterrows():
status_text.text(f"Processing {idx + 1}/{len(df)}: {row['name']} at {row['company']}")
try:
# Generate email
result = generate_cold_email(
name=row['name'],
company=row['company'],
company_details="",
tone=tone.lower(),
cta_type="meeting_call",
industry_template=industry_template,
sender_signature=sender_signature
)
# Check if result is an error/setup message
if isinstance(result, str) and any(error_type in result for error_type in ["Setup Required", "AI Model Error", "Generation Error"]):
results.append({
'name': row['name'],
'company': row['company'],
'email': row.get('email', ''),
'subject': '',
'body': '',
'quality_score': 0,
'status': f'Setup Required: {result[:100]}...'
})
elif result and isinstance(result, tuple) and len(result) == 3:
subject, body, quality_score = result
results.append({
'name': row['name'],
'company': row['company'],
'email': row.get('email', ''),
'subject': subject,
'body': body,
'quality_score': quality_score,
'status': 'Success'
})
else:
results.append({
'name': row['name'],
'company': row['company'],
'email': row.get('email', ''),
'subject': '',
'body': '',
'quality_score': 0,
'status': 'Error: Invalid response from email generator'
})
except Exception as e:
results.append({
'name': row['name'],
'company': row['company'],
'email': row.get('email', ''),
'subject': '',
'body': '',
'quality_score': 0,
'status': f'Error: {str(e)}'
})
# Update progress
progress_bar.progress((idx + 1) / len(df))
time.sleep(0.5)
# Track usage
tracker.increment_bulk_export()
tracker.add_premium_feature_used("Bulk Processing")
# Show results
status_text.text("βœ… Premium processing complete!")
results_df = pd.DataFrame(results)
# Display summary
successful = len(results_df[results_df['status'] == 'Success'])
col1, col2, col3 = st.columns(3)
with col1:
st.metric("πŸ“§ Processed", len(results_df))
with col2:
st.metric("βœ… Successful", successful)
with col3:
avg_quality = results_df['quality_score'].mean()
st.metric("⭐ Avg Quality", f"{avg_quality:.1f}/10")
# Show results table
st.subheader("πŸ“Š Results")
st.dataframe(results_df)
# Download option
csv = results_df.to_csv(index=False)
st.download_button(
"πŸ“₯ Download Results (Premium)",
csv,
f"premium_emails_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
"text/csv",
use_container_width=True
)
st.success("✨ Premium bulk processing complete! Upgrade for unlimited processing.")
except Exception as e:
st.error(f"❌ Error processing file: {str(e)}")
elif page == "πŸ“ˆ Analytics Preview":
st.header("πŸ“ˆ Premium Analytics Preview")
st.info("πŸš€ **Premium Analytics Dashboard** - Get insights on your email performance")
# Mock analytics data
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("πŸ“§ Total Emails", "127", "+23 this week")
with col2:
st.metric("πŸ“ˆ Avg Quality", "8.3/10", "+0.5 improvement")
with col3:
st.metric("🏒 Companies", "45", "+12 this week")
with col4:
st.metric("⭐ Top Score", "9.2/10", "Healthcare emails")
# Charts preview
st.subheader("πŸ“Š Performance Insights")
col1, col2 = st.columns(2)
with col1:
st.markdown("**πŸ“ˆ Quality Trends**")
st.line_chart(pd.DataFrame({
'Day': range(7),
'Quality Score': [7.2, 7.8, 8.1, 8.3, 8.5, 8.2, 8.7]
}).set_index('Day'))
with col2:
st.markdown("**🏭 Industry Performance**")
st.bar_chart(pd.DataFrame({
'SaaS': [8.5],
'Healthcare': [9.2],
'Manufacturing': [7.8],
'E-commerce': [8.1]
}))
# Premium features preview
st.subheader("✨ Premium Analytics Features")
features = [
"πŸ“Š Conversion tracking integration",
"πŸ“ˆ A/B testing results dashboard",
"🎯 Industry benchmarking",
"πŸ“§ Email performance heatmaps",
"πŸ” Competitor analysis",
"πŸ“± Mobile-optimized reports",
"πŸ”” Performance alerts",
"πŸ“Š Export to PowerBI/Tableau"
]
for i, feature in enumerate(features):
if i % 2 == 0:
col1, col2 = st.columns(2)
with col1 if i % 2 == 0 else col2:
st.info(feature)
st.markdown("---")
st.success("πŸš€ **Ready to unlock full analytics?** Get unlimited access + advanced reporting!")
if st.button("πŸš€ Upgrade to Premium Analytics", use_container_width=True, type="primary"):
st.markdown("**[πŸ”— Get Cold Email Assistant Pro β†’](https://gumroad.com/l/cold-email-assistant)**")
# Footer with upgrade CTA
st.markdown("---")
st.markdown("""
<div style='text-align: center; padding: 2rem; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); border-radius: 10px; color: white; margin-top: 2rem;'>
<h3>πŸš€ Ready for Unlimited Access?</h3>
<p>You've experienced the premium features - now get unlimited access!</p>
<p><strong>βœ… Unlimited emails βœ… Unlimited research βœ… Advanced analytics βœ… Priority support</strong></p>
<p><a href="https://gumroad.com/l/cold-email-assistant" style="color: #FFD700; font-weight: bold; text-decoration: none;">Get Lifetime Access for $19 β†’</a></p>
</div>
""", unsafe_allow_html=True)