erdemyavuz/ai_memory_graph
1
1import streamlit as st2import datetime3import requests4from streamlit_extras.add_vertical_space import add_vertical_space5from streamlit_lottie import st_lottie6import streamlit.components.v1 as components7 8# Senin lokal servislerini doğrudan içeri aktarıyoruz (FastAPI veya Render'a gerek yok!)9from app.services.nlp_triplet import extract_triplets_from_text10from app.services.memory_engine import group_by_author, count_predicates, most_common_subjects11from app.services.graph_builder import build_graph_from_triplets12from app.services.graph_visualizer import visualize_graph13 14st.set_page_config(page_title="AI Memory Graph", layout="wide", page_icon="🧠")15 16# Lottie Animasyonu Yükleme17def load_lottieurl(url: str):18 r = requests.get(url)19 if r.status_code != 200: return None20 return r.json()21 22lottie_ai = load_lottieurl("https://assets9.lottiefiles.com/packages/lf20_touohxv0.json")23 24col1, col2 = st.columns([4, 1])25with col1:26 st.title("🧠 AI Memory Graph")27 st.markdown("A visual way to extract and understand multi-user chat memories using NLP + Graphs.")28with col2:29 if lottie_ai:30 st_lottie(lottie_ai, height=100, key="ai")31 32add_vertical_space(1)33 34# Session State Tanımlamaları35if "messages" not in st.session_state:36 st.session_state["messages"] = []37if "triplets" not in st.session_state:38 st.session_state["triplets"] = []39 40# --- SOHBET GİRİŞ ALANI ---41st.subheader("💬 Add Chat Messages")42with st.form("message_form", clear_on_submit=True):43 col_sender, col_msg = st.columns([1, 3])44 with col_sender:45 sender = st.text_input("Sender", placeholder="e.g. Erdem")46 with col_msg:47 text = st.text_input("Message", placeholder="e.g. I recommend using FastAPI for the backend.")48 49 submitted = st.form_submit_button("➕ Add Message")50 if submitted and sender and text:51 st.session_state["messages"].append({52 "sender": sender,53 "text": text,54 "timestamp": datetime.datetime.utcnow().isoformat()55 })56 st.success(f"Message added for {sender}!")57 58# Eklenen mesajları göster59if st.session_state["messages"]:60 with st.expander("📑 View Current Messages", expanded=False):61 st.json(st.session_state["messages"])62 63 add_vertical_space(1)64 65 # --- İŞLEM BUTONLARI ---66 c1, c2, c3 = st.columns(3)67 68 # 1. Triplet Çıkarma İşlemi69 with c1:70 if st.button("🔍 Extract Triplets", use_container_width=True):71 with st.spinner("Analyzing text with SpaCy Transformer..."):72 all_triplets = []73 for msg in st.session_state["messages"]:74 extracted = extract_triplets_from_text(msg["text"])75 for triplet in extracted:76 triplet["timestamp"] = msg["timestamp"]77 triplet["author"] = msg["sender"]78 all_triplets.append(triplet)79 80 st.session_state["triplets"] = all_triplets81 st.success(f"Extracted {len(all_triplets)} triplets!")82 st.json(all_triplets)83 84 # 2. Hafıza Özeti İşlemi85 with c2:86 if st.button("📝 Memory Summary", use_container_width=True):87 if not st.session_state["triplets"]:88 st.warning("Please extract triplets first!")89 else:90 summary = {91 "total_triplets": len(st.session_state["triplets"]),92 "by_user": group_by_author(st.session_state["triplets"]),93 "predicate_counts": count_predicates(st.session_state["triplets"]),94 "common_subjects": most_common_subjects(st.session_state["triplets"])95 }96 st.write("### 📊 Stats")97 st.json(summary)98 99 # 3. Grafik Çizdirme İşlemi100 with c3:101 if st.button("🌐 Show Knowledge Graph", use_container_width=True):102 if not st.session_state["triplets"]:103 st.warning("Please extract triplets first!")104 else:105 with st.spinner("Building and rendering graph..."):106 # Grafiği oluştur107 G = build_graph_from_triplets(st.session_state["triplets"])108 109 # HTML olarak kaydet (webbrowser.open KESİNLİKLE KAPALI OLMALI)110 visualize_graph(G, output_path="memory_graph.html")111 112 # Kaydedilen HTML'i Streamlit içine göm113 try:114 with open("memory_graph.html", "r", encoding="utf-8") as f:115 html_content = f.read()116 st.write("### 🕸️ Graph Visualization")117 components.html(html_content, height=600, scrolling=True)118 except FileNotFoundError:119 st.error("Graph HTML file could not be generated.")120 121# Footer122add_vertical_space(3)123st.markdown("---")124st.caption("Developed by Erdem Yavuz Hacisoftaoglu | Powered by SpaCy, NetworkX & Streamlit")