Spaces:
Runtime error
Runtime error
File size: 6,951 Bytes
e6a6feb 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 d98928c 52e91a5 e6a6feb 52e91a5 | 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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | 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)
# ==========================================
@st.cache_resource
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)) |