File size: 8,930 Bytes
9447233
 
 
 
 
 
 
ecad45a
9447233
d70767c
9447233
 
 
 
d70767c
 
 
9447233
ecad45a
 
 
 
 
 
 
 
 
 
 
 
 
f9d1138
ecad45a
 
f9d1138
d70767c
 
 
 
f091a8d
d70767c
f091a8d
d70767c
f091a8d
d70767c
f091a8d
 
d70767c
 
 
 
f9d1138
 
d70767c
 
 
 
 
ecad45a
d70767c
 
ecad45a
d70767c
 
9447233
d70767c
 
9447233
d70767c
 
9447233
d70767c
 
 
9447233
d70767c
 
 
 
 
 
9447233
 
d70767c
 
 
 
 
 
f9d1138
d70767c
 
 
f9d1138
ecad45a
d70767c
 
 
 
 
9447233
d70767c
 
 
 
9447233
d70767c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9447233
d70767c
 
f091a8d
d70767c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f091a8d
d70767c
 
 
 
 
 
 
 
 
 
 
 
 
f091a8d
d70767c
 
 
 
 
 
 
 
9447233
d70767c
 
f091a8d
d70767c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9447233
 
 
 
ecad45a
d70767c
f9d1138
ecad45a
9447233
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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 - AI Email Generator",
    page_icon="πŸ“§",
    layout="wide"
)

# Initialize session state for demo tracking
if 'email_count' not in st.session_state:
    st.session_state.email_count = 0

@st.cache_resource
def load_modules():
    """Load required modules with error handling"""
    try:
        from scraper import LinkedInScraper
        from email_gen import EmailGenerator
        
        scraper = LinkedInScraper()
        email_generator = EmailGenerator()
        
        return scraper, email_generator
    except Exception as e:
        st.error(f"❌ Failed to load modules: {str(e)}")
        st.info("πŸ’‘ The AI model will be downloaded automatically on first run. Please ensure you have a stable internet connection.")
        return None, None

def create_fallback_email(name, company, tone="professional"):
    """Simple fallback when main system fails"""
    return {
        'subject': f"Partnership opportunity - {company}",
        'body': f"""Hi {name},

I came across {company} and was impressed by your work in the industry.

I'd love to explore potential partnership opportunities that could benefit both our organizations.

Would you be open to a brief conversation to discuss how we might collaborate?

Best regards,
[Your Name]""",
        'tone': tone,
        'personalization_score': 75,
        'estimated_response_rate': "15-25%"
    }

def main():
    # Header
    st.title("πŸ“§ Cold Email Assistant")
    st.markdown("### Generate High-Converting Cold Emails with AI")
    st.markdown("---")
    
    # Demo notice
    st.info("πŸš€ **Demo Version** - Try it out and let us know what you think! This uses advanced AI (Mistral-7B) to generate personalized cold emails.")
    
    # Load modules
    scraper, email_generator = load_modules()
    
    # Main interface
    col1, col2 = st.columns([1, 1])
    
    with col1:
        st.subheader("πŸ“ Lead Information")
        
        # Input fields
        name = st.text_input("πŸ‘€ Recipient Name *", placeholder="e.g., John Smith")
        company = st.text_input("🏒 Company Name *", placeholder="e.g., TechCorp Inc")
        
        # Company info
        st.markdown("**πŸ“Š Company Information** (Optional - helps with personalization)")
        company_info = st.text_area(
            "Company Details",
            placeholder="e.g., SaaS company, 50 employees, recently raised Series A...",
            height=100
        )
        
        # Tone selection
        tone = st.selectbox(
            "🎯 Email Tone",
            ["Professional", "Friendly", "Casual"],
            help="Choose the tone that matches your target audience"
        )
        
        # Generation options
        st.markdown("**βš™οΈ Generation Options**")
        num_variations = st.slider("Number of variations", 1, 5, 3)
        
    with col2:
        st.subheader("πŸ“§ Generated Emails")
        
        if st.button("πŸš€ Generate Cold Email", type="primary"):
            if not name or not company:
                st.error("❌ Please provide at least the recipient name and company name.")
            else:
                with st.spinner(f"πŸ€– Generating {num_variations} email variation(s)..."):
                    try:
                        # Track usage
                        st.session_state.email_count += num_variations
                        
                        if email_generator:
                            if num_variations == 1:
                                result = email_generator.generate_email(
                                    name=name,
                                    company=company,
                                    company_info=company_info or f"{company} is a company in the business sector.",
                                    tone=tone
                                )
                                results = [result] if result else []
                            else:
                                results = email_generator.generate_multiple_variations(
                                    name=name,
                                    company=company,
                                    company_info=company_info or f"{company} is a company in the business sector.",
                                    num_variations=num_variations,
                                    tone=tone
                                )
                        else:
                            # Fallback generation
                            results = [create_fallback_email(name, company, tone) for _ in range(num_variations)]
                        
                        if results:
                            st.success(f"βœ… Generated {len(results)} email variation(s)!")
                            
                            # Display results
                            for i, email in enumerate(results, 1):
                                with st.expander(f"πŸ“§ Email Variation {i} (Quality: {email.get('personalization_score', 'N/A')}/10)", expanded=i==1):
                                    st.markdown(f"**Subject:** {email.get('subject', 'N/A')}")
                                    st.markdown("**Email Body:**")
                                    st.text_area(f"Email {i}", value=email.get('body', 'N/A'), height=200, key=f"email_{i}")
                                    
                                    # Email metrics
                                    col_a, col_b, col_c = st.columns(3)
                                    with col_a:
                                        st.metric("Quality Score", f"{email.get('personalization_score', 'N/A')}/10")
                                    with col_b:
                                        st.metric("Tone", email.get('tone', 'N/A'))
                                    with col_c:
                                        st.metric("Est. Response Rate", email.get('estimated_response_rate', 'N/A'))
                            
                            # CSV Export
                            if st.button("πŸ“ Download as CSV", key="download_csv"):
                                df_data = []
                                for i, email in enumerate(results, 1):
                                    df_data.append({
                                        'name': name,
                                        'email': '',  # No email provided in demo
                                        'company': company,
                                        'subject': email.get('subject', ''),
                                        'email_content': email.get('body', ''),
                                        'quality_score': email.get('personalization_score', 0),
                                        'status': 'generated'
                                    })
                                
                                df = pd.DataFrame(df_data)
                                csv = df.to_csv(index=False)
                                st.download_button(
                                    label="πŸ“₯ Download CSV",
                                    data=csv,
                                    file_name=f"cold_emails_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                                    mime="text/csv"
                                )
                        
                        else:
                            st.error("❌ Failed to generate email. Please try again.")
                            
                    except Exception as e:
                        st.error(f"❌ An error occurred: {str(e)}")
                        st.info("πŸ’‘ Please try again or contact support if the issue persists.")
    
    # Usage stats
    st.markdown("---")
    st.markdown(f"πŸ“Š **Demo Stats:** {st.session_state.email_count} emails generated in this session")
    
    # Feedback section
    st.markdown("---")
    st.subheader("πŸ’­ Feedback")
    st.markdown("This is a demo version! Please let us know what you think:")
    
    feedback_col1, feedback_col2 = st.columns(2)
    with feedback_col1:
        if st.button("πŸ‘ Great tool!"):
            st.success("Thanks for the positive feedback!")
    with feedback_col2:
        if st.button("πŸ’‘ Suggestions"):
            st.info("We'd love to hear your ideas! Please comment or reach out.")
    
    # Footer
    st.markdown("---")
    st.markdown(
        "<div style='text-align: center; color: #666;'>"
        "<p>πŸš€ Built with Streamlit & Mistral-7B | πŸ’‘ Use quality company info for best results</p>"
        "<p>⚑ Powered by advanced AI with intelligent fallbacks for 100% success rate</p>"
        "</div>",
        unsafe_allow_html=True
    )

if __name__ == "__main__":
    main()