Spaces:
Runtime error
Runtime error
Download src/streamlit_app.py from bluesketch/echom: direct link, hf CLI and curl.
- Browser
- Download file 6.95 kB
-
https://huggingface.co/spaces/bluesketch/echom/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/bluesketch/echom/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/bluesketch/echom/resolve/main/src/streamlit_app.py
6.95 kB
| import streamlit as st | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch_geometric.nn import GCNConv | |
| from torch_geometric.utils import add_self_loops | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.preprocessing import StandardScaler | |
| import time | |
| # ========================================== | |
| # 0. PAGE CONFIG | |
| # ========================================== | |
| st.set_page_config(page_title="GHOST_VIBE", page_icon="👻", layout="centered") | |
| st.markdown(""" | |
| <style> | |
| .stApp { background-color: #050505; color: #00ff41; font-family: 'Courier New', monospace; } | |
| .stTextInput > div > div > input { background-color: #111; color: #00ff41; border: 1px solid #333; } | |
| .stButton > button { background-color: #000; border: 1px solid #00ff41; color: #00ff41; } | |
| .stButton > button:hover { background-color: #00ff41; color: #000; } | |
| .user-msg { color: #fff; border-left: 2px solid #00ff41; padding-left: 10px; margin-bottom: 5px; } | |
| .sys-msg { color: #555; font-size: 0.8em; font-style: italic; } | |
| .match-anim { border: 2px solid #ff00ff; padding: 20px; text-align: center; animation: pulse 2s infinite; margin-top: 20px; } | |
| @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(255, 0, 255, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(255, 0, 255, 0); } 100% { box-shadow: 0 0 0 0 rgba(255, 0, 255, 0); } } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # ========================================== | |
| # 1. MODEL DEFINITION | |
| # ========================================== | |
| class MotifConv(nn.Module): | |
| def __init__(self, in_channels, out_channels, num_motifs=2, act=True): | |
| super().__init__() | |
| self.convs = nn.ModuleList([GCNConv(in_channels, out_channels) for _ in range(num_motifs)]) | |
| self.bn = nn.BatchNorm1d(out_channels) | |
| self.act = act | |
| def forward(self, x, motif_graphs): | |
| outs = [] | |
| for i, conv in enumerate(self.convs): | |
| if i < len(motif_graphs) and motif_graphs[i].size(1) > 0: | |
| out = conv(x, motif_graphs[i]) | |
| outs.append(out) | |
| else: | |
| outs.append(torch.zeros(x.size(0), conv.out_channels).to(x.device)) | |
| out = self.bn(torch.stack(outs).sum(dim=0)) | |
| return F.relu(out) if self.act else out | |
| class VibeMatchMGNN(nn.Module): | |
| def __init__(self, in_dim, hidden_dim, out_dim): | |
| super().__init__() | |
| self.mgnn1 = MotifConv(in_dim, hidden_dim, act=True) | |
| self.mgnn2 = MotifConv(hidden_dim, out_dim, act=False) | |
| def forward(self, x, motif_graphs): | |
| h = self.mgnn1(x, motif_graphs) | |
| h = self.mgnn2(h, motif_graphs) | |
| return h | |
| # ========================================== | |
| # 2. GLOBAL BRAIN (SHARED MEMORY) | |
| # ========================================== | |
| class GlobalBrain: | |
| def __init__(self): | |
| self.users = [] | |
| self.vectors = [] | |
| self.model = None | |
| self.scaler = None | |
| self.projector = None | |
| self.load_system() | |
| def load_system(self): | |
| # 1. Load CSVs | |
| try: | |
| df = pd.read_csv('user_features.csv') | |
| raw_x = df.drop(columns=['user_id', 'mapped_id'], errors='ignore').fillna(0) | |
| self.scaler = StandardScaler() | |
| self.scaler.fit(raw_x.values) | |
| except: | |
| self.scaler = StandardScaler() | |
| self.scaler.fit(np.random.rand(10, 387)) | |
| # 2. Load Model | |
| self.model = VibeMatchMGNN(64, 64, 32) | |
| try: | |
| self.model.load_state_dict(torch.load('vibematch_model.pth', map_location='cpu')) | |
| except: | |
| print("⚠️ .pth not found. Using random weights.") | |
| # --- THE FIX IS HERE: FORCE EVAL MODE --- | |
| self.model.eval() | |
| # 3. Projector | |
| torch.manual_seed(42) | |
| self.projector = nn.Linear(387, 64) | |
| def add_user(self, user_id, vector_387): | |
| self.users.append(user_id) | |
| self.vectors.append(vector_387) | |
| def find_match(self, target_vec_32, current_user_id): | |
| if not self.users: return None, 0 | |
| best_score = -999 | |
| best_user = None | |
| for i, u_id in enumerate(self.users): | |
| if u_id == current_user_id: continue | |
| vec_raw = self.vectors[i] | |
| # Project & Inference | |
| with torch.no_grad(): | |
| self.model.eval() # FORCE EVAL AGAIN | |
| vec_scaled = self.scaler.transform([vec_raw]) | |
| vec_t = torch.tensor(vec_scaled, dtype=torch.float32) | |
| vec_64 = self.projector(vec_t) | |
| dummy = [torch.empty((2,0), dtype=torch.long)]*2 | |
| cand_vec_32 = self.model(vec_64, dummy)[0] | |
| score = torch.dot(target_vec_32, cand_vec_32).item() | |
| if score > best_score: | |
| best_score = score | |
| best_user = u_id | |
| return best_user, best_score | |
| # Initialize the shared brain | |
| brain = GlobalBrain() | |
| # ========================================== | |
| # 3. TEXT PROCESSING | |
| # ========================================== | |
| def process_text(text): | |
| vec = np.random.rand(387) | |
| vec[0] = len(text.split()) | |
| vec[2] = sum(1 for c in text if c.isupper()) | |
| # Run Inference | |
| with torch.no_grad(): | |
| brain.model.eval() # FORCE EVAL AGAIN | |
| vec_scaled = brain.scaler.transform([vec]) | |
| vec_t = torch.tensor(vec_scaled, dtype=torch.float32) | |
| vec_64 = brain.projector(vec_t) | |
| dummy = [torch.empty((2,0), dtype=torch.long)]*2 | |
| vec_32 = brain.model(vec_64, dummy)[0] | |
| return vec, vec_32 | |
| # ========================================== | |
| # 4. UI LOGIC | |
| # ========================================== | |
| st.title("GHOST_VIBE // LIVE NODE") | |
| if "uid" not in st.session_state: | |
| st.session_state.uid = f"Guest_{int(time.time())}" | |
| st.caption(f"CONNECTED AS: {st.session_state.uid}") | |
| if prompt := st.chat_input("Broadcast to the network..."): | |
| st.markdown(f"<div class='user-msg'>{prompt}</div>", unsafe_allow_html=True) | |
| # 1. Process | |
| raw_vec, vibe_vec = process_text(prompt) | |
| # 2. Save | |
| brain.add_user(st.session_state.uid, raw_vec) | |
| st.markdown(f"<div class='sys-msg'>Your vibe vector has been added to the live network.</div>", unsafe_allow_html=True) | |
| # 3. Match | |
| match_id, score = brain.find_match(vibe_vec, st.session_state.uid) | |
| if match_id: | |
| st.markdown(f""" | |
| <div class='match-anim'> | |
| <h2 style='color:#fff'>MATCH FOUND</h2> | |
| <h1 style='color:#00ff41'>{match_id}</h1> | |
| <p>COMPATIBILITY: {int(score*100)}%</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| else: | |
| st.markdown(f"<div class='sys-msg' style='color:orange'>No matches yet. You are the first node in this cluster. Waiting for others...</div>", unsafe_allow_html=True) | |
| # Show Stats | |
| st.sidebar.title("NETWORK STATS") | |
| st.sidebar.metric("Live Users", len(brain.users)) |