File size: 12,419 Bytes
d896b5f
2a918a3
 
21e772e
d896b5f
 
2a918a3
21e772e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d896b5f
 
21e772e
 
 
 
 
 
 
 
d896b5f
2a918a3
d896b5f
21e772e
2a918a3
 
21e772e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c1f293
21e772e
 
 
 
8c1f293
21e772e
8c1f293
21e772e
 
 
 
8c1f293
21e772e
 
 
8c1f293
 
2a918a3
 
 
21e772e
2a918a3
8c1f293
21e772e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c1f293
2a918a3
 
21e772e
2a918a3
21e772e
 
 
 
 
 
 
 
 
 
8c1f293
21e772e
 
2a918a3
 
 
 
 
8c1f293
21e772e
 
2a918a3
 
8c1f293
21e772e
 
 
2a918a3
21e772e
 
 
 
 
2a918a3
8c1f293
21e772e
2a918a3
21e772e
77057e7
26371fd
21e772e
 
 
 
 
2a918a3
 
 
 
 
8c1f293
2a918a3
 
 
 
8c1f293
21e772e
2a918a3
 
21e772e
 
8c1f293
21e772e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c1f293
2a918a3
21e772e
 
 
8c1f293
2a918a3
 
8c1f293
2a918a3
21e772e
 
 
 
 
 
 
 
 
 
 
 
 
8c1f293
2a918a3
 
 
 
 
 
8c1f293
2a918a3
 
21e772e
 
 
2a918a3
 
8c1f293
2a918a3
 
 
21e772e
 
2a918a3
 
 
 
 
8c1f293
2a918a3
d896b5f
 
21e772e
 
 
 
 
 
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
import streamlit as st
import os
from groq import Groq
from typing import List, Dict, Optional, Union
import json
from datetime import datetime
import time
from functools import lru_cache
import logging
from contextlib import contextmanager

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Constants
MAX_RETRIES = 3
RETRY_DELAY = 1
DEFAULT_TEMPERATURE = 0.5
MAX_TOKENS = 1024
MODEL_NAME = "llama3-8b-8192"

class APIError(Exception):
    """Custom exception for API-related errors"""
    pass

class JSONParsingError(Exception):
    """Custom exception for JSON parsing errors"""
    pass

@contextmanager
def error_handler(context: str):
    """Context manager for handling errors with specific context"""
    try:
        yield
    except Exception as e:
        logger.error(f"Error in {context}: {str(e)}")
        st.error(f"An error occurred in {context}. Please try again.")
        raise

@st.cache_resource
def get_groq_client() -> Groq:
    """Initialize and cache Groq client"""
    try:
        return Groq(api_key=st.secrets["groq_api_key"])
    except Exception as e:
        logger.error(f"Failed to initialize Groq client: {str(e)}")
        st.error("Failed to initialize AI service. Please check your API key.")
        raise APIError("Failed to initialize Groq client")

class ContentAnalysisAgent:
    def __init__(self):
        """Initialize the agent with Groq client and default settings"""
        self.client = get_groq_client()
        self.system_prompt = """You are an expert social media content analyzer with deep understanding of engagement, 
        audience psychology, and content optimization. You must ALWAYS return responses in valid JSON format when requested.
        Analyze content step by step using a systematic approach."""
        
    @staticmethod
    def _display_thinking(thought: str):
        """Display agent's thinking process in a collapsible container"""
        with st.expander("πŸ€” Analysis Process", expanded=False):
            st.markdown(f"```\n{thought}\n```")

    def _call_api(self, messages: List[Dict], retries: int = MAX_RETRIES) -> Optional[str]:
        """Make API call with retry logic"""
        for attempt in range(retries):
            try:
                response = self.client.chat.completions.create(
                    messages=messages,
                    model=MODEL_NAME,
                    temperature=DEFAULT_TEMPERATURE,
                    max_tokens=MAX_TOKENS
                )
                return response.choices[0].message.content
            except Exception as e:
                if attempt == retries - 1:
                    logger.error(f"API call failed after {retries} attempts: {str(e)}")
                    raise APIError(f"Failed to get response from AI service: {str(e)}")
                time.sleep(RETRY_DELAY)
        return None

    @staticmethod
    def _parse_json(response: str) -> Dict:
        """Parse JSON from response with enhanced error handling"""
        try:
            # First attempt: direct JSON parsing
            return json.loads(response)
        except json.JSONDecodeError:
            try:
                # Second attempt: extract JSON structure
                start_idx = response.find('{')
                end_idx = response.rfind('}') + 1
                if start_idx != -1 and end_idx > start_idx:
                    json_str = response[start_idx:end_idx]
                    # Clean up common formatting issues
                    json_str = (json_str.replace('\n', ' ')
                              .replace('```json', '')
                              .replace('```', '')
                              .strip())
                    return json.loads(json_str)
            except (json.JSONDecodeError, ValueError) as e:
                logger.warning(f"JSON parsing failed: {str(e)}")
                # Return fallback structure
                return {
                    "style": "unknown",
                    "tones": ["neutral"],
                    "rating": "3",
                    "engagement_score": "50",
                    "analysis": {
                        "strengths": ["Content provided"],
                        "improvements": ["Format needs review"],
                        "audience_fit": "medium"
                    },
                    "error": "Response parsing failed"
                }

    def analyze_post(self, post_text: str) -> Dict:
        """Analyze post content with comprehensive error handling"""
        analysis_prompt = f"""Analyze this social media post and return ONLY a valid JSON object:
POST: {post_text}

Required structure:
{{
    "style": "posting style",
    "tones": ["tone1", "tone2"],
    "rating": "1-5",
    "engagement_score": "0-100",
    "analysis": {{
        "strengths": ["strength1", "strength2"],
        "improvements": ["improvement1", "improvement2"],
        "audience_fit": "low/medium/high"
    }}
}}"""

        messages = [
            {"role": "system", "content": self.system_prompt},
            {"role": "user", "content": analysis_prompt}
        ]

        with st.spinner("πŸ” Analyzing content..."):
            try:
                analysis_response = self._call_api(messages)
                if not analysis_response:
                    raise APIError("No response received from API")
                
                analysis_result = self._parse_json(analysis_response)
                
                # Get recommendations
                recommendation_prompt = """Provide exactly 3 specific, actionable recommendations 
                to improve engagement. Return as a JSON array of strings."""
                
                messages.append({"role": "user", "content": recommendation_prompt})
                recommendations = self._call_api(messages)
                
                if recommendations:
                    try:
                        parsed_recommendations = json.loads(recommendations)
                        if isinstance(parsed_recommendations, list):
                            analysis_result["recommendations"] = parsed_recommendations
                        else:
                            analysis_result["recommendations"] = [recommendations.strip()]
                    except json.JSONDecodeError:
                        analysis_result["recommendations"] = [recommendations.strip()]
                
                return analysis_result
                
            except Exception as e:
                logger.error(f"Analysis failed: {str(e)}")
                st.error("Analysis failed. Please try again.")
                return None

class GraicieApp:
    def __init__(self):
        """Initialize the Graicie application"""
        self.agent = ContentAnalysisAgent()
        self.example_posts = {
            "Viral Marketing": "πŸš€ HUGE ANNOUNCEMENT! After months of work, my online course is finally LIVE! πŸŽ‰\n"
                             "Learn how I grew from 0 to 100K followers in 6 months! Early bird pricing ends tomorrow! πŸ’«\n"
                             "#socialmedia #digitalmarketing #success",
            "Personal Story": "Sometimes life throws you curveballs... Today I faced my biggest fear and went "
                            "skydiving! πŸͺ‚ Swipe to see my reaction! Remember: growth happens outside your comfort zone πŸ’•\n"
                            "#personalgrowth #motivation",
            "Educational": "🧠 5 Python Tips You Didn't Know:\n1. List comprehensions\n2. f-strings\n3. Walrus operator\n"
                         "4. Context managers\n5. Lambda functions\nSave this for later! πŸ’‘\n#coding #programming"
        }

    def _display_header(self):
        """Display application header"""
        st.title("πŸ€– Project Graicie - Advanced Content Analyzer")
        st.markdown("""
        ### Powered by LLaMA 3 & Agentic AI
        Get deep, AI-powered insights into your social media content using advanced language models.
        """)

    def _display_metrics(self, results: Dict):
        """Display analysis metrics in a structured format"""
        if not results:
            return

        # Main metrics
        cols = st.columns(4)
        with cols[0]:
            st.metric("Style", results["style"])
        with cols[1]:
            st.metric("Engagement", f"{results['engagement_score']}/100")
        with cols[2]:
            st.metric("Rating", f"{results['rating']}/5")
        with cols[3]:
            st.metric("Audience Fit", results["analysis"]["audience_fit"])

        # Content tones
        st.subheader("πŸ“Š Content Tones")
        tone_html = " ".join([
            f"<span style='background-color: black ; padding: 4px 8px; "
            f"margin: 4px; border-radius: 12px;'>{tone}</span>"
            for tone in results["tones"]
        ])
        st.markdown(tone_html, unsafe_allow_html=True)

        # Analysis details
        col1, col2 = st.columns(2)
        with col1:
            st.subheader("πŸ’ͺ Strengths")
            for strength in results["analysis"]["strengths"]:
                st.markdown(f"βœ… {strength}")

        with col2:
            st.subheader("🎯 Areas to Improve")
            for improvement in results["analysis"]["improvements"]:
                st.markdown(f"πŸ“Œ {improvement}")

        # Recommendations
        if "recommendations" in results:
            st.subheader("πŸš€ Specific Recommendations")
            for idx, rec in enumerate(results["recommendations"], 1):
                st.markdown(f"{idx}. {rec}")

    def _display_sidebar(self):
        """Display sidebar with tips and information"""
        with st.sidebar:
            st.subheader("πŸ’‘ Pro Tips")
            st.info("""
            **Content Best Practices:**
            1. Tell authentic stories
            2. Use relevant hashtags
            3. Include call-to-actions
            4. Add visual elements
            5. Engage with questions
            """)

            st.markdown("### πŸ“Š Optimal Post Elements")
            st.markdown("""
            - Length: 80-150 characters
            - Hashtags: 3-5 relevant tags
            - Emojis: 2-3 key emojis
            - CTA: One clear action
            """)

    def run(self):
        """Run the Graicie application"""
        self._display_header()
        self._display_sidebar()

        # Main content area
        col1, col2 = st.columns([2, 1])

        with col1:
            st.subheader("πŸ“± Try an Example Post")
            selected_example = st.selectbox(
                "Select an example:", 
                list(self.example_posts.keys())
            )

            if selected_example:
                example_text = self.example_posts[selected_example]
                st.text_area("Example Post", example_text, height=100, disabled=True)
                if st.button("Analyze Example", use_container_width=True):
                    with error_handler("example analysis"):
                        results = self.agent.analyze_post(example_text)
                        self._display_metrics(results)

            st.subheader("πŸ“ Analyze Your Post")
            user_post = st.text_area(
                "Enter your post content:",
                height=150,
                placeholder="Type or paste your content here..."
            )

            if st.button("πŸ” Analyze My Post", use_container_width=True):
                if user_post:
                    with error_handler("user post analysis"):
                        results = self.agent.analyze_post(user_post)
                        self._display_metrics(results)
                else:
                    st.warning("Please enter some content to analyze!")

        # Footer
        st.markdown(
            """
            <div style='text-align: center; padding: 20px;'>
                <p style='color: #666;'>
                    Powered by LLaMA 3 & Groq | Made with ❀️ by Project Graicie Team | 
                    Β© 2024 Project Graicie
                </p>
            </div>
            """,
            unsafe_allow_html=True,
        )

if __name__ == "__main__":
    try:
        app = GraicieApp()
        app.run()
    except Exception as e:
        logger.error(f"Application failed to start: {str(e)}")
        st.error("Application failed to start. Please check the logs.")