MBilal-72 commited on
Commit
ac748c8
·
verified ·
1 Parent(s): a9b6f92

Update utils/optimizer.py

Browse files
Files changed (1) hide show
  1. utils/optimizer.py +74 -32
utils/optimizer.py CHANGED
@@ -78,8 +78,48 @@ class ContentOptimizer:
78
  )
79
 
80
  # Competitive content analysis prompt
81
- self.competitive_analysis_prompt = ("Analyze the following content for AI search optimization gaps in entities, questions, clarity, flow, and semantic links. Return JSON with gaps and actionable recommendations.\nContent: {content}")
82
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
 
85
  # Dedicated prompt for rewriting/optimizing content
@@ -108,9 +148,9 @@ class ContentOptimizer:
108
  """
109
  try:
110
  # Choose optimization approach
111
- if optimization_type == "seo":
112
  return self._seo_style_optimization(content, analyze_only)
113
- elif optimization_type == "competitive":
114
  return self._competitive_optimization(content)
115
  else:
116
  return self._standard_optimization(content, analyze_only, include_keywords)
@@ -121,7 +161,8 @@ class ContentOptimizer:
121
  def _standard_optimization(self, content: str, analyze_only: bool, include_keywords: bool) -> Dict[str, Any]:
122
  """Standard content optimization using enhancement prompt"""
123
  try:
124
- if analyze_only:
 
125
  prompt_text = self.enhancement_prompt
126
  prompt_text = prompt_text.replace(
127
  "Rewrite the text to improve:",
@@ -130,38 +171,37 @@ class ContentOptimizer:
130
  '"optimized_text": "..."',
131
  '"optimization_suggestions": ["suggestion 1", "suggestion 2"]'
132
  )
133
- # else:
134
- # # Use dedicated rewrite prompt for optimization
135
- # prompt_text = self.optimization_rewrite_prompt
136
-
137
- if not include_keywords:
138
- prompt_text = prompt_text.replace(
139
- '"keywords": ["example", "installation", "setup"],',
140
- ''
141
- )
142
 
143
- prompt_template = ChatPromptTemplate.from_messages([
144
- SystemMessagePromptTemplate.from_template(prompt_text),
145
- HumanMessagePromptTemplate.from_template(content[:6000])
146
- ])
147
 
148
- chain = prompt_template | self.llm
149
- result = chain.invoke({})
150
 
151
- result_content = result.content if hasattr(result, 'content') else str(result)
152
- parsed_result = self._parse_optimization_result(result_content)
153
 
154
- parsed_result.update({
155
- 'optimization_type': 'standard',
156
- 'analyze_only': analyze_only,
157
- 'original_length': len(content),
158
- 'original_word_count': len(content.split())
159
- })
160
 
161
- return parsed_result
162
 
163
- except Exception as e:
164
- return {'error': f"Standard optimization failed: {str(e)}"}
165
  def _seo_style_optimization(self, content: str, analyze_only: bool) -> Dict[str, Any]:
166
  """SEO-focused optimization for AI search engines"""
167
  try:
@@ -432,7 +472,9 @@ class ContentOptimizer:
432
  Dict: Voice search optimization results
433
  """
434
  try:
435
- self.voice_prompt = ("Optimize the following content for voice search and conversational AI by improving natural language flow, question-based structure, tone, and featured snippet potential. Return JSON with improved content, Q&A pairs, snippet candidates, and a conversational score.\nContent: {content}")
 
 
436
  prompt_template = ChatPromptTemplate.from_messages([
437
  SystemMessagePromptTemplate.from_template(voice_prompt.format(content=content[:4000])),
438
  HumanMessagePromptTemplate.from_template("Optimize for voice search.")
 
78
  )
79
 
80
  # Competitive content analysis prompt
81
+ # self.competitive_analysis_prompt = ("Analyze the following content for AI search optimization gaps in entities, questions, clarity, flow, and semantic links. Return JSON with gaps and actionable recommendations.\nContent: {content}")
82
+ self.competitive_analysis_prompt = (
83
+ "Analyze the following content for AI search optimization gaps in entities, questions, clarity, flow, and semantic links. "
84
+ "Return JSON with gaps and actionable recommendations.\n"
85
+ "Content: {content}\n"
86
+ "Provide competitive analysis in JSON format:\n"
87
+ "{{\n"
88
+ " \"competitive_analysis\": {{\n"
89
+ " \"entity_gaps\": [\"gap1\", \"gap2\"],\n"
90
+ " \"question_coverage\": \"summary of coverage\",\n"
91
+ " \"factual_clarity\": \"assessment\",\n"
92
+ " \"conversational_flow\": \"assessment\",\n"
93
+ " \"semantic_relationships\": [\"relationship1\", \"relationship2\"]\n"
94
+ " }},\n"
95
+ " \"recommendations\": [\"recommendation 1\", \"recommendation 2\"]\n"
96
+ "}}\n"
97
+ )
98
+ self.voice_prompt = (
99
+ """
100
+ Optimize this content for voice search and conversational AI systems.
101
+ Focus on:
102
+ 1. Natural language patterns
103
+ 2. Question-based structure
104
+ 3. Conversational tone
105
+ 4. Clear, direct answers
106
+ 5. Featured snippet optimization
107
+ Original content: {content}
108
+ Provide optimization in JSON:
109
+ ```json
110
+ {{
111
+ "voice_optimized_content": "conversational version...",
112
+ "question_answer_pairs": [
113
+ {{"question": "What is...", "answer": "Direct answer..."}},
114
+ {{"question": "How does...", "answer": "Step by step..."}}
115
+ ],
116
+ "featured_snippet_candidates": ["snippet 1", "snippet 2"],
117
+ "natural_language_improvements": ["improvement 1", "improvement 2"],
118
+ "conversational_score": 8.5
119
+ }}
120
+ ```
121
+ """
122
+ )
123
 
124
 
125
  # Dedicated prompt for rewriting/optimizing content
 
148
  """
149
  try:
150
  # Choose optimization approach
151
+ if optimization_type == "seo" and not analyze_only:
152
  return self._seo_style_optimization(content, analyze_only)
153
+ elif optimization_type == "competitive" and not analyze_only:
154
  return self._competitive_optimization(content)
155
  else:
156
  return self._standard_optimization(content, analyze_only, include_keywords)
 
161
  def _standard_optimization(self, content: str, analyze_only: bool, include_keywords: bool) -> Dict[str, Any]:
162
  """Standard content optimization using enhancement prompt"""
163
  try:
164
+ # Always assign prompt_text
165
+ if analyze_only is True:
166
  prompt_text = self.enhancement_prompt
167
  prompt_text = prompt_text.replace(
168
  "Rewrite the text to improve:",
 
171
  '"optimized_text": "..."',
172
  '"optimization_suggestions": ["suggestion 1", "suggestion 2"]'
173
  )
174
+ if not include_keywords:
175
+ prompt_text = prompt_text.replace(
176
+ '"keywords": ["example", "installation", "setup"],',
177
+ ''
178
+ )
179
+ else:
180
+ # Use dedicated rewrite prompt for optimization
181
+ prompt_text = self.optimization_rewrite_prompt
 
182
 
183
+ prompt_template = ChatPromptTemplate.from_messages([
184
+ SystemMessagePromptTemplate.from_template(prompt_text),
185
+ HumanMessagePromptTemplate.from_template(content[:6000])
186
+ ])
187
 
188
+ chain = prompt_template | self.llm
189
+ result = chain.invoke({})
190
 
191
+ result_content = result.content if hasattr(result, 'content') else str(result)
192
+ parsed_result = self._parse_optimization_result(result_content)
193
 
194
+ parsed_result.update({
195
+ 'optimization_type': 'standard',
196
+ 'analyze_only': analyze_only,
197
+ 'original_length': len(content),
198
+ 'original_word_count': len(content.split())
199
+ })
200
 
201
+ return parsed_result
202
 
203
+ except Exception as e:
204
+ return {'error': f"Standard optimization failed: {str(e)}"}
205
  def _seo_style_optimization(self, content: str, analyze_only: bool) -> Dict[str, Any]:
206
  """SEO-focused optimization for AI search engines"""
207
  try:
 
472
  Dict: Voice search optimization results
473
  """
474
  try:
475
+ # self.voice_prompt = ("Optimize the following content for voice search and conversational AI by improving natural language flow, question-based structure, tone, and featured snippet potential. Return JSON with improved content, Q&A pairs, snippet candidates, and a conversational score.\nContent: {content}")
476
+
477
+
478
  prompt_template = ChatPromptTemplate.from_messages([
479
  SystemMessagePromptTemplate.from_template(voice_prompt.format(content=content[:4000])),
480
  HumanMessagePromptTemplate.from_template("Optimize for voice search.")