File size: 13,324 Bytes
1e13436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
"""
Manual Dashboard UI - Visual tool interface
"""

import gradio as gr
import asyncio
from pathlib import Path
from typing import List
import json


def create_manual_dashboard(agent):
    """Create manual dashboard interface"""
    
    # State for uploaded files
    uploaded_files_state = gr.State([])
    
    with gr.Row():
        # Left sidebar - File upload and management
        with gr.Column(scale=1):
            gr.Markdown("### πŸ“ File Manager")
            
            file_upload = gr.File(
                label="Upload Files",
                file_count="multiple",
                file_types=[".pdf", ".png", ".jpg", ".jpeg", ".docx", ".txt", ".csv"]
            )
            
            files_list = gr.Textbox(
                label="Uploaded Files",
                placeholder="No files uploaded yet",
                interactive=False,
                lines=5
            )
            
            gr.Markdown("---")
            gr.Markdown("### πŸ”§ Quick Actions")
            
            with gr.Group():
                ocr_btn = gr.Button("πŸ” Extract Text (OCR)", variant="secondary", size="sm")
                summarize_btn = gr.Button("πŸ“ Summarize Document", variant="secondary", size="sm")
                metadata_btn = gr.Button("πŸ“Š Extract Metadata", variant="secondary", size="sm")
                calendar_btn = gr.Button("πŸ“… Create Calendar Event", variant="secondary", size="sm")
                email_btn = gr.Button("βœ‰οΈ Draft Email", variant="secondary", size="sm")
                organize_btn = gr.Button("πŸ—‚οΈ Organize Files", variant="secondary", size="sm")
        
        # Main content area
        with gr.Column(scale=2):
            gr.Markdown("### 🎯 Tool Operations")
            
            # Tabbed interface for different tools
            with gr.Tabs():
                # OCR Tool
                with gr.Tab("πŸ” OCR"):
                    with gr.Row():
                        ocr_file_select = gr.Dropdown(
                            label="Select File",
                            choices=[],
                            interactive=True
                        )
                        ocr_language = gr.Dropdown(
                            label="Language",
                            choices=["en", "es", "fr", "de", "zh"],
                            value="en"
                        )
                    
                    ocr_execute_btn = gr.Button("Extract Text", variant="primary")
                    
                    ocr_output = gr.Textbox(
                        label="Extracted Text",
                        lines=10,
                        placeholder="Text will appear here..."
                    )
                    
                    ocr_confidence = gr.Textbox(label="Confidence Score")
                
                # PDF Summarization Tool
                with gr.Tab("πŸ“ Summarize"):
                    pdf_file_select = gr.Dropdown(
                        label="Select PDF",
                        choices=[],
                        interactive=True
                    )
                    
                    summary_length = gr.Slider(
                        label="Summary Length (words)",
                        minimum=100,
                        maximum=1000,
                        value=300,
                        step=50
                    )
                    
                    summarize_execute_btn = gr.Button("Generate Summary", variant="primary")
                    
                    summary_output = gr.Textbox(
                        label="Summary",
                        lines=10,
                        placeholder="Summary will appear here..."
                    )
                    
                    pdf_metadata = gr.JSON(label="Document Metadata")
                
                # Calendar Tool
                with gr.Tab("πŸ“… Calendar"):
                    with gr.Row():
                        event_title = gr.Textbox(label="Event Title", placeholder="Meeting with team")
                        event_location = gr.Textbox(label="Location (optional)", placeholder="Conference Room A")
                    
                    with gr.Row():
                        event_start = gr.Textbox(
                            label="Start Date/Time",
                            placeholder="2024-12-01 10:00 or Dec 1, 2024 10:00 AM"
                        )
                        event_end = gr.Textbox(
                            label="End Date/Time",
                            placeholder="2024-12-01 11:00"
                        )
                    
                    event_description = gr.Textbox(
                        label="Description",
                        lines=3,
                        placeholder="Event details..."
                    )
                    
                    calendar_execute_btn = gr.Button("Create Event", variant="primary")
                    
                    calendar_output = gr.File(label="Download ICS File")
                    calendar_status = gr.Textbox(label="Status")
                
                # Email Drafting Tool
                with gr.Tab("βœ‰οΈ Email"):
                    with gr.Row():
                        email_recipient = gr.Textbox(label="Recipient", placeholder="john@example.com")
                        email_subject = gr.Textbox(label="Subject", placeholder="Regarding...")
                    
                    email_context = gr.Textbox(
                        label="Context/Purpose",
                        lines=4,
                        placeholder="What should this email be about?"
                    )
                    
                    email_tone = gr.Radio(
                        label="Tone",
                        choices=["professional", "friendly", "formal", "casual"],
                        value="professional"
                    )
                    
                    email_execute_btn = gr.Button("Draft Email", variant="primary")
                    
                    email_output = gr.Textbox(
                        label="Draft Email",
                        lines=10,
                        placeholder="Email draft will appear here..."
                    )
                    
                    email_download = gr.File(label="Download Email Files")
                
                # Form Filler Tool
                with gr.Tab("πŸ“‹ Form Filler"):
                    form_template = gr.File(label="Upload Form Template (.docx or .xlsx)")
                    
                    form_data = gr.Textbox(
                        label="Form Data (JSON)",
                        lines=8,
                        placeholder='{\n  "name": "John Doe",\n  "email": "john@example.com",\n  "date": "2024-12-01"\n}',
                        value='{}'
                    )
                    
                    form_execute_btn = gr.Button("Fill Form", variant="primary")
                    
                    form_output = gr.File(label="Download Filled Form")
                    form_status = gr.Textbox(label="Status")
                
                # File Organizer Tool
                with gr.Tab("πŸ—‚οΈ Organize"):
                    organize_strategy = gr.Radio(
                        label="Organization Strategy",
                        choices=["by_type", "by_date", "by_size"],
                        value="by_type"
                    )
                    
                    organize_execute_btn = gr.Button("Organize Files", variant="primary")
                    
                    organize_output = gr.JSON(label="Organization Results")
    
    # Event handlers
    async def handle_file_upload(files):
        if not files:
            return "No files uploaded", [], []
        
        file_list = []
        file_info = []
        
        for file in files:
            # Copy to uploads directory
            from utils.file_utils import copy_file, get_file_info
            
            dest_path = f"data/uploads/{Path(file.name).name}"
            copy_file(file.name, dest_path)
            
            info = get_file_info(dest_path)
            file_list.append(dest_path)
            file_info.append(f"βœ“ {info['name']} ({info['size_mb']} MB)")
            
            # Add to RAG
            await agent.process_files_to_rag([{'path': dest_path, 'name': info['name']}])
        
        files_text = "\n".join(file_info)
        return files_text, file_list, file_list
    
    async def handle_ocr(file_path, language):
        if not file_path:
            return "Please select a file", ""
        
        result = await agent.manual_tool_call(
            'ocr_extract_text',
            {'file_path': file_path, 'language': language}
        )
        
        if result['success']:
            data = result['result']
            return data.get('text', ''), f"Confidence: {data.get('confidence', 0):.2%}"
        else:
            return f"Error: {result['error']}", ""
    
    async def handle_summarize(file_path, max_length):
        if not file_path:
            return "Please select a file", {}
        
        result = await agent.manual_tool_call(
            'pdf_summarize',
            {'file_path': file_path, 'max_length': max_length}
        )
        
        if result['success']:
            data = result['result']
            return data.get('summary', ''), data.get('metadata', {})
        else:
            return f"Error: {result['error']}", {}
    
    async def handle_calendar(title, start, end, description, location):
        result = await agent.manual_tool_call(
            'calendar_create_event',
            {
                'title': title,
                'start': start,
                'end': end,
                'description': description,
                'location': location
            }
        )
        
        if result['success']:
            data = result['result']
            return data.get('output_path'), f"βœ“ Event created: {title}"
        else:
            return None, f"βœ— Error: {result['error']}"
    
    async def handle_email(recipient, subject, context, tone):
        result = await agent.manual_tool_call(
            'email_draft',
            {
                'recipient': recipient,
                'subject': subject,
                'context': context,
                'tone': tone
            }
        )
        
        if result['success']:
            data = result['result']
            return data.get('email_body', ''), data.get('output_path_html')
        else:
            return f"Error: {result['error']}", None
    
    async def handle_form_fill(template_file, data_json):
        if not template_file:
            return None, "Please upload a form template"
        
        try:
            data = json.loads(data_json)
        except:
            return None, "Invalid JSON data"
        
        result = await agent.manual_tool_call(
            'form_fill',
            {
                'template_path': template_file.name,
                'data': data
            }
        )
        
        if result['success']:
            res_data = result['result']
            return res_data.get('output_path'), f"βœ“ Form filled: {len(res_data.get('fields_filled', []))} fields"
        else:
            return None, f"βœ— Error: {result['error']}"
    
    async def handle_organize(file_list, strategy):
        if not file_list:
            return {"error": "No files to organize"}
        
        # Use upload directory
        result = await agent.manual_tool_call(
            'file_organize',
            {
                'directory': 'data/uploads',
                'strategy': strategy
            }
        )
        
        if result['success']:
            return result['result']
        else:
            return {"error": result['error']}
    
    # Wire up events
    file_upload.change(
        fn=handle_file_upload,
        inputs=[file_upload],
        outputs=[files_list, uploaded_files_state, ocr_file_select, pdf_file_select]
    )
    
    ocr_execute_btn.click(
        fn=handle_ocr,
        inputs=[ocr_file_select, ocr_language],
        outputs=[ocr_output, ocr_confidence]
    )
    
    ocr_btn.click(
        fn=lambda: gr.Tabs.update(selected="πŸ” OCR"),
        outputs=[]
    )
    
    summarize_execute_btn.click(
        fn=handle_summarize,
        inputs=[pdf_file_select, summary_length],
        outputs=[summary_output, pdf_metadata]
    )
    
    calendar_execute_btn.click(
        fn=handle_calendar,
        inputs=[event_title, event_start, event_end, event_description, event_location],
        outputs=[calendar_output, calendar_status]
    )
    
    email_execute_btn.click(
        fn=handle_email,
        inputs=[email_recipient, email_subject, email_context, email_tone],
        outputs=[email_output, email_download]
    )
    
    form_execute_btn.click(
        fn=handle_form_fill,
        inputs=[form_template, form_data],
        outputs=[form_output, form_status]
    )
    
    organize_execute_btn.click(
        fn=handle_organize,
        inputs=[uploaded_files_state, organize_strategy],
        outputs=[organize_output]
    )