Hopefully fixed model fetching form supabase
Browse filesFiles changed (4)
7 unmodified lines891011121333 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141157 unmodified linesimport mathimport pandas as pdimport streamlit.components.v1 as components# --- PAGE CONFIG ---st.set_page_config(layout="wide", page_title="Topic Buzz Explorer")33 unmodified linesCACHE_FILE = "mastodon_network.pkl"LABELS_FILE = "topic_labels.json"@st.cache_resourcedef load_data():data = {"G": None, "labels": {}, "min_ts": 0, "max_ts": 1}if os.path.exists(CACHE_FILE):with open(CACHE_FILE, 'rb') as f:data["G"] = pickle.load(f)# Pre-calculate Time RangeG = data["G"]timestamps = [d['last_timestamp']for u, v, d in G.edges(data=True)if 'last_timestamp' in d and d['last_timestamp'] > 0]if timestamps:data["min_ts"] = min(timestamps)data["max_ts"] = max(timestamps)if os.path.exists(LABELS_FILE):with open(LABELS_FILE, 'r') as f:data["labels"] = json.load(f)return data# ```# ### How to create the Multi-Page Structure# 1. **Keep `app.py` (above):** This is your "Home" page.# 2. **Create a folder** named `pages` in the same directory.# 3. **Create `pages/1_Graph_Explorer.py`:** Copy your **original** graph logic (the massive script we just built) into this file.# 4. **Create `pages/2_Topic_List.py`:** (Optional) A simple page to list all topics and their keywords.# **Example Directory Structure:**# ```text# /topic_buzz/# βββ app.py # Landing Page# βββ mastodon_network.pkl # Data# βββ topic_labels.json # Data# βββ pages/# βββ 1_Graph_Explorer.py # The interactive graph code# βββ 2_Topic_List.py # New simple page# ```# ### Code for `pages/1_Graph_Explorer.py`# *(This is just your previous `app.py` code, but you need to import `load_data` from the main app or duplicate the function).*# It is often cleaner to put the `load_data` function in a separate file (e.g., `utils.py`) and import it in both `app.py` and `pages/1_Graph_Explorer.py` to ensure the cache is shared efficiently.# **Example `utils.py`:**# ```python# import streamlit as st# import pickle# import os# import json# @st.cache_resource# def load_data():# # ... (paste the load_data logic here) ...# return data# ```# Then in every page:# ```python# from utils import load_data# data = load_data()7 unmodified lines89101112131433 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171187 unmodified linesimport mathimport pandas as pdimport streamlit.components.v1 as componentsfrom supabase import create_client, Client# --- PAGE CONFIG ---st.set_page_config(layout="wide", page_title="Topic Buzz Explorer")33 unmodified linesCACHE_FILE = "mastodon_network.pkl"LABELS_FILE = "topic_labels.json"SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)CACHE_FILE = "mastodon_network.pkl"BUCKET = "topic_assets"@st.cache_resourcedef ensure_local_file(filename):"""Checks if a file exists locally. If not, attempts to download itfrom Supabase Storage and save it to disk."""if os.path.exists(filename):return Trueprint(f"βοΈ File {filename} not found locally. Downloading from Supabase...")try:# 1. Get the bytes from Supabasefile_bytes = supabase.storage.from_(BUCKET).download(filename)# 2. Save bytes to local diskwith open(filename, "wb") as f: # 'wb' = Write Binaryf.write(file_bytes)print(f"β Downloaded {filename}")return Trueexcept Exception as e:st.error(f"β Failed to download {filename} from bucket '{BUCKET}': {e}")return False@st.cache_resourcedef load_data():data = {"G": None, "labels": {}, "min_ts": 0, "max_ts": 1}# 1. LOAD GRAPH (Pickle)if ensure_local_file(CACHE_FILE):try:with open(CACHE_FILE, 'rb') as f:data["G"] = pickle.load(f)# Pre-calculate Time RangeG = data["G"]timestamps = [d['last_timestamp']for u, v, d in G.edges(data=True)if 'last_timestamp' in d and d['last_timestamp'] > 0]if timestamps:data["min_ts"] = min(timestamps)data["max_ts"] = max(timestamps)except Exception as e:st.error(f"Error loading pickle file: {e}")# 2. LOAD LABELS (JSON)if ensure_local_file(LABELS_FILE):try:with open(LABELS_FILE, 'r') as f:data["labels"] = json.load(f)except Exception as e:st.warning(f"Could not load labels (check JSON format): {e}")return data# Trigger the load immediately so files are ready for other pagesif __name__ == "__main__":load_data()
111 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200111 unmodified lines)print("β Done! Graph cached and uploaded.")except Exception as e:print(f"β Upload failed: {e}")# import chromadb# import networkx as nx# import pickle# import os# # --- CONFIGURATION ---# CHROMA_PATH = "/home/wyomike/topicBuzz/my_mastodon_db"# COLLECTION_NAME = "mastodon_posts"# CACHE_FILE = "mastodon_network.pkl"# BATCH_SIZE = 10000# # --- 1. Connect ---# print("Connecting to DB...")# client = chromadb.PersistentClient(path=CHROMA_PATH)# collection = client.get_collection(COLLECTION_NAME)# total_docs = collection.count()# # --- 2. Build Graph with Weights & Time ---# print(f"Building weighted temporal graph from {total_docs} docs...")# G = nx.Graph()# topic_counts = {}# for offset in range(0, total_docs, BATCH_SIZE):# batch = collection.get(# limit=BATCH_SIZE,# offset=offset,# include=["metadatas"]# )# for meta in batch["metadatas"]:# if not meta: continue# user_id = meta.get("author_user_id")# topic_id = meta.get("cluster_id")# # Try to get timestamp, handle reblogs if necessary# ts = meta.get("post_timestamp")# if ts is None:# ts = meta.get("reblog_timestamp", 0)# if user_id and topic_id is not None and topic_id != -1:# u_node = f"User_{user_id}"# t_node = f"Topic_{topic_id}"# # Ensure nodes exist# if u_node not in G:# G.add_node(u_node, label=f"User {user_id}", group="users", color="#97C2FC", size=10)# if t_node not in G:# G.add_node(t_node, label=f"Topic {topic_id}", group="topics", color="#FB7E81", size=20)# # --- Edge Logic: Weight + Time ---# if G.has_edge(u_node, t_node):# # Increment weight# G[u_node][t_node]['weight'] += 1# # Keep the MOST RECENT timestamp# if ts > G[u_node][t_node]['last_timestamp']:# G[u_node][t_node]['last_timestamp'] = ts# else:# # Initialize new connection# G.add_edge(u_node, t_node, weight=1, last_timestamp=ts)# # Track counts# topic_counts[topic_id] = topic_counts.get(topic_id, 0) + 1# if offset % 50000 == 0:# print(f" Processed {offset}/{total_docs}...")# # Resize topics# print("Resizing topic nodes...")# for topic_id, count in topic_counts.items():# t_node = f"Topic_{topic_id}"# if t_node in G:# G.nodes[t_node]['size'] = max(20, min(60, count / 5))# G.nodes[t_node]['title'] = f"Topic {topic_id}: {count} posts"# # --- 3. Save Cache ---# print(f"Saving graph to '{CACHE_FILE}'...")# with open(CACHE_FILE, 'wb') as f:# pickle.dump(G, f)# print(f"Done! Graph cached.")111 unmodified lines112113114115111 unmodified lines)print("β Done! Graph cached and uploaded.")except Exception as e:print(f"β Upload failed: {e}")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408# # import os# # import json# # import time# # from tqdm import tqdm# # import google.genai as genai# # from google.genai import types # Import types for configuration# # from bertopic import BERTopic# # from supabase import create_client, Client# # # --- CONFIGURATION ---# # SUPABASE_URL = os.environ.get("SUPABASE_URL")# # SUPABASE_KEY = os.environ.get("SUPABASE_KEY")# # GOOGLE_API_KEY = os.environ.get("GOOGLE_KEY")# # MODEL_FILE = "my_online_mastodon_model.pkl"# # OUTPUT_JSON = "topic_labels.json"# # BUCKET = "topic_assets"# # NSFW_KEYWORDS = {# # "nsfw", "porn", "nude", "naked", "sex", "18+", "xxx",# # "cum", "dick", "pussy", "hentai", "erotic", "onlyfans",# # "boobs", "tits", "cock", "slut", "whore", "bitch", "incest",# # "lewd", "horny", "sensual", "fetish", "bondage"# # }# # # --- SETUP ---# # if not SUPABASE_URL or not SUPABASE_KEY or not GOOGLE_API_KEY:# # raise ValueError("β Missing API Keys (Supabase or Google) in environment variables.")# # supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)# # client = genai.Client(api_key=GOOGLE_API_KEY)# # # --- HELPER: Download/Load Model ---# # def load_remote_model():# # """Downloads model from Supabase if not present locally."""# # if not os.path.exists(MODEL_FILE):# # print(f"βοΈ Downloading {MODEL_FILE} from Supabase Storage...")# # try:# # with open(MODEL_FILE, 'wb') as f:# # res = supabase.storage.from_(BUCKET).download(MODEL_FILE)# # f.write(res)# # except Exception as e:# # print(f"β Error downloading model: {e}")# # return None# # print(f"Loading BERTopic model from {MODEL_FILE}...")# # try:# # return BERTopic.load(MODEL_FILE)# # except Exception as e:# # print(f"β Error loading pickle: {e}")# # return None# # def get_safe_topic_ids(model, nsfw_set):# # """# # Returns a list of Topic IDs that do NOT contain any blocklisted words# # in their top 10 keywords.# # """# # safe_ids = []# # unsafe_ids = []# # # get_topics() returns a dictionary: {topic_id: [(word, score), ...]}# # all_topics = model.get_topics()# # print(f"Scanning {len(all_topics)} topics for NSFW content...")# # for topic_id, words_with_scores in all_topics.items():# # # Topic -1 is outliers.# # topic_words = {word for word, score in words_with_scores}# # # Check for intersection# # intersection = topic_words.intersection(nsfw_set)# # if intersection:# # # print(f" [BLOCKED] Topic {topic_id}")# # unsafe_ids.append(topic_id)# # else:# # safe_ids.append(topic_id)# # print(f"\nResult: {len(safe_ids)} Safe, {len(unsafe_ids)} Unsafe.")# # return safe_ids# # def generate_labels():# # # 1. Load Model# # topic_model = load_remote_model()# # if topic_model is None:# # return# # # 2. Get Info# # info = topic_model.get_topic_info()# # print(f"Found {len(info)} topics.")# # safe_topics = get_safe_topic_ids(topic_model, nsfw_set=NSFW_KEYWORDS)# # labels_map = {}# # print("Asking Gemini to label topics (with Rate Limit handling)...")# # for index, row in tqdm(info.iterrows(), total=len(info)):# # topic_id = row['Topic']# # # Skip unsafe topics# # if topic_id not in safe_topics:# # labels_map[f"Topic_{topic_id}"] = "NSFW Content"# # continue# # # Handle Outliers# # if topic_id == -1:# # labels_map[f"Topic_{topic_id}"] = "Outliers / Noise"# # continue# # # 3. Extract Data & Handle Missing Docs# # keywords = row['Representation']# # docs = row['Representative_Docs']# # if not isinstance(docs, list) or len(docs) == 0:# # try:# # res = supabase.table("posts") \# # .select("content") \# # .eq("cluster_id", int(topic_id)) \# # .limit(3) \# # .execute()# # docs = [r['content'] for r in res.data]# # except Exception:# # docs = []# # if not docs:# # docs_text = "(No examples available yet)"# # else:# # docs_text = chr(10).join([f"- {str(d)[:300]}..." for d in docs[:3]])# # # 4. Construct Prompt (Unchanged)# # prompt = f"""# # I have a cluster of social media posts from Mastodon.# # Keywords: {', '.join(keywords[:10])}# # Representative Posts:# # {docs_text}# # Based on this, provide a short, specific, natural language label (max 5 words) for this topic.# # Do not use quotes. Just the label.# # """# # # --- NEW: Configure Safety Settings to BLOCK_NONE ---# # # This prevents Gemini from refusing to label "spicy" but non-pornographic topics# # safety_config = [# # types.SafetySetting(# # category="HARM_CATEGORY_HATE_SPEECH",# # threshold="BLOCK_NONE",# # ),# # types.SafetySetting(# # category="HARM_CATEGORY_DANGEROUS_CONTENT",# # threshold="BLOCK_NONE",# # ),# # types.SafetySetting(# # category="HARM_CATEGORY_SEXUALLY_EXPLICIT",# # threshold="BLOCK_NONE",# # ),# # types.SafetySetting(# # category="HARM_CATEGORY_HARASSMENT",# # threshold="BLOCK_NONE",# # ),# # ]# # # 5. Call Gemini with RETRY LOGIC# # max_retries = 3# # attempt = 0# # success = False# # while attempt < max_retries:# # try:# # response = client.models.generate_content(# # model='gemini-2.0-flash-lite-preview-02-05',# # contents=prompt,# # config=types.GenerateContentConfig(# # safety_settings=safety_config# # )# # )# # # Check if the response was blocked despite settings# # if not response.text:# # raise ValueError("Empty response (likely safety block)")# # label = response.text.strip()# # labels_map[f"Topic_{topic_id}"] = label# # time.sleep(1.5) # Reduced sleep slightly as 4.0 is conservative# # success = True# # break# # except Exception as e:# # error_str = str(e)# # if "429" in error_str or "RESOURCE_EXHAUSTED" in error_str:# # print(f"\n β³ Quota limit hit on Topic {topic_id}. Sleeping 60s...")# # time.sleep(60)# # attempt += 1# # else:# # print(f"\n β Error on Topic {topic_id}: {e}")# # # Do not break immediately; logic will just try again or fail gracefully# # attempt += 1# # # 6. IMPROVED FALLBACK# # if not success:# # # If API fails, use the top 3 keywords naturally joined# # fallback_label = ", ".join(keywords[:3]).title()# # print(f" β οΈ Failed to generate. Using fallback: {fallback_label}")# # labels_map[f"Topic_{topic_id}"] = fallback_label# # if __name__ == "__main__":# # generate_labels()# import os# import json# import time# from tqdm import tqdm# from bertopic import BERTopic# from supabase import create_client, Client# # --- NEW: Import Local LLM Library ---# # If you get an import error: pip install llama-cpp-python# from llama_cpp import Llama# # --- CONFIGURATION ---# SUPABASE_URL = os.environ.get("SUPABASE_URL")# SUPABASE_KEY = os.environ.get("SUPABASE_KEY")# MODEL_FILE = "my_online_mastodon_model.pkl"# OUTPUT_JSON = "topic_labels.json"# BUCKET = "topic_assets"# # Converted Windows path to WSL (Linux) path# # Original: C:\Users\betha\.lmstudio\models\matrixportalx\Meta-Llama-3.1-8B-Instruct-Q3_K_M-GGUF\meta-llama-3.1-8b-instruct-q3_k_m.gguf# LOCAL_MODEL_PATH = "/home/wyomike/temp/meta-llama-3.1-8b-instruct-q3_k_m.gguf"# NSFW_KEYWORDS = {# "nsfw", "porn", "nude", "naked", "sex", "18+", "xxx",# "cum", "dick", "pussy", "hentai", "erotic", "onlyfans",# "boobs", "tits", "cock", "slut", "whore", "bitch", "incest",# "lewd", "horny", "sensual", "fetish", "bondage"# }# # --- SETUP ---# if not SUPABASE_URL or not SUPABASE_KEY:# raise ValueError("β Missing Supabase API Keys.")# if not os.path.exists(LOCAL_MODEL_PATH):# raise FileNotFoundError(f"β Cannot find model file at: {LOCAL_MODEL_PATH}\n(Make sure you are pointing to the correct /mnt/c/ path in WSL)")# supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)# # --- LOAD LOCAL LLM ---# print(f"π Loading Local Llama 3.1 from disk...")# # n_gpu_layers=-1 tells it to put ALL layers on your GTX 1060# # n_ctx=4096 sets the context window (reduce to 2048 if you run out of VRAM)# llm = Llama(# model_path=LOCAL_MODEL_PATH,# n_gpu_layers=-1,# n_ctx=4096,# verbose=False# )# # --- HELPER: Download/Load Model ---# def load_remote_model():# """Downloads model from Supabase if not present locally."""# if not os.path.exists(MODEL_FILE):# print(f"βοΈ Downloading {MODEL_FILE} from Supabase Storage...")# try:# with open(MODEL_FILE, 'wb') as f:# res = supabase.storage.from_(BUCKET).download(MODEL_FILE)# f.write(res)# except Exception as e:# print(f"β Error downloading model: {e}")# return None# print(f"Loading BERTopic model from {MODEL_FILE}...")# try:# return BERTopic.load(MODEL_FILE)# except Exception as e:# print(f"β Error loading pickle: {e}")# return None# def get_safe_topic_ids(model, nsfw_set):# """# Returns a list of Topic IDs that do NOT contain any blocklisted words# in their top 10 keywords.# """# safe_ids = []# unsafe_ids = []# all_topics = model.get_topics()# print(f"Scanning {len(all_topics)} topics for NSFW content...")# for topic_id, words_with_scores in all_topics.items():# topic_words = {word for word, score in words_with_scores}# intersection = topic_words.intersection(nsfw_set)# if intersection:# unsafe_ids.append(topic_id)# else:# safe_ids.append(topic_id)# print(f"\nResult: {len(safe_ids)} Safe, {len(unsafe_ids)} Unsafe.")# return safe_ids# def generate_labels():# # 1. Load Model# topic_model = load_remote_model()# if topic_model is None:# return# # 2. Get Info# info = topic_model.get_topic_info()# print(f"Found {len(info)} topics.")# safe_topics = get_safe_topic_ids(topic_model, nsfw_set=NSFW_KEYWORDS)# labels_map = {}# print("running local generation with Llama 3.1...")# for index, row in tqdm(info.iterrows(), total=len(info)):# topic_id = row['Topic']# # Skip unsafe topics# if topic_id not in safe_topics:# labels_map[f"Topic_{topic_id}"] = "NSFW Content"# continue# # Handle Outliers# if topic_id == -1:# labels_map[f"Topic_{topic_id}"] = "Outliers / Noise"# continue# # 3. Extract Data# keywords = row['Representation']# docs = row['Representative_Docs']# if not isinstance(docs, list) or len(docs) == 0:# try:# res = supabase.table("posts") \# .select("content") \# .eq("cluster_id", int(topic_id)) \# .limit(3) \# .execute()# docs = [r['content'] for r in res.data]# except Exception:# docs = []# if not docs:# docs_text = "(No examples available)"# else:# docs_text = "\n".join([f"- {str(d)[:200]}..." for d in docs[:3]])# # 4. Construct Prompt# # Llama 3.1 Instruct works best with a specific chat format.# # We make it concise to save context window space.# system_msg = "You are a helpful classifier. Create a label (max 5 words) for the topic described by the keywords and posts. Do not use quotes."# user_msg = f"""# Keywords: {', '.join(keywords[:10])}# Posts:# {docs_text}# Label:# """# # 5. Call Local LLM# try:# response = llm.create_chat_completion(# messages=[# {"role": "system", "content": system_msg},# {"role": "user", "content": user_msg}# ],# temperature=0.3, # Low temperature for consistency# max_tokens=20, # We only need a short label# )# label = response['choices'][0]['message']['content'].strip().replace('"', '')# labels_map[f"Topic_{topic_id}"] = label# except Exception as e:# print(f"\n β Error on Topic {topic_id}: {e}")# # Fallback# fallback = ", ".join(keywords[:3]).title()# labels_map[f"Topic_{topic_id}"] = fallback# # 6. Save locally# with open(OUTPUT_JSON, "w") as f:# json.dump(labels_map, f, indent=2)# # 7. Upload to Supabase# print(f"βοΈ Uploading {OUTPUT_JSON} to Supabase...")# with open(OUTPUT_JSON, "rb") as f:# supabase.storage.from_(BUCKET).upload(# OUTPUT_JSON,# f,# file_options={"x-upsert": "true"}# )# print(f"Success! Labels saved and uploaded.")# if __name__ == "__main__":# generate_labels()import osimport jsonimport time123import osimport jsonimport time
476 unmodified lines477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531476 unmodified lines1. **Select a Topic** to see who is talking about it.2. **Select a User** to see what they are interested in.3. **Use the Sliders** inside the graph to filter noise and explore connections.""")# def generate_html(center_node, max_neighbors, depth):# # 1. Python BFS (Pre-Filtering)# nodes_to_include = {center_node}# edges_to_include = []# l1_neighbors = list(G.neighbors(center_node))# # --- CHANGE 1: Sort by Recency (last_timestamp) ---# l1_neighbors.sort(key=lambda x: G[center_node][x].get('last_timestamp', 0), reverse=True)# l1_neighbors = l1_neighbors[:MAX_PRE_FETCH]# for n1 in l1_neighbors:# if not is_node_allowed(n1): continue# nodes_to_include.add(n1)# edges_to_include.append((center_node, n1))# l2_neighbors = list(G.neighbors(n1))# # --- CHANGE 2: Sort Level 2 by Recency as well ---# l2_neighbors.sort(key=lambda x: G[n1][x].get('last_timestamp', 0), reverse=True)# l2_neighbors = l2_neighbors[:MAX_PRE_FETCH]# for n2 in l2_neighbors:# if not is_node_allowed(n2): continue# if n2 != center_node:# nodes_to_include.add(n2)# edges_to_include.append((n1, n2))# # ... rest of the function remains the same ...# # ... inside the "Metrics & Analysis" section ...# # Column 1: Direct Neighbors# with col1:# st.markdown("#### π Top Connections (Newest First)") # Updated Title# neighbors = list(G.neighbors(target_node))# # --- CHANGE 3: Sort Table by Recency ---# neighbors.sort(key=lambda x: G[target_node][x].get('last_timestamp', 0), reverse=True)# # Convert to DataFrame# conn_data = []# for n in neighbors[:15]:# # ... rest of loop ...476 unmodified lines477478479480476 unmodified lines1. **Select a Topic** to see who is talking about it.2. **Select a User** to see what they are interested in.3. **Use the Sliders** inside the graph to filter noise and explore connections.""")
app.py+63-60
modelUpdating/cacheTheGraph_4.py+1-86
modelUpdating/naturalLanguageTopics_3.py-405
pages/TopicWeb.py+1-52