import datetime as dt import json import os import re import textwrap import time from typing import Optional from typing import Any import pandas as pd import requests import streamlit as st DATA_FILE = os.path.join("data", "content_library.jsonl") GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" REQUEST_LIMIT = 8 REQUEST_WINDOW_SECONDS = 60 MAX_RELATED = 5 CONTENT_TYPES = ["blog", "video_script", "social_post", "case_study", "whitepaper", "email_campaign", "help_doc", "press_release"] def init_state() -> None: defaults = { "selected_id": None, "analysis_cache": {}, "request_timestamps": [], "search_query": "", "filter_types": CONTENT_TYPES.copy(), "filter_tags": [], "date_start": None, "date_end": None, "created_content": None, } for k, v in defaults.items(): if k not in st.session_state: st.session_state[k] = v @st.cache_data def load_library(path: str) -> list[dict[str, Any]]: items = [] if not os.path.exists(path): return items with open(path, "r", encoding="utf-8") as f: for line_no, line in enumerate(f, start=1): raw = line.strip() if not raw: continue try: payload = json.loads(raw) except json.JSONDecodeError: st.warning(f"Skipped invalid JSON line {line_no}.") continue normalized = normalize_item(payload) if normalized: items.append(normalized) items.sort(key=lambda x: x["date"], reverse=True) return items def normalize_item(item: dict[str, Any]) -> Optional[dict[str, Any]]: required = ["id", "title", "type", "tags", "author", "date", "engagement_score", "word_count", "summary", "body_preview"] if any(k not in item for k in required): return None try: parsed_date = dt.date.fromisoformat(str(item["date"])) engagement = float(item["engagement_score"]) word_count = int(item["word_count"]) except (TypeError, ValueError): return None tags = item["tags"] if isinstance(item["tags"], list) else [] return { "id": str(item["id"]), "title": str(item["title"]), "type": str(item["type"]), "tags": [str(t) for t in tags], "author": str(item["author"]), "date": parsed_date, "engagement_score": min(max(engagement, 0.0), 1.0), "word_count": max(word_count, 1), "summary": str(item["summary"]), "body_preview": str(item["body_preview"]), } def map_by_id(items: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: return {i["id"]: i for i in items} def intersect_tags(a: list[str], b: list[str]) -> set[str]: return set(a).intersection(set(b)) def days_old(date_val: dt.date) -> int: return max((dt.date.today() - date_val).days, 0) def recency_weight(date_val: dt.date) -> float: age = days_old(date_val) if age <= 14: return 1.15 if age <= 45: return 1.0 if age <= 120: return 0.9 return 0.78 def fallback_related(selected: dict[str, Any], library: list[dict[str, Any]], n: int = MAX_RELATED) -> list[dict[str, Any]]: ranked = [] for item in library: if item["id"] == selected["id"]: continue overlap = intersect_tags(selected["tags"], item["tags"]) if not overlap: continue overlap_score = len(overlap) * 1.6 engagement_weight = item["engagement_score"] * 1.3 type_diversity = 0.35 if item["type"] != selected["type"] else 0.0 score = (overlap_score + engagement_weight + type_diversity) * recency_weight(item["date"]) ranked.append((score, item, overlap)) ranked.sort(key=lambda x: x[0], reverse=True) out = [] for score, item, overlap in ranked[:n]: out.append( { "id": item["id"], "title": item["title"], "confidence": round(min(score / 6.0, 0.99), 2), "reason": f"Shared tags ({', '.join(sorted(overlap))}) plus strong historical engagement.", } ) if out: return out fallback_top = sorted([i for i in library if i["id"] != selected["id"]], key=lambda x: x["engagement_score"], reverse=True) for item in fallback_top[:n]: out.append( { "id": item["id"], "title": item["title"], "confidence": round(item["engagement_score"], 2), "reason": "High-performing adjacent content from the same enterprise library.", } ) return out def fallback_transformations(item: dict[str, Any]) -> list[dict[str, Any]]: title = item["title"] base = [ { "target_format": "social_thread", "idea": f"Turn '{title}' into a 7-post social narrative with one idea per post.", "reason": "Expands short-form reach while preserving main positioning.", }, { "target_format": "email_campaign", "idea": "Repurpose into a 3-touch nurture sequence by awareness stage.", "reason": "Supports lifecycle progression and repeat touchpoints.", }, ] by_type = { "blog": [ { "target_format": "video_script", "idea": "Adapt key sections into a 90-second explainer script.", "reason": "Video format improves completion on product narratives.", }, { "target_format": "help_doc", "idea": "Extract the practical steps into a procedural help article.", "reason": "Captures high-intent support and implementation traffic.", }, ], "whitepaper": [ { "target_format": "case_study", "idea": "Convert strongest evidence into a customer outcome story.", "reason": "Case studies perform well in later sales stages.", } ], "video_script": [ { "target_format": "blog", "idea": "Expand the narrative beats into a long-form SEO article.", "reason": "Creates discoverable evergreen value from script assets.", } ], "help_doc": [ { "target_format": "press_release", "idea": "Elevate key improvements into a release-style announcement.", "reason": "Reuses validated messaging for external stakeholders.", } ], } suggestions = base + by_type.get(item["type"], []) if re.search(r"\bAI\b|machine learning|model", item["summary"], flags=re.IGNORECASE): suggestions.append( { "target_format": "webinar_outline", "idea": "Package insights into a 20-minute expert webinar outline.", "reason": "AI education content usually drives qualified attendance.", } ) return suggestions[:4] def fallback_prediction(selected: dict[str, Any], related: list[dict[str, Any]]) -> dict[str, Any]: score = selected["engagement_score"] reasons = [] high_interest = {"AI", "analytics", "security", "product"} hits = len(set(selected["tags"]).intersection(high_interest)) if hits: score += hits * 0.03 reasons.append("Topic overlap with consistently high-interest enterprise themes.") wc = selected["word_count"] if 650 <= wc <= 1700: score += 0.05 reasons.append("Word count is within common high-performing editorial range.") elif wc > 2800: score -= 0.04 reasons.append("Long format may reduce completion without serialization.") age = days_old(selected["date"]) if age <= 30: score += 0.04 reasons.append("Recent publication timing supports market relevance.") elif age >= 160: score -= 0.03 reasons.append("Older publication may need reframing for current campaigns.") if related: avg_conf = sum(r["confidence"] for r in related) / len(related) score += min(avg_conf * 0.07, 0.05) reasons.append("Cross-link opportunities can improve dwell time and follow-up clicks.") score = round(min(max(score, 0.05), 0.98), 2) label = "High" if score >= 0.8 else "Moderate" if score >= 0.62 else "Needs Optimization" return {"score": score, "label": label, "reasoning": reasons[:4] or ["Estimate based on historical baseline performance."]} def build_context(selected_id: str, library: list[dict[str, Any]], cap: int = 10) -> str: lines = [] for item in library: if item["id"] == selected_id: continue lines.append( f"- {item['id']} | {item['title']} | type={item['type']} | tags={', '.join(item['tags'])} | engagement={item['engagement_score']:.2f}" ) if len(lines) >= cap: break return "\n".join(lines) def build_prompt(selected: dict[str, Any], context: str) -> str: prompt = f""" You are an AI content strategist for an enterprise CMS-like content library. Analyze the selected asset and return STRICT JSON only. Selected content: - id: {selected['id']} - title: {selected['title']} - type: {selected['type']} - tags: {', '.join(selected['tags'])} - author: {selected['author']} - date: {selected['date'].isoformat()} - engagement_score: {selected['engagement_score']:.2f} - word_count: {selected['word_count']} - summary: {selected['summary']} - body_preview: {selected['body_preview']} Library context: {context} Return this schema: {{ "related_content": [ {{"id": "CL-000", "title": "...", "reason": "...", "confidence": 0.0}} ], "transformations": [ {{"target_format": "...", "idea": "...", "reason": "..."}} ], "engagement_prediction": {{ "score": 0.0, "label": "High | Moderate | Needs Optimization", "reasoning": ["...", "..."] }} }} Constraints: - related_content max 5 - transformations max 4 - confidence and score in [0, 1] - concise practical rationale - JSON only, no markdown fences """ return textwrap.dedent(prompt).strip() def call_gemini(api_key: str, prompt: str) -> Optional[str]: try: response = requests.post( f"{GEMINI_URL}?key={api_key}", json={"contents": [{"parts": [{"text": prompt}]}]}, timeout=25, ) except Exception: return None try: payload = response.json() except Exception: return None try: return payload["candidates"][0]["content"]["parts"][0]["text"] except Exception: return None def extract_json_blob(text: str) -> Optional[str]: if not text: return None match = re.search(r"\{.*\}", text, flags=re.DOTALL) return match.group(0) if match else None def parse_gemini(text: str) -> Optional[dict[str, Any]]: blob = extract_json_blob(text) if not blob: return None try: raw = json.loads(blob) except json.JSONDecodeError: return None related = raw.get("related_content", []) transforms = raw.get("transformations", []) prediction = raw.get("engagement_prediction", {}) if not isinstance(related, list) or not isinstance(transforms, list) or not isinstance(prediction, dict): return None normalized_related = [] for row in related[:MAX_RELATED]: if not isinstance(row, dict): continue try: conf = float(row.get("confidence", 0.5)) except (TypeError, ValueError): conf = 0.5 normalized_related.append( { "id": str(row.get("id", "Unknown")), "title": str(row.get("title", "Untitled recommendation")), "reason": str(row.get("reason", "No rationale provided.")), "confidence": round(min(max(conf, 0.0), 1.0), 2), } ) normalized_transforms = [] for row in transforms[:4]: if not isinstance(row, dict): continue normalized_transforms.append( { "target_format": str(row.get("target_format", "new_format")), "idea": str(row.get("idea", "Repurpose this asset into another channel.")), "reason": str(row.get("reason", "Improves channel coverage and audience fit.")), } ) try: score = float(prediction.get("score", 0.5)) except (TypeError, ValueError): score = 0.5 reasons = prediction.get("reasoning", ["Model supplied limited rationale."]) if not isinstance(reasons, list): reasons = ["Model supplied limited rationale."] normalized_prediction = { "score": round(min(max(score, 0.0), 1.0), 2), "label": str(prediction.get("label", "Moderate")), "reasoning": [str(r) for r in reasons][:5], } return { "related_content": normalized_related, "transformations": normalized_transforms, "engagement_prediction": normalized_prediction, } def make_fallback(selected: dict[str, Any], library: list[dict[str, Any]]) -> dict[str, Any]: related = fallback_related(selected, library) return { "source": "fallback", "related_content": related, "transformations": fallback_transformations(selected), "engagement_prediction": fallback_prediction(selected, related), "generated_at": dt.datetime.now().isoformat(timespec="seconds"), } def run_analysis(selected: dict[str, Any], library: list[dict[str, Any]], api_key: Optional[str]) -> dict[str, Any]: fallback = make_fallback(selected, library) if not api_key: return fallback prompt = build_prompt(selected, build_context(selected["id"], library)) model_text = call_gemini(api_key, prompt) if model_text is None: return fallback parsed = parse_gemini(model_text) if parsed is None: return fallback parsed["source"] = "gemini" parsed["generated_at"] = dt.datetime.now().isoformat(timespec="seconds") return parsed def check_rate_limit() -> tuple[bool, int]: now = time.time() recent = [ts for ts in st.session_state.get("request_timestamps", []) if now - ts < REQUEST_WINDOW_SECONDS] st.session_state["request_timestamps"] = recent if len(recent) >= REQUEST_LIMIT: oldest = min(recent) retry_after = max(1, int(REQUEST_WINDOW_SECONDS - (now - oldest))) return False, retry_after recent.append(now) st.session_state["request_timestamps"] = recent return True, 0 def filter_library(items: list[dict[str, Any]], query: str, selected_types: list[str], selected_tags: list[str], start: dt.date, end: dt.date) -> list[dict[str, Any]]: needle = query.strip().lower() filtered = [] for item in items: if item["type"] not in selected_types: continue if selected_tags and not intersect_tags(item["tags"], selected_tags): continue if item["date"] < start or item["date"] > end: continue if needle: haystack = " ".join([item["title"], item["summary"], item["body_preview"], item["author"], " ".join(item["tags"])]).lower() if needle not in haystack: continue filtered.append(item) return filtered def inject_css() -> None: st.markdown( """ """, unsafe_allow_html=True, ) def render_card(item: dict[str, Any]) -> None: with st.container(border=True): st.markdown("