cryogenic22 commited on
Commit
b171d30
·
verified ·
1 Parent(s): e7f2507

Update utils/legal_notebook_interface.py

Browse files
Files changed (1) hide show
  1. utils/legal_notebook_interface.py +83 -80
utils/legal_notebook_interface.py CHANGED
@@ -2,13 +2,14 @@ import streamlit as st
2
  from typing import List, Dict
3
  import datetime
4
 
 
5
  class LegalNotebookInterface:
6
  def __init__(self, case_manager, vector_store, document_processor):
7
  """Initialize the notebook interface with required components."""
8
  self.case_manager = case_manager
9
  self.vector_store = vector_store
10
  self.document_processor = document_processor
11
-
12
  # Initialize session state
13
  if "active_documents" not in st.session_state:
14
  st.session_state.active_documents = []
@@ -20,37 +21,40 @@ class LegalNotebookInterface:
20
  def render(self):
21
  """Render the main notebook interface."""
22
  # Add custom styling
23
- st.markdown("""
24
- <style>
25
- .document-panel {
26
- background-color: #f8f9fa;
27
- border-radius: 10px;
28
- padding: 20px;
29
- margin: 10px;
30
- }
31
- .message {
32
- padding: 15px;
33
- margin: 10px 0;
34
- border-radius: 8px;
35
- }
36
- .user-message {
37
- background-color: #f0f7ff;
38
- border-left: 4px solid #1976d2;
39
- }
40
- .assistant-message {
41
- background-color: #f8f9fa;
42
- border-left: 4px solid #4caf50;
43
- }
44
- .suggestion-chip {
45
- display: inline-block;
46
- padding: 5px 15px;
47
- margin: 5px;
48
- background-color: #e3f2fd;
49
- border-radius: 20px;
50
- cursor: pointer;
51
- }
52
- </style>
53
- """, unsafe_allow_html=True)
 
 
 
54
 
55
  # Create two-column layout
56
  col1, col2 = st.columns([2, 3])
@@ -66,7 +70,7 @@ class LegalNotebookInterface:
66
  def _render_document_panel(self):
67
  """Render the document viewing and management panel."""
68
  st.markdown("### 📚 Documents")
69
-
70
  # Document selection
71
  cases = self.case_manager.get_all_cases()
72
  if not cases:
@@ -78,11 +82,11 @@ class LegalNotebookInterface:
78
  cases,
79
  format_func=lambda x: x['title']
80
  )
81
-
82
  if selected_case:
83
  st.session_state.current_case = selected_case['id']
84
  documents = self.case_manager.list_documents(selected_case['id'])
85
-
86
  if documents:
87
  st.write("#### Available Documents")
88
  for doc in documents:
@@ -97,7 +101,7 @@ class LegalNotebookInterface:
97
  def _render_chat_panel(self):
98
  """Render the chat and analysis interface."""
99
  st.markdown("### 💬 Document Analysis")
100
-
101
  if not st.session_state.current_case:
102
  st.info("Please select a case from the left panel to start analysis.")
103
  return
@@ -105,49 +109,51 @@ class LegalNotebookInterface:
105
  # Display chat history
106
  for message in st.session_state.chat_history:
107
  message_class = "user-message" if message["role"] == "user" else "assistant-message"
108
- st.markdown(f"""
 
109
  <div class="message {message_class}">
110
  {message["content"]}
111
  </div>
112
- """, unsafe_allow_html=True)
 
 
113
 
114
  # Chat input
115
  if prompt := st.chat_input("Ask about your documents..."):
116
  self._handle_chat_input(prompt)
117
 
118
  def _handle_chat_input(self, prompt: str):
119
- """Process user input and generate response."""
120
- if not st.session_state.current_case:
121
- st.error("Please select a case first.")
122
- return
123
-
124
- # Add user message
125
- st.session_state.chat_history.append({
126
- "role": "user",
127
- "content": prompt,
128
- "timestamp": datetime.datetime.now().isoformat()
129
- })
130
-
131
- try:
132
- # Get documents from current case
133
- documents = self.case_manager.list_documents(st.session_state.current_case)
134
- if not documents:
135
- st.error("No documents available for analysis.")
136
  return
137
 
138
- # Get relevant chunks
 
 
 
 
 
 
139
  try:
 
 
 
 
 
 
 
140
  results = self.vector_store.similarity_search(
141
  query=prompt,
142
  k=3 # Number of chunks to retrieve
143
  )
144
-
145
  if not results:
146
  response = "I couldn't find relevant information in the documents. Please try rephrasing your question."
147
  else:
148
  # Generate response from results
149
  response = self._generate_response(prompt, results)
150
-
151
  # Add response to chat history
152
  st.session_state.chat_history.append({
153
  "role": "assistant",
@@ -163,39 +169,36 @@ class LegalNotebookInterface:
163
  "timestamp": datetime.datetime.now().isoformat()
164
  })
165
 
166
- except Exception as e:
167
- st.error(f"Error analyzing documents: {str(e)}")
168
-
169
  def _generate_response(self, prompt: str, results: List[Dict]) -> str:
170
- """Generate response based on search results."""
171
- if not results:
172
- return "I couldn't find relevant information in the documents."
173
-
174
- # Format the response with chunks
175
- response = "Based on the documents, here's what I found:\n\n"
176
-
177
- for i, result in enumerate(results, 1):
178
- response += f"**Excerpt {i}**\n"
179
- response += f"{result.get('text', '')[:200]}...\n\n"
180
- if result.get('metadata', {}).get('title'):
181
- response += f"*Source: {result['metadata']['title']}*\n\n"
182
-
183
- response += "\nWould you like me to elaborate on any of these points?"
184
-
185
- return response
186
 
187
  def _show_document_details(self, doc: Dict):
188
  """Show detailed document information."""
189
  st.markdown("#### Document Details")
190
  st.write("**Title:** ", doc['title'])
191
  st.write("**Added:** ", doc.get('added_at', 'Unknown'))
192
-
193
  metadata = doc.get('metadata', {})
194
  if metadata:
195
  st.write("**Document Type:** ", metadata.get('document_type', 'Unknown'))
196
  st.write("**Word Count:** ", metadata.get('word_count', 'Unknown'))
197
-
198
  if 'entities' in metadata:
199
  st.write("**Named Entities:** ")
200
  for entity_type, entities in metadata['entities'].items():
201
- st.write(f"- {entity_type}: {', '.join(entities[:5])}")
 
2
  from typing import List, Dict
3
  import datetime
4
 
5
+
6
  class LegalNotebookInterface:
7
  def __init__(self, case_manager, vector_store, document_processor):
8
  """Initialize the notebook interface with required components."""
9
  self.case_manager = case_manager
10
  self.vector_store = vector_store
11
  self.document_processor = document_processor
12
+
13
  # Initialize session state
14
  if "active_documents" not in st.session_state:
15
  st.session_state.active_documents = []
 
21
  def render(self):
22
  """Render the main notebook interface."""
23
  # Add custom styling
24
+ st.markdown(
25
+ """
26
+ <style>
27
+ .document-panel {
28
+ background-color: #f8f9fa;
29
+ border-radius: 10px;
30
+ padding: 20px;
31
+ margin: 10px;
32
+ }
33
+ .message {
34
+ padding: 15px;
35
+ margin: 10px 0;
36
+ border-radius: 8px;
37
+ }
38
+ .user-message {
39
+ background-color: #f0f7ff;
40
+ border-left: 4px solid #1976d2;
41
+ }
42
+ .assistant-message {
43
+ background-color: #f8f9fa;
44
+ border-left: 4px solid #4caf50;
45
+ }
46
+ .suggestion-chip {
47
+ display: inline-block;
48
+ padding: 5px 15px;
49
+ margin: 5px;
50
+ background-color: #e3f2fd;
51
+ border-radius: 20px;
52
+ cursor: pointer;
53
+ }
54
+ </style>
55
+ """,
56
+ unsafe_allow_html=True,
57
+ )
58
 
59
  # Create two-column layout
60
  col1, col2 = st.columns([2, 3])
 
70
  def _render_document_panel(self):
71
  """Render the document viewing and management panel."""
72
  st.markdown("### 📚 Documents")
73
+
74
  # Document selection
75
  cases = self.case_manager.get_all_cases()
76
  if not cases:
 
82
  cases,
83
  format_func=lambda x: x['title']
84
  )
85
+
86
  if selected_case:
87
  st.session_state.current_case = selected_case['id']
88
  documents = self.case_manager.list_documents(selected_case['id'])
89
+
90
  if documents:
91
  st.write("#### Available Documents")
92
  for doc in documents:
 
101
  def _render_chat_panel(self):
102
  """Render the chat and analysis interface."""
103
  st.markdown("### 💬 Document Analysis")
104
+
105
  if not st.session_state.current_case:
106
  st.info("Please select a case from the left panel to start analysis.")
107
  return
 
109
  # Display chat history
110
  for message in st.session_state.chat_history:
111
  message_class = "user-message" if message["role"] == "user" else "assistant-message"
112
+ st.markdown(
113
+ f"""
114
  <div class="message {message_class}">
115
  {message["content"]}
116
  </div>
117
+ """,
118
+ unsafe_allow_html=True,
119
+ )
120
 
121
  # Chat input
122
  if prompt := st.chat_input("Ask about your documents..."):
123
  self._handle_chat_input(prompt)
124
 
125
  def _handle_chat_input(self, prompt: str):
126
+ """Process user input and generate response."""
127
+ if not st.session_state.current_case:
128
+ st.error("Please select a case first.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  return
130
 
131
+ # Add user message
132
+ st.session_state.chat_history.append({
133
+ "role": "user",
134
+ "content": prompt,
135
+ "timestamp": datetime.datetime.now().isoformat()
136
+ })
137
+
138
  try:
139
+ # Get documents from current case
140
+ documents = self.case_manager.list_documents(st.session_state.current_case)
141
+ if not documents:
142
+ st.error("No documents available for analysis.")
143
+ return
144
+
145
+ # Get relevant chunks
146
  results = self.vector_store.similarity_search(
147
  query=prompt,
148
  k=3 # Number of chunks to retrieve
149
  )
150
+
151
  if not results:
152
  response = "I couldn't find relevant information in the documents. Please try rephrasing your question."
153
  else:
154
  # Generate response from results
155
  response = self._generate_response(prompt, results)
156
+
157
  # Add response to chat history
158
  st.session_state.chat_history.append({
159
  "role": "assistant",
 
169
  "timestamp": datetime.datetime.now().isoformat()
170
  })
171
 
 
 
 
172
  def _generate_response(self, prompt: str, results: List[Dict]) -> str:
173
+ """Generate response based on search results."""
174
+ if not results:
175
+ return "I couldn't find relevant information in the documents."
176
+
177
+ # Format the response with chunks
178
+ response = "Based on the documents, here's what I found:\n\n"
179
+
180
+ for i, result in enumerate(results, 1):
181
+ response += f"**Excerpt {i}**\n"
182
+ response += f"{result.get('text', '')[:200]}...\n\n"
183
+ if result.get('metadata', {}).get('title'):
184
+ response += f"*Source: {result['metadata']['title']}*\n\n"
185
+
186
+ response += "\nWould you like me to elaborate on any of these points?"
187
+
188
+ return response
189
 
190
  def _show_document_details(self, doc: Dict):
191
  """Show detailed document information."""
192
  st.markdown("#### Document Details")
193
  st.write("**Title:** ", doc['title'])
194
  st.write("**Added:** ", doc.get('added_at', 'Unknown'))
195
+
196
  metadata = doc.get('metadata', {})
197
  if metadata:
198
  st.write("**Document Type:** ", metadata.get('document_type', 'Unknown'))
199
  st.write("**Word Count:** ", metadata.get('word_count', 'Unknown'))
200
+
201
  if 'entities' in metadata:
202
  st.write("**Named Entities:** ")
203
  for entity_type, entities in metadata['entities'].items():
204
+ st.write(f"- {entity_type}: {', '.join(entities[:5])}")