content-library / app.py
arcalab's picture
Upload folder using huggingface_hub
ec261f5 verified
Raw History Blame Contribute Delete
26.5 kB
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(
"""
<style>
.thumb {
width: 100%;
height: 84px;
border-radius: 12px;
border: 1px solid rgba(250,250,250,0.12);
background: linear-gradient(135deg, rgba(108,99,255,0.35), rgba(26,29,41,0.92));
display: flex;
align-items: center;
justify-content: center;
color: #FAFAFA;
letter-spacing: 0.02em;
font-size: 0.82rem;
margin-bottom: 0.7rem;
}
.badge {
display: inline-block;
border-radius: 999px;
padding: 0.18rem 0.55rem;
background: rgba(108,99,255,0.2);
border: 1px solid rgba(108,99,255,0.4);
font-size: 0.75rem;
margin-right: 0.4rem;
}
.score {
color: #D0D4E3;
font-size: 0.76rem;
}
</style>
""",
unsafe_allow_html=True,
)
def render_card(item: dict[str, Any]) -> None:
with st.container(border=True):
st.markdown("<div class='thumb'>Thumbnail Placeholder</div>", unsafe_allow_html=True)
st.markdown(f"### {item['title']}")
st.markdown(
f"<span class='badge'>{item['type']}</span><span class='score'>Engagement {item['engagement_score']:.2f}</span>",
unsafe_allow_html=True,
)
st.caption(f"{item['author']} | {item['date'].isoformat()} | {item['word_count']} words")
st.write(item["summary"])
st.caption("Tags: " + ", ".join(item["tags"]))
if st.button("Select", key=f"select_{item['id']}"):
st.session_state["selected_id"] = item["id"]
def render_analysis(result: dict[str, Any], id_lookup: dict[str, dict[str, Any]]) -> None:
source = "Gemini" if result.get("source") == "gemini" else "Fallback Heuristic"
st.markdown(f"#### AI Insight Panel ({source})")
st.caption(f"Generated at: {result.get('generated_at', 'N/A')}")
st.markdown("**Related Content Recommendations**")
for rec in result.get("related_content", []):
mapped = id_lookup.get(rec.get("id", ""), {})
title = mapped.get("title", rec.get("title", "Untitled recommendation"))
st.markdown(f"- `{rec.get('id', 'N/A')}` {title} (confidence {rec.get('confidence', 0.0):.2f})")
st.caption(rec.get("reason", "No rationale provided."))
st.markdown("**Suggested Format Transformations**")
for item in result.get("transformations", []):
st.markdown(f"- `{item.get('target_format', 'format')}`: {item.get('idea', '')}")
st.caption(item.get("reason", ""))
prediction = result.get("engagement_prediction", {})
score = float(prediction.get("score", 0.0))
st.markdown("**Engagement Prediction**")
st.progress(score)
st.write(f"Predicted Outcome: **{prediction.get('label', 'Moderate')}** ({score:.2f})")
for reason in prediction.get("reasoning", []):
st.markdown(f"- {reason}")
def to_jsonl(items: list[dict[str, Any]]) -> str:
lines = []
for item in items:
serializable = {**item, "date": item["date"].isoformat()}
lines.append(json.dumps(serializable, ensure_ascii=True))
return "\n".join(lines)
def main() -> None:
st.set_page_config(page_title="Context-Aware AI Content Library", page_icon="📚", layout="wide", initial_sidebar_state="expanded")
init_state()
inject_css()
st.title("Context-Aware AI Content Library")
st.caption("Search enterprise assets and generate context-aware recommendations, format transformations, and engagement predictions.")
library = load_library(DATA_FILE)
if not library:
st.error("No dataset found. Add valid lines in data/content_library.jsonl.")
st.stop()
id_lookup = map_by_id(library)
all_tags = sorted({tag for item in library for tag in item["tags"]})
min_date = min(item["date"] for item in library)
max_date = max(item["date"] for item in library)
api_key = os.getenv("GEMINI_API_KEY", "").strip() or None
with st.sidebar:
has_key = bool(api_key)
st.caption(f"AI: {'Gemini active' if has_key else 'Heuristic fallback'}")
st.subheader("Filters")
st.session_state["search_query"] = st.text_input("Search", value=st.session_state.get("search_query", ""), placeholder="title, summary, author, tag...")
st.session_state["filter_types"] = st.multiselect("Content Type", options=CONTENT_TYPES, default=st.session_state.get("filter_types", CONTENT_TYPES))
st.session_state["filter_tags"] = st.multiselect("Topic / Tag", options=all_tags, default=st.session_state.get("filter_tags", []))
date_range = st.date_input("Date Range", value=(min_date, max_date), min_value=min_date, max_value=max_date)
if isinstance(date_range, tuple) and len(date_range) == 2:
st.session_state["date_start"], st.session_state["date_end"] = date_range
else:
st.session_state["date_start"], st.session_state["date_end"] = min_date, max_date
if not st.session_state["filter_types"]:
st.info("Select at least one content type.")
st.stop()
filtered = filter_library(
library,
query=st.session_state["search_query"],
selected_types=st.session_state["filter_types"],
selected_tags=st.session_state["filter_tags"],
start=st.session_state["date_start"],
end=st.session_state["date_end"],
)
controls = st.columns([1, 1, 2])
if controls[0].button("Load Example"):
st.session_state["selected_id"] = "CL-004"
if controls[1].button("Clear Selection"):
st.session_state["selected_id"] = None
controls[2].metric("Filtered Assets", len(filtered), delta=f"of {len(library)} total")
st.markdown("### Content Library")
if not filtered:
st.warning("No assets matched current search and filters.")
else:
for i in range(0, len(filtered), 2):
row = filtered[i : i + 2]
cols = st.columns(2)
for col, item in zip(cols, row):
with col:
render_card(item)
selected_id = st.session_state.get("selected_id")
selected = id_lookup.get(selected_id) if selected_id else None
st.markdown("---")
st.markdown("### Analysis Workspace")
if not selected:
st.info("Select a content item to generate AI recommendations.")
else:
st.write(f"Selected: **{selected['id']} - {selected['title']}**")
st.caption(f"Type: {selected['type']} | Tags: {', '.join(selected['tags'])} | Published: {selected['date'].isoformat()}")
if st.button("Run AI Analysis", type="primary"):
allowed, retry_after = check_rate_limit()
if not allowed:
st.warning(f"Rate limit reached: {REQUEST_LIMIT} requests/{REQUEST_WINDOW_SECONDS}s. Retry in {retry_after}s.")
else:
with st.spinner("Generating context-aware analysis..."):
st.session_state["analysis_cache"][selected["id"]] = run_analysis(selected, library, api_key)
result = st.session_state["analysis_cache"].get(selected["id"])
if result:
render_analysis(result, id_lookup)
else:
st.caption("No analysis yet. Click 'Run AI Analysis'.")
st.markdown("---")
st.markdown("### Create New Content")
col1, col2 = st.columns([2, 1])
with col1:
topic = st.text_area("Content Topic / Goal", placeholder="Describe what content you want to create...", height=80)
with col2:
format_choice = st.selectbox("Target Format", options=CONTENT_TYPES)
audience = st.text_input("Target Audience", placeholder="e.g., Enterprise CTOs, Developer teams")
tone = st.selectbox("Tone", options=["Professional", "Conversational", "Technical", "Executive"])
word_count = st.slider("Target Word Count", min_value=100, max_value=2000, value=500, step=100)
sample_cols = st.columns([1, 1, 2])
if sample_cols[0].button("Try with sample"):
topic = "Best practices for AI-powered customer support automation"
format_choice = "blog"
audience = "Enterprise IT leaders"
tone = "Professional"
word_count = 800
st.session_state["_sample_filled"] = True
if sample_cols[1].button("Generate Draft", type="primary"):
if not topic.strip():
st.error("Please describe the content topic.")
else:
allowed, retry_after = check_rate_limit()
if not allowed:
st.warning(f"Rate limit reached: {REQUEST_LIMIT} requests/{REQUEST_WINDOW_SECONDS}s. Retry in {retry_after}s.")
else:
with st.spinner("Generating content draft..."):
creation_prompt = f"""You are an expert content creator for enterprise audiences.
Generate a {format_choice} about: {topic}
Target audience: {audience}
Tone: {tone}
Target length: approximately {word_count} words
Create engaging, professional content that directly addresses the topic and audience.
Return ONLY the content text, no metadata or JSON."""
if api_key:
model_text = call_gemini(api_key, creation_prompt)
else:
model_text = None
if model_text:
st.session_state["created_content"] = model_text
else:
fallback_outline = f"""# {topic}
## Introduction
Introduce the topic and its relevance to {audience}.
## Key Points
- Point 1: Core concept and importance
- Point 2: Implementation considerations
- Point 3: Best practices and recommendations
## Conclusion
Summarize key takeaways and next steps.
---
[Generated as fallback outline - approximately {word_count} words target]"""
st.session_state["created_content"] = fallback_outline
if st.session_state.get("created_content"):
st.markdown("---")
st.markdown("**Generated Content:**")
with st.container(border=True):
st.write(st.session_state["created_content"])
st.download_button(
label="Download as .txt",
data=st.session_state["created_content"],
file_name=f"content_{format_choice}_{int(time.time())}.txt",
mime="text/plain"
)
st.markdown("---")
with st.expander("Sample Dataset", expanded=True):
df = pd.DataFrame(library)
df_display = df.copy()
df_display["date"] = df_display["date"].astype(str)
st.dataframe(df_display, use_container_width=True, hide_index=True)
st.download_button("Download JSONL", data=to_jsonl(library), file_name="content_library.jsonl", mime="application/json")
if __name__ == "__main__":
main()