-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathmain.py
More file actions
145 lines (111 loc) · 3.78 KB
/
Copy pathmain.py
File metadata and controls
145 lines (111 loc) · 3.78 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
import os
import ast
import operator
import webbrowser
import datetime
_ALLOWED_OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def safe_eval(expression):
"""Safely evaluate a purely arithmetic expression without using eval()."""
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
if isinstance(node, ast.Constant):
if isinstance(node.value, (int, float)):
return node.value
raise ValueError("Only numeric constants are allowed")
if isinstance(node, ast.BinOp) and type(node.op) in _ALLOWED_OPERATORS:
return _ALLOWED_OPERATORS[type(node.op)](_eval(node.left), _eval(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in _ALLOWED_OPERATORS:
return _ALLOWED_OPERATORS[type(node.op)](_eval(node.operand))
raise ValueError("Unsupported expression")
return _eval(ast.parse(expression, mode="eval"))
def parse_command(command):
command = command.lower().strip()
if "time" in command:
return ("time", None)
elif "date" in command:
return ("date", None)
elif command.startswith("open "):
return ("open", command.replace("open ", "").strip())
elif command.startswith("create file "):
return ("create", command.replace("create file ", "").strip())
elif command.startswith("delete file "):
return ("delete", command.replace("delete file ", "").strip())
elif command.startswith("search "):
return ("search", command.replace("search ", "").strip())
elif command.startswith("calc "):
return ("calc", command.replace("calc ", "").strip())
elif command == "help":
return ("help", None)
elif "exit" in command or "quit" in command:
return ("exit", None)
return ("unknown", command)
def execute(action, value):
if action == "time":
print("🕒", datetime.datetime.now().strftime("%H:%M:%S"))
elif action == "date":
print("📅", datetime.date.today())
elif action == "open":
try:
print(f"🌐 Opening {value}...")
webbrowser.open(f"https://{value}.com")
except:
print("❌ Failed to open.")
elif action == "create":
try:
with open(value, "w") as f:
f.write("Created by AI Terminal Assistant\n")
print(f"📄 File '{value}' created.")
except:
print("❌ Error creating file.")
elif action == "delete":
if os.path.exists(value):
os.remove(value)
print(f"🗑️ File '{value}' deleted.")
else:
print("❌ File not found.")
elif action == "search":
print(f"🔍 Searching: {value}")
webbrowser.open(f"https://www.google.com/search?q={value}")
elif action == "calc":
try:
result = safe_eval(value)
print(f"🧮 Result: {result}")
except:
print("❌ Invalid calculation.")
elif action == "help":
print("""
Commands:
- open <site>
- create file <name>
- delete file <name>
- search <query>
- calc <expression>
- time / date
- help
- exit
""")
elif action == "exit":
print("👋 Exiting...")
exit()
else:
print("🤖 Command not recognized. Type 'help'.")
def main():
print("🚀 AI Terminal Assistant")
print("Type 'help' to see commands.\n")
while True:
user_input = input("💬 > ")
action, value = parse_command(user_input)
execute(action, value)
if __name__ == "__main__":
main()