added content relevance
Browse filesFiles changed (8)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# content_relevance_service.py"""Business logic service for Content Relevance analysis."""import jsonimport loggingimport google.generativeai as genaifrom typing import Dict, Anyfrom app.page_speed.config import settings
# Create a module-level loggerglogger = logging.getLogger(__name__)
class ContentRelevanceService: """ Service class for generating Content Relevance reports via Gemini AI. """ def __init__(self): self.gemini_api_key = settings.gemini_api_key if self.gemini_api_key: glogger.info("Configuring Gemini AI for Content Relevance reporting.") genai.configure(api_key=self.gemini_api_key) else: glogger.warning("No Gemini API key found. Reporting will fail if called.")
def generate_content_relevance_report(self, data: Dict[str, Any]) -> str: """ Generate a Content Relevance report using Gemini AI. """ glogger.info("Starting Content Relevance report generation.") if not self.gemini_api_key: glogger.error("Gemini API key not configured") raise Exception("Gemini API key not configured")
try: prompt = self._create_relevance_prompt(data) glogger.debug("Relevance prompt: %s", prompt[:200]) response = genai.GenerativeModel("gemini-2.0-flash").generate_content(prompt) text = getattr(response, "text", None) if not text: glogger.error("Empty response from Gemini") raise Exception("Empty response from Gemini") glogger.info("Content Relevance report generated successfully.") return text.strip() except Exception as e: glogger.error("Error during report generation: %s", e, exc_info=True) raise
def _create_relevance_prompt(self, data: Dict[str, Any]) -> str: """ Build the enhanced prompt for Content Relevance analysis, including benchmarks, examples, and impact estimates. """ keywords = data.get('keywords', []) keyword_list = ", ".join(keywords) return f"""You are a **Content Strategy Expert**. Analyze the following content metrics and target keywords for relevance, coverage, and practical SEO impact. Provide a detailed report in Markdown, using structured sections do not add tables in the report, with the following enhancements:
1. **Summary of Relevance**: - Brief overview of alignment with keywords: {keyword_list} - Overall Content Relevance Score: {data.get('contentRelevanceScore')} (out of 10)
2. **Metric Breakdown**: For each metric below, include: - **Value** (from data) - **Benchmark** (ideal or industry standard) - **Status**: good / needs improvement / critical - **Why It Matters**: concise rationale - **Specific Example**: show where/how to improve (e.g., exact H1 text with keyword) - **Expected Impact**: estimated uplift (e.g., `+5% relevance`)
- **Keyword Coverage Score**: {data.get('keywordCoverageScore')} - **Density Score**: {data.get('densityScore')}% (ideal 1β3%) - **Readability**: {data.get('readabilityScoreOutOf10')} / 10 (ideal β₯ 6) - **Word Count**: {data.get('wordCount')} words (benchmark 1500β3000) - **Media Richness**: Images = {data.get('imageCount')}, Videos = {data.get('videoCount')} (ideal β₯ 2 videos)
3. **Top Strengths**: - List top 3 areas where the actual values exceed benchmarks, referencing metric names and values.
4. **Key Issues & Recommendations**: For each of the top 3 issues, provide: - **Issue**: name and value vs. benchmark - **Actionable Fix**: code or content snippet example, e.g.: ```html <h1>{keywords[0].capitalize()} Services for Your Business</h1> ``` - **Effort**: low / medium / high - **Expected Impact**: e.g., `+10% coverage`, `+3 readability`
5. **Priority Action Plan**: - Top 5 actions, with columns: Priority (1β5), Action, Effort, Expected Impact.
6. **Monitoring & Next Steps**: - Weekly or monthly tracking recommendations
7. **Bonus**: Suggest 2 related long-tail keywords to enhance depth.
Make the report engaging, use code blocks, and bullet lists where appropriate. Do not output JSONβprovide a human-readable Markdown report. and do not write anything outside the report format."""
def generate_content_priority(self, report: str) -> Dict[str, Any]: """ Generate prioritized content relevance recommendations based on the AI-generated report.
Args: report (str): The Markdown-formatted content relevance report.
Returns: Dict[str, Any]: Dictionary mapping priority levels to recommendation lists.
Raises: Exception: If priority generation fails. """ glogger.info("Generating prioritized suggestions from the content relevance report.") if not self.gemini_api_key: msg = "Gemini API key not configured" glogger.error(msg) raise Exception(msg) try: model = genai.GenerativeModel("gemini-2.0-flash") prompt = f"""You are a **Content Strategy Expert**. Extract all actionable recommendations from the following content relevance report and organize them into a JSON object with keys: "high", "medium", "low".
For each recommendation, include:- "recommendation": the action text- "impact": the expected impact (e.g. "+5% relevance")- "effort": low/medium/high
Important:- Respond with *only* a valid JSON object.- Do NOT include any commentary or explanation outside the JSON. of t
Report:{report}
Respond with only a JSON object.""" response = model.generate_content(prompt) raw = (response.text or "").strip() glogger.debug("Raw priority response: %s", raw[:200]) # Extract JSON start = raw.find('{') end = raw.rfind('}') if start == -1 or end == -1 or end <= start: raise ValueError("No JSON object found in response") json_str = raw[start:end+1] suggestions = json.loads(json_str) if not isinstance(suggestions, dict): raise ValueError("Parsed JSON is not a dictionary") for key in ("high", "medium", "low", "unknown"): suggestions.setdefault(key, []) glogger.info("Priority suggestions generated successfully.") return suggestions except json.JSONDecodeError as je: msg = f"Failed to parse JSON: {je}" glogger.error(msg, exc_info=True) raise Exception(msg) except Exception as e: msg = f"Error generating content priority suggestions: {e}" glogger.error(msg, exc_info=True) raise123456789101112131415161718192021222324252627# models.pyfrom pydantic import BaseModelfrom typing import Any, Dict, List, Optionalimport logging
# Optionally create a logger here if you need to log model-related eventsmodel_logger = logging.getLogger(__name__)
class ContentRelevanceRequest(BaseModel): data: Dict[str, Any]
def __init__(self, **data): super().__init__(**data) model_logger.debug("Initialized ContentRelevanceRequest with data: %s", self.data)
class ContentRelevanceResponse(BaseModel): success: bool report: str priorities: Dict[str, Any]
def __init__(self, **data): super().__init__(**data) model_logger.debug( "Initialized ContentRelevanceResponse with success=%s, keys: %s", self.success, list(self.priorities.keys()) if self.priorities else [] )1234567891011121314151617181920212223242526272829303132# routes.pyfrom fastapi import APIRouter, HTTPException, Requestimport loggingfrom .content_relevance_service import ContentRelevanceServicefrom .models import ContentRelevanceRequest, ContentRelevanceResponse
# Create a module-level loggerrouter_logger = logging.getLogger(__name__)
router = APIRouter(prefix="/content-relevance", tags=["ContentRelevance"])service = ContentRelevanceService()
@router.post("/report", response_model=ContentRelevanceResponse)async def generate_full_content_relevance(request: Request, payload: ContentRelevanceRequest): """ Generate a full Content Relevance report and corresponding prioritized suggestions. """ router_logger.info("Received content relevance request from %s", request.client.host) router_logger.debug("Payload data: %s", payload.data)
try: report = service.generate_content_relevance_report(payload.data) router_logger.info("Report generated successfully")
priorities = service.generate_content_priority(report) router_logger.info("Priorities extracted successfully")
return ContentRelevanceResponse(success=True, report=report, priorities=priorities)
except Exception as e: router_logger.error("Error during content relevance processing: %s", e, exc_info=True) raise HTTPException(status_code=500, detail=str(e))14 unmodified lines1516171819202137 unmodified lines59606162636414 unmodified linesfrom app.rag.routes import router as rag_routerfrom app.seo import routes as seo_routesfrom app.page_speed import routes as page_speed_routes# ------------------------# Configure root logger37 unmodified linesapp.include_router(seo_routes.router)# Mount PageSpeed routerapp.include_router(page_speed_routes.router)14 unmodified lines1516171819202137 unmodified lines596061626364656614 unmodified linesfrom app.rag.routes import router as rag_routerfrom app.seo import routes as seo_routesfrom app.page_speed import routes as page_speed_routesfrom app.content_relevence import routes as content_relevance_routes# ------------------------# Configure root logger37 unmodified linesapp.include_router(seo_routes.router)app.include_router(content_relevance_routes.router)# Mount PageSpeed routerapp.include_router(page_speed_routes.router)
173 unmodified lines174175176177178179180173 unmodified lines- Do **not** output JSON or code blocks unless specifically required.- Use a tone that's **professional, helpful, and non-technical**.- Help the reader understand what needs fixing and why it matters for their website and users.Example phrasing:> "Your site currently loads in about 3.2 seconds for most users, which is considered average. Improving this can reduce bounce rates and improve conversions."173 unmodified lines174175176177178179180181173 unmodified lines- Do **not** output JSON or code blocks unless specifically required.- Use a tone that's **professional, helpful, and non-technical**.- Help the reader understand what needs fixing and why it matters for their website and users.- Don't add anything outside the report format.Example phrasing:> "Your site currently loads in about 3.2 seconds for most users, which is considered average. Improving this can reduce bounce rates and improve conversions."
69 unmodified lines7071727369 unmodified lines("system", seo_prompt_template),("human", "{question}"),])69 unmodified lines70717273747576777879808182838485868788899091929394959669 unmodified lines("system", seo_prompt_template),("human", "{question}"),])# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 4. Prompt Template for Content Relevance RAG Chatbot# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Prompt Template for Content Relevance RAG Chatbotcontent_relevance_prompt_template = """You are a Content Relevance Assistant specialized in evaluating and enhancing written content for keyword alignment and coverage.Use the provided context (metrics and keyword list) to answer the user's question.If the context lacks sufficient information, respond with "I don't know." Avoid fabricating details.Retrieved context:{context}User's question:{question}Your response:"""content_relevance_prompt = ChatPromptTemplate.from_messages([("system", content_relevance_prompt_template),("human", "{question}"),])
19 unmodified lines2021222324252659 unmodified lines8687888990919219 unmodified lines@router.post("/initialization/{onboarding_id}/{doc_type}", response_model=SetupResponse)async def setup_rag_session(onboarding_id: str = Path(..., description="Unique onboarding identifier"),doc_type: str = Path(..., description="Type of document (e.g., page_speed, seo, uiux)"),body: SetupRequest = ...):"""59 unmodified linesonboarding_id: str = Path(...),doc_type: str = Path(...),chat_id: str = Path(...),prompt_type: str = Query(..., description="Prompt type, e.g., page_speed or seo"),body: ChatRequest = ...):"""19 unmodified lines2021222324252659 unmodified lines8687888990919219 unmodified lines@router.post("/initialization/{onboarding_id}/{doc_type}", response_model=SetupResponse)async def setup_rag_session(onboarding_id: str = Path(..., description="Unique onboarding identifier"),doc_type: str = Path(..., description="Type of document (e.g., page_speed, seo, content_relevance or uiux)"),body: SetupRequest = ...):"""59 unmodified linesonboarding_id: str = Path(...),doc_type: str = Path(...),chat_id: str = Path(...),prompt_type: str = Query(..., description="Prompt type, e.g., page_speed, content_relevance or seo"),body: ChatRequest = ...):"""
13 unmodified lines1415161718192070 unmodified lines91929394959613 unmodified linesfrom .prompt_library import (default_user_prompt,page_speed_prompt,seo_prompt)# 1. Path with doc_type70 unmodified linesuser_prompt = page_speed_promptelif prompt_type == "seo":user_prompt = seo_promptelse:user_prompt = default_user_prompt13 unmodified lines141516171819202170 unmodified lines929394959697989913 unmodified linesfrom .prompt_library import (default_user_prompt,page_speed_prompt,seo_prompt,content_relevance_prompt)# 1. Path with doc_type70 unmodified linesuser_prompt = page_speed_promptelif prompt_type == "seo":user_prompt = seo_promptelif prompt_type == "content_relevance":user_prompt = content_relevance_promptelse:user_prompt = default_user_prompt
app/content_relevence/content_relevance_service.pyAdded+162
app/content_relevence/models.pyAdded+27
app/content_relevence/routes.pyAdded+32
app/main.py+3-1
app/page_speed/services.py+2-1
app/rag/prompt_library.py+24-1
app/rag/routes.py+2-2
app/rag/utils.py+4-1