Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,183 +1,267 @@
|
|
1 |
import streamlit as st
|
2 |
-
|
3 |
-
|
4 |
from typing import List, Dict
|
5 |
import json
|
6 |
-
import plotly.express as px
|
7 |
from datetime import datetime
|
|
|
8 |
|
9 |
-
# Initialize
|
10 |
@st.cache_resource
|
11 |
-
def
|
12 |
-
return
|
13 |
|
14 |
-
class
|
15 |
def __init__(self):
|
16 |
-
"""Initialize the
|
17 |
-
self.
|
|
|
|
|
18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
def analyze_post(self, post_text: str) -> Dict:
|
20 |
-
"""
|
21 |
-
#
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
-
#
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
#
|
28 |
-
|
|
|
29 |
|
30 |
-
|
31 |
-
rating = self._calculate_rating(post_text)
|
32 |
|
33 |
-
|
34 |
-
|
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
|
47 |
-
|
48 |
-
|
49 |
-
|
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 |
-
|
62 |
-
|
63 |
-
|
64 |
-
text_lower = text.lower()
|
65 |
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
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 |
-
|
81 |
-
|
82 |
-
|
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 |
-
|
89 |
-
|
90 |
-
adult_themes = ["drunk", "sex", "nsfw", "18+"]
|
91 |
|
92 |
-
if
|
93 |
-
|
94 |
-
|
95 |
-
|
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 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
|
121 |
-
|
|
|
|
|
122 |
|
123 |
-
|
124 |
-
|
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 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
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 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
-
#
|
173 |
-
st.
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
|
|
|
|
|
|
|
|
181 |
|
182 |
if __name__ == "__main__":
|
183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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()
|