Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -6,27 +6,22 @@ import json
|
|
6 |
from datetime import datetime
|
7 |
import time
|
8 |
|
9 |
-
# Initialize Groq client
|
10 |
-
|
11 |
-
|
12 |
@st.cache_resource
|
13 |
def get_groq_client():
|
14 |
return Groq(api_key=st.secrets["groq_api_key"])
|
15 |
|
16 |
-
|
17 |
-
|
18 |
class ContentAnalysisAgent:
|
19 |
def __init__(self):
|
20 |
"""Initialize the agent with Groq client"""
|
21 |
self.client = get_groq_client()
|
22 |
self.system_prompt = """You are an expert social media content analyzer with deep understanding of engagement,
|
23 |
audience psychology, and content optimization. Analyze content step by step using a systematic approach."""
|
24 |
-
|
25 |
def _think(self, thought_process: str) -> None:
|
26 |
"""Display agent's thinking process"""
|
27 |
with st.expander("π€ Agent's Thought Process", expanded=False):
|
28 |
st.write(thought_process)
|
29 |
-
|
30 |
def _get_llm_response(self, messages: List[Dict]) -> str:
|
31 |
"""Get response from Groq LLM"""
|
32 |
try:
|
@@ -44,135 +39,119 @@ class ContentAnalysisAgent:
|
|
44 |
def _create_analysis_prompt(self, text: str) -> str:
|
45 |
"""Create a detailed analysis prompt with agentic thinking"""
|
46 |
return f"""Let's analyze this social media post step by step:
|
47 |
-
|
48 |
POST: {text}
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
Think through the following aspects:
|
53 |
-
|
54 |
1. CONTENT STRUCTURE ANALYSIS
|
55 |
- Examine length, formatting, and organization
|
56 |
- Identify key message components
|
57 |
- Note special characters and emoji usage
|
58 |
-
|
59 |
2. AUDIENCE PSYCHOLOGY
|
60 |
- Who is the target audience?
|
61 |
- What emotional triggers are present?
|
62 |
- What call-to-actions exist?
|
63 |
-
|
64 |
3. ENGAGEMENT POTENTIAL
|
65 |
- Analyze hook effectiveness
|
66 |
- Evaluate storytelling elements
|
67 |
- Assess viral potential
|
68 |
-
|
69 |
4. STYLE AND TONE
|
70 |
- Determine primary content style
|
71 |
- Identify emotional undertones
|
72 |
- Evaluate brand voice consistency
|
73 |
-
|
74 |
-
|
75 |
5. OPTIMIZATION OPPORTUNITIES
|
76 |
- Identify areas for improvement
|
77 |
- Suggest engagement boosters
|
78 |
- Note potential risks or concerns
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
Return a JSON structured response with:
|
83 |
-
{
|
84 |
"style": "primary posting style",
|
85 |
"tones": ["list of detected tones"],
|
86 |
"rating": "1-5 rating for content appropriateness",
|
87 |
"engagement_score": "0-100 engagement potential",
|
88 |
-
"analysis": {
|
89 |
"strengths": ["list of strong points"],
|
90 |
"improvements": ["areas to enhance"],
|
91 |
"audience_fit": "target audience match score"
|
92 |
-
}
|
93 |
-
}"""
|
94 |
|
95 |
def analyze_post(self, post_text: str) -> Dict:
|
96 |
"""Perform comprehensive post analysis"""
|
97 |
# First thinking phase - Initial Assessment
|
98 |
self._think("π Phase 1: Initial Assessment\nAnalyzing post structure and basic elements...")
|
99 |
-
|
100 |
# Create conversation with system prompt and analysis request
|
101 |
messages = [
|
102 |
{"role": "system", "content": self.system_prompt},
|
103 |
{"role": "user", "content": self._create_analysis_prompt(post_text)}
|
104 |
]
|
105 |
-
|
106 |
# Get initial analysis
|
107 |
with st.spinner("π€ Analyzing content..."):
|
108 |
analysis_response = self._get_llm_response(messages)
|
109 |
-
|
110 |
if not analysis_response:
|
111 |
return None
|
112 |
|
113 |
-
|
114 |
-
|
115 |
# Parse JSON response
|
116 |
try:
|
117 |
analysis_result = json.loads(analysis_response)
|
118 |
except json.JSONDecodeError:
|
119 |
st.error("Error parsing LLM response")
|
120 |
return None
|
121 |
-
|
122 |
# Second thinking phase - Refinement
|
123 |
self._think("π― Phase 2: Refinement\nRefining analysis and generating specific recommendations...")
|
124 |
-
|
125 |
# Get specific recommendations
|
126 |
recommendation_prompt = f"""Based on the initial analysis of this post:
|
127 |
{post_text}
|
128 |
-
|
129 |
Provide 3 specific, actionable recommendations to improve engagement."""
|
130 |
-
|
131 |
messages.append({"role": "user", "content": recommendation_prompt})
|
132 |
recommendations = self._get_llm_response(messages)
|
133 |
-
|
134 |
if recommendations:
|
135 |
analysis_result["recommendations"] = recommendations
|
136 |
-
|
137 |
return analysis_result
|
138 |
|
|
|
139 |
class GraicieApp:
|
140 |
def __init__(self):
|
141 |
self.agent = ContentAnalysisAgent()
|
142 |
-
|
143 |
def display_header(self):
|
144 |
st.title("π€ Project Graicie - Advanced Content Analyzer")
|
145 |
st.markdown("""
|
146 |
### Powered by LLaMA 3 & Agentic AI
|
147 |
Get deep, AI-powered insights into your social media content using advanced language models.
|
148 |
""")
|
149 |
-
|
150 |
def display_example_posts(self):
|
151 |
examples = {
|
152 |
"Viral Post": "π HUGE ANNOUNCEMENT! After months of work, my online course is finally LIVE! π\n"
|
153 |
"Learn how I grew from 0 to 100K followers in 6 months! Early bird pricing ends tomorrow! π«\n"
|
154 |
"#socialmedia #digitalmarketing #success",
|
155 |
-
|
156 |
"Personal Story": "Sometimes life throws you curveballs... Today I faced my biggest fear and went "
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
"Educational": "π§ 5 Python Tips You Didn't Know:\n1. List comprehensions\n2. f-strings\n3. Walrus operator\n"
|
161 |
-
|
162 |
}
|
163 |
-
|
164 |
st.subheader("π± Try an Example Post")
|
165 |
selected_example = st.selectbox("Select an example post:", list(examples.keys()))
|
166 |
-
|
167 |
if selected_example:
|
168 |
st.text_area("Example Post", examples[selected_example], height=100, disabled=True)
|
169 |
if st.button("Analyze Example", use_container_width=True):
|
170 |
self.analyze_and_display(examples[selected_example])
|
171 |
-
|
172 |
def display_results(self, results: Dict):
|
173 |
if not results:
|
174 |
return
|
175 |
-
|
176 |
# Display main metrics
|
177 |
col1, col2, col3, col4 = st.columns(4)
|
178 |
with col1:
|
@@ -183,57 +162,57 @@ class GraicieApp:
|
|
183 |
st.metric("Content Rating", f"{results['rating']}/5")
|
184 |
with col4:
|
185 |
st.metric("Audience Fit", results["analysis"]["audience_fit"])
|
186 |
-
|
187 |
# Display tones
|
188 |
st.subheader("π Content Tones")
|
189 |
for tone in results["tones"]:
|
190 |
st.markdown(f"<span style='background-color: #e6f3ff; padding: 5px 10px; "
|
191 |
-
|
192 |
-
|
193 |
# Display strengths and improvements
|
194 |
col1, col2 = st.columns(2)
|
195 |
with col1:
|
196 |
st.subheader("πͺ Strengths")
|
197 |
for strength in results["analysis"]["strengths"]:
|
198 |
st.markdown(f"β
{strength}")
|
199 |
-
|
200 |
with col2:
|
201 |
st.subheader("π― Areas to Improve")
|
202 |
for improvement in results["analysis"]["improvements"]:
|
203 |
st.markdown(f"π {improvement}")
|
204 |
-
|
205 |
# Display recommendations
|
206 |
if "recommendations" in results:
|
207 |
st.subheader("π Specific Recommendations")
|
208 |
st.markdown(results["recommendations"])
|
209 |
-
|
210 |
def analyze_and_display(self, text: str):
|
211 |
results = self.agent.analyze_post(text)
|
212 |
if results:
|
213 |
self.display_results(results)
|
214 |
-
|
215 |
def run(self):
|
216 |
self.display_header()
|
217 |
-
|
218 |
# Main content area
|
219 |
col1, col2 = st.columns([2, 1])
|
220 |
-
|
221 |
with col1:
|
222 |
self.display_example_posts()
|
223 |
-
|
224 |
st.subheader("π Analyze Your Post")
|
225 |
user_post = st.text_area(
|
226 |
"Enter your post content:",
|
227 |
height=150,
|
228 |
placeholder="Type or paste your content here..."
|
229 |
)
|
230 |
-
|
231 |
if st.button("π Analyze My Post", use_container_width=True):
|
232 |
if user_post:
|
233 |
self.analyze_and_display(user_post)
|
234 |
else:
|
235 |
st.warning("Please enter some content to analyze!")
|
236 |
-
|
237 |
with col2:
|
238 |
st.subheader("π‘ Pro Tips")
|
239 |
st.info("""
|
@@ -244,7 +223,7 @@ class GraicieApp:
|
|
244 |
4. Add visual elements
|
245 |
5. Engage with questions
|
246 |
""")
|
247 |
-
|
248 |
st.markdown("### π Optimal Post Elements")
|
249 |
st.markdown("""
|
250 |
- Length: 80-150 characters
|
@@ -252,7 +231,7 @@ class GraicieApp:
|
|
252 |
- Emojis: 2-3 key emojis
|
253 |
- CTA: One clear action
|
254 |
""")
|
255 |
-
|
256 |
# Footer
|
257 |
st.markdown(
|
258 |
"""
|
@@ -264,15 +243,10 @@ class GraicieApp:
|
|
264 |
</p>
|
265 |
</div>
|
266 |
""",
|
267 |
-
unsafe_allow_html=True
|
268 |
)
|
269 |
|
|
|
270 |
if __name__ == "__main__":
|
271 |
-
st.set_page_config(
|
272 |
-
page_title="Project Graicie - AI Content Analyzer",
|
273 |
-
page_icon="π€",
|
274 |
-
layout="wide"
|
275 |
-
)
|
276 |
-
|
277 |
app = GraicieApp()
|
278 |
-
app.run()
|
|
|
6 |
from datetime import datetime
|
7 |
import time
|
8 |
|
|
|
|
|
|
|
9 |
@st.cache_resource
|
10 |
def get_groq_client():
|
11 |
return Groq(api_key=st.secrets["groq_api_key"])
|
12 |
|
|
|
|
|
13 |
class ContentAnalysisAgent:
|
14 |
def __init__(self):
|
15 |
"""Initialize the agent with Groq client"""
|
16 |
self.client = get_groq_client()
|
17 |
self.system_prompt = """You are an expert social media content analyzer with deep understanding of engagement,
|
18 |
audience psychology, and content optimization. Analyze content step by step using a systematic approach."""
|
19 |
+
|
20 |
def _think(self, thought_process: str) -> None:
|
21 |
"""Display agent's thinking process"""
|
22 |
with st.expander("π€ Agent's Thought Process", expanded=False):
|
23 |
st.write(thought_process)
|
24 |
+
|
25 |
def _get_llm_response(self, messages: List[Dict]) -> str:
|
26 |
"""Get response from Groq LLM"""
|
27 |
try:
|
|
|
39 |
def _create_analysis_prompt(self, text: str) -> str:
|
40 |
"""Create a detailed analysis prompt with agentic thinking"""
|
41 |
return f"""Let's analyze this social media post step by step:
|
|
|
42 |
POST: {text}
|
|
|
|
|
|
|
43 |
Think through the following aspects:
|
|
|
44 |
1. CONTENT STRUCTURE ANALYSIS
|
45 |
- Examine length, formatting, and organization
|
46 |
- Identify key message components
|
47 |
- Note special characters and emoji usage
|
|
|
48 |
2. AUDIENCE PSYCHOLOGY
|
49 |
- Who is the target audience?
|
50 |
- What emotional triggers are present?
|
51 |
- What call-to-actions exist?
|
|
|
52 |
3. ENGAGEMENT POTENTIAL
|
53 |
- Analyze hook effectiveness
|
54 |
- Evaluate storytelling elements
|
55 |
- Assess viral potential
|
|
|
56 |
4. STYLE AND TONE
|
57 |
- Determine primary content style
|
58 |
- Identify emotional undertones
|
59 |
- Evaluate brand voice consistency
|
|
|
|
|
60 |
5. OPTIMIZATION OPPORTUNITIES
|
61 |
- Identify areas for improvement
|
62 |
- Suggest engagement boosters
|
63 |
- Note potential risks or concerns
|
|
|
|
|
|
|
64 |
Return a JSON structured response with:
|
65 |
+
{{
|
66 |
"style": "primary posting style",
|
67 |
"tones": ["list of detected tones"],
|
68 |
"rating": "1-5 rating for content appropriateness",
|
69 |
"engagement_score": "0-100 engagement potential",
|
70 |
+
"analysis": {{
|
71 |
"strengths": ["list of strong points"],
|
72 |
"improvements": ["areas to enhance"],
|
73 |
"audience_fit": "target audience match score"
|
74 |
+
}}
|
75 |
+
}}"""
|
76 |
|
77 |
def analyze_post(self, post_text: str) -> Dict:
|
78 |
"""Perform comprehensive post analysis"""
|
79 |
# First thinking phase - Initial Assessment
|
80 |
self._think("π Phase 1: Initial Assessment\nAnalyzing post structure and basic elements...")
|
81 |
+
|
82 |
# Create conversation with system prompt and analysis request
|
83 |
messages = [
|
84 |
{"role": "system", "content": self.system_prompt},
|
85 |
{"role": "user", "content": self._create_analysis_prompt(post_text)}
|
86 |
]
|
87 |
+
|
88 |
# Get initial analysis
|
89 |
with st.spinner("π€ Analyzing content..."):
|
90 |
analysis_response = self._get_llm_response(messages)
|
91 |
+
|
92 |
if not analysis_response:
|
93 |
return None
|
94 |
|
|
|
|
|
95 |
# Parse JSON response
|
96 |
try:
|
97 |
analysis_result = json.loads(analysis_response)
|
98 |
except json.JSONDecodeError:
|
99 |
st.error("Error parsing LLM response")
|
100 |
return None
|
101 |
+
|
102 |
# Second thinking phase - Refinement
|
103 |
self._think("π― Phase 2: Refinement\nRefining analysis and generating specific recommendations...")
|
104 |
+
|
105 |
# Get specific recommendations
|
106 |
recommendation_prompt = f"""Based on the initial analysis of this post:
|
107 |
{post_text}
|
108 |
+
|
109 |
Provide 3 specific, actionable recommendations to improve engagement."""
|
110 |
+
|
111 |
messages.append({"role": "user", "content": recommendation_prompt})
|
112 |
recommendations = self._get_llm_response(messages)
|
113 |
+
|
114 |
if recommendations:
|
115 |
analysis_result["recommendations"] = recommendations
|
116 |
+
|
117 |
return analysis_result
|
118 |
|
119 |
+
|
120 |
class GraicieApp:
|
121 |
def __init__(self):
|
122 |
self.agent = ContentAnalysisAgent()
|
123 |
+
|
124 |
def display_header(self):
|
125 |
st.title("π€ Project Graicie - Advanced Content Analyzer")
|
126 |
st.markdown("""
|
127 |
### Powered by LLaMA 3 & Agentic AI
|
128 |
Get deep, AI-powered insights into your social media content using advanced language models.
|
129 |
""")
|
130 |
+
|
131 |
def display_example_posts(self):
|
132 |
examples = {
|
133 |
"Viral Post": "π HUGE ANNOUNCEMENT! After months of work, my online course is finally LIVE! π\n"
|
134 |
"Learn how I grew from 0 to 100K followers in 6 months! Early bird pricing ends tomorrow! π«\n"
|
135 |
"#socialmedia #digitalmarketing #success",
|
|
|
136 |
"Personal Story": "Sometimes life throws you curveballs... Today I faced my biggest fear and went "
|
137 |
+
"skydiving! πͺ Swipe to see my reaction! Remember: growth happens outside your comfort zone π\n"
|
138 |
+
"#personalgrowth #motivation",
|
|
|
139 |
"Educational": "π§ 5 Python Tips You Didn't Know:\n1. List comprehensions\n2. f-strings\n3. Walrus operator\n"
|
140 |
+
"4. Context managers\n5. Lambda functions\nSave this for later! π‘\n#coding #programming"
|
141 |
}
|
142 |
+
|
143 |
st.subheader("π± Try an Example Post")
|
144 |
selected_example = st.selectbox("Select an example post:", list(examples.keys()))
|
145 |
+
|
146 |
if selected_example:
|
147 |
st.text_area("Example Post", examples[selected_example], height=100, disabled=True)
|
148 |
if st.button("Analyze Example", use_container_width=True):
|
149 |
self.analyze_and_display(examples[selected_example])
|
150 |
+
|
151 |
def display_results(self, results: Dict):
|
152 |
if not results:
|
153 |
return
|
154 |
+
|
155 |
# Display main metrics
|
156 |
col1, col2, col3, col4 = st.columns(4)
|
157 |
with col1:
|
|
|
162 |
st.metric("Content Rating", f"{results['rating']}/5")
|
163 |
with col4:
|
164 |
st.metric("Audience Fit", results["analysis"]["audience_fit"])
|
165 |
+
|
166 |
# Display tones
|
167 |
st.subheader("π Content Tones")
|
168 |
for tone in results["tones"]:
|
169 |
st.markdown(f"<span style='background-color: #e6f3ff; padding: 5px 10px; "
|
170 |
+
f"margin: 5px; border-radius: 15px;'>{tone}</span>", unsafe_allow_html=True)
|
171 |
+
|
172 |
# Display strengths and improvements
|
173 |
col1, col2 = st.columns(2)
|
174 |
with col1:
|
175 |
st.subheader("πͺ Strengths")
|
176 |
for strength in results["analysis"]["strengths"]:
|
177 |
st.markdown(f"β
{strength}")
|
178 |
+
|
179 |
with col2:
|
180 |
st.subheader("π― Areas to Improve")
|
181 |
for improvement in results["analysis"]["improvements"]:
|
182 |
st.markdown(f"π {improvement}")
|
183 |
+
|
184 |
# Display recommendations
|
185 |
if "recommendations" in results:
|
186 |
st.subheader("π Specific Recommendations")
|
187 |
st.markdown(results["recommendations"])
|
188 |
+
|
189 |
def analyze_and_display(self, text: str):
|
190 |
results = self.agent.analyze_post(text)
|
191 |
if results:
|
192 |
self.display_results(results)
|
193 |
+
|
194 |
def run(self):
|
195 |
self.display_header()
|
196 |
+
|
197 |
# Main content area
|
198 |
col1, col2 = st.columns([2, 1])
|
199 |
+
|
200 |
with col1:
|
201 |
self.display_example_posts()
|
202 |
+
|
203 |
st.subheader("π Analyze Your Post")
|
204 |
user_post = st.text_area(
|
205 |
"Enter your post content:",
|
206 |
height=150,
|
207 |
placeholder="Type or paste your content here..."
|
208 |
)
|
209 |
+
|
210 |
if st.button("π Analyze My Post", use_container_width=True):
|
211 |
if user_post:
|
212 |
self.analyze_and_display(user_post)
|
213 |
else:
|
214 |
st.warning("Please enter some content to analyze!")
|
215 |
+
|
216 |
with col2:
|
217 |
st.subheader("π‘ Pro Tips")
|
218 |
st.info("""
|
|
|
223 |
4. Add visual elements
|
224 |
5. Engage with questions
|
225 |
""")
|
226 |
+
|
227 |
st.markdown("### π Optimal Post Elements")
|
228 |
st.markdown("""
|
229 |
- Length: 80-150 characters
|
|
|
231 |
- Emojis: 2-3 key emojis
|
232 |
- CTA: One clear action
|
233 |
""")
|
234 |
+
|
235 |
# Footer
|
236 |
st.markdown(
|
237 |
"""
|
|
|
243 |
</p>
|
244 |
</div>
|
245 |
""",
|
246 |
+
unsafe_allow_html=True,
|
247 |
)
|
248 |
|
249 |
+
|
250 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
251 |
app = GraicieApp()
|
252 |
+
app.run()
|