File size: 3,461 Bytes
8498ff5
 
fe6177f
8498ff5
76c80b3
8498ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022f5f2
8498ff5
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# streamlit_app.py

import os
import time
import streamlit as st
from datetime import datetime
from dotenv import load_dotenv

load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '..', '.env'))
os.environ['HF_HOME'] = '/app/model_cache'

from reddit_client import search_reddit
from embedding import get_embeddings
from llm_analysis import get_llm_pipelines, analyze_post
from vector_search import build_faiss_index, search_similar

st.set_page_config(page_title="BrandSight AI - Reddit Brand Monitor", layout="wide", page_icon="πŸ”")
st.title("πŸ” Proactive Brand Intelligence Monitor")
st.caption(f"πŸ•’ Last checked: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

# Load models once
with st.spinner("Loading AI models... (first time only)"):
    classifier, sentiment_pipe, summarizer = get_llm_pipelines()

brand = st.text_input("Enter a brand or keyword to search on Reddit (e.g., 'Nvidia')")

if brand:
    if 'results' not in st.session_state or st.session_state.get('brand') != brand:
        st.session_state.brand = brand
        with st.spinner(f"πŸ” Fetching Reddit posts for **{brand}**..."):
            t0 = time.time()
            posts = search_reddit(brand, limit=10)
            st.write(f"⏱️ Reddit fetch time: {round(time.time() - t0, 2)} seconds")

        if not posts:
            st.warning("❌ No posts found. Try a different keyword.")
            st.stop()

        texts = [p.title + " " + (p.selftext or "") for p in posts]
        results = []

        with st.spinner("πŸ€– Analyzing Reddit posts with AI..."):
            t1 = time.time()
            for text in texts:
                results.append(analyze_post(text, classifier, sentiment_pipe, summarizer))
            st.write(f"⏱️ AI Analysis time: {round(time.time() - t1, 2)} seconds")

        st.session_state.posts = posts
        st.session_state.results = results
        st.session_state.embeddings = get_embeddings(texts)
        st.session_state.index = build_faiss_index(st.session_state.embeddings)

    st.header(f"πŸ“Ÿ Results for: {st.session_state.brand}")
    categories = ["Bug Report", "Feature Request", "Competitor Mention", "Positive Feedback"]
    category_filter = st.multiselect("Filter by category:", categories, default=categories)

    for i, post in enumerate(st.session_state.posts):
        result = st.session_state.results[i]
        if result["category"] in category_filter:
            with st.expander(f"{post.title} (r/{post.subreddit.display_name})"):
                st.markdown(f"**Category:** {result['category']} | **Sentiment:** {result['sentiment']}")
                st.markdown(f"**Summary:** *{result['summary']}*")
                st.write(f"πŸ”— [View on Reddit](https://reddit.com{post.permalink})")

    st.header("πŸ”Ž Find Similar Posts")
    query = st.text_input("Search similar topics (e.g., 'overheating issue')")

    if query:
        q_emb = get_embeddings([query])
        distances, indices = search_similar(st.session_state.index, q_emb)
        st.subheader("Top 5 similar Reddit posts:")
        for rank, idx in enumerate(indices[0]):
            sim_post = st.session_state.posts[idx]
            sim_res = st.session_state.results[idx]
            st.markdown(f"**{rank + 1}. {sim_post.title}** (r/{sim_post.subreddit.display_name})")
            st.markdown(f"> *{sim_res['summary']}*")
            st.write("---")
else:
    st.info("Type a brand or keyword above to begin.")