Spaces:
Runtime error
Runtime error
Update file_management.py
Browse files- file_management.py +191 -30
file_management.py
CHANGED
@@ -1,30 +1,191 @@
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import uuid
|
4 |
+
import traceback
|
5 |
+
import logging
|
6 |
+
from pathlib import Path
|
7 |
+
import numpy as np
|
8 |
+
import pandas as pd
|
9 |
+
from typing import Dict, Any
|
10 |
+
|
11 |
+
# Import the base intelligent agent.
|
12 |
+
# Adjust this import as necessary if you move IntelligentAgent to a separate module.
|
13 |
+
from app import IntelligentAgent
|
14 |
+
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
class FileManagementAgent(IntelligentAgent):
|
18 |
+
def __init__(self, hub):
|
19 |
+
super().__init__("file_management", hub)
|
20 |
+
|
21 |
+
def process_task(self, task: str) -> Dict[str, Any]:
|
22 |
+
logger.info(f"FileManagementAgent processing: {task}")
|
23 |
+
task_lower = task.lower()
|
24 |
+
if any(word in task_lower for word in ["create", "make", "generate", "write"]):
|
25 |
+
operation = "create"
|
26 |
+
elif any(word in task_lower for word in ["read", "open", "show", "display", "content"]):
|
27 |
+
operation = "read"
|
28 |
+
elif any(word in task_lower for word in ["list", "find", "directory", "folder", "files in"]):
|
29 |
+
operation = "list"
|
30 |
+
elif any(word in task_lower for word in ["delete", "remove"]):
|
31 |
+
operation = "delete"
|
32 |
+
else:
|
33 |
+
operation = "unknown"
|
34 |
+
|
35 |
+
filename = None
|
36 |
+
file_extensions = ['.txt', '.json', '.csv', '.md', '.py', '.html', '.js', '.css']
|
37 |
+
words = task.split()
|
38 |
+
for word in words:
|
39 |
+
for ext in file_extensions:
|
40 |
+
if ext in word.lower():
|
41 |
+
filename = word.strip(':"\'.,;')
|
42 |
+
break
|
43 |
+
if filename:
|
44 |
+
break
|
45 |
+
|
46 |
+
if not filename:
|
47 |
+
file_keywords = ["file", "named", "called", "filename"]
|
48 |
+
for i, word in enumerate(words):
|
49 |
+
if word.lower() in file_keywords and i < len(words) - 1:
|
50 |
+
potential_name = words[i+1].strip(':"\'.,;')
|
51 |
+
if '.' not in potential_name:
|
52 |
+
if "json" in task_lower:
|
53 |
+
potential_name += ".json"
|
54 |
+
elif "csv" in task_lower:
|
55 |
+
potential_name += ".csv"
|
56 |
+
elif "python" in task_lower or "py" in task_lower:
|
57 |
+
potential_name += ".py"
|
58 |
+
else:
|
59 |
+
potential_name += ".txt"
|
60 |
+
filename = potential_name
|
61 |
+
break
|
62 |
+
|
63 |
+
if not filename:
|
64 |
+
if "json" in task_lower:
|
65 |
+
filename = f"data_{uuid.uuid4().hex[:6]}.json"
|
66 |
+
elif "csv" in task_lower:
|
67 |
+
filename = f"data_{uuid.uuid4().hex[:6]}.csv"
|
68 |
+
elif "python" in task_lower or "py" in task_lower:
|
69 |
+
filename = f"script_{uuid.uuid4().hex[:6]}.py"
|
70 |
+
elif "log" in task_lower:
|
71 |
+
filename = f"log_{uuid.uuid4().hex[:6]}.txt"
|
72 |
+
else:
|
73 |
+
filename = f"file_{uuid.uuid4().hex[:6]}.txt"
|
74 |
+
|
75 |
+
result = {}
|
76 |
+
if operation == "create":
|
77 |
+
if filename.endswith('.json'):
|
78 |
+
content = json.dumps({
|
79 |
+
"name": "Sample Data",
|
80 |
+
"description": task,
|
81 |
+
"created": pd.Timestamp.now().isoformat(),
|
82 |
+
"values": [1, 2, 3, 4, 5],
|
83 |
+
"metadata": {"source": "FileManagementAgent", "version": "1.0"}
|
84 |
+
}, indent=2)
|
85 |
+
elif filename.endswith('.csv'):
|
86 |
+
content = "id,name,value,timestamp\n"
|
87 |
+
for i in range(5):
|
88 |
+
content += f"{i+1},Item{i+1},{np.random.randint(1, 100)},{pd.Timestamp.now().isoformat()}\n"
|
89 |
+
elif filename.endswith('.py'):
|
90 |
+
content = f"""# Generated Python Script: {filename}
|
91 |
+
# Created: {pd.Timestamp.now().isoformat()}
|
92 |
+
# Description: {task}
|
93 |
+
|
94 |
+
def main():
|
95 |
+
print("Hello from the FileManagementAgent!")
|
96 |
+
data = [1, 2, 3, 4, 5]
|
97 |
+
result = sum(data)
|
98 |
+
print(f"Sample calculation: sum(data) = {{result}}")
|
99 |
+
return result
|
100 |
+
|
101 |
+
if __name__ == "__main__":
|
102 |
+
main()
|
103 |
+
"""
|
104 |
+
else:
|
105 |
+
content = f"File created by FileManagementAgent\nCreated: {pd.Timestamp.now().isoformat()}\nBased on request: {task}\n\nThis is sample content."
|
106 |
+
|
107 |
+
try:
|
108 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
109 |
+
f.write(content)
|
110 |
+
result = {
|
111 |
+
"text": f"Successfully created file: {filename}",
|
112 |
+
"operation": "create",
|
113 |
+
"filename": filename,
|
114 |
+
"size": len(content),
|
115 |
+
"preview": content[:200] + "..." if len(content) > 200 else content
|
116 |
+
}
|
117 |
+
self.memory.add_short_term({"operation": "create", "filename": filename, "timestamp": pd.Timestamp.now().isoformat()})
|
118 |
+
self.memory.add_long_term(f"file:{filename}", {"operation": "create", "type": Path(filename).suffix, "timestamp": pd.Timestamp.now().isoformat()})
|
119 |
+
except Exception as e:
|
120 |
+
error_msg = f"Error creating file {filename}: {str(e)}"
|
121 |
+
logger.error(error_msg)
|
122 |
+
result = {"text": error_msg, "error": str(e)}
|
123 |
+
elif operation == "read":
|
124 |
+
if not filename:
|
125 |
+
result = {"text": "Please specify a filename to read."}
|
126 |
+
elif not Path(filename).exists():
|
127 |
+
result = {"text": f"File '{filename}' not found."}
|
128 |
+
else:
|
129 |
+
try:
|
130 |
+
with open(filename, 'r', encoding='utf-8') as f:
|
131 |
+
content = f.read()
|
132 |
+
result = {"text": f"Content of {filename}:\n\n{content}", "operation": "read", "filename": filename, "content": content, "size": len(content)}
|
133 |
+
self.memory.add_short_term({"operation": "read", "filename": filename, "timestamp": pd.Timestamp.now().isoformat()})
|
134 |
+
except Exception as e:
|
135 |
+
error_msg = f"Error reading file {filename}: {str(e)}"
|
136 |
+
logger.error(error_msg)
|
137 |
+
result = {"text": error_msg, "error": str(e)}
|
138 |
+
elif operation == "list":
|
139 |
+
try:
|
140 |
+
directory = "."
|
141 |
+
for term in ["directory", "folder", "in"]:
|
142 |
+
if term in task_lower:
|
143 |
+
parts = task_lower.split(term)
|
144 |
+
if len(parts) > 1:
|
145 |
+
potential_dir = parts[1].strip().split()[0].strip(':"\'.,;')
|
146 |
+
if Path(potential_dir).exists() and Path(potential_dir).is_dir():
|
147 |
+
directory = potential_dir
|
148 |
+
extension_filter = None
|
149 |
+
for ext in file_extensions:
|
150 |
+
if ext in task_lower:
|
151 |
+
extension_filter = ext
|
152 |
+
break
|
153 |
+
files = list(Path(directory).glob('*' + (extension_filter or '')))
|
154 |
+
file_groups = {}
|
155 |
+
for file in files:
|
156 |
+
file_groups.setdefault(file.suffix, []).append({
|
157 |
+
"name": file.name,
|
158 |
+
"size": file.stat().st_size,
|
159 |
+
"modified": pd.Timestamp(file.stat().st_mtime, unit='s').isoformat()
|
160 |
+
})
|
161 |
+
response_text = f"Found {len(files)} files" + (f" with extension {extension_filter}" if extension_filter else "") + f" in {directory}:\n\n"
|
162 |
+
for ext, group in file_groups.items():
|
163 |
+
response_text += f"{ext} files ({len(group)}):\n"
|
164 |
+
for file_info in sorted(group, key=lambda x: x["name"]):
|
165 |
+
size_kb = file_info["size"] / 1024
|
166 |
+
response_text += f"- {file_info['name']} ({size_kb:.1f} KB, modified: {file_info['modified']})\n"
|
167 |
+
response_text += "\n"
|
168 |
+
result = {"text": response_text, "operation": "list", "directory": directory, "file_count": len(files), "files": file_groups}
|
169 |
+
self.memory.add_short_term({"operation": "list", "directory": directory, "file_count": len(files), "timestamp": pd.Timestamp.now().isoformat()})
|
170 |
+
except Exception as e:
|
171 |
+
error_msg = f"Error listing files: {str(e)}"
|
172 |
+
logger.error(error_msg)
|
173 |
+
result = {"text": error_msg, "error": str(e)}
|
174 |
+
elif operation == "delete":
|
175 |
+
if not filename:
|
176 |
+
result = {"text": "Please specify a filename to delete."}
|
177 |
+
elif not Path(filename).exists():
|
178 |
+
result = {"text": f"File '{filename}' not found."}
|
179 |
+
else:
|
180 |
+
try:
|
181 |
+
os.remove(filename)
|
182 |
+
result = {"text": f"Successfully deleted file: {filename}", "operation": "delete", "filename": filename}
|
183 |
+
self.memory.add_short_term({"operation": "delete", "filename": filename, "timestamp": pd.Timestamp.now().isoformat()})
|
184 |
+
self.memory.add_long_term(f"file:{filename}", {"operation": "delete", "timestamp": pd.Timestamp.now().isoformat()})
|
185 |
+
except Exception as e:
|
186 |
+
error_msg = f"Error deleting file {filename}: {str(e)}"
|
187 |
+
logger.error(error_msg)
|
188 |
+
result = {"text": error_msg, "error": str(e)}
|
189 |
+
else:
|
190 |
+
result = {"text": f"Unknown operation requested in task: {task}"}
|
191 |
+
return result
|