File size: 3,564 Bytes
4d20258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f629d6
4d20258
 
 
 
 
 
 
 
 
 
 
 
 
8f629d6
 
 
 
4d20258
 
 
 
 
 
 
8f629d6
 
 
 
 
 
 
 
 
 
 
4d20258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f629d6
4d20258
 
8f629d6
4d20258
8f629d6
4d20258
 
 
 
 
 
8f629d6
4d20258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import streamlit as st
import pandas as pd
import os
from dotenv import load_dotenv
from google import genai

st.set_page_config(
    page_title="Admin Dashboard | AI Feedback System",
    layout="wide"
)

st.title("📊 Admin Dashboard")
st.caption("Monitor user feedback, AI summaries, and recommended actions")

client = genai.Client()


import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# Load Google credentials from HF Secret
creds_dict = json.loads(os.environ["GOOGLE_CREDS_JSON"])

scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/drive"
]

creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
gs_client = gspread.authorize(creds)

sheet = gs_client.open("feedback").sheet1

def load_data():
    records = sheet.get_all_records()
    if not records:
        return pd.DataFrame()

    df = pd.DataFrame(records)

    # Ensure string columns
    df["ai_summary"] = df["ai_summary"].fillna("").astype(str)
    df["recommended_action"] = df["recommended_action"].fillna("").astype(str)

    return df


def generate_summary_and_action(review, rating):
    prompt = f"""
You are an AI assistant for business owners.

User Rating: {rating}
User Review: "{review}"

Return EXACTLY in this format (no extra text):

SUMMARY: <one concise sentence>
ACTION: <one clear recommended action>
"""

    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=prompt
    )

    text = response.text.strip()

    summary = ""
    action = ""

    for line in text.split("\n"):
        line = line.strip()
        if line.startswith("SUMMARY:"):
            summary = line.replace("SUMMARY:", "").strip()
        elif line.startswith("ACTION:"):
            action = line.replace("ACTION:", "").strip()

    return summary, action


def update_missing_ai_fields(df):
    updated = False

    for idx, row in df.iterrows():
        summary_val = str(row["ai_summary"]).strip().lower()
        action_val = str(row["recommended_action"]).strip().lower()

        if summary_val in ["", "nan"] or action_val in ["", "nan"]:
            summary, action = generate_summary_and_action(
                row["user_review"],
                row["user_rating"]
            )

            df.at[idx, "ai_summary"] = summary
            df.at[idx, "recommended_action"] = action
            updated = True

    if updated:
        # Rewrite entire sheet safely
        sheet.clear()
        sheet.append_row(df.columns.tolist())

        for _, row in df.iterrows():
            sheet.append_row(row.astype(str).tolist())

    return df


df = load_data()


if df.empty:
    st.info("No feedback submissions yet.")
    st.stop()

with st.spinner("Generating AI summaries and recommendations..."):
    df = update_missing_ai_fields(df)


col1, col2, col3 = st.columns(3)

with col1:
    st.metric("Total Feedback", len(df))

with col2:
    st.metric("Average Rating", round(df["user_rating"].mean(), 2))

with col3:
    low_ratings = (df["user_rating"] <= 2).sum()
    st.metric("Low Ratings (≤2)", low_ratings)

st.divider()


st.subheader("📈 Analytics")

# Rating distribution bar chart (compact)
rating_counts = df["user_rating"].value_counts().sort_index()

st.bar_chart(
    rating_counts,
    height=300  
)

# Analytics Table

st.subheader("📈 All Feedback Data")

st.dataframe(
    df[[
        "user_rating",
        "user_review",
        "ai_summary",
        "recommended_action"
    ]],
    use_container_width=True
)