Spaces:
Runtime error
Runtime error
shitstarted
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201import streamlit as stimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch_geometric.nn import GCNConvfrom torch_geometric.utils import add_self_loopsimport pandas as pdimport numpy as npfrom sklearn.preprocessing import StandardScalerimport 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 = actdef 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 outclass 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)# ==========================================@st.cache_resourceclass GlobalBrain:def __init__(self):self.users = [] # Stores real user IDsself.vectors = [] # Stores real user vectorsself.model = Noneself.scaler = Noneself.projector = Noneself.load_system()def load_system(self):# 1. Load CSVs (OPTIONAL: Use as 'Seed' data if present)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)# Load initial users into memory (Seed Data)# Comment this out if you want a TRULY EMPTY start# self.users = df['user_id'].tolist()# x_scaled = self.scaler.transform(raw_x.values)# self.vectors = [torch.tensor(v, dtype=torch.float32) for v in x_scaled]except:# Fallback if no CSVself.scaler = StandardScaler()# Fit on dummy data just to initializeself.scaler.fit(np.random.rand(10, 387))# 2. Load Modelself.model = VibeMatchMGNN(64, 64, 32)try:self.model.load_state_dict(torch.load('vibematch_model.pth', map_location='cpu'))self.model.eval()except:pass # Use random weights if missing# 3. Projectortorch.manual_seed(42)self.projector = nn.Linear(387, 64)def add_user(self, user_id, vector_387):# Store the new user in the live memoryself.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# Convert memory list to tensor batch# We need to project ALL saved vectors to 32-dim to compare# (Optimized: In real app, we'd cache the 32-dim versions)best_score = -1best_user = None# Iterate through live usersfor i, u_id in enumerate(self.users):if u_id == current_user_id: continue # Don't match self# Get stored vectorvec_raw = self.vectors[i]# Project & Inferencewith torch.no_grad():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)]*2cand_vec_32 = self.model(vec_64, dummy)[0]# Scorescore = torch.dot(target_vec_32, cand_vec_32).item()if score > best_score:best_score = scorebest_user = u_idreturn best_user, best_score# Initialize the shared brainbrain = GlobalBrain()# ==========================================# 3. TEXT PROCESSING# ==========================================def process_text(text):# Extract featuresvec = np.random.rand(387) # Hash-based placeholder + statsvec[0] = len(text.split())vec[2] = sum(1 for c in text if c.isupper())# Run Inferencewith torch.no_grad():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)]*2vec_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..."):# Show User Msgst.markdown(f"<div class='user-msg'>{prompt}</div>", unsafe_allow_html=True)# 1. Processraw_vec, vibe_vec = process_text(prompt)# 2. Save to Memory (The "Real Platform" feature)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. Find Matchmatch_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 Statsst.sidebar.title("NETWORK STATS")st.sidebar.metric("Live Users", len(brain.users))
src/streamlit_app.py+199-38