erdemyavuz commited on
Commit
3dbf4e8
·
verified ·
1 Parent(s): 99a316d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -0
app.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import datetime
3
+ import requests
4
+ from streamlit_extras.add_vertical_space import add_vertical_space
5
+ from streamlit_lottie import st_lottie
6
+ import streamlit.components.v1 as components
7
+
8
+ # Senin lokal servislerini doğrudan içeri aktarıyoruz (FastAPI veya Render'a gerek yok!)
9
+ from app.services.nlp_triplet import extract_triplets_from_text
10
+ from app.services.memory_engine import group_by_author, count_predicates, most_common_subjects
11
+ from app.services.graph_builder import build_graph_from_triplets
12
+ from app.services.graph_visualizer import visualize_graph
13
+
14
+ st.set_page_config(page_title="AI Memory Graph", layout="wide", page_icon="🧠")
15
+
16
+ # Lottie Animasyonu Yükleme
17
+ def load_lottieurl(url: str):
18
+ r = requests.get(url)
19
+ if r.status_code != 200: return None
20
+ return r.json()
21
+
22
+ lottie_ai = load_lottieurl("https://assets9.lottiefiles.com/packages/lf20_touohxv0.json")
23
+
24
+ col1, col2 = st.columns([4, 1])
25
+ with col1:
26
+ st.title("🧠 AI Memory Graph")
27
+ st.markdown("A visual way to extract and understand multi-user chat memories using NLP + Graphs.")
28
+ with col2:
29
+ if lottie_ai:
30
+ st_lottie(lottie_ai, height=100, key="ai")
31
+
32
+ add_vertical_space(1)
33
+
34
+ # Session State Tanımlamaları
35
+ if "messages" not in st.session_state:
36
+ st.session_state["messages"] = []
37
+ if "triplets" not in st.session_state:
38
+ st.session_state["triplets"] = []
39
+
40
+ # --- SOHBET GİRİŞ ALANI ---
41
+ st.subheader("💬 Add Chat Messages")
42
+ with 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öster
59
+ if 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 İşlemi
69
+ 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_triplets
81
+ st.success(f"Extracted {len(all_triplets)} triplets!")
82
+ st.json(all_triplets)
83
+
84
+ # 2. Hafıza Özeti İşlemi
85
+ 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 İşlemi
100
+ 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ştur
107
+ 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öm
113
+ 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
+ # Footer
122
+ add_vertical_space(3)
123
+ st.markdown("---")
124
+ st.caption("Developed by Erdem Yavuz Hacisoftaoglu | Powered by SpaCy, NetworkX & Streamlit")