File size: 11,652 Bytes
f154798
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import streamlit as st
import time
import os
from utils.run_agent import execute_agent
from config.configs import AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, AZURE_DEPLOYMENT
from config.generation_config import get_generation_prompt, get_hashtag_suggestions, DEFAULT_SETTINGS
from utils.credential_manager import CredentialManager, format_endpoint_url, mask_api_key

st.set_page_config(
    page_title="LinkedIn Post Generator",
    page_icon="πŸ“",
    layout="wide",
    initial_sidebar_state="expanded"
)

st.markdown("""
<style>
    .main-header {
        background: linear-gradient(90deg, #0077B5, #00A0DC);
        padding: 2rem;
        border-radius: 10px;
        color: white;
        text-align: center;
        margin-bottom: 2rem;
    }
    
    .sidebar-header {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
    }
    
    .config-section {
        background: #f8f9fa;
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
        border-left: 4px solid #0077B5;
    }
    
    .output-container {
        background: #f8f9fa;
        padding: 1.5rem;
        border-radius: 10px;
        border: 1px solid #dee2e6;
        margin-top: 1rem;
    }
    
    .loading-spinner {
        text-align: center;
        padding: 2rem;
    }
    
    .success-message {
        background: #d4edda;
        color: #155724;
        padding: 1rem;
        border-radius: 8px;
        border: 1px solid #c3e6cb;
        margin: 1rem 0;
    }
    
    .error-message {
        background: #f8d7da;
        color: #721c24;
        padding: 1rem;
        border-radius: 8px;
        border: 1px solid #f5c6cb;
        margin: 1rem 0;
    }
    
    .credentials-section {
        background: #fff3cd;
        padding: 1rem;
        border-radius: 8px;
        border: 1px solid #ffeaa7;
        margin-bottom: 1rem;
    }
</style>
""", unsafe_allow_html=True)

# Initialize session state for credentials
if 'azure_api_key' not in st.session_state:
    st.session_state.azure_api_key = ""
if 'azure_endpoint' not in st.session_state:
    st.session_state.azure_endpoint = ""
if 'azure_deployment' not in st.session_state:
    st.session_state.azure_deployment = ""
if 'azure_api_version' not in st.session_state:
    st.session_state.azure_api_version = "2024-02-01"

with st.sidebar:
    st.title("βš™οΈ Configuration")

    st.subheader("πŸ”‘ Azure OpenAI Credentials")
    
    st.info("πŸ’‘ Enter your Azure OpenAI credentials below:")
    
    api_key = st.text_input(
        "Azure OpenAI API Key",
        value=st.session_state.azure_api_key,
        type="password",
        help="Your Azure OpenAI API key"
    )
    
    endpoint = st.text_input(
        "Azure OpenAI Endpoint",
        value=st.session_state.azure_endpoint,
        placeholder="https://your-resource.openai.azure.com/",
        help="Your Azure OpenAI endpoint URL"
    )
    
    deployment = st.text_input(
        "Deployment Name",
        value=st.session_state.azure_deployment,
        placeholder="gpt-35-turbo",
        help="Name of your deployed model"
    )
    
    api_version = st.text_input(
        "API Version",
        value=st.session_state.azure_api_version,
        placeholder="2024-02-01",
        help="Azure OpenAI API version"
    )
    
    if st.button("πŸ’Ύ Save Credentials", use_container_width=True):
        credentials = {
            'api_key': api_key,
            'endpoint': format_endpoint_url(endpoint) if endpoint else '',
            'deployment': deployment,
            'api_version': api_version
        }
        
        is_valid, message = CredentialManager.validate_credentials(credentials)
        
        if is_valid:
            CredentialManager.save_credentials_to_session(
                credentials['api_key'],
                credentials['endpoint'],
                credentials['deployment'],
                credentials['api_version']
            )
            st.success("βœ… Credentials saved successfully!")
            st.rerun()
        else:
            st.error(f"❌ {message}")
    
    if st.button("πŸ—‘οΈ Clear Credentials", use_container_width=True):
        CredentialManager.clear_session_credentials()
        st.success("βœ… Credentials cleared!")
        st.rerun()
    
    st.markdown('</div>', unsafe_allow_html=True)
    
    st.subheader("πŸ” API Status")
    
    current_credentials = CredentialManager.get_credentials_from_session()
    
    if current_credentials['api_key']:
        masked_key = mask_api_key(current_credentials['api_key'])
        st.success(f"βœ… API Key: {masked_key}")
    else:
        st.error("❌ API Key not found")
    
    if current_credentials['endpoint']:
        st.success(f"βœ… Endpoint: {current_credentials['endpoint']}")
    else:
        st.warning("⚠️ Endpoint not configured")
    
    if current_credentials['deployment']:
        st.success(f"βœ… Deployment: {current_credentials['deployment']}")
    else:
        st.warning("⚠️ Deployment not configured")
    
    if all(current_credentials.values()):
        if st.button("πŸ§ͺ Test Connection", use_container_width=True):
            with st.spinner("Testing Azure OpenAI connection..."):
                try:
                    CredentialManager.set_environment_variables(current_credentials)
                    
                    test_output = execute_agent("Test connection")
                    st.success("βœ… Connection successful! Azure OpenAI is working.")
                except Exception as e:
                    st.error(f"❌ Connection failed: {str(e)}")
    
    st.subheader("🎯 Generation Settings")
    
    post_length = st.selectbox(
        "Post Length",
        ["Short (100-200 words)", "Medium (200-400 words)", "Long (400-600 words)"],
        index=1
    )
    
    tone = st.selectbox(
        "Tone",
        ["Professional", "Casual", "Enthusiastic", "Educational", "Inspirational"],
        index=0
    )
    
    include_hashtags = st.checkbox("Include Hashtags", value=True)
    include_call_to_action = st.checkbox("Include Call to Action", value=True)
    
    st.subheader("ℹ️ About")
    st.write("**LinkedIn Post Generator**")
    st.write("Powered by LangGraph and Azure OpenAI")
    st.write("Version: 1.0.0")

st.title("πŸ“ LinkedIn Post Generator")
st.markdown("Transform your ideas into engaging LinkedIn posts using AI")

col1, col2 = st.columns([2, 1])

with col1:
    st.subheader("🎯 What would you like to write about?")
    
    user_input = st.text_area(
        "Enter your topic, idea, or subject matter:",
        value=st.session_state.get("user_input", ""),
        placeholder="e.g., 'The future of artificial intelligence in healthcare' or 'Tips for remote team collaboration'",
        height=100,
        help="Be specific about your topic to get better results"
    )
    
    if user_input and include_hashtags:
        suggested_hashtags = get_hashtag_suggestions(user_input)
        st.info(f"πŸ’‘ **Suggested hashtags for '{user_input}':**")
        hashtag_cols = st.columns(3)
        for i, hashtag in enumerate(suggested_hashtags[:3]):
            with hashtag_cols[i]:
                st.write(f"β€’ {hashtag}")
    
    with st.expander("πŸ” Additional Context (Optional)"):
        context = st.text_area(
            "Add any specific details, target audience, or context:",
            placeholder="e.g., 'Target audience: Tech professionals, Focus on practical applications'",
            height=80
        )
    
    col1_btn, col2_btn = st.columns([3, 1])
    
    with col1_btn:
        generate_clicked = st.button("πŸš€ Generate LinkedIn Post", type="primary", use_container_width=True)
    
    with col2_btn:
        clear_clicked = st.button("πŸ—‘οΈ Clear", use_container_width=True)
    
    if clear_clicked:
        st.session_state.user_input = ""
        st.session_state.example_topic = ""
        st.rerun()
    
    if generate_clicked:
        if user_input:
            current_credentials = CredentialManager.get_credentials_from_session()
            
            if not all(current_credentials.values()):
                st.error("❌ Please configure your Azure OpenAI credentials in the sidebar first.")
            else:
                CredentialManager.set_environment_variables(current_credentials)
                
                with st.spinner("πŸ€– AI is crafting your perfect LinkedIn post..."):
                    try:
                        settings = {
                            "post_length": post_length,
                            "tone": tone,
                            "include_hashtags": include_hashtags,
                            "include_call_to_action": include_call_to_action
                        }
                        
                        # Generate formatted prompt using the configuration
                        full_query = get_generation_prompt(user_input, context, settings)
                        
                        # Execute the agent
                        output = execute_agent(full_query)
                        
                        # Update session state
                        if 'generated_posts' not in st.session_state:
                            st.session_state.generated_posts = 0
                        st.session_state.generated_posts += 1
                        
                        st.success("βœ… Your LinkedIn post has been generated successfully!")                    

                        st.subheader("πŸ“„ Generated LinkedIn Post")
                        st.markdown("---")
                        st.write(output)
                        st.markdown("---")
                        
                        if st.button("πŸ“‹ Copy to Clipboard", use_container_width=True):
                            st.write("πŸ“‹ Post copied to clipboard!")
                            
                    except Exception as e:
                        st.error(f"❌ An error occurred: {str(e)}")
        else:
            st.warning("⚠️ Please enter a topic to generate a post.")

with col2:
    st.subheader("πŸ’‘ Tips for Better Posts")
    
    tips = [
        "🎯 Be specific about your topic",
        "πŸ‘₯ Consider your target audience",
        "πŸ“Š Include relevant statistics if applicable",
        "πŸ’¬ Ask engaging questions",
        "πŸ”— Reference current trends or news",
        "πŸ“ Keep paragraphs short and readable",
        "🎨 Use emojis sparingly but effectively"
    ]
    
    for tip in tips:
        st.write(tip)
    
    st.markdown("---")
    
    st.subheader("πŸ“ˆ Post Analytics")
    if 'generated_posts' not in st.session_state:
        st.session_state.generated_posts = 0
    
    st.metric("Posts Generated", st.session_state.generated_posts)

    st.subheader("🎯 Example Topics")
    example_topics = [
        "AI in healthcare",
        "Remote work productivity",
        "Digital transformation",
        "Leadership skills",
        "Innovation in business"
    ]
    
    for topic in example_topics:
        if st.button(topic, key=f"example_{topic}"):
            st.session_state.example_topic = topic
            st.session_state.user_input = topic
            st.rerun()

st.markdown("---")
st.markdown(
    """
    <div style='text-align: center; color: #666; padding: 1rem;'>
        <p>Made with ❀️ using Streamlit, LangGraph, and Azure OpenAI</p>
        <p>For questions or support, please check the documentation</p>
    </div>
    """,
    unsafe_allow_html=True
)