Maheen001 commited on
Commit
c4e553b
·
verified ·
1 Parent(s): 1845bc1

Update ui/lifeadmin_coach_ui.py

Browse files
Files changed (1) hide show
  1. ui/lifeadmin_coach_ui.py +132 -18
ui/lifeadmin_coach_ui.py CHANGED
@@ -1,34 +1,70 @@
1
  """
2
- LifeAdmin Coach UI - AI Chatbot Assistant
3
- Provides conversational interface with RAG context and memory
4
  """
5
 
6
  import gradio as gr
7
  import asyncio
8
  from datetime import datetime
 
 
9
 
10
 
11
  def create_lifeadmin_coach_ui(agent):
12
- """Create LifeAdmin Coach chatbot interface"""
13
 
14
  async def chat_with_coach(message, history):
15
- """Process chat message with RAG and memory context"""
16
  if not message or not message.strip():
17
  return history, ""
18
 
19
  try:
20
  # Get relevant context from RAG
21
  rag_context = ""
 
22
  try:
23
  rag_results = await agent.rag_engine.search(message, k=3)
24
  if rag_results:
25
  rag_context = "\n".join([
26
- f"- {doc.get('text', '')[:200]}..."
27
  for doc in rag_results
28
  ])
 
 
 
 
 
29
  except Exception:
30
  pass
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  # Get relevant memories
33
  memory_context = ""
34
  try:
@@ -36,34 +72,106 @@ def create_lifeadmin_coach_ui(agent):
36
  except Exception:
37
  pass
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  # Build enhanced prompt
40
  system_context = f"""You are LifeAdmin Coach, a helpful AI assistant that helps users manage their life admin tasks.
41
 
42
  You have access to:
43
- - User's uploaded documents and files (via RAG)
 
 
44
  - Past conversation history (via memory)
45
- - Various tools for task automation
46
 
47
  Your role:
48
  - Answer questions about uploaded documents
49
- - Provide advice on life admin tasks (bills, forms, scheduling, etc.)
 
50
  - Help organize and plan tasks
51
  - Be friendly, concise, and actionable
52
 
53
  """
54
 
 
 
 
55
  if rag_context:
56
- system_context += f"\n📚 **Relevant Documents:**\n{rag_context}\n"
 
 
 
 
 
 
57
 
58
  if memory_context:
59
  system_context += f"\n💭 **Past Context:**\n{memory_context}\n"
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # Build full prompt
62
  full_prompt = f"""{system_context}
63
 
 
 
64
  **User Question:** {message}
65
 
66
- Provide a helpful, concise response. If the user asks about their documents, reference the relevant documents context above.
67
  """
68
 
69
  # Get LLM response
@@ -88,9 +196,11 @@ Provide a helpful, concise response. If the user asks about their documents, ref
88
  return history, ""
89
 
90
  except Exception as e:
91
- error_msg = f"⚠️ Error: {str(e)}"
 
 
92
  history.append({"role": "user", "content": message})
93
- history.append({"role": "assistant", "content": error_msg})
94
  return history, ""
95
 
96
  async def quick_action(action_type, history):
@@ -120,11 +230,14 @@ Provide a helpful, concise response. If the user asks about their documents, ref
120
  get advice on tasks, or chat about anything related to organizing your life!
121
 
122
  **I can help you with:**
123
- - Answering questions about uploaded documents
 
124
  - Finding deadlines and important dates
 
125
  - Organizing tasks and creating plans
126
- - Drafting emails and messages
127
  - General life admin advice
 
 
128
  """)
129
 
130
  # Chat interface
@@ -159,10 +272,11 @@ Provide a helpful, concise response. If the user asks about their documents, ref
159
  gr.Examples(
160
  examples=[
161
  "What documents have I uploaded?",
162
- "Are there any bills I need to pay?",
163
- "Help me organize my tasks for this week",
164
- "Draft an email to follow up on my membership application",
165
- "What are the key points from my PDF?",
 
166
  "Find all phone numbers and emails in my documents",
167
  "When is my next deadline?",
168
  ],
 
1
  """
2
+ LifeAdmin Coach UI - AI Chatbot Assistant with Tool Access
3
+ Provides conversational interface with RAG context, memory, and tool calling
4
  """
5
 
6
  import gradio as gr
7
  import asyncio
8
  from datetime import datetime
9
+ import json
10
+ import os
11
 
12
 
13
  def create_lifeadmin_coach_ui(agent):
14
+ """Create LifeAdmin Coach chatbot interface with tool access"""
15
 
16
  async def chat_with_coach(message, history):
17
+ """Process chat message with RAG, memory, and tool execution"""
18
  if not message or not message.strip():
19
  return history, ""
20
 
21
  try:
22
  # Get relevant context from RAG
23
  rag_context = ""
24
+ uploaded_files = []
25
  try:
26
  rag_results = await agent.rag_engine.search(message, k=3)
27
  if rag_results:
28
  rag_context = "\n".join([
29
+ f"- {doc.get('metadata', {}).get('filename', 'Unknown')}: {doc.get('text', '')[:200]}..."
30
  for doc in rag_results
31
  ])
32
+ # Get list of uploaded files
33
+ for doc in rag_results:
34
+ filename = doc.get('metadata', {}).get('filename')
35
+ if filename and filename not in uploaded_files:
36
+ uploaded_files.append(filename)
37
  except Exception:
38
  pass
39
 
40
+ # Check for files in upload directory
41
+ upload_dir = "data/uploads"
42
+ if os.path.exists(upload_dir):
43
+ try:
44
+ files_in_dir = [f for f in os.listdir(upload_dir) if os.path.isfile(os.path.join(upload_dir, f))]
45
+ for f in files_in_dir:
46
+ if f not in uploaded_files:
47
+ uploaded_files.append(f)
48
+ except Exception:
49
+ pass
50
+
51
+ # Check for calendar events
52
+ calendar_files = []
53
+ output_dir = "data/outputs"
54
+ if os.path.exists(output_dir):
55
+ try:
56
+ calendar_files = [f for f in os.listdir(output_dir) if f.endswith('.ics')]
57
+ except Exception:
58
+ pass
59
+
60
+ # Check for drafted emails
61
+ email_files = []
62
+ if os.path.exists(output_dir):
63
+ try:
64
+ email_files = [f for f in os.listdir(output_dir) if 'email' in f.lower() and (f.endswith('.txt') or f.endswith('.html'))]
65
+ except Exception:
66
+ pass
67
+
68
  # Get relevant memories
69
  memory_context = ""
70
  try:
 
72
  except Exception:
73
  pass
74
 
75
+ # Detect if user is asking about specific tools/actions
76
+ message_lower = message.lower()
77
+ needs_tool = False
78
+ tool_action = None
79
+
80
+ # Detect tool requests
81
+ if any(word in message_lower for word in ['summarize', 'summary', 'key points', 'main points']):
82
+ if uploaded_files:
83
+ needs_tool = True
84
+ tool_action = "summarize"
85
+ elif any(word in message_lower for word in ['extract text', 'read', 'show content']):
86
+ if uploaded_files:
87
+ needs_tool = True
88
+ tool_action = "extract"
89
+ elif any(word in message_lower for word in ['draft email', 'write email', 'compose email']):
90
+ needs_tool = True
91
+ tool_action = "draft_email"
92
+ elif any(word in message_lower for word in ['calendar', 'events', 'schedule', 'meeting']):
93
+ needs_tool = True
94
+ tool_action = "calendar"
95
+ elif any(word in message_lower for word in ['uploaded', 'files', 'documents']):
96
+ tool_action = "list_files"
97
+
98
  # Build enhanced prompt
99
  system_context = f"""You are LifeAdmin Coach, a helpful AI assistant that helps users manage their life admin tasks.
100
 
101
  You have access to:
102
+ - User's uploaded documents: {len(uploaded_files)} files
103
+ - Calendar events: {len(calendar_files)} events
104
+ - Drafted emails: {len(email_files)} drafts
105
  - Past conversation history (via memory)
106
+ - Various automation tools
107
 
108
  Your role:
109
  - Answer questions about uploaded documents
110
+ - Provide information about calendar events and emails
111
+ - Provide advice on life admin tasks
112
  - Help organize and plan tasks
113
  - Be friendly, concise, and actionable
114
 
115
  """
116
 
117
+ if uploaded_files:
118
+ system_context += f"\n📂 **Uploaded Files:**\n" + "\n".join([f" • {f}" for f in uploaded_files[:10]]) + "\n"
119
+
120
  if rag_context:
121
+ system_context += f"\n📚 **Document Content:**\n{rag_context}\n"
122
+
123
+ if calendar_files:
124
+ system_context += f"\n📅 **Calendar Events:**\n" + "\n".join([f" • {f}" for f in calendar_files[:5]]) + "\n"
125
+
126
+ if email_files:
127
+ system_context += f"\n✉️ **Drafted Emails:**\n" + "\n".join([f" • {f}" for f in email_files[:5]]) + "\n"
128
 
129
  if memory_context:
130
  system_context += f"\n💭 **Past Context:**\n{memory_context}\n"
131
 
132
+ # Execute tools if needed
133
+ tool_result = ""
134
+ if needs_tool and tool_action:
135
+ if tool_action == "summarize" and uploaded_files:
136
+ # Use the first PDF file
137
+ pdf_file = next((f for f in uploaded_files if f.lower().endswith('.pdf')), uploaded_files[0])
138
+ try:
139
+ from tools import summarize_pdf
140
+ result = await summarize_pdf(f"data/uploads/{pdf_file}", max_length=300)
141
+ if isinstance(result, dict) and 'summary' in result:
142
+ tool_result = f"\n**Summary of {pdf_file}:**\n{result['summary']}\n"
143
+ except Exception as e:
144
+ tool_result = f"\nCouldn't summarize: {str(e)}\n"
145
+
146
+ elif tool_action == "extract" and uploaded_files:
147
+ # Extract text from first file
148
+ file = uploaded_files[0]
149
+ try:
150
+ if file.lower().endswith('.pdf'):
151
+ from utils.pdf_utils import extract_text_from_pdf
152
+ text = extract_text_from_pdf(f"data/uploads/{file}")
153
+ tool_result = f"\n**Text from {file}:**\n{text[:500]}...\n"
154
+ elif file.lower().endswith(('.png', '.jpg', '.jpeg')):
155
+ from tools import extract_text_ocr
156
+ result = await extract_text_ocr(f"data/uploads/{file}", 'en')
157
+ tool_result = f"\n**Text from {file}:**\n{result.get('text', '')[:500]}...\n"
158
+ except Exception as e:
159
+ tool_result = f"\nCouldn't extract text: {str(e)}\n"
160
+
161
+ elif tool_action == "calendar":
162
+ if calendar_files:
163
+ tool_result = f"\n**Calendar Events:**\n" + "\n".join([f" • {f}" for f in calendar_files]) + "\n"
164
+ else:
165
+ tool_result = "\nNo calendar events created yet. You can create events in the Manual Dashboard.\n"
166
+
167
  # Build full prompt
168
  full_prompt = f"""{system_context}
169
 
170
+ {tool_result}
171
+
172
  **User Question:** {message}
173
 
174
+ Provide a helpful, concise response. Reference the documents and information available above.
175
  """
176
 
177
  # Get LLM response
 
196
  return history, ""
197
 
198
  except Exception as e:
199
+ import traceback
200
+ error_msg = f"⚠️ Error: {str(e)}\n\n{traceback.format_exc()}"
201
+ print(error_msg)
202
  history.append({"role": "user", "content": message})
203
+ history.append({"role": "assistant", "content": f"⚠️ Sorry, I encountered an error: {str(e)}"})
204
  return history, ""
205
 
206
  async def quick_action(action_type, history):
 
230
  get advice on tasks, or chat about anything related to organizing your life!
231
 
232
  **I can help you with:**
233
+ - Answering questions about uploaded documents (from Manual Dashboard)
234
+ - Summarizing PDFs and extracting key information
235
  - Finding deadlines and important dates
236
+ - Checking your calendar events and drafted emails
237
  - Organizing tasks and creating plans
 
238
  - General life admin advice
239
+
240
+ **💡 Tip:** Upload files in the Manual Dashboard first, then ask me questions here!
241
  """)
242
 
243
  # Chat interface
 
272
  gr.Examples(
273
  examples=[
274
  "What documents have I uploaded?",
275
+ "Summarize my PDF document",
276
+ "What calendar events do I have?",
277
+ "Have I drafted any emails?",
278
+ "Extract text from my uploaded image",
279
+ "What are the key points from my documents?",
280
  "Find all phone numbers and emails in my documents",
281
  "When is my next deadline?",
282
  ],