-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradio_interface.py
More file actions
207 lines (163 loc) · 7.76 KB
/
Copy pathgradio_interface.py
File metadata and controls
207 lines (163 loc) · 7.76 KB
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
import gradio as gr
import os
from pathlib import Path
from local_ai_system import LocalAIFileManager
class GradioInterface:
"""Alternative Gradio interface for the Local AI system"""
def __init__(self):
self.ai_manager = LocalAIFileManager()
self.current_directory = str(Path.home())
def scan_directory_interface(self, directory_path, include_system):
"""Interface function for directory scanning"""
try:
files = self.ai_manager.scan_directory(directory_path, include_system)
# Format results for display
results = f"Found {len(files)} files\\n\\n"
# Summary statistics
total_size = sum(f['size'] for f in files)
processable = len([f for f in files if f['is_processable']])
results += f"Total Size: {total_size / 1024 / 1024:.1f} MB\\n"
results += f"Processable Files: {processable}\\n"
results += f"File Types: {len(set(f['extension'] for f in files))}\\n\\n"
# File list (first 20)
results += "Files (showing first 20):\\n"
for i, file in enumerate(files[:20]):
size_mb = file['size'] / 1024 / 1024
results += f"{i+1}. {file['name']} ({size_mb:.1f} MB) - {file['extension']}\\n"
if len(files) > 20:
results += f"... and {len(files) - 20} more files\\n"
return results, files
except Exception as e:
return f"Error scanning directory: {e}", []
def process_files_interface(self, files_data):
"""Interface function for processing files"""
if not files_data:
return "No files to process. Please scan a directory first."
try:
processable_files = [f['path'] for f in files_data if f['is_processable']]
if not processable_files:
return "No processable files found."
success = self.ai_manager.process_documents(processable_files[:50]) # Limit to 50 files
if success:
return f"Successfully processed {min(len(processable_files), 50)} files!"
else:
return "Failed to process files."
except Exception as e:
return f"Error processing files: {e}"
def query_interface(self, query):
"""Interface function for querying documents"""
if not query:
return "Please enter a query."
try:
result = self.ai_manager.query_documents(query)
if isinstance(result, dict):
response = f"Answer:\\n{result['answer']}\\n\\n"
if result['sources']:
response += "Sources:\\n"
for i, source in enumerate(result['sources'], 1):
response += f"{i}. {source['file']}\\n"
response += f" Preview: {source['content_preview'][:100]}...\\n\\n"
return response
else:
return str(result)
except Exception as e:
return f"Error querying documents: {e}"
def create_interface(self):
"""Create the Gradio interface"""
with gr.Blocks(title="Local AI File Manager", theme=gr.themes.Soft()) as interface:
gr.Markdown("# 🤖 Local AI File Manager")
gr.Markdown("**Comprehensive local AI system for file management and analysis**")
# State to store scanned files
files_state = gr.State([])
with gr.Tab("📁 File Scanner"):
with gr.Row():
with gr.Column(scale=3):
directory_input = gr.Textbox(
label="Directory to scan",
value=str(Path.home()),
placeholder="Enter directory path"
)
with gr.Column(scale=1):
include_system_files = gr.Checkbox(
label="Include system files",
value=False
)
scan_btn = gr.Button("Scan Directory", variant="primary")
scan_results = gr.Textbox(
label="Scan Results",
lines=15,
max_lines=20
)
process_btn = gr.Button("Add to AI Knowledge Base", variant="secondary")
process_results = gr.Textbox(
label="Processing Results",
lines=3
)
# Connect scan button
scan_btn.click(
fn=self.scan_directory_interface,
inputs=[directory_input, include_system_files],
outputs=[scan_results, files_state]
)
# Connect process button
process_btn.click(
fn=self.process_files_interface,
inputs=[files_state],
outputs=[process_results]
)
with gr.Tab("🔍 AI Query"):
query_input = gr.Textbox(
label="Ask about your files",
placeholder="e.g., 'Summarize all PDF documents', 'Find Python files', 'What configuration files do I have?'",
lines=3
)
query_btn = gr.Button("Search", variant="primary")
query_results = gr.Textbox(
label="AI Response",
lines=15,
max_lines=25
)
# Connect query button
query_btn.click(
fn=self.query_interface,
inputs=[query_input],
outputs=[query_results]
)
with gr.Tab("📊 System Info"):
gr.Markdown("### System Information")
system_info = f"""
**Base Directory:** {self.ai_manager.base_dir}
**AI Model:** {self.ai_manager.model_name}
**Vector Store:** {self.ai_manager.vector_store_path}
**Status:** Ready
"""
gr.Markdown(system_info)
# Clear knowledge base button
clear_btn = gr.Button("Clear AI Knowledge Base", variant="stop")
clear_status = gr.Textbox(label="Status", lines=2)
def clear_knowledge_base():
try:
if self.ai_manager.vector_store:
self.ai_manager.vector_store.delete_collection()
self.ai_manager.vector_store = None
return "Knowledge base cleared successfully!"
except Exception as e:
return f"Error clearing knowledge base: {e}"
clear_btn.click(
fn=clear_knowledge_base,
outputs=[clear_status]
)
return interface
def main():
"""Main function to launch Gradio interface"""
app = GradioInterface()
interface = app.create_interface()
# Launch with sharing enabled for remote access
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
debug=True
)
if __name__ == "__main__":
main()