ibrahim313 commited on
Commit
2a918a3
Β·
verified Β·
1 Parent(s): a71069e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +238 -154
app.py CHANGED
@@ -1,183 +1,267 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- import pandas as pd
4
  from typing import List, Dict
5
  import json
6
- import plotly.express as px
7
  from datetime import datetime
 
8
 
9
- # Initialize sentiment analysis pipeline
10
  @st.cache_resource
11
- def load_model():
12
- return pipeline("sentiment-analysis")
13
 
14
- class GraicieAnalyzer:
15
  def __init__(self):
16
- """Initialize the analyzer"""
17
- self.sentiment_pipeline = load_model()
 
 
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def analyze_post(self, post_text: str) -> Dict:
20
- """Analyze a single post and return all metrics"""
21
- # Get base sentiment
22
- sentiment_result = self.sentiment_pipeline(post_text)[0]
 
 
 
 
 
 
23
 
24
- # Determine style based on post characteristics
25
- style = self._determine_style(post_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Determine tone based on content
28
- tones = self._determine_tone(post_text, sentiment_result)
 
29
 
30
- # Calculate rating
31
- rating = self._calculate_rating(post_text)
32
 
33
- return {
34
- "post": post_text,
35
- "style": style,
36
- "tones": tones,
37
- "rating": rating,
38
- "sentiment": sentiment_result["label"],
39
- "confidence": f"{sentiment_result['score']:.2%}"
40
- }
41
-
42
- def _determine_style(self, text: str) -> str:
43
- """Determine post style based on characteristics"""
44
- text_lower = text.lower()
45
 
46
- if "!" in text or "?" in text or "😱" in text or "🀯" in text:
47
- return "Hooking"
48
- elif len(text.split()) <= 10:
49
- return "Short & Sweet"
50
- elif text.count('πŸ†') > 0 or text.count('πŸ“ˆ') > 0:
51
- return "Audience-focused"
52
- elif text.count('😊') > 0 or "i feel" in text_lower or "just" in text_lower:
53
- return "Authentic"
54
- elif text.count('πŸ“Έ') > 0 or text.count('😍') > 0:
55
- return "Visually appealing"
56
- elif "?" in text or "what do you think" in text_lower:
57
- return "Controversial"
58
- else:
59
- return "Storytelling"
60
 
61
- def _determine_tone(self, text: str, sentiment: Dict) -> List[str]:
62
- """Determine post tone"""
63
- tones = []
64
- text_lower = text.lower()
65
 
66
- if sentiment["label"] == "POSITIVE":
67
- tones.append("Optimistic")
68
- else:
69
- tones.append("Pessimistic")
 
 
 
 
 
 
 
 
70
 
71
- if "?" in text:
72
- tones.append("Curious")
73
- if "!" in text:
74
- tones.append("Assertive")
75
- if any(word in text_lower for word in ["learn", "guide", "how to", "tips"]):
76
- tones.append("Informative")
77
- if any(emoji in text for emoji in ["πŸ˜‚", "πŸ˜†", "🀣"]):
78
- tones.append("Entertaining")
79
 
80
- return tones
81
-
82
- def _calculate_rating(self, text: str) -> int:
83
- """Calculate content rating"""
84
- text_lower = text.lower()
85
- # Simple rating system based on content markers
86
- rating = 1 # Start with family-friendly
87
 
88
- sensitive_words = ["damn", "hell", "stupid", "idiot"]
89
- very_sensitive_words = ["fuck", "shit", "ass"]
90
- adult_themes = ["drunk", "sex", "nsfw", "18+"]
91
 
92
- if any(word in text_lower for word in sensitive_words):
93
- rating = max(rating, 2)
94
- if any(word in text_lower for word in very_sensitive_words):
95
- rating = max(rating, 4)
96
- if any(word in text_lower for word in adult_themes):
97
- rating = max(rating, 5)
98
-
99
- return rating
100
-
101
- def main():
102
- # Set page config
103
- st.set_page_config(
104
- page_title="Project Graicie - Social Media Content Analyzer",
105
- page_icon="πŸ“±",
106
- layout="wide"
107
- )
108
-
109
- # Title and description
110
- st.title("πŸ€– Project Graicie")
111
- st.markdown("""
112
- ### AI-Powered Social Media Content Analysis
113
- Analyze your social media content to understand its style, tone, and appropriateness.
114
- Get insights to improve your social media presence!
115
- """)
116
 
117
- # Initialize analyzer
118
- analyzer = GraicieAnalyzer()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- # Create columns for better layout
121
- col1, col2 = st.columns([2, 1])
 
 
122
 
123
- with col1:
124
- # Input area
125
- st.subheader("πŸ“ Content Analysis")
126
- post_text = st.text_area(
127
- "Enter your social media post here:",
128
- height=150,
129
- placeholder="Type or paste your post content here..."
130
- )
131
 
132
- if st.button("πŸ” Analyze Content", use_container_width=True):
133
- if post_text:
134
- with st.spinner("Analyzing your content..."):
135
- # Get analysis
136
- result = analyzer.analyze_post(post_text)
137
-
138
- # Display results in an organized way
139
- st.success("Analysis Complete!")
140
-
141
- # Create three columns for results
142
- res_col1, res_col2, res_col3 = st.columns(3)
143
-
144
- with res_col1:
145
- st.metric("Style", result["style"])
146
-
147
- with res_col2:
148
- st.metric("Sentiment", f"{result['sentiment']} ({result['confidence']})")
149
-
150
- with res_col3:
151
- st.metric("Content Rating", f"{result['rating']}/5")
152
-
153
- # Show tones
154
- st.subheader("πŸ“Š Detected Tones")
155
- tone_html = " ".join([f'<span style="background-color: #e6f3ff; padding: 5px 10px; margin: 5px; border-radius: 15px;">{tone}</span>' for tone in result["tones"]])
156
- st.markdown(f"<div style='margin-top: 10px;'>{tone_html}</div>", unsafe_allow_html=True)
157
 
158
- else:
159
- st.warning("Please enter some content to analyze!")
160
-
161
- with col2:
162
- # Tips and information
163
- st.subheader("πŸ’‘ Tips")
164
- st.info("""
165
- **For better results:**
166
- - Write naturally
167
- - Include relevant emojis
168
- - Add hashtags if relevant
169
- - Keep your audience in mind
170
- """)
 
 
 
 
 
171
 
172
- # Rating guide
173
- st.subheader("πŸ“‹ Rating Guide")
174
- st.markdown("""
175
- 1️⃣ Family-friendly
176
- 2️⃣ Minor concerns
177
- 3️⃣ Teen-appropriate
178
- 4️⃣ Mature content
179
- 5️⃣ Adult/Sensitive content
180
- """)
 
 
 
 
181
 
182
  if __name__ == "__main__":
183
- main()
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import os
3
+ from groq import Groq
4
  from typing import List, Dict
5
  import json
 
6
  from datetime import datetime
7
+ import time
8
 
9
+ # Initialize Groq client
10
  @st.cache_resource
11
+ def get_groq_client():
12
+ return Groq(api_key=st.secrets["groq_api_key"])
13
 
14
+ class ContentAnalysisAgent:
15
  def __init__(self):
16
+ """Initialize the agent with Groq client"""
17
+ self.client = get_groq_client()
18
+ self.system_prompt = """You are an expert social media content analyzer with deep understanding of engagement,
19
+ audience psychology, and content optimization. Analyze content step by step using a systematic approach."""
20
 
21
+ def _think(self, thought_process: str) -> None:
22
+ """Display agent's thinking process"""
23
+ with st.expander("πŸ€” Agent's Thought Process", expanded=False):
24
+ st.write(thought_process)
25
+
26
+ def _get_llm_response(self, messages: List[Dict]) -> str:
27
+ """Get response from Groq LLM"""
28
+ try:
29
+ response = self.client.chat.completions.create(
30
+ messages=messages,
31
+ model="llama3-8b-8192",
32
+ temperature=0.7,
33
+ max_tokens=1024,
34
+ )
35
+ return response.choices[0].message.content
36
+ except Exception as e:
37
+ st.error(f"Error in LLM processing: {str(e)}")
38
+ return None
39
+
40
+ def _create_analysis_prompt(self, text: str) -> str:
41
+ """Create a detailed analysis prompt with agentic thinking"""
42
+ return f"""Let's analyze this social media post step by step:
43
+
44
+ POST: {text}
45
+
46
+ Think through the following aspects:
47
+
48
+ 1. CONTENT STRUCTURE ANALYSIS
49
+ - Examine length, formatting, and organization
50
+ - Identify key message components
51
+ - Note special characters and emoji usage
52
+
53
+ 2. AUDIENCE PSYCHOLOGY
54
+ - Who is the target audience?
55
+ - What emotional triggers are present?
56
+ - What call-to-actions exist?
57
+
58
+ 3. ENGAGEMENT POTENTIAL
59
+ - Analyze hook effectiveness
60
+ - Evaluate storytelling elements
61
+ - Assess viral potential
62
+
63
+ 4. STYLE AND TONE
64
+ - Determine primary content style
65
+ - Identify emotional undertones
66
+ - Evaluate brand voice consistency
67
+
68
+ 5. OPTIMIZATION OPPORTUNITIES
69
+ - Identify areas for improvement
70
+ - Suggest engagement boosters
71
+ - Note potential risks or concerns
72
+
73
+ Return a JSON structured response with:
74
+ {
75
+ "style": "primary posting style",
76
+ "tones": ["list of detected tones"],
77
+ "rating": "1-5 rating for content appropriateness",
78
+ "engagement_score": "0-100 engagement potential",
79
+ "analysis": {
80
+ "strengths": ["list of strong points"],
81
+ "improvements": ["areas to enhance"],
82
+ "audience_fit": "target audience match score"
83
+ }
84
+ }"""
85
+
86
  def analyze_post(self, post_text: str) -> Dict:
87
+ """Perform comprehensive post analysis"""
88
+ # First thinking phase - Initial Assessment
89
+ self._think("πŸ” Phase 1: Initial Assessment\nAnalyzing post structure and basic elements...")
90
+
91
+ # Create conversation with system prompt and analysis request
92
+ messages = [
93
+ {"role": "system", "content": self.system_prompt},
94
+ {"role": "user", "content": self._create_analysis_prompt(post_text)}
95
+ ]
96
 
97
+ # Get initial analysis
98
+ with st.spinner("πŸ€– Analyzing content..."):
99
+ analysis_response = self._get_llm_response(messages)
100
+
101
+ if not analysis_response:
102
+ return None
103
+
104
+ # Parse JSON response
105
+ try:
106
+ analysis_result = json.loads(analysis_response)
107
+ except json.JSONDecodeError:
108
+ st.error("Error parsing LLM response")
109
+ return None
110
+
111
+ # Second thinking phase - Refinement
112
+ self._think("🎯 Phase 2: Refinement\nRefining analysis and generating specific recommendations...")
113
 
114
+ # Get specific recommendations
115
+ recommendation_prompt = f"""Based on the initial analysis of this post:
116
+ {post_text}
117
 
118
+ Provide 3 specific, actionable recommendations to improve engagement."""
 
119
 
120
+ messages.append({"role": "user", "content": recommendation_prompt})
121
+ recommendations = self._get_llm_response(messages)
 
 
 
 
 
 
 
 
 
 
122
 
123
+ if recommendations:
124
+ analysis_result["recommendations"] = recommendations
125
+
126
+ return analysis_result
 
 
 
 
 
 
 
 
 
 
127
 
128
+ class GraicieApp:
129
+ def __init__(self):
130
+ self.agent = ContentAnalysisAgent()
 
131
 
132
+ def display_header(self):
133
+ st.title("πŸ€– Project Graicie - Advanced Content Analyzer")
134
+ st.markdown("""
135
+ ### Powered by LLaMA 3 & Agentic AI
136
+ Get deep, AI-powered insights into your social media content using advanced language models.
137
+ """)
138
+
139
+ def display_example_posts(self):
140
+ examples = {
141
+ "Viral Post": "πŸš€ HUGE ANNOUNCEMENT! After months of work, my online course is finally LIVE! πŸŽ‰\n"
142
+ "Learn how I grew from 0 to 100K followers in 6 months! Early bird pricing ends tomorrow! πŸ’«\n"
143
+ "#socialmedia #digitalmarketing #success",
144
 
145
+ "Personal Story": "Sometimes life throws you curveballs... Today I faced my biggest fear and went "
146
+ "skydiving! πŸͺ‚ Swipe to see my reaction! Remember: growth happens outside your comfort zone πŸ’•\n"
147
+ "#personalgrowth #motivation",
 
 
 
 
 
148
 
149
+ "Educational": "🧠 5 Python Tips You Didn't Know:\n1. List comprehensions\n2. f-strings\n3. Walrus operator\n"
150
+ "4. Context managers\n5. Lambda functions\nSave this for later! πŸ’‘\n#coding #programming"
151
+ }
 
 
 
 
152
 
153
+ st.subheader("πŸ“± Try an Example Post")
154
+ selected_example = st.selectbox("Select an example post:", list(examples.keys()))
 
155
 
156
+ if selected_example:
157
+ st.text_area("Example Post", examples[selected_example], height=100, disabled=True)
158
+ if st.button("Analyze Example", use_container_width=True):
159
+ self.analyze_and_display(examples[selected_example])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
+ def display_results(self, results: Dict):
162
+ if not results:
163
+ return
164
+
165
+ # Display main metrics
166
+ col1, col2, col3, col4 = st.columns(4)
167
+ with col1:
168
+ st.metric("Style", results["style"])
169
+ with col2:
170
+ st.metric("Engagement Score", f"{results['engagement_score']}/100")
171
+ with col3:
172
+ st.metric("Content Rating", f"{results['rating']}/5")
173
+ with col4:
174
+ st.metric("Audience Fit", results["analysis"]["audience_fit"])
175
+
176
+ # Display tones
177
+ st.subheader("πŸ“Š Content Tones")
178
+ for tone in results["tones"]:
179
+ st.markdown(f"<span style='background-color: #e6f3ff; padding: 5px 10px; "
180
+ f"margin: 5px; border-radius: 15px;'>{tone}</span>", unsafe_allow_html=True)
181
+
182
+ # Display strengths and improvements
183
+ col1, col2 = st.columns(2)
184
+ with col1:
185
+ st.subheader("πŸ’ͺ Strengths")
186
+ for strength in results["analysis"]["strengths"]:
187
+ st.markdown(f"βœ… {strength}")
188
+
189
+ with col2:
190
+ st.subheader("🎯 Areas to Improve")
191
+ for improvement in results["analysis"]["improvements"]:
192
+ st.markdown(f"πŸ“Œ {improvement}")
193
+
194
+ # Display recommendations
195
+ if "recommendations" in results:
196
+ st.subheader("πŸš€ Specific Recommendations")
197
+ st.markdown(results["recommendations"])
198
 
199
+ def analyze_and_display(self, text: str):
200
+ results = self.agent.analyze_post(text)
201
+ if results:
202
+ self.display_results(results)
203
 
204
+ def run(self):
205
+ self.display_header()
 
 
 
 
 
 
206
 
207
+ # Main content area
208
+ col1, col2 = st.columns([2, 1])
209
+
210
+ with col1:
211
+ self.display_example_posts()
212
+
213
+ st.subheader("πŸ“ Analyze Your Post")
214
+ user_post = st.text_area(
215
+ "Enter your post content:",
216
+ height=150,
217
+ placeholder="Type or paste your content here..."
218
+ )
219
+
220
+ if st.button("πŸ” Analyze My Post", use_container_width=True):
221
+ if user_post:
222
+ self.analyze_and_display(user_post)
223
+ else:
224
+ st.warning("Please enter some content to analyze!")
 
 
 
 
 
 
 
225
 
226
+ with col2:
227
+ st.subheader("πŸ’‘ Pro Tips")
228
+ st.info("""
229
+ **Content That Works:**
230
+ 1. Tell authentic stories
231
+ 2. Use relevant hashtags
232
+ 3. Include call-to-actions
233
+ 4. Add visual elements
234
+ 5. Engage with questions
235
+ """)
236
+
237
+ st.markdown("### πŸ“Š Optimal Post Elements")
238
+ st.markdown("""
239
+ - Length: 80-150 characters
240
+ - Hashtags: 3-5 relevant tags
241
+ - Emojis: 2-3 key emojis
242
+ - CTA: One clear action
243
+ """)
244
 
245
+ # Footer
246
+ st.markdown(
247
+ """
248
+ <div style='position: fixed; bottom: 0; width: 100%; background-color: #f0f2f6;
249
+ padding: 10px; text-align: center;'>
250
+ <p style='margin: 0; color: #666;'>
251
+ Powered by LLaMA 3 & Groq | Made with ❀️ by Project Graicie Team |
252
+ Β© 2024 Project Graicie
253
+ </p>
254
+ </div>
255
+ """,
256
+ unsafe_allow_html=True
257
+ )
258
 
259
  if __name__ == "__main__":
260
+ st.set_page_config(
261
+ page_title="Project Graicie - AI Content Analyzer",
262
+ page_icon="πŸ€–",
263
+ layout="wide"
264
+ )
265
+
266
+ app = GraicieApp()
267
+ app.run()