import streamlit as st import pandas as pd import numpy as np import joblib import os from sklearn.ensemble import RandomForestClassifier from sklearn.calibration import CalibratedClassifierCV from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, brier_score_loss, confusion_matrix, classification_report) import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') st.set_page_config( page_title="๐Ÿ’€ Ghosting Predictor", page_icon="๐Ÿ‘ป", layout="wide", initial_sidebar_state="collapsed" ) st.markdown(""" """, unsafe_allow_html=True) # โ”€โ”€ Feature config โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ NUM_FEATURES = [ 'last_message_length', 'response_time_gap', 'conversation_length', 'reply_ratio', 'avg_response_time', 'emoji_count', 'question_asked', 'seen_ignored', 'past_ghosting_history', 'effort_score', 'delay', 'is_dry', 'is_long_gap', 'engagement_score', 'ghost_risk_combo', 'seen_delay', 'initiator_flag', 'inconsistency', 'decay_score', 'effort_mismatch' ] CAT_FEATURES = ['initiator', 'message_tone', 'time_of_day', 'user_type'] def make_preprocessor(): num_t = Pipeline([('imp', SimpleImputer(strategy='median')), ('sc', StandardScaler())]) cat_t = Pipeline([('imp', SimpleImputer(strategy='most_frequent')), ('ohe', OneHotEncoder(handle_unknown='ignore'))]) return ColumnTransformer([('num', num_t, NUM_FEATURES), ('cat', cat_t, CAT_FEATURES)], remainder='drop') # โ”€โ”€ Load / train models โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @st.cache_resource def load_models(): rp = 'rf_reply_model.pkl'; gp = 'rf_ghost_model.pkl'; mp = 'model_metrics.pkl' if os.path.exists(rp) and os.path.exists(gp) and os.path.exists(mp): try: return joblib.load(rp), joblib.load(gp), joblib.load(mp) except Exception as e: st.warning(f"โš ๏ธ Saved models failed ({str(e)[:60]}). Retraining...") with st.spinner("๐Ÿค– Training models... (~30 sec)"): try: df = pd.read_csv('ghosting_dataset5.csv') except FileNotFoundError: st.error("โŒ ghosting_dataset5.csv not found. Run gen_data5.py first.") st.stop() df['effort_score'] = df['last_message_length'] + (df['emoji_count'] * 2) + (df['question_asked'] * 5) df['delay'] = df['response_time_gap'].apply(lambda x: 0 if x < 6 else 1 if x < 24 else 2) df['is_dry'] = (df['message_tone'] == 'dry').astype(int) df['is_long_gap'] = (df['response_time_gap'] > 24).astype(int) df['engagement_score'] = df['reply_ratio'] * df['conversation_length'] df['ghost_risk_combo'] = ((df['response_time_gap'] > 24) & (df['reply_ratio'] < 0.4)).astype(int) df['seen_delay'] = ((df['seen_ignored'] == 1) & (df['response_time_gap'] > 12)).astype(int) df['initiator_flag'] = (df['initiator'] == 'me').astype(int) df['inconsistency'] = (abs(df['response_time_gap'] - df['avg_response_time']) > 20).astype(int) df['decay_score'] = (df['conversation_length'] / 200).clip(0, 1) df['effort_mismatch'] = ((df['last_message_length'] > 20) & (df['reply_ratio'] < 0.3)).astype(int) def _train(df, target): X = df[NUM_FEATURES + CAT_FEATURES]; y = df[target] # โ”€โ”€ Proper 3-way split โžบ no leakage โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ X_tv, X_test, y_tv, y_test = train_test_split(X, y, test_size=0.15, random_state=42, stratify=y) X_tr, X_val, y_tr, y_val = train_test_split(X_tv, y_tv, test_size=0.15/0.85, random_state=42, stratify=y_tv) mdl = Pipeline([('pre', make_preprocessor()), ('clf', RandomForestClassifier(n_estimators=400, max_depth=20, class_weight='balanced', random_state=42, n_jobs=-1))]) mdl.fit(X_tr, y_tr) # Calibrate on val only; evaluate on test only cal = CalibratedClassifierCV(mdl, method='sigmoid', cv=3) cal.fit(X_val, y_val) yp = cal.predict(X_test); yproba = cal.predict_proba(X_test)[:, 1] return cal, { 'accuracy': accuracy_score(y_test, yp), 'precision': precision_score(y_test, yp, zero_division=0), 'recall': recall_score(y_test, yp, zero_division=0), 'f1_score': f1_score(y_test, yp, zero_division=0), 'roc_auc': roc_auc_score(y_test, yproba), 'brier': brier_score_loss(y_test, yproba), 'confusion_matrix': confusion_matrix(y_test, yp).tolist(), 'classification_report': classification_report(y_test, yp), 'train_size': len(X_tr), 'val_size': len(X_val), 'test_size': len(X_test), 'y_test': y_test.tolist(), 'y_pred_prob': yproba.tolist(), } rm, rmets = _train(df, 'reply') gm, gmets = _train(df, 'ghosted') joblib.dump(rm, rp); joblib.dump(gm, gp) joblib.dump({'reply': rmets, 'ghosted': gmets}, mp) return rm, gm, {'reply': rmets, 'ghosted': gmets} reply_model, ghost_model, all_metrics = load_models() # โ”€โ”€ Feature builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def build_input(msg_len, tone, asked_q, resp_time, seen_ign, emoji, conv_len=25, rr=None, avg_rt=None, past_ghost=0, user_type='casual'): if rr is None: rr = 0.70 if asked_q else 0.50 if avg_rt is None: avg_rt = max(1.0, resp_time * 0.5) tod = 'night' if resp_time > 20 else ('morning' if resp_time < 8 else 'day') return pd.DataFrame({ 'last_message_length': [msg_len], 'response_time_gap': [float(resp_time)], 'conversation_length': [conv_len], 'reply_ratio': [rr], 'avg_response_time': [float(avg_rt)], 'emoji_count': [emoji], 'question_asked': [int(asked_q)], 'seen_ignored': [seen_ign], 'past_ghosting_history': [past_ghost], 'effort_score': [msg_len + (emoji * 2) + (5 if asked_q else 0)], 'delay': [0 if resp_time < 6 else (1 if resp_time < 24 else 2)], 'is_dry': [int(tone == 'dry')], 'is_long_gap': [int(resp_time > 24)], 'engagement_score': [rr * conv_len], 'ghost_risk_combo': [int(resp_time > 24 and rr < 0.4)], 'seen_delay': [int(seen_ign == 1 and resp_time > 12)], 'initiator_flag': [int(asked_q)], 'inconsistency': [int(abs(resp_time - avg_rt) > 20)], 'decay_score': [min(conv_len / 200, 1.0)], 'effort_mismatch': [int(msg_len > 20 and rr < 0.3)], 'initiator': ['me' if asked_q else 'them'], 'message_tone': [tone], 'time_of_day': [tod], 'user_type': [user_type], }) def predict_both(row): rp = reply_model.predict_proba(row)[0][1] gp = ghost_model.predict_proba(row)[0][1] return round(rp, 4), round(gp, 4) # โ”€โ”€ Mode-adjusted probabilities โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # The ML model gives one true probability. Each mode nudges it to tell a # coherent story consistent with that mode's personality: # Savage: slightly pessimistic โžบ surfaces the worst-case reading # Emotional: softens ghost risk, because the point is empathy not alarm # Delusional: bumps reply up, tanks ghost risk โžบ the world is fine, always # Normal: raw model output, no adjustment # # Adjustments are additive deltas, clamped to [0.05, 0.95]. # The base probability is always stored in session_state so switching modes # always starts from the same model output โžบ no drift across mode switches. MODE_PROB_DELTA = { # reply_delta ghost_delta 'normal': ( 0.00, 0.00), 'savage': ( -0.07, +0.10), # pessimistic โžบ "realistically, it's worse" 'emotional': ( +0.04, -0.06), # softer framing โžบ ghost risk feels lower 'delusional':( +0.15, -0.18), # copium โžบ everything looks fine } def apply_mode(base_rp, base_gp, mode): rd, gd = MODE_PROB_DELTA[mode] rp = max(0.05, min(0.95, base_rp + rd)) gp = max(0.05, min(0.95, base_gp + gd)) return round(rp, 4), round(gp, 4) # โ”€โ”€ Mode-aware text โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # BUG FIX: All text that changes with mode must be derived AFTER reading mode # from session_state, and the cache key must include mode. MODE_QUOTES = { 'savage': { 'high': ("Not bad. They might actually respond. Don't ruin it by double-texting.", "You're doing well. Shockingly."), 'mid': ("50/50. A coin toss. Even randomness has standards.", "You're in the grey zone. Be honest โžบ you already know."), 'low': ("They saw it. Chose silence. That's your answer.", "This isn't a delay. This is an exit."), 'ghost_high': "They're already gone. The AI just confirmed what you felt.", 'ghost_mid': "It could go either way. But look at that response time.", 'ghost_low': "Slim chance. Still a chance. Do with that what you will.", }, 'emotional': { 'high': ("There's still warmth here. Don't give up on this connection ๐Ÿ’›", "The signs are good. You deserve someone who shows up."), 'mid': ("It's uncertain, and that uncertainty is exhausting. You're not alone in this.", "You deserve clarity. This situation doesn't give you that yet."), 'low': ("It's okay to feel this. Silence hurts. Your feelings are valid.", "Sometimes people fade. That's not a reflection of your worth."), 'ghost_high': "This is hard to hear, but you already sensed something was off.", 'ghost_mid': "The uncertainty is real. You deserve better than wondering.", 'ghost_low': "There's still a thread here. But protect your heart either way.", }, 'delusional': { 'high': ("They're DEFINITELY writing a 3-paragraph reply right now ๐Ÿ”ฅ", "They literally can't stop thinking about you. Facts."), 'mid': ("They're just playing it cool. They're SO into you. Obviously.", "This is called mystery. They're keeping you guessing because you're special."), 'low': ("They're probably just in a coma. Or lost their phone. In the ocean.", "WiFi issues. 100%. They'll reply any second now. Any. Second."), 'ghost_high': "Ghost risk?? No no no. They're just... composing the perfect reply.", 'ghost_mid': "The model is clearly broken. You two have something special.", 'ghost_low': "See?? Low ghost risk. They adore you. Manifesting the reply rn.", }, 'normal': { 'high': ("Good signs based on your inputs. Message has solid energy.", "The indicators are positive here."), 'mid': ("This one could genuinely go either way. Hard to call.", "Mixed signals in the data โžบ reply is uncertain."), 'low': ("The probability here is low based on current signals.", "Several risk factors are stacking up in this scenario."), 'ghost_high': "Multiple ghosting indicators are present.", 'ghost_mid': "Some ghosting signals detected โžบ not conclusive.", 'ghost_low': "Low ghosting probability based on the inputs.", } } # BUG FIX: Final Verdict text must also be mode-aware VERDICT_TEXT = { 'normal': { 'clear_ok': ("You're overcomplicating this. They'll reply.", "#00b894"), 'mixed': ("Mixed signals. Reply likely but something feels off.", "#fdcb6e"), 'one_sided': ("This is one-sided. You're investing more than they are.", "#e17055"), 'move_on': ("Move on. The data agrees with your gut.", "#d63031"), 'uncertain': ("It's uncertain. Give it one more day before deciding.", "#636e72"), }, 'savage': { 'clear_ok': ("They'll reply. Don't sabotage it now.", "#00b894"), 'mixed': ("Reply likely. Ghost possible. Classic mixed energy situation.", "#fdcb6e"), 'one_sided': ("You're the only one putting in effort here. Read that again.", "#e17055"), 'move_on': ("It's over. Your gut knew. Now you have data too.", "#d63031"), 'uncertain': ("Genuinely unclear. But your anxiety already picked a side.", "#636e72"), }, 'emotional': { 'clear_ok': ("There's real connection here. Let it breathe.", "#00b894"), 'mixed': ("Something good is here, but something's also holding back.", "#fdcb6e"), 'one_sided': ("You deserve reciprocity. This doesn't look balanced right now.", "#e17055"), 'move_on': ("It's okay to let go. That's not giving up, it's self-respect.", "#d63031"), 'uncertain': ("Uncertainty is painful. Whatever happens, you'll be okay.", "#636e72"), }, 'delusional': { 'clear_ok': ("Obviously they'll reply. You two are basically soulmates.", "#00b894"), 'mixed': ("The universe is just building tension before the plot twist ๐ŸŒŸ", "#fdcb6e"), 'one_sided': ("You're the main character. They're just processing their feelings.", "#e17055"), 'move_on': ("'Move on'?? The AI doesn't understand your unique connection.", "#d63031"), 'uncertain': ("The model is just shy. It doesn't understand romance.", "#636e72"), }, } def get_verdict_key(reply_prob, ghost_prob): if reply_prob > 0.65 and ghost_prob < 0.40: return 'clear_ok' if reply_prob > 0.65 and ghost_prob >= 0.40: return 'mixed' if reply_prob > 0.40: return 'one_sided' if ghost_prob > 0.65: return 'move_on' return 'uncertain' def get_quotes(mode, reply_prob, ghost_prob): rb = 'high' if reply_prob > 0.65 else ('mid' if reply_prob > 0.40 else 'low') gb = 'ghost_high' if ghost_prob > 0.65 else ('ghost_mid' if ghost_prob > 0.40 else 'ghost_low') q = MODE_QUOTES[mode][rb] return (q[0], q[1]), MODE_QUOTES[mode][gb] def interest_label(reply_prob): if reply_prob > 0.70: return "HIGH", "val-high" if reply_prob > 0.45: return "MEDIUM", "val-mid" return "LOW", "val-low" def effort_label(msg_len, asked_q, emoji): score = (msg_len / 50) + (2 if asked_q else 0) + (emoji * 0.3) if score > 4: return "HIGH", "val-high" if score > 2: return "BALANCED", "val-mid" return "ONE-SIDED", "val-low" def ghost_risk_label(ghost_prob): if ghost_prob > 0.65: return "HIGH", "val-low" if ghost_prob > 0.40: return "MEDIUM", "val-mid" return "LOW", "val-high" # โ”€โ”€ Header โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ st.markdown("
๐Ÿ’€ GHOSTING PREDICTOR
", unsafe_allow_html=True) st.markdown("
AI-powered relationship reality check โžบ be honest, it already knows
", unsafe_allow_html=True) # โ”€โ”€ Personality mode selector โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ st.markdown("#### Choose your vibe") if "personality_mode" not in st.session_state: st.session_state["personality_mode"] = "normal" mode_cols = st.columns(4) modes = [("๐Ÿง  Normal", "normal"), ("๐Ÿ’€ Savage", "savage"), ("๐Ÿ˜ญ Emotional", "emotional"), ("๐Ÿคก Delusional", "delusional")] for i, (lbl, key) in enumerate(modes): with mode_cols[i]: if st.button(lbl, use_container_width=True, type="primary" if st.session_state["personality_mode"] == key else "secondary"): if st.session_state.get("last_clicked") == key: # Double-click detected, toggle to red st.session_state["personality_mode"] = "savage" else: st.session_state["personality_mode"] = key st.session_state["last_clicked"] = key # NO st.rerun() here. Streamlit re-renders naturally on button click. # st.rerun() caused a second render cycle where tab widgets hadn't # initialized yet โ€” ikey matched stale session values and base_rp/base_gp # fell back to mode defaults instead of the user's actual inputs. # Read mode ONCE here โžบ everything below uses this single variable mode = st.session_state["personality_mode"] mode_banner = { "normal": ("๐Ÿง  Normal Mode", "#636e72"), "savage": ("๐Ÿ’€ Savage Mode โžบ No feelings were harmed. They were obliterated.", "#d63031"), "emotional": ("๐Ÿ˜ญ Emotional Mode โžบ We see you. Your feelings are valid.", "#6c5ce7"), "delusional": ("๐Ÿคก Delusional Mode โžบ Stay hopeful! (AI thinks you're cooked.)", "#e17055"), } banner_text, banner_color = mode_banner[mode] st.markdown( f"
" f"{banner_text}
", unsafe_allow_html=True ) st.divider() # โ”€โ”€ Tabs: 3 tabs only (message analyzer removed) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ tab1, tab2, tab3 = st.tabs(["๐Ÿ”ฎ Predict", "๐Ÿ“Š What-If", "๐ŸŽ“ Model Metrics"]) # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• # TAB 1 โžบ MAIN PREDICTION # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• with tab1: col1, col2 = st.columns(2, gap="large") with col1: st.markdown("#### ๐Ÿ“ฑ Your message") message_length = st.slider("Message length (chars)", 1, 500, 80, 5) message_tone = st.selectbox("Tone", ['dry', 'neutral', 'enthusiastic'], index=1) asked_question = st.toggle("Asked a question?", value=True) emoji_count = st.slider("Emojis used", 0, 10, 1) past_ghost = st.toggle("Have they ghosted you before?", value=False) with col2: st.markdown("#### โฑ๏ธ Their behaviour") response_time = st.slider("Hours since you sent it", 0, 72, 4, 1) seen_raw = st.radio("Did they see it?", ["๐Ÿ‘๏ธ Yes, seen", "โ“ Not seen yet"], horizontal=True) seen_ignored = 1 if "Yes" in seen_raw else 0 conv_len = st.slider("How long has the convo been? (messages)", 1, 200, 20) user_type_map = { "๐Ÿ˜Š Seems interested": "interested", "๐Ÿ’ฌ Normal/casual": "casual", "๐ŸŒต Very dry texter": "dry_texter", "๐Ÿ‘ป Known to ghost": "ghoster", } user_type_label = st.selectbox("How would you describe them?", list(user_type_map.keys())) user_type = user_type_map[user_type_label] st.divider() # โ”€โ”€ Predictions โžบ cache key includes mode so text refreshes on mode change โ”€โ”€ # ikey tracks input changes only (not mode) โžบ model is only re-run when # inputs change. Base probabilities are stored raw (no mode applied). # Mode adjustment is applied on every render so switching mode instantly # changes the displayed numbers without re-running the model. ikey = (message_length, message_tone, asked_question, response_time, seen_ignored, emoji_count, conv_len, user_type, int(past_ghost)) # Always run prediction if base_rp/base_gp are missing OR if inputs changed needs_predict = ( st.session_state.get("ikey") != ikey or "base_rp" not in st.session_state or "base_gp" not in st.session_state ) if needs_predict: try: row = build_input(message_length, message_tone, asked_question, response_time, seen_ignored, emoji_count, conv_len=conv_len, past_ghost=int(past_ghost), user_type=user_type) base_rp, base_gp = predict_both(row) except Exception as e: st.error(f"Prediction error: {e}") base_rp, base_gp = 0.5, 0.4 st.session_state.update({"ikey": ikey, "base_rp": base_rp, "base_gp": base_gp}) # Apply mode delta on every render โžบ no model re-run needed reply_prob, ghost_prob = apply_mode( st.session_state["base_rp"], st.session_state["base_gp"], mode ) # Derive ALL mode-dependent text here, after reading mode from session_state (main_q, sub_q), ghost_q = get_quotes(mode, reply_prob, ghost_prob) verdict_key = get_verdict_key(reply_prob, ghost_prob) verdict_text, verdict_color = VERDICT_TEXT[mode][verdict_key] # โ”€โ”€ Dual verdict cards โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ vc1, vc2 = st.columns(2) with vc1: vclass = "verdict-high" if reply_prob > 0.65 else ("verdict-mid" if reply_prob > 0.40 else "verdict-low") vlabel = "They'll reply ๐Ÿ”ฅ" if reply_prob > 0.65 else ("Could go either way ๐Ÿ˜ฌ" if reply_prob > 0.40 else "They're ghosting you ๐Ÿ’€") st.markdown(f"""
Reply probability
{reply_prob*100:.0f}%
{vlabel}
"{main_q}"
""", unsafe_allow_html=True) with vc2: gclass = "verdict-low" if ghost_prob > 0.65 else ("verdict-mid" if ghost_prob > 0.40 else "verdict-high") glabel = "High ghost risk ๐Ÿ’€" if ghost_prob > 0.65 else ("Uncertain ๐Ÿ˜ฌ" if ghost_prob > 0.40 else "Probably fine ๐Ÿ™‚") st.markdown(f"""
Ghost probability
{ghost_prob*100:.0f}%
{glabel}
"{ghost_q}"
""", unsafe_allow_html=True) # โ”€โ”€ Conversation Diagnosis โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # BUG FIX: Diagnosis values are derived from ML probabilities (correct), # but the Read Status now also reflects mode tone st.markdown("#### ๐Ÿง  Conversation Diagnosis") int_lbl, int_cls = interest_label(reply_prob) eff_lbl, eff_cls = effort_label(message_length, asked_question, emoji_count) gr_lbl, gr_cls = ghost_risk_label(ghost_prob) # Read status changes with mode (delusional gives an excuse, savage is blunt) if seen_ignored and response_time > 6: seen_txt = { 'normal': "IGNORED ๐Ÿšจ", 'savage': "SEEN. IGNORED. ๐Ÿ’€", 'emotional': "SEEN, NO REPLY ๐Ÿ’”", 'delusional':"SEEN (composing!!) โœ๏ธ", }[mode] seen_cls = "val-low" elif seen_ignored: seen_txt = "SEEN โœ“"; seen_cls = "val-mid" else: seen_txt = "NOT SEEN"; seen_cls = "val-mid" st.markdown(f"""
Interest Level
{int_lbl}
Effort Balance
{eff_lbl}
Ghost Risk
{gr_lbl}
Read Status
{seen_txt}
""", unsafe_allow_html=True) # โ”€โ”€ Signal Breakdown โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ st.markdown("#### ๐Ÿšฉ Signal Breakdown") fc1, fc2 = st.columns(2) red_flags, green_flags = [], [] if seen_ignored and response_time > 6: red_flags.append("They saw your message. They chose silence.") if response_time > 48: red_flags.append(f"It's been {response_time}h. That's not busy, that's avoidance.") elif response_time > 24: red_flags.append("Over 24 hours โžบ the energy is cooling off.") if message_tone == 'dry': red_flags.append("Dry tone doesn't open doors.") if not asked_question: red_flags.append("No question = no reason to reply.") if message_length < 30: red_flags.append("Short message โžบ looks like low effort.") if user_type == 'ghoster': red_flags.append("You described them as a known ghoster. That's data.") if past_ghost: red_flags.append("They've ghosted you before. Pattern recognised.") if emoji_count == 0 and message_tone == 'dry': red_flags.append("Zero warmth signals in this message.") if asked_question: green_flags.append("Asked a question โžบ gives them something to respond to.") if message_length > 100: green_flags.append("Substantial message โžบ shows you put in effort.") if message_tone == 'enthusiastic': green_flags.append("Enthusiastic tone โžบ energy is contagious.") if response_time < 12: green_flags.append("Sent recently โžบ they still might be composing a reply.") if emoji_count > 0: green_flags.append("Used emojis โžบ lightens the vibe.") if user_type == 'interested': green_flags.append("You described them as interested โžบ that matters.") if not past_ghost: green_flags.append("No ghosting history โžบ fresh start.") with fc1: st.markdown("**Red flags**") for f in red_flags: st.markdown(f"
๐Ÿšฉ {f}
", unsafe_allow_html=True) if not red_flags: st.markdown("
โœ… No major red flags detected.
", unsafe_allow_html=True) with fc2: st.markdown("**Green flags**") for g in green_flags: st.markdown(f"
โœ… {g}
", unsafe_allow_html=True) if not green_flags: st.markdown("
๐Ÿšฉ Hmm, not many positives here.
", unsafe_allow_html=True) st.divider() # โ”€โ”€ Final Verdict โžบ mode-aware โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # BUG FIX: verdict_text and verdict_color now come from VERDICT_TEXT[mode] st.markdown("#### ๐ŸŽฏ Final Verdict") st.markdown( f"
" f"{verdict_text}
", unsafe_allow_html=True ) if sub_q: st.markdown( f"
๐Ÿ’ญ {sub_q}
", unsafe_allow_html=True ) st.divider() # โ”€โ”€ Shareable card โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ st.markdown("#### ๐Ÿ“ธ Share Your Result") share_label = "They'll probably reply ๐Ÿ”ฅ" if reply_prob > 0.65 else ("It's a coin flip ๐Ÿ˜ฌ" if reply_prob > 0.40 else "Ghosting incoming ๐Ÿ’€") ghost_label = "Ghost risk: HIGH ๐Ÿ’€" if ghost_prob > 0.65 else ("Ghost risk: MEDIUM โš ๏ธ" if ghost_prob > 0.40 else "Ghost risk: LOW โœ…") st.markdown(f"""
AI Reality Check
{reply_prob*100:.0f}%
{share_label}
{ghost_label}
"{main_q}"
#GhostingPredictor โ€ข ghostingpredictor.app
""", unsafe_allow_html=True) share_text = (f"๐Ÿ’€ Ghosting Predictor says:\n" f"Reply chance: {reply_prob*100:.0f}% โžบ {share_label}\n" f"{ghost_label}\n" f'"{main_q}"\n' f"#GhostingPredictor #AI #Dating") # FIX: st.button causes a full page rerun which resets widget defaults โ†’ # changes ikey โ†’ triggers fresh prediction with default inputs โ†’ wrong %. # Solution: always render the share text in a st.text_area (read-only style). # st.text_area does NOT trigger a rerun when the user clicks inside it to # select/copy โžบ it only reruns on actual value change, which can't happen # because the value is set programmatically and the user just selects text. st.markdown("
๐Ÿ“‹ Click inside, Ctrl+A, Ctrl+C to copy:
", unsafe_allow_html=True) st.text_area( label="share_text_area", value=share_text, height=120, label_visibility="collapsed", key=f"share_ta_{hash(share_text)}", # stable key tied to content, not mode ) st.markdown("
๐Ÿ“ธ Or screenshot the card above and post it
", unsafe_allow_html=True) st.markdown("
Drop your situation in the comments โžบ I'll tell you what the model says ๐Ÿ‘‡
", unsafe_allow_html=True) # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• # TAB 2 โžบ WHAT-IF SIMULATOR # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• with tab2: st.markdown("#### ๐Ÿ“Š What-If Simulator") st.markdown("
See how your odds change if you tweak one thing. Experiment freely.
", unsafe_allow_html=True) if "base_rp" not in st.session_state: st.info("Go to the **Predict** tab first to set your base scenario.") else: base_rp, base_gp = apply_mode( st.session_state["base_rp"], st.session_state["base_gp"], mode ) ml, tone, aq, rt, si, ec, cl_val, ut, pg = st.session_state["ikey"] rclr = "#00b894" if base_rp > 0.65 else ("#fdcb6e" if base_rp > 0.4 else "#ff7675") gclr = "#ff7675" if base_gp > 0.65 else ("#fdcb6e" if base_gp > 0.4 else "#00b894") st.markdown(f"""
Your current situation
Reply: {base_rp*100:.0f}%    Ghost: {base_gp*100:.0f}%
""", unsafe_allow_html=True) scenarios = [] if not aq: r = build_input(ml, tone, True, rt, si, ec, cl_val, user_type=ut) nr, ng = predict_both(r) scenarios.append(("โ“ If you added a question", nr, ng)) if tone != 'enthusiastic': r = build_input(ml, 'enthusiastic', aq, rt, si, ec, cl_val, user_type=ut) nr, ng = predict_both(r) scenarios.append(("๐Ÿ˜„ If your tone was enthusiastic", nr, ng)) if ml < 150: r = build_input(150, tone, aq, rt, si, ec, cl_val, user_type=ut) nr, ng = predict_both(r) scenarios.append(("๐Ÿ“ If your message was longer (150 chars)", nr, ng)) if rt > 12: r = build_input(ml, tone, aq, 2, si, ec, cl_val, user_type=ut) nr, ng = predict_both(r) scenarios.append(("โฑ๏ธ If you followed up now (2h gap)", nr, ng)) if ec == 0: r = build_input(ml, tone, aq, rt, si, 3, cl_val, user_type=ut) nr, ng = predict_both(r) scenarios.append(("๐Ÿ˜‚ If you added 3 emojis", nr, ng)) r = build_input(max(ml, 120), 'enthusiastic', True, min(rt, 4), si, max(ec, 2), cl_val, user_type=ut) nr, ng = predict_both(r) scenarios.append(("๐Ÿš€ Best case (all fixes applied)", nr, ng)) st.markdown("**How your odds change:**") for label, nr, ng in scenarios: rdiff = (nr - base_rp) * 100 gdiff = (ng - base_gp) * 100 rc = "whatif-boost" if rdiff > 0 else "whatif-drop" gc = "whatif-drop" if gdiff > 0 else "whatif-boost" rs = "+" if rdiff >= 0 else ""; gs = "+" if gdiff >= 0 else "" st.markdown(f"""
{label} Reply: {rs}{rdiff:.0f}%  |  Ghost: {gs}{gdiff:.0f}%
""", unsafe_allow_html=True) st.markdown("
All scenarios keep the rest of your inputs unchanged.
", unsafe_allow_html=True) # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• # TAB 3 โžบ MODEL METRICS # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• with tab3: st.markdown("#### ๐ŸŽ“ Model Performance") st.markdown("
Two calibrated Random Forest models โžบ reply prediction and ghost prediction. Evaluated on a clean held-out test set.
", unsafe_allow_html=True) for key, label in [('reply', '๐Ÿ“ฉ Reply Model'), ('ghosted', '๐Ÿ‘ป Ghost Model')]: m = all_metrics[key] st.markdown(f"### {label}") mc = st.columns(5) mc[0].markdown(f"
{m['accuracy']*100:.1f}%
Accuracy
", unsafe_allow_html=True) mc[1].markdown(f"
{m['precision']*100:.1f}%
Precision
", unsafe_allow_html=True) mc[2].markdown(f"
{m['recall']*100:.1f}%
Recall
", unsafe_allow_html=True) mc[3].markdown(f"
{m['f1_score']:.3f}
F1 Score
", unsafe_allow_html=True) mc[4].markdown(f"
{m['roc_auc']:.3f}
ROC-AUC
", unsafe_allow_html=True) with st.expander(f"Confusion matrix & report โžบ {label}", expanded=False): e1, e2 = st.columns(2) with e1: cm_arr = np.array(m['confusion_matrix']) fig, ax = plt.subplots(figsize=(4, 3)) sns.heatmap(cm_arr, annot=True, fmt='d', cmap='Blues', xticklabels=['No', 'Yes'], yticklabels=['No', 'Yes'], ax=ax, cbar=False, annot_kws={'size': 13, 'weight': 'bold'}) ax.set_xlabel('Predicted', color='white'); ax.set_ylabel('Actual', color='white') ax.set_title('Confusion Matrix', color='white', fontsize=11) fig.patch.set_facecolor('#1a1a2e'); ax.set_facecolor('#1a1a2e') ax.tick_params(colors='white') plt.tight_layout(); st.pyplot(fig, use_container_width=True) with e2: try: from sklearn.metrics import roc_curve fpr, tpr, _ = roc_curve(np.array(m['y_test']), np.array(m['y_pred_prob'])) fig2, ax2 = plt.subplots(figsize=(4, 3)) ax2.plot(fpr, tpr, color='#ee5a24', lw=2, label=f"AUC={m['roc_auc']:.3f}") ax2.plot([0,1],[0,1],'--',color='gray',lw=1) ax2.fill_between(fpr, tpr, alpha=0.12, color='#ee5a24') ax2.set_xlabel('FPR', color='white'); ax2.set_ylabel('TPR', color='white') ax2.set_title('ROC Curve', color='white', fontsize=11) ax2.legend(fontsize=9); ax2.tick_params(colors='white') ax2.set_facecolor('#1a1a2e'); fig2.patch.set_facecolor('#1a1a2e') plt.tight_layout(); st.pyplot(fig2, use_container_width=True) except: pass st.code(m['classification_report'], language=None) st.divider() st.markdown(f"""
Architecture: Random Forest (400 trees, depth=20, class_weight=balanced) + Sigmoid calibration (cv=3)
Split: 70% train / 15% calibration val / 15% test โžบ no data leakage between steps
Dataset: 10,000 synthetic samples โžบ ghosting_dataset5.csv
Features: 20 numerical + 4 categorical (including user_type persona)
""", unsafe_allow_html=True) # โ”€โ”€ Footer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ st.markdown("""
๐Ÿ’ญ You already know the answer. The AI just confirmed it.
Powered by Random Forest ML ยท Not liable for heartbreak ๐Ÿ’”
""", unsafe_allow_html=True)