File size: 13,625 Bytes
52e61df
c4e553b
 
52e61df
 
 
 
 
c4e553b
 
52e61df
 
 
c4e553b
52e61df
 
c4e553b
52e61df
 
 
 
 
 
c4e553b
52e61df
 
 
 
c4e553b
52e61df
 
c4e553b
 
 
 
 
52e61df
 
 
c4e553b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e61df
 
 
 
 
 
 
c4e553b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e61df
 
 
 
c4e553b
 
 
52e61df
c4e553b
52e61df
 
 
c4e553b
 
52e61df
 
 
 
 
c4e553b
 
 
52e61df
c4e553b
 
 
 
 
 
 
52e61df
 
 
 
c4e553b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e61df
 
 
c4e553b
 
52e61df
 
c4e553b
52e61df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e553b
 
 
52e61df
c4e553b
52e61df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e553b
 
52e61df
c4e553b
52e61df
 
c4e553b
 
52e61df
 
 
 
 
1845bc1
52e61df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e553b
 
 
 
 
52e61df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""
LifeAdmin Coach UI - AI Chatbot Assistant with Tool Access
Provides conversational interface with RAG context, memory, and tool calling
"""

import gradio as gr
import asyncio
from datetime import datetime
import json
import os


def create_lifeadmin_coach_ui(agent):
    """Create LifeAdmin Coach chatbot interface with tool access"""
    
    async def chat_with_coach(message, history):
        """Process chat message with RAG, memory, and tool execution"""
        if not message or not message.strip():
            return history, ""
        
        try:
            # Get relevant context from RAG
            rag_context = ""
            uploaded_files = []
            try:
                rag_results = await agent.rag_engine.search(message, k=3)
                if rag_results:
                    rag_context = "\n".join([
                        f"- {doc.get('metadata', {}).get('filename', 'Unknown')}: {doc.get('text', '')[:200]}..." 
                        for doc in rag_results
                    ])
                    # Get list of uploaded files
                    for doc in rag_results:
                        filename = doc.get('metadata', {}).get('filename')
                        if filename and filename not in uploaded_files:
                            uploaded_files.append(filename)
            except Exception:
                pass
            
            # Check for files in upload directory
            upload_dir = "data/uploads"
            if os.path.exists(upload_dir):
                try:
                    files_in_dir = [f for f in os.listdir(upload_dir) if os.path.isfile(os.path.join(upload_dir, f))]
                    for f in files_in_dir:
                        if f not in uploaded_files:
                            uploaded_files.append(f)
                except Exception:
                    pass
            
            # Check for calendar events
            calendar_files = []
            output_dir = "data/outputs"
            if os.path.exists(output_dir):
                try:
                    calendar_files = [f for f in os.listdir(output_dir) if f.endswith('.ics')]
                except Exception:
                    pass
            
            # Check for drafted emails
            email_files = []
            if os.path.exists(output_dir):
                try:
                    email_files = [f for f in os.listdir(output_dir) if 'email' in f.lower() and (f.endswith('.txt') or f.endswith('.html'))]
                except Exception:
                    pass
            
            # Get relevant memories
            memory_context = ""
            try:
                memory_context = agent.memory.get_relevant_memories(message, k=3)
            except Exception:
                pass
            
            # Detect if user is asking about specific tools/actions
            message_lower = message.lower()
            needs_tool = False
            tool_action = None
            
            # Detect tool requests
            if any(word in message_lower for word in ['summarize', 'summary', 'key points', 'main points']):
                if uploaded_files:
                    needs_tool = True
                    tool_action = "summarize"
            elif any(word in message_lower for word in ['extract text', 'read', 'show content']):
                if uploaded_files:
                    needs_tool = True
                    tool_action = "extract"
            elif any(word in message_lower for word in ['draft email', 'write email', 'compose email']):
                needs_tool = True
                tool_action = "draft_email"
            elif any(word in message_lower for word in ['calendar', 'events', 'schedule', 'meeting']):
                needs_tool = True
                tool_action = "calendar"
            elif any(word in message_lower for word in ['uploaded', 'files', 'documents']):
                tool_action = "list_files"
            
            # Build enhanced prompt
            system_context = f"""You are LifeAdmin Coach, a helpful AI assistant that helps users manage their life admin tasks.

You have access to:
- User's uploaded documents: {len(uploaded_files)} files
- Calendar events: {len(calendar_files)} events
- Drafted emails: {len(email_files)} drafts
- Past conversation history (via memory)
- Various automation tools

Your role:
- Answer questions about uploaded documents
- Provide information about calendar events and emails
- Provide advice on life admin tasks
- Help organize and plan tasks
- Be friendly, concise, and actionable

"""
            
            if uploaded_files:
                system_context += f"\nπŸ“‚ **Uploaded Files:**\n" + "\n".join([f"  β€’ {f}" for f in uploaded_files[:10]]) + "\n"
            
            if rag_context:
                system_context += f"\nπŸ“š **Document Content:**\n{rag_context}\n"
            
            if calendar_files:
                system_context += f"\nπŸ“… **Calendar Events:**\n" + "\n".join([f"  β€’ {f}" for f in calendar_files[:5]]) + "\n"
            
            if email_files:
                system_context += f"\nβœ‰οΈ **Drafted Emails:**\n" + "\n".join([f"  β€’ {f}" for f in email_files[:5]]) + "\n"
            
            if memory_context:
                system_context += f"\nπŸ’­ **Past Context:**\n{memory_context}\n"
            
            # Execute tools if needed
            tool_result = ""
            if needs_tool and tool_action:
                if tool_action == "summarize" and uploaded_files:
                    # Use the first PDF file
                    pdf_file = next((f for f in uploaded_files if f.lower().endswith('.pdf')), uploaded_files[0])
                    try:
                        from tools import summarize_pdf
                        result = await summarize_pdf(f"data/uploads/{pdf_file}", max_length=300)
                        if isinstance(result, dict) and 'summary' in result:
                            tool_result = f"\n**Summary of {pdf_file}:**\n{result['summary']}\n"
                    except Exception as e:
                        tool_result = f"\nCouldn't summarize: {str(e)}\n"
                
                elif tool_action == "extract" and uploaded_files:
                    # Extract text from first file
                    file = uploaded_files[0]
                    try:
                        if file.lower().endswith('.pdf'):
                            from utils.pdf_utils import extract_text_from_pdf
                            text = extract_text_from_pdf(f"data/uploads/{file}")
                            tool_result = f"\n**Text from {file}:**\n{text[:500]}...\n"
                        elif file.lower().endswith(('.png', '.jpg', '.jpeg')):
                            from tools import extract_text_ocr
                            result = await extract_text_ocr(f"data/uploads/{file}", 'en')
                            tool_result = f"\n**Text from {file}:**\n{result.get('text', '')[:500]}...\n"
                    except Exception as e:
                        tool_result = f"\nCouldn't extract text: {str(e)}\n"
                
                elif tool_action == "calendar":
                    if calendar_files:
                        tool_result = f"\n**Calendar Events:**\n" + "\n".join([f"  β€’ {f}" for f in calendar_files]) + "\n"
                    else:
                        tool_result = "\nNo calendar events created yet. You can create events in the Manual Dashboard.\n"
            
            # Build full prompt
            full_prompt = f"""{system_context}

{tool_result}

**User Question:** {message}

Provide a helpful, concise response. Reference the documents and information available above.
"""
            
            # Get LLM response
            from utils.llm_utils import get_llm_response
            response = await get_llm_response(full_prompt, temperature=0.7, max_tokens=1000)
            
            # Save to memory
            try:
                agent.memory.add_memory(
                    content=f"User: {message}\nCoach: {response}",
                    memory_type='conversation',
                    metadata={'timestamp': datetime.now().isoformat()},
                    importance=5
                )
            except Exception:
                pass
            
            # Update history
            history.append({"role": "user", "content": message})
            history.append({"role": "assistant", "content": response})
            
            return history, ""
            
        except Exception as e:
            import traceback
            error_msg = f"⚠️ Error: {str(e)}\n\n{traceback.format_exc()}"
            print(error_msg)
            history.append({"role": "user", "content": message})
            history.append({"role": "assistant", "content": f"⚠️ Sorry, I encountered an error: {str(e)}"})
            return history, ""
    
    async def quick_action(action_type, history):
        """Handle quick action buttons"""
        actions = {
            "summarize_docs": "Can you summarize all the documents I've uploaded?",
            "list_tasks": "What tasks or action items can you find in my documents?",
            "deadlines": "Are there any deadlines or important dates I should know about?",
            "help": "What can you help me with?"
        }
        
        message = actions.get(action_type, "")
        if message:
            return await chat_with_coach(message, history)
        return history, ""
    
    def clear_chat():
        """Clear chat history"""
        return [], ""
    
    # Build UI
    with gr.Column():
        gr.Markdown("""
        ## πŸ€– LifeAdmin Coach
        
        Your AI assistant for managing life admin tasks. Ask questions about your documents,
        get advice on tasks, or chat about anything related to organizing your life!
        
        **I can help you with:**
        - Answering questions about uploaded documents (from Manual Dashboard)
        - Summarizing PDFs and extracting key information
        - Finding deadlines and important dates
        - Checking your calendar events and drafted emails
        - Organizing tasks and creating plans
        - General life admin advice
        
        **πŸ’‘ Tip:** Upload files in the Manual Dashboard first, then ask me questions here!
        """)
        
        # Chat interface
        chatbot = gr.Chatbot(
            label="πŸ’¬ Chat with LifeAdmin Coach",
            height=500
        )
        
        # Input area
        with gr.Row():
            msg_input = gr.Textbox(
                label="",
                placeholder="Ask me anything about your documents or life admin tasks...",
                scale=4,
                lines=2
            )
            send_btn = gr.Button("Send", variant="primary", scale=1)
        
        # Quick action buttons
        with gr.Row():
            gr.Markdown("**Quick Actions:**")
        
        with gr.Row():
            summarize_btn = gr.Button("πŸ“„ Summarize Docs", size="sm")
            tasks_btn = gr.Button("βœ… List Tasks", size="sm")
            deadlines_btn = gr.Button("πŸ“… Find Deadlines", size="sm")
            help_btn = gr.Button("❓ Help", size="sm")
            clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", size="sm", variant="stop")
        
        # Examples
        with gr.Accordion("πŸ’‘ Example Questions", open=False):
            gr.Examples(
                examples=[
                    "What documents have I uploaded?",
                    "Summarize my PDF document",
                    "What calendar events do I have?",
                    "Have I drafted any emails?",
                    "Extract text from my uploaded image",
                    "What are the key points from my documents?",
                    "Find all phone numbers and emails in my documents",
                    "When is my next deadline?",
                ],
                inputs=msg_input
            )
        
        # Event handlers
        def chat_wrapper(message, history):
            """Sync wrapper for async chat function"""
            return asyncio.run(chat_with_coach(message, history))
        
        def quick_action_wrapper(action_type, history):
            """Sync wrapper for quick actions"""
            return asyncio.run(quick_action(action_type, history))
        
        # Connect events
        msg_input.submit(
            fn=chat_wrapper,
            inputs=[msg_input, chatbot],
            outputs=[chatbot, msg_input]
        )
        
        send_btn.click(
            fn=chat_wrapper,
            inputs=[msg_input, chatbot],
            outputs=[chatbot, msg_input]
        )
        
        summarize_btn.click(
            fn=lambda h: quick_action_wrapper("summarize_docs", h),
            inputs=[chatbot],
            outputs=[chatbot, msg_input]
        )
        
        tasks_btn.click(
            fn=lambda h: quick_action_wrapper("list_tasks", h),
            inputs=[chatbot],
            outputs=[chatbot, msg_input]
        )
        
        deadlines_btn.click(
            fn=lambda h: quick_action_wrapper("deadlines", h),
            inputs=[chatbot],
            outputs=[chatbot, msg_input]
        )
        
        help_btn.click(
            fn=lambda h: quick_action_wrapper("help", h),
            inputs=[chatbot],
            outputs=[chatbot, msg_input]
        )
        
        clear_btn.click(
            fn=clear_chat,
            outputs=[chatbot, msg_input]
        )
    
    return gr.Column()