Sumedhzz commited on
Commit
2faf678
Β·
1 Parent(s): c8e0039

Final deployment with cloud bypass

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +37 -103
src/streamlit_app.py CHANGED
@@ -13,85 +13,44 @@ st.set_page_config(page_title="Sentiment Analyzer AI | Bilingual Engine", page_i
13
  # --- PROFESSIONAL NEUMORPHIC / GLASS CSS ---
14
  st.markdown("""
15
  <style>
16
- .stApp {
17
- background: linear-gradient(135deg, #12141d 0%, #1a1c2c 100%);
18
- color: #ffffff;
19
- }
20
-
21
- div[data-baseweb="input"] {
22
- background: rgba(255, 255, 255, 0.05) !important;
23
- backdrop-filter: blur(10px) !important;
24
- border-radius: 15px !important;
25
- border: 1px solid rgba(255, 255, 255, 0.1) !important;
26
- padding: 5px !important;
27
- }
28
-
29
- .glass-card {
30
- background: rgba(255, 255, 255, 0.05);
31
- backdrop-filter: blur(10px);
32
- border-radius: 20px;
33
- border: 1px solid rgba(255, 255, 255, 0.1);
34
- padding: 30px;
35
- margin-top: 20px;
36
- margin-bottom: 25px;
37
- transition: 0.4s ease;
38
- }
39
-
40
- .stButton>button {
41
- background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
42
- color: white;
43
- border: none;
44
- border-radius: 12px;
45
- font-weight: 600;
46
- letter-spacing: 0.5px;
47
- height: 3rem;
48
- transition: all 0.3s ease;
49
- }
50
- .stButton>button:hover {
51
- box-shadow: 0 0 20px rgba(79, 172, 254, 0.4);
52
- transform: scale(1.02);
53
- }
54
-
55
  [data-testid="stMetricValue"] { color: #00f2fe; font-weight: 800; }
56
  </style>
57
  """, unsafe_allow_html=True)
58
 
59
  # --- CLOUD DATA LOGGING (GOOGLE SHEETS) ---
60
- # This manual approach bypasses the buggy Streamlit "auto-discovery"
61
  def get_connection():
62
- # Use .get() so it doesn't crash if the vault is momentarily empty
63
- json_secrets = st.secrets.get("GSHEETS_JSON")
64
- sheet_url = st.secrets.get("GSHEETS_URL")
65
-
66
- if not json_secrets:
67
- st.error("❌ 'GSHEETS_JSON' not found in Hugging Face Secrets!")
68
- st.stop()
69
- if not sheet_url:
70
- st.error("❌ 'GSHEETS_URL' not found in Hugging Face Secrets!")
71
- st.stop()
72
-
73
  try:
74
- creds_dict = json.loads(json_secrets)
75
- return st.connection("gsheets", type=GSheetsConnection, credentials=creds_dict), sheet_url
76
- except Exception as e:
77
- st.error(f"⚠️ JSON Parsing Error: {e}")
78
- st.stop()
79
-
80
- # 2. Convert string to a real Python dictionary
81
- creds_dict = json.loads(json_secrets)
82
 
83
- # 3. Create the connection manually
84
  return st.connection("gsheets", type=GSheetsConnection, credentials=creds_dict), sheet_url
85
  except Exception as e:
86
- st.error(f"Vault Connection Error: {e}")
87
  st.stop()
88
 
89
- # Initialize connection and get URL
90
- conn, GSHEETS_URL = get_connection()
 
 
 
 
 
 
91
 
92
  def save_to_cloud(text, ai_label, ai_score, corrected_label=None):
93
  try:
94
- # Read the current sheet (Worksheet name MUST be "Sheet1")
95
  existing_data = conn.read(spreadsheet=GSHEETS_URL, worksheet="Sheet1", ttl=0)
96
 
97
  new_entry = pd.DataFrame([{
@@ -114,7 +73,6 @@ MODEL_PATH = "SumedhGajbhiye/Sentiment-Analyzer"
114
 
115
  @st.cache_resource
116
  def load_engine(path):
117
- # Pulls directly from your HF Model Repo
118
  return pipeline("sentiment-analysis", model=path, tokenizer=path)
119
 
120
  # --- HEADER SECTION ---
@@ -127,9 +85,8 @@ with col_h1:
127
  with st.sidebar:
128
  st.markdown("### πŸ› οΈ ENGINE STATUS")
129
  try:
130
- sheet_url = st.secrets.get("GSHEETS_URL", "")
131
- df_log = conn.read(spreadsheet=sheet_url, worksheet="Sheet1", ttl=0)
132
- st.metric("Total Ingested", len(df_log))
133
  st.divider()
134
  st.download_button("πŸ“€ Export Dataset", df_log.to_csv(index=False), "engine_feedback.csv", "text/csv")
135
  except:
@@ -139,12 +96,7 @@ with st.sidebar:
139
  classifier = load_engine(MODEL_PATH)
140
 
141
  if classifier:
142
- user_input = st.text_input(
143
- "QUERY INPUT:",
144
- placeholder="Enter sentence for deep sentiment analysis...",
145
- key="main_input",
146
- label_visibility="collapsed"
147
- )
148
 
149
  if user_input:
150
  with st.status("Initializing Neural Weights...", expanded=False) as status:
@@ -158,7 +110,6 @@ if classifier:
158
  emoji_map = {"Positive": "🟒", "Neutral": "🟑", "Negative": "πŸ”΄"}
159
  color = "#00ff88" if "POS" in label.upper() else "#ff4b4b" if "NEG" in label.upper() else "#ffaa00"
160
 
161
- # --- RESULTS GLASS CARD ---
162
  st.markdown(f'''
163
  <div class="glass-card">
164
  <h4 style="color: #888; margin:0;">CLASSIFICATION RESULT</h4>
@@ -167,29 +118,13 @@ if classifier:
167
  </div>
168
  ''', unsafe_allow_html=True)
169
 
170
- # --- CHART & CORRECTION ROW ---
171
  col_chart, col_feed = st.columns([1, 2])
172
-
173
  with col_chart:
174
  fig = go.Figure(go.Indicator(
175
- mode = "gauge+number",
176
- value = score * 100,
177
- domain = {'x': [0, 1], 'y': [0, 1]},
178
- gauge = {
179
- 'axis': {'range': [None, 100], 'tickcolor': "#888", 'tickwidth': 2},
180
- 'bar': {'color': color},
181
- 'bgcolor': "rgba(0,0,0,0)",
182
- 'borderwidth': 2,
183
- 'bordercolor': "rgba(255,255,255,0.1)",
184
- }
185
  ))
186
-
187
- fig.update_layout(
188
- height=280,
189
- margin=dict(t=50, b=50, l=40, r=40),
190
- paper_bgcolor='rgba(0,0,0,0)',
191
- font={'color': "#fff", 'family': "Inter"}
192
- )
193
  st.plotly_chart(fig, use_container_width=True)
194
 
195
  with col_feed:
@@ -197,18 +132,17 @@ if classifier:
197
  c1, c2 = st.columns(2)
198
  with c1:
199
  if st.button("CONFIRM ACCURACY"):
200
- save_to_cloud(user_input, label, score)
201
- st.toast("Logic logged to cloud database.")
202
- time.sleep(1.0)
203
- st.rerun()
204
-
205
  with c2:
206
  correction = st.selectbox("OVERRIDE LABEL:", ["Positive", "Neutral", "Negative"])
207
  if st.button("FORCE UPDATE ENGINE"):
208
- save_to_cloud(user_input, label, score, corrected_label=correction)
209
- st.toast(f"Engine forced to {correction}")
210
- time.sleep(1.0)
211
- st.rerun()
212
 
213
  # --- RECENT LOGS ---
214
  try:
 
13
  # --- PROFESSIONAL NEUMORPHIC / GLASS CSS ---
14
  st.markdown("""
15
  <style>
16
+ .stApp { background: linear-gradient(135deg, #12141d 0%, #1a1c2c 100%); color: #ffffff; }
17
+ div[data-baseweb="input"] { background: rgba(255, 255, 255, 0.05) !important; backdrop-filter: blur(10px) !important; border-radius: 15px !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; padding: 5px !important; }
18
+ .glass-card { background: rgba(255, 255, 255, 0.05); backdrop-filter: blur(10px); border-radius: 20px; border: 1px solid rgba(255, 255, 255, 0.1); padding: 30px; margin-top: 20px; margin-bottom: 25px; transition: 0.4s ease; }
19
+ .stButton>button { background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%); color: white; border: none; border-radius: 12px; font-weight: 600; letter-spacing: 0.5px; height: 3rem; transition: all 0.3s ease; }
20
+ .stButton>button:hover { box-shadow: 0 0 20px rgba(79, 172, 254, 0.4); transform: scale(1.02); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  [data-testid="stMetricValue"] { color: #00f2fe; font-weight: 800; }
22
  </style>
23
  """, unsafe_allow_html=True)
24
 
25
  # --- CLOUD DATA LOGGING (GOOGLE SHEETS) ---
 
26
  def get_connection():
 
 
 
 
 
 
 
 
 
 
 
27
  try:
28
+ # Check if secrets exist to avoid the auto-crash you saw earlier
29
+ if "GSHEETS_JSON" not in st.secrets or "GSHEETS_URL" not in st.secrets:
30
+ st.warning("πŸš€ System Initializing... Please ensure GSHEETS_JSON is set in HF Settings.")
31
+ st.stop()
32
+
33
+ json_secrets = st.secrets["GSHEETS_JSON"]
34
+ sheet_url = st.secrets["GSHEETS_URL"]
 
35
 
36
+ creds_dict = json.loads(json_secrets)
37
  return st.connection("gsheets", type=GSheetsConnection, credentials=creds_dict), sheet_url
38
  except Exception as e:
39
+ st.error(f"Waiting for Vault access... (Technical Error: {e})")
40
  st.stop()
41
 
42
+ # Initialize connection safely using Session State
43
+ if 'conn' not in st.session_state:
44
+ conn, GSHEETS_URL = get_connection()
45
+ st.session_state.conn = conn
46
+ st.session_state.url = GSHEETS_URL
47
+ else:
48
+ conn = st.session_state.conn
49
+ GSHEETS_URL = st.session_state.url
50
 
51
  def save_to_cloud(text, ai_label, ai_score, corrected_label=None):
52
  try:
53
+ # Use Sheet1 as the target
54
  existing_data = conn.read(spreadsheet=GSHEETS_URL, worksheet="Sheet1", ttl=0)
55
 
56
  new_entry = pd.DataFrame([{
 
73
 
74
  @st.cache_resource
75
  def load_engine(path):
 
76
  return pipeline("sentiment-analysis", model=path, tokenizer=path)
77
 
78
  # --- HEADER SECTION ---
 
85
  with st.sidebar:
86
  st.markdown("### πŸ› οΈ ENGINE STATUS")
87
  try:
88
+ df_log = conn.read(spreadsheet=GSHEETS_URL, worksheet="Sheet1", ttl=0)
89
+ st.metric("Total Ingested", len(df_log)) # Shows count from your sheet
 
90
  st.divider()
91
  st.download_button("πŸ“€ Export Dataset", df_log.to_csv(index=False), "engine_feedback.csv", "text/csv")
92
  except:
 
96
  classifier = load_engine(MODEL_PATH)
97
 
98
  if classifier:
99
+ user_input = st.text_input("QUERY INPUT:", placeholder="Enter sentence...", key="main_input", label_visibility="collapsed")
 
 
 
 
 
100
 
101
  if user_input:
102
  with st.status("Initializing Neural Weights...", expanded=False) as status:
 
110
  emoji_map = {"Positive": "🟒", "Neutral": "🟑", "Negative": "πŸ”΄"}
111
  color = "#00ff88" if "POS" in label.upper() else "#ff4b4b" if "NEG" in label.upper() else "#ffaa00"
112
 
 
113
  st.markdown(f'''
114
  <div class="glass-card">
115
  <h4 style="color: #888; margin:0;">CLASSIFICATION RESULT</h4>
 
118
  </div>
119
  ''', unsafe_allow_html=True)
120
 
 
121
  col_chart, col_feed = st.columns([1, 2])
 
122
  with col_chart:
123
  fig = go.Figure(go.Indicator(
124
+ mode = "gauge+number", value = score * 100,
125
+ gauge = {'axis': {'range': [None, 100]}, 'bar': {'color': color}, 'bgcolor': "rgba(0,0,0,0)"}
 
 
 
 
 
 
 
 
126
  ))
127
+ fig.update_layout(height=280, margin=dict(t=50, b=50, l=40, r=40), paper_bgcolor='rgba(0,0,0,0)', font={'color': "#fff"})
 
 
 
 
 
 
128
  st.plotly_chart(fig, use_container_width=True)
129
 
130
  with col_feed:
 
132
  c1, c2 = st.columns(2)
133
  with c1:
134
  if st.button("CONFIRM ACCURACY"):
135
+ if save_to_cloud(user_input, label, score):
136
+ st.toast("Logic logged to cloud database.")
137
+ time.sleep(1.0)
138
+ st.rerun()
 
139
  with c2:
140
  correction = st.selectbox("OVERRIDE LABEL:", ["Positive", "Neutral", "Negative"])
141
  if st.button("FORCE UPDATE ENGINE"):
142
+ if save_to_cloud(user_input, label, score, corrected_label=correction):
143
+ st.toast(f"Engine forced to {correction}")
144
+ time.sleep(1.0)
145
+ st.rerun()
146
 
147
  # --- RECENT LOGS ---
148
  try: