Spaces:
Runtime error
Runtime error
Update utils/scorer.py
Browse files- utils/scorer.py +581 -251
utils/scorer.py
CHANGED
|
@@ -1,330 +1,660 @@
|
|
| 1 |
"""
|
| 2 |
-
GEO
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
|
|
|
|
|
|
|
| 6 |
import logging
|
| 7 |
from typing import Dict, Any, List, Union, Optional
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
def __init__(self, logger
|
| 13 |
-
self.
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
def
|
| 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 |
-
def
|
| 48 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
#
|
| 51 |
content_fields = ['content', 'text', 'body', 'html_content', 'page_content', 'main_content']
|
| 52 |
-
title_fields = ['title', 'page_title', 'heading', 'h1', 'name']
|
| 53 |
-
url_fields = ['url', 'link', 'page_url', 'source_url', 'href']
|
| 54 |
-
|
| 55 |
-
# Extract content (try multiple possible field names)
|
| 56 |
content = ""
|
|
|
|
| 57 |
for field in content_fields:
|
| 58 |
if field in page_data and page_data[field]:
|
| 59 |
content = str(page_data[field])
|
| 60 |
break
|
| 61 |
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
title = "Untitled Page"
|
|
|
|
| 64 |
for field in title_fields:
|
| 65 |
if field in page_data and page_data[field]:
|
| 66 |
title = str(page_data[field])
|
| 67 |
break
|
| 68 |
|
| 69 |
-
#
|
|
|
|
| 70 |
url = ""
|
|
|
|
| 71 |
for field in url_fields:
|
| 72 |
if field in page_data and page_data[field]:
|
| 73 |
url = str(page_data[field])
|
| 74 |
break
|
| 75 |
|
| 76 |
-
|
| 77 |
-
normalized = {
|
| 78 |
'content': content,
|
| 79 |
'title': title,
|
| 80 |
'url': url,
|
| 81 |
-
'word_count': len(content.split()) if content else 0
|
| 82 |
-
'original_data': page_data # Keep original for debugging
|
| 83 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
"""Validate normalized data and provide diagnostics"""
|
| 95 |
-
|
| 96 |
-
validation_results = {
|
| 97 |
-
'total_pages': len(normalized_data),
|
| 98 |
-
'valid_pages': 0,
|
| 99 |
-
'invalid_pages': 0,
|
| 100 |
-
'issues': [],
|
| 101 |
-
'summary': {}
|
| 102 |
-
}
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
issues.append(f"Page {i}: Missing or empty content")
|
| 110 |
-
elif len(page['content'].strip()) < 50:
|
| 111 |
-
issues.append(f"Page {i}: Content too short ({len(page['content'])} chars)")
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
| 119 |
else:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
'
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
def
|
| 144 |
"""
|
| 145 |
-
Analyze
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
"""
|
| 154 |
-
self.logger.info("Starting analysis of scraped data")
|
| 155 |
-
|
| 156 |
try:
|
| 157 |
-
|
| 158 |
-
|
| 159 |
|
| 160 |
-
if not
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
return {
|
| 162 |
-
'error': 'No valid
|
| 163 |
-
'error_type': '
|
| 164 |
-
'
|
| 165 |
-
'
|
|
|
|
| 166 |
}
|
| 167 |
|
| 168 |
-
#
|
| 169 |
-
|
|
|
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
aggregate_results = self.calculate_aggregate_scores(analysis_results)
|
| 176 |
|
| 177 |
-
#
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
'processing_summary': {
|
| 183 |
-
'pages_scraped': validation_results['total_pages'],
|
| 184 |
-
'pages_analyzed': len([r for r in analysis_results if not r.get('error')]),
|
| 185 |
-
'overall_success_rate': validation_results['valid_pages'] / max(validation_results['total_pages'], 1),
|
| 186 |
-
'analysis_type': 'detailed' if detailed else 'quick'
|
| 187 |
-
}
|
| 188 |
-
}
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
-
except Exception as e:
|
| 194 |
-
self.logger.error(f"Scraped data analysis failed: {e}")
|
| 195 |
return {
|
| 196 |
-
'
|
| 197 |
-
'
|
| 198 |
-
'
|
| 199 |
-
'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
}
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
"""
|
| 206 |
-
Debug utility to understand the structure of scraped data
|
| 207 |
-
|
| 208 |
-
Args:
|
| 209 |
-
scraped_data: The raw scraped data causing issues
|
| 210 |
-
|
| 211 |
-
Returns:
|
| 212 |
-
Dict: Detailed breakdown of the data structure
|
| 213 |
-
"""
|
| 214 |
-
debug_info = {
|
| 215 |
-
'data_type': str(type(scraped_data)),
|
| 216 |
-
'data_structure': {},
|
| 217 |
-
'sample_content': {},
|
| 218 |
-
'recommendations': []
|
| 219 |
-
}
|
| 220 |
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
}
|
| 228 |
|
| 229 |
-
|
| 230 |
-
for i, (key, value) in enumerate(list(scraped_data.items())[:5]):
|
| 231 |
-
debug_info['sample_content'][key] = {
|
| 232 |
-
'type': str(type(value)),
|
| 233 |
-
'length': len(str(value)) if value else 0,
|
| 234 |
-
'sample': str(value)[:100] if value else None
|
| 235 |
-
}
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
debug_info['data_structure'] = {
|
| 248 |
-
'is_list': True,
|
| 249 |
-
'length': len(scraped_data),
|
| 250 |
-
'first_item_type': str(type(scraped_data[0])) if scraped_data else 'empty'
|
| 251 |
-
}
|
| 252 |
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
else:
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
debug_info['error'] = f"Debug analysis failed: {str(e)}"
|
| 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 |
-
def
|
| 298 |
-
"""
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
for i, data in enumerate(test_data):
|
| 305 |
-
print(f"\n--- Debug Info for Test Data {i+1} ---")
|
| 306 |
-
debug_info = debug_scraped_data(data)
|
| 307 |
-
print(f"Data type: {debug_info['data_type']}")
|
| 308 |
-
print(f"Keys: {debug_info['data_structure'].get('keys', 'N/A')}")
|
| 309 |
-
print(f"Recommendations: {debug_info['recommendations']}")
|
| 310 |
-
|
| 311 |
-
# Test normalization
|
| 312 |
-
adapter = GEODataAdapter()
|
| 313 |
-
normalized = adapter.normalize_scraped_data(test_data)
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
| 319 |
-
|
| 320 |
-
print(f"
|
|
|
|
|
|
|
| 321 |
|
| 322 |
-
|
| 323 |
-
validation = adapter.validate_normalized_data(normalized)
|
| 324 |
-
print(f"\n--- Validation Results ---")
|
| 325 |
-
print(f"Valid pages: {validation['valid_pages']}/{validation['total_pages']}")
|
| 326 |
-
print(f"Issues: {validation['issues']}")
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
if __name__ == "__main__":
|
| 330 |
-
test_data_integration()
|
|
|
|
| 1 |
"""
|
| 2 |
+
Fixed GEO Scoring Module - Drop-in replacement for your original
|
| 3 |
+
This version fixes the data format issues while keeping your existing structure
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
import logging
|
| 9 |
from typing import Dict, Any, List, Union, Optional
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
|
| 12 |
|
| 13 |
+
|
| 14 |
+
class GEOScorer:
|
| 15 |
+
"""Main class for calculating GEO scores and analysis - IMPROVED VERSION"""
|
| 16 |
|
| 17 |
+
def __init__(self, llm, logger=None):
|
| 18 |
+
self.llm = llm
|
| 19 |
+
self.logger = logger or self._setup_logger()
|
| 20 |
+
self.setup_prompts()
|
| 21 |
|
| 22 |
+
def _setup_logger(self):
|
| 23 |
+
"""Setup default logger"""
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
if not logger.handlers:
|
| 26 |
+
handler = logging.StreamHandler()
|
| 27 |
+
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
|
| 28 |
+
handler.setFormatter(formatter)
|
| 29 |
+
logger.addHandler(handler)
|
| 30 |
+
logger.setLevel(logging.INFO)
|
| 31 |
+
return logger
|
| 32 |
+
|
| 33 |
+
def setup_prompts(self):
|
| 34 |
+
"""Initialize prompts for different types of analysis"""
|
| 35 |
|
| 36 |
+
# Main GEO analysis prompt
|
| 37 |
+
self.geo_analysis_prompt = """You are a Generative Engine Optimizer (GEO) specialist. Analyze the provided content for its effectiveness in AI-powered search engines and LLM systems.
|
| 38 |
+
|
| 39 |
+
Evaluate the content based on these GEO criteria (score 1-10 each):
|
| 40 |
+
|
| 41 |
+
1. **AI Search Visibility**: How likely is this content to be surfaced by AI search engines?
|
| 42 |
+
2. **Query Intent Matching**: How well does the content match common user queries?
|
| 43 |
+
3. **Factual Accuracy & Authority**: How trustworthy and authoritative is the information?
|
| 44 |
+
4. **Conversational Readiness**: How suitable is the content for AI chat responses?
|
| 45 |
+
5. **Semantic Richness**: How well does the content use relevant semantic keywords?
|
| 46 |
+
6. **Context Completeness**: Does the content provide complete, self-contained answers?
|
| 47 |
+
7. **Citation Worthiness**: How likely are AI systems to cite this content?
|
| 48 |
+
8. **Multi-Query Coverage**: Does the content answer multiple related questions?
|
| 49 |
+
|
| 50 |
+
Also identify:
|
| 51 |
+
- Primary topics and entities
|
| 52 |
+
- Missing information gaps
|
| 53 |
+
- Optimization opportunities
|
| 54 |
+
- Specific enhancement recommendations
|
| 55 |
+
|
| 56 |
+
IMPORTANT: Respond ONLY with valid JSON. Do not include any text before or after the JSON.
|
| 57 |
+
|
| 58 |
+
{
|
| 59 |
+
"geo_scores": {
|
| 60 |
+
"ai_search_visibility": 7.5,
|
| 61 |
+
"query_intent_matching": 8.0,
|
| 62 |
+
"factual_accuracy": 9.0,
|
| 63 |
+
"conversational_readiness": 6.5,
|
| 64 |
+
"semantic_richness": 7.0,
|
| 65 |
+
"context_completeness": 8.5,
|
| 66 |
+
"citation_worthiness": 7.8,
|
| 67 |
+
"multi_query_coverage": 6.0
|
| 68 |
+
},
|
| 69 |
+
"overall_geo_score": 7.5,
|
| 70 |
+
"primary_topics": ["topic1", "topic2"],
|
| 71 |
+
"entities": ["entity1", "entity2"],
|
| 72 |
+
"missing_gaps": ["gap1", "gap2"],
|
| 73 |
+
"optimization_opportunities": [
|
| 74 |
+
{
|
| 75 |
+
"type": "semantic_enhancement",
|
| 76 |
+
"description": "Add more related terms",
|
| 77 |
+
"priority": "high"
|
| 78 |
+
}
|
| 79 |
+
],
|
| 80 |
+
"recommendations": [
|
| 81 |
+
"Specific actionable recommendation 1",
|
| 82 |
+
"Specific actionable recommendation 2"
|
| 83 |
+
]
|
| 84 |
+
}"""
|
| 85 |
+
|
| 86 |
+
# Quick scoring prompt for faster analysis
|
| 87 |
+
self.quick_score_prompt = """Analyze this content for AI search optimization. Provide scores (1-10) for:
|
| 88 |
+
|
| 89 |
+
1. AI Search Visibility
|
| 90 |
+
2. Query Intent Matching
|
| 91 |
+
3. Conversational Readiness
|
| 92 |
+
4. Citation Worthiness
|
| 93 |
+
|
| 94 |
+
IMPORTANT: Respond ONLY with valid JSON. Do not include any text before or after the JSON.
|
| 95 |
+
|
| 96 |
+
{
|
| 97 |
+
"scores": {
|
| 98 |
+
"ai_search_visibility": 7.5,
|
| 99 |
+
"query_intent_matching": 8.0,
|
| 100 |
+
"conversational_readiness": 6.5,
|
| 101 |
+
"citation_worthiness": 7.8
|
| 102 |
+
},
|
| 103 |
+
"overall_score": 7.5,
|
| 104 |
+
"top_recommendation": "Most important improvement needed"
|
| 105 |
+
}"""
|
| 106 |
+
|
| 107 |
+
# Competitive analysis prompt
|
| 108 |
+
self.competitive_prompt = """Compare these content pieces for GEO performance. Identify which performs better for AI search and why.
|
| 109 |
+
|
| 110 |
+
Content A: {content_a}
|
| 111 |
+
|
| 112 |
+
Content B: {content_b}
|
| 113 |
+
|
| 114 |
+
IMPORTANT: Respond ONLY with valid JSON. Do not include any text before or after the JSON.
|
| 115 |
+
|
| 116 |
+
{
|
| 117 |
+
"winner": "A",
|
| 118 |
+
"score_comparison": {
|
| 119 |
+
"content_a_score": 7.5,
|
| 120 |
+
"content_b_score": 8.2
|
| 121 |
+
},
|
| 122 |
+
"key_differences": ["difference1", "difference2"],
|
| 123 |
+
"improvement_suggestions": {
|
| 124 |
+
"content_a": ["suggestion1"],
|
| 125 |
+
"content_b": ["suggestion1"]
|
| 126 |
+
}
|
| 127 |
+
}"""
|
| 128 |
|
| 129 |
+
def _normalize_page_data(self, page_data):
|
| 130 |
+
"""
|
| 131 |
+
FIXED: Normalize different data formats from web scrapers
|
| 132 |
+
This handles the 'content' key error you were seeing
|
| 133 |
+
"""
|
| 134 |
+
if not isinstance(page_data, dict):
|
| 135 |
+
self.logger.warning(f"Expected dict, got {type(page_data)}")
|
| 136 |
+
return None
|
| 137 |
|
| 138 |
+
# Try different field names for content
|
| 139 |
content_fields = ['content', 'text', 'body', 'html_content', 'page_content', 'main_content']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
content = ""
|
| 141 |
+
|
| 142 |
for field in content_fields:
|
| 143 |
if field in page_data and page_data[field]:
|
| 144 |
content = str(page_data[field])
|
| 145 |
break
|
| 146 |
|
| 147 |
+
if not content:
|
| 148 |
+
self.logger.warning(f"No content found in page data. Available keys: {list(page_data.keys())}")
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
# Try different field names for title
|
| 152 |
+
title_fields = ['title', 'page_title', 'heading', 'h1', 'name']
|
| 153 |
title = "Untitled Page"
|
| 154 |
+
|
| 155 |
for field in title_fields:
|
| 156 |
if field in page_data and page_data[field]:
|
| 157 |
title = str(page_data[field])
|
| 158 |
break
|
| 159 |
|
| 160 |
+
# Try different field names for URL
|
| 161 |
+
url_fields = ['url', 'link', 'page_url', 'source_url', 'href']
|
| 162 |
url = ""
|
| 163 |
+
|
| 164 |
for field in url_fields:
|
| 165 |
if field in page_data and page_data[field]:
|
| 166 |
url = str(page_data[field])
|
| 167 |
break
|
| 168 |
|
| 169 |
+
return {
|
|
|
|
| 170 |
'content': content,
|
| 171 |
'title': title,
|
| 172 |
'url': url,
|
| 173 |
+
'word_count': len(content.split()) if content else 0
|
|
|
|
| 174 |
}
|
| 175 |
+
|
| 176 |
+
def _sanitize_content(self, content):
|
| 177 |
+
"""Basic content sanitization"""
|
| 178 |
+
if not content:
|
| 179 |
+
return ""
|
| 180 |
|
| 181 |
+
# Remove potential prompt injection patterns
|
| 182 |
+
dangerous_patterns = [
|
| 183 |
+
r'ignore\s+previous\s+instructions',
|
| 184 |
+
r'system\s*:',
|
| 185 |
+
r'assistant\s*:',
|
| 186 |
+
]
|
| 187 |
|
| 188 |
+
sanitized = content
|
| 189 |
+
for pattern in dangerous_patterns:
|
| 190 |
+
sanitized = re.sub(pattern, '[FILTERED]', sanitized, flags=re.IGNORECASE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
return sanitized[:8000] # Limit length
|
| 193 |
+
|
| 194 |
+
def analyze_page_geo(self, content: str, title: str, detailed: bool = True) -> Dict[str, Any]:
|
| 195 |
+
"""
|
| 196 |
+
Analyze a single page for GEO performance
|
| 197 |
+
FIXED: Better error handling and validation
|
| 198 |
+
"""
|
| 199 |
+
try:
|
| 200 |
+
# Input validation
|
| 201 |
+
if not content or not content.strip():
|
| 202 |
+
return {'error': 'Empty or missing content', 'error_type': 'validation'}
|
| 203 |
|
| 204 |
+
if len(content.strip()) < 50:
|
| 205 |
+
return {'error': 'Content too short for analysis', 'error_type': 'validation'}
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
+
# Sanitize content
|
| 208 |
+
sanitized_content = self._sanitize_content(content)
|
| 209 |
|
| 210 |
+
# Choose prompt based on detail level
|
| 211 |
+
if detailed:
|
| 212 |
+
system_prompt = self.geo_analysis_prompt
|
| 213 |
+
max_length = 8000
|
| 214 |
else:
|
| 215 |
+
system_prompt = self.quick_score_prompt
|
| 216 |
+
max_length = 4000
|
| 217 |
+
|
| 218 |
+
# Smart truncation
|
| 219 |
+
if len(sanitized_content) > max_length:
|
| 220 |
+
truncated = sanitized_content[:max_length]
|
| 221 |
+
# Try to end at a sentence
|
| 222 |
+
last_period = truncated.rfind('. ')
|
| 223 |
+
if last_period > max_length * 0.8:
|
| 224 |
+
sanitized_content = truncated[:last_period + 1]
|
| 225 |
+
else:
|
| 226 |
+
sanitized_content = truncated + "..."
|
| 227 |
+
|
| 228 |
+
user_message = f"Title: {title}\n\nContent: {sanitized_content}"
|
| 229 |
|
| 230 |
+
# Build prompt and run analysis
|
| 231 |
+
prompt_template = ChatPromptTemplate.from_messages([
|
| 232 |
+
SystemMessagePromptTemplate.from_template(system_prompt),
|
| 233 |
+
HumanMessagePromptTemplate.from_template(user_message)
|
| 234 |
+
])
|
| 235 |
+
|
| 236 |
+
chain = prompt_template | self.llm
|
| 237 |
+
result = chain.invoke({})
|
| 238 |
|
| 239 |
+
# Extract and parse result
|
| 240 |
+
result_content = result.content if hasattr(result, 'content') else str(result)
|
| 241 |
+
parsed_result = self._parse_llm_response(result_content)
|
| 242 |
+
|
| 243 |
+
# Add metadata
|
| 244 |
+
parsed_result.update({
|
| 245 |
+
'analyzed_title': title,
|
| 246 |
+
'content_length': len(content),
|
| 247 |
+
'word_count': len(content.split()),
|
| 248 |
+
'analysis_type': 'detailed' if detailed else 'quick'
|
| 249 |
+
})
|
| 250 |
+
|
| 251 |
+
return parsed_result
|
| 252 |
+
|
| 253 |
+
except json.JSONDecodeError as e:
|
| 254 |
+
self.logger.error(f"JSON parsing failed for '{title}': {e}")
|
| 255 |
+
return {'error': 'Invalid response format from LLM', 'error_type': 'parsing'}
|
| 256 |
+
except Exception as e:
|
| 257 |
+
self.logger.error(f"Analysis failed for '{title}': {e}")
|
| 258 |
+
return {'error': f"Analysis failed: {str(e)}", 'error_type': 'system'}
|
| 259 |
|
| 260 |
+
def analyze_multiple_pages(self, pages_data: List[Dict[str, Any]], detailed: bool = True) -> List[Dict[str, Any]]:
|
| 261 |
"""
|
| 262 |
+
FIXED: Analyze multiple pages with automatic data normalization
|
| 263 |
+
This handles different data formats from web scrapers
|
| 264 |
+
"""
|
| 265 |
+
if not pages_data:
|
| 266 |
+
self.logger.error("No pages data provided")
|
| 267 |
+
return [{'error': 'No pages data provided', 'error_type': 'validation'}]
|
| 268 |
+
|
| 269 |
+
results = []
|
| 270 |
+
successful_analyses = 0
|
| 271 |
|
| 272 |
+
self.logger.info(f"Starting analysis of {len(pages_data)} pages")
|
| 273 |
+
|
| 274 |
+
for i, page_data in enumerate(pages_data):
|
| 275 |
+
try:
|
| 276 |
+
# FIXED: Normalize the data format
|
| 277 |
+
normalized_page = self._normalize_page_data(page_data)
|
| 278 |
+
|
| 279 |
+
if not normalized_page:
|
| 280 |
+
self.logger.warning(f"Page {i}: Could not extract content. Available keys: {list(page_data.keys()) if isinstance(page_data, dict) else 'Not a dict'}")
|
| 281 |
+
results.append({
|
| 282 |
+
'page_index': i,
|
| 283 |
+
'error': 'Could not extract content from page data',
|
| 284 |
+
'error_type': 'data_format',
|
| 285 |
+
'available_keys': list(page_data.keys()) if isinstance(page_data, dict) else None
|
| 286 |
+
})
|
| 287 |
+
continue
|
| 288 |
+
|
| 289 |
+
content = normalized_page['content']
|
| 290 |
+
title = normalized_page['title']
|
| 291 |
+
|
| 292 |
+
analysis = self.analyze_page_geo(content, title, detailed)
|
| 293 |
+
|
| 294 |
+
# Add page-specific metadata
|
| 295 |
+
analysis.update({
|
| 296 |
+
'page_url': normalized_page.get('url', ''),
|
| 297 |
+
'page_index': i,
|
| 298 |
+
'source_word_count': normalized_page.get('word_count', 0)
|
| 299 |
+
})
|
| 300 |
+
|
| 301 |
+
if 'error' not in analysis:
|
| 302 |
+
successful_analyses += 1
|
| 303 |
+
|
| 304 |
+
results.append(analysis)
|
| 305 |
+
|
| 306 |
+
except Exception as e:
|
| 307 |
+
self.logger.error(f"Failed to analyze page {i}: {e}")
|
| 308 |
+
results.append({
|
| 309 |
+
'page_index': i,
|
| 310 |
+
'error': f"Analysis failed: {str(e)}",
|
| 311 |
+
'error_type': 'system'
|
| 312 |
+
})
|
| 313 |
+
|
| 314 |
+
self.logger.info(f"Completed analysis: {successful_analyses}/{len(pages_data)} successful")
|
| 315 |
+
return results
|
| 316 |
+
|
| 317 |
+
def compare_content_geo(self, content_a: str, content_b: str, titles: tuple = None) -> Dict[str, Any]:
|
| 318 |
+
"""
|
| 319 |
+
Compare two pieces of content for GEO performance
|
| 320 |
+
"""
|
| 321 |
+
try:
|
| 322 |
+
title_a, title_b = titles if titles else ("Content A", "Content B")
|
| 323 |
+
|
| 324 |
+
# Sanitize content
|
| 325 |
+
content_a = self._sanitize_content(content_a)
|
| 326 |
+
content_b = self._sanitize_content(content_b)
|
| 327 |
+
|
| 328 |
+
# Format the competitive analysis prompt
|
| 329 |
+
formatted_prompt = self.competitive_prompt.format(
|
| 330 |
+
content_a=f"Title: {title_a}\nContent: {content_a[:4000]}",
|
| 331 |
+
content_b=f"Title: {title_b}\nContent: {content_b[:4000]}"
|
| 332 |
+
)
|
| 333 |
|
| 334 |
+
chain = ChatPromptTemplate.from_messages([
|
| 335 |
+
("system", formatted_prompt),
|
| 336 |
+
("user", "Perform the comparison analysis.")
|
| 337 |
+
]) | self.llm
|
| 338 |
+
|
| 339 |
+
result = chain.invoke({})
|
| 340 |
+
result_content = result.content if hasattr(result, 'content') else str(result)
|
| 341 |
+
|
| 342 |
+
return self._parse_llm_response(result_content)
|
| 343 |
+
|
| 344 |
+
except Exception as e:
|
| 345 |
+
self.logger.error(f"Comparison analysis failed: {e}")
|
| 346 |
+
return {'error': f"Comparison analysis failed: {str(e)}", 'error_type': 'system'}
|
| 347 |
+
|
| 348 |
+
def calculate_aggregate_scores(self, individual_results: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 349 |
+
"""
|
| 350 |
+
Calculate aggregate GEO scores from multiple page analyses
|
| 351 |
+
FIXED: Better error handling for missing data
|
| 352 |
"""
|
|
|
|
|
|
|
| 353 |
try:
|
| 354 |
+
valid_results = [r for r in individual_results if 'geo_scores' in r and not r.get('error')]
|
| 355 |
+
error_results = [r for r in individual_results if r.get('error')]
|
| 356 |
|
| 357 |
+
if not valid_results:
|
| 358 |
+
error_summary = {}
|
| 359 |
+
for result in error_results:
|
| 360 |
+
error_type = result.get('error_type', 'unknown')
|
| 361 |
+
error_summary[error_type] = error_summary.get(error_type, 0) + 1
|
| 362 |
+
|
| 363 |
return {
|
| 364 |
+
'error': 'No valid results to aggregate',
|
| 365 |
+
'error_type': 'no_data',
|
| 366 |
+
'total_pages': len(individual_results),
|
| 367 |
+
'error_breakdown': error_summary,
|
| 368 |
+
'sample_errors': [r.get('error', 'Unknown error') for r in error_results[:3]]
|
| 369 |
}
|
| 370 |
|
| 371 |
+
# Calculate average scores
|
| 372 |
+
score_keys = list(valid_results[0]['geo_scores'].keys())
|
| 373 |
+
avg_scores = {}
|
| 374 |
|
| 375 |
+
for key in score_keys:
|
| 376 |
+
scores = [r['geo_scores'][key] for r in valid_results if key in r['geo_scores']]
|
| 377 |
+
avg_scores[key] = sum(scores) / len(scores) if scores else 0
|
| 378 |
|
| 379 |
+
overall_avg = sum(avg_scores.values()) / len(avg_scores) if avg_scores else 0
|
|
|
|
| 380 |
|
| 381 |
+
# Collect all recommendations and opportunities
|
| 382 |
+
all_recommendations = []
|
| 383 |
+
all_opportunities = []
|
| 384 |
+
all_topics = []
|
| 385 |
+
all_entities = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
+
for result in valid_results:
|
| 388 |
+
all_recommendations.extend(result.get('recommendations', []))
|
| 389 |
+
all_opportunities.extend(result.get('optimization_opportunities', []))
|
| 390 |
+
all_topics.extend(result.get('primary_topics', []))
|
| 391 |
+
all_entities.extend(result.get('entities', []))
|
| 392 |
+
|
| 393 |
+
# Remove duplicates
|
| 394 |
+
unique_recommendations = list(set(all_recommendations))
|
| 395 |
+
unique_topics = list(set(all_topics))
|
| 396 |
+
unique_entities = list(set(all_entities))
|
| 397 |
+
|
| 398 |
+
# Find highest and lowest performing areas
|
| 399 |
+
best_score = max(avg_scores.items(), key=lambda x: x[1]) if avg_scores else ('none', 0)
|
| 400 |
+
worst_score = min(avg_scores.items(), key=lambda x: x[1]) if avg_scores else ('none', 0)
|
| 401 |
|
|
|
|
|
|
|
| 402 |
return {
|
| 403 |
+
'aggregate_scores': avg_scores,
|
| 404 |
+
'overall_score': overall_avg,
|
| 405 |
+
'pages_analyzed': len(valid_results),
|
| 406 |
+
'pages_with_errors': len(error_results),
|
| 407 |
+
'success_rate': len(valid_results) / len(individual_results) if individual_results else 0,
|
| 408 |
+
'best_performing_metric': {
|
| 409 |
+
'metric': best_score[0],
|
| 410 |
+
'score': best_score[1]
|
| 411 |
+
},
|
| 412 |
+
'lowest_performing_metric': {
|
| 413 |
+
'metric': worst_score[0],
|
| 414 |
+
'score': worst_score[1]
|
| 415 |
+
},
|
| 416 |
+
'consolidated_recommendations': unique_recommendations[:10],
|
| 417 |
+
'all_topics': unique_topics,
|
| 418 |
+
'all_entities': unique_entities,
|
| 419 |
+
'high_priority_opportunities': [
|
| 420 |
+
opp for opp in all_opportunities
|
| 421 |
+
if isinstance(opp, dict) and opp.get('priority') == 'high'
|
| 422 |
+
][:5],
|
| 423 |
+
'score_distribution': self._calculate_score_distribution(avg_scores)
|
| 424 |
}
|
| 425 |
+
|
| 426 |
+
except Exception as e:
|
| 427 |
+
self.logger.error(f"Aggregation failed: {e}")
|
| 428 |
+
return {'error': f"Aggregation failed: {str(e)}", 'error_type': 'system'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
|
| 430 |
+
def generate_geo_report(self, analysis_results: Dict[str, Any], website_url: str = None) -> Dict[str, Any]:
|
| 431 |
+
"""
|
| 432 |
+
Generate a comprehensive GEO report
|
| 433 |
+
"""
|
| 434 |
+
try:
|
| 435 |
+
report = {
|
| 436 |
+
'report_metadata': {
|
| 437 |
+
'generated_at': self._get_timestamp(),
|
| 438 |
+
'website_url': website_url,
|
| 439 |
+
'analysis_type': 'GEO Performance Report'
|
| 440 |
+
},
|
| 441 |
+
'executive_summary': self._generate_executive_summary(analysis_results),
|
| 442 |
+
'detailed_scores': analysis_results.get('aggregate_scores', {}),
|
| 443 |
+
'performance_insights': self._generate_performance_insights(analysis_results),
|
| 444 |
+
'actionable_recommendations': self._prioritize_recommendations(
|
| 445 |
+
analysis_results.get('consolidated_recommendations', [])
|
| 446 |
+
),
|
| 447 |
+
'optimization_roadmap': self._create_optimization_roadmap(analysis_results),
|
| 448 |
+
'competitive_position': self._assess_competitive_position(analysis_results),
|
| 449 |
+
'technical_details': {
|
| 450 |
+
'pages_analyzed': analysis_results.get('pages_analyzed', 0),
|
| 451 |
+
'overall_score': analysis_results.get('overall_score', 0),
|
| 452 |
+
'score_distribution': analysis_results.get('score_distribution', {})
|
| 453 |
+
}
|
| 454 |
}
|
| 455 |
|
| 456 |
+
return report
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
+
except Exception as e:
|
| 459 |
+
self.logger.error(f"Report generation failed: {e}")
|
| 460 |
+
return {'error': f"Report generation failed: {str(e)}", 'error_type': 'system'}
|
| 461 |
+
|
| 462 |
+
def _parse_llm_response(self, response_text: str) -> Dict[str, Any]:
|
| 463 |
+
"""FIXED: Enhanced LLM response parsing"""
|
| 464 |
+
try:
|
| 465 |
+
# Clean response text
|
| 466 |
+
cleaned_response = response_text.strip()
|
| 467 |
|
| 468 |
+
# Try to find JSON content with multiple patterns
|
| 469 |
+
json_patterns = [
|
| 470 |
+
r'\{.*\}', # Simple JSON object
|
| 471 |
+
r'```json\s*(\{.*?\})\s*```', # JSON in code blocks
|
| 472 |
+
r'```\s*(\{.*?\})\s*```' # Generic code blocks
|
| 473 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
|
| 475 |
+
for pattern in json_patterns:
|
| 476 |
+
matches = re.findall(pattern, cleaned_response, re.DOTALL)
|
| 477 |
+
if matches:
|
| 478 |
+
json_str = matches[0] if len(matches) == 1 else matches[0]
|
| 479 |
+
try:
|
| 480 |
+
return json.loads(json_str)
|
| 481 |
+
except json.JSONDecodeError:
|
| 482 |
+
continue
|
| 483 |
+
|
| 484 |
+
# Try parsing the entire response
|
| 485 |
+
try:
|
| 486 |
+
return json.loads(cleaned_response)
|
| 487 |
+
except json.JSONDecodeError:
|
| 488 |
+
pass
|
| 489 |
+
|
| 490 |
+
# If all else fails, return structured error
|
| 491 |
+
return {
|
| 492 |
+
'raw_response': response_text[:500],
|
| 493 |
+
'parsing_error': 'No valid JSON found in LLM response',
|
| 494 |
+
'error_type': 'parsing'
|
| 495 |
+
}
|
| 496 |
|
| 497 |
+
except Exception as e:
|
| 498 |
+
return {
|
| 499 |
+
'raw_response': response_text[:500],
|
| 500 |
+
'parsing_error': f'Parsing error: {str(e)}',
|
| 501 |
+
'error_type': 'parsing'
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
def _calculate_score_distribution(self, scores: Dict[str, float]) -> Dict[str, Any]:
|
| 505 |
+
"""Calculate distribution of scores for insights"""
|
| 506 |
+
if not scores:
|
| 507 |
+
return {}
|
| 508 |
+
|
| 509 |
+
score_values = list(scores.values())
|
| 510 |
+
|
| 511 |
+
return {
|
| 512 |
+
'highest_score': max(score_values),
|
| 513 |
+
'lowest_score': min(score_values),
|
| 514 |
+
'average_score': sum(score_values) / len(score_values),
|
| 515 |
+
'score_range': max(score_values) - min(score_values),
|
| 516 |
+
'scores_above_7': len([s for s in score_values if s >= 7.0]),
|
| 517 |
+
'scores_below_5': len([s for s in score_values if s < 5.0])
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
def _generate_executive_summary(self, analysis_results: Dict[str, Any]) -> str:
|
| 521 |
+
"""Generate executive summary based on analysis results"""
|
| 522 |
+
overall_score = analysis_results.get('overall_score', 0)
|
| 523 |
+
pages_analyzed = analysis_results.get('pages_analyzed', 0)
|
| 524 |
+
|
| 525 |
+
if overall_score >= 8.0:
|
| 526 |
+
performance = "excellent"
|
| 527 |
+
elif overall_score >= 6.5:
|
| 528 |
+
performance = "good"
|
| 529 |
+
elif overall_score >= 5.0:
|
| 530 |
+
performance = "moderate"
|
| 531 |
else:
|
| 532 |
+
performance = "needs improvement"
|
| 533 |
+
|
| 534 |
+
return f"Analysis of {pages_analyzed} pages shows {performance} GEO performance with an overall score of {overall_score:.1f}/10. Key opportunities exist in {analysis_results.get('lowest_performing_metric', {}).get('metric', 'multiple areas')}."
|
|
|
|
| 535 |
|
| 536 |
+
def _generate_performance_insights(self, analysis_results: Dict[str, Any]) -> List[str]:
|
| 537 |
+
"""Generate performance insights based on analysis"""
|
| 538 |
+
insights = []
|
| 539 |
+
|
| 540 |
+
best_metric = analysis_results.get('best_performing_metric', {})
|
| 541 |
+
worst_metric = analysis_results.get('lowest_performing_metric', {})
|
| 542 |
+
|
| 543 |
+
if best_metric.get('score', 0) >= 8.0:
|
| 544 |
+
insights.append(f"Strong performance in {best_metric.get('metric', 'unknown')} (score: {best_metric.get('score', 0):.1f})")
|
| 545 |
+
|
| 546 |
+
if worst_metric.get('score', 10) < 6.0:
|
| 547 |
+
insights.append(f"Significant improvement needed in {worst_metric.get('metric', 'unknown')} (score: {worst_metric.get('score', 0):.1f})")
|
| 548 |
+
|
| 549 |
+
score_dist = analysis_results.get('score_distribution', {})
|
| 550 |
+
if score_dist.get('score_range', 0) > 3.0:
|
| 551 |
+
insights.append("High variability in scores indicates inconsistent optimization across metrics")
|
| 552 |
+
|
| 553 |
+
return insights
|
| 554 |
|
| 555 |
+
def _prioritize_recommendations(self, recommendations: List[str]) -> List[Dict[str, Any]]:
|
| 556 |
+
"""Prioritize recommendations based on impact potential"""
|
| 557 |
+
prioritized = []
|
| 558 |
+
|
| 559 |
+
# Simple prioritization based on keywords
|
| 560 |
+
high_impact_keywords = ['semantic', 'structure', 'authority', 'factual']
|
| 561 |
+
medium_impact_keywords = ['readability', 'clarity', 'format']
|
| 562 |
+
|
| 563 |
+
for i, rec in enumerate(recommendations):
|
| 564 |
+
priority = 'low'
|
| 565 |
+
if any(keyword in rec.lower() for keyword in high_impact_keywords):
|
| 566 |
+
priority = 'high'
|
| 567 |
+
elif any(keyword in rec.lower() for keyword in medium_impact_keywords):
|
| 568 |
+
priority = 'medium'
|
| 569 |
+
|
| 570 |
+
prioritized.append({
|
| 571 |
+
'recommendation': rec,
|
| 572 |
+
'priority': priority,
|
| 573 |
+
'order': i + 1
|
| 574 |
+
})
|
| 575 |
+
|
| 576 |
+
# Sort by priority
|
| 577 |
+
priority_order = {'high': 1, 'medium': 2, 'low': 3}
|
| 578 |
+
prioritized.sort(key=lambda x: priority_order[x['priority']])
|
| 579 |
+
|
| 580 |
+
return prioritized
|
| 581 |
|
| 582 |
+
def _create_optimization_roadmap(self, analysis_results: Dict[str, Any]) -> Dict[str, List[str]]:
|
| 583 |
+
"""Create a phased optimization roadmap"""
|
| 584 |
+
roadmap = {
|
| 585 |
+
'immediate_actions': [],
|
| 586 |
+
'short_term_goals': [],
|
| 587 |
+
'long_term_strategy': []
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
overall_score = analysis_results.get('overall_score', 0)
|
| 591 |
+
worst_metric = analysis_results.get('lowest_performing_metric', {})
|
| 592 |
+
|
| 593 |
+
# Immediate actions based on worst performing metric
|
| 594 |
+
if worst_metric.get('score', 10) < 5.0:
|
| 595 |
+
roadmap['immediate_actions'].append(f"Address critical issues in {worst_metric.get('metric', 'low-scoring areas')}")
|
| 596 |
+
|
| 597 |
+
# Short-term goals
|
| 598 |
+
if overall_score < 7.0:
|
| 599 |
+
roadmap['short_term_goals'].append("Improve overall GEO score to above 7.0")
|
| 600 |
+
roadmap['short_term_goals'].append("Enhance content structure and semantic richness")
|
| 601 |
+
|
| 602 |
+
# Long-term strategy
|
| 603 |
+
roadmap['long_term_strategy'].append("Establish consistent GEO optimization process")
|
| 604 |
+
roadmap['long_term_strategy'].append("Monitor and track AI search performance")
|
| 605 |
+
|
| 606 |
+
return roadmap
|
| 607 |
|
| 608 |
+
def _assess_competitive_position(self, analysis_results: Dict[str, Any]) -> Dict[str, Any]:
|
| 609 |
+
"""Assess competitive position based on scores"""
|
| 610 |
+
overall_score = analysis_results.get('overall_score', 0)
|
| 611 |
+
|
| 612 |
+
if overall_score >= 8.5:
|
| 613 |
+
position = "market_leader"
|
| 614 |
+
description = "Content is highly optimized for AI search engines"
|
| 615 |
+
elif overall_score >= 7.0:
|
| 616 |
+
position = "competitive"
|
| 617 |
+
description = "Content performs well but has room for improvement"
|
| 618 |
+
elif overall_score >= 5.5:
|
| 619 |
+
position = "average"
|
| 620 |
+
description = "Content meets basic standards but lacks optimization"
|
| 621 |
+
else:
|
| 622 |
+
position = "needs_work"
|
| 623 |
+
description = "Content requires significant optimization for AI search"
|
| 624 |
+
|
| 625 |
+
return {
|
| 626 |
+
'position': position,
|
| 627 |
+
'description': description,
|
| 628 |
+
'score': overall_score,
|
| 629 |
+
'percentile_estimate': min(overall_score * 10, 100)
|
| 630 |
}
|
|
|
|
| 631 |
|
| 632 |
+
def _get_timestamp(self) -> str:
|
| 633 |
+
"""Get current timestamp"""
|
| 634 |
+
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 635 |
|
| 636 |
|
| 637 |
+
# Debug utility function
|
| 638 |
+
def debug_scraped_data_format(scraped_data):
|
| 639 |
+
"""
|
| 640 |
+
Quick debug function to see what your scraper is returning
|
| 641 |
+
Add this to your code to debug data format issues
|
| 642 |
+
"""
|
| 643 |
+
print("=== SCRAPED DATA DEBUG ===")
|
| 644 |
+
print(f"Data type: {type(scraped_data)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
|
| 646 |
+
if isinstance(scraped_data, list):
|
| 647 |
+
print(f"List length: {len(scraped_data)}")
|
| 648 |
+
if scraped_data:
|
| 649 |
+
print(f"First item type: {type(scraped_data[0])}")
|
| 650 |
+
if isinstance(scraped_data[0], dict):
|
| 651 |
+
print(f"First item keys: {list(scraped_data[0].keys())}")
|
| 652 |
+
for key, value in list(scraped_data[0].items())[:3]:
|
| 653 |
+
print(f" {key}: {str(value)[:100]}...")
|
| 654 |
|
| 655 |
+
elif isinstance(scraped_data, dict):
|
| 656 |
+
print(f"Dict keys: {list(scraped_data.keys())}")
|
| 657 |
+
for key, value in list(scraped_data.items())[:3]:
|
| 658 |
+
print(f" {key}: {str(value)[:100]}...")
|
| 659 |
|
| 660 |
+
print("=== END DEBUG ===")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|