File size: 3,923 Bytes
1243cd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21923fc
1243cd0
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
import os
import shutil
import psutil
# Try to import readline or fallback to pyreadline3 (Windows)
try:
    import readline
except ImportError:
    try:
        import pyreadline3 as readline
    except ImportError:
        readline = None  # no history/autocomplete on Windows if missing


# ========== Optional AI Module (Natural Language Commands) ==========
try:
    from transformers import pipeline
    ai_enabled = True
    nlp = pipeline("text2text-generation", model="google/flan-t5-small")
except Exception:
    ai_enabled = False


# ========== Command Handlers ==========
def cmd_ls(args):
    path = args[0] if args else "."
    try:
        for item in os.listdir(path):
            print(item)
    except FileNotFoundError:
        print(f"ls: cannot access '{path}': No such file or directory")


def cmd_cd(args):
    if not args:
        print("cd: missing operand")
        return
    try:
        os.chdir(args[0])
    except FileNotFoundError:
        print(f"cd: {args[0]}: No such file or directory")


def cmd_pwd(args):
    print(os.getcwd())


def cmd_mkdir(args):
    if not args:
        print("mkdir: missing operand")
        return
    try:
        os.mkdir(args[0])
    except FileExistsError:
        print(f"mkdir: cannot create directory '{args[0]}': File exists")


def cmd_rm(args):
    if not args:
        print("rm: missing operand")
        return
    target = args[0]
    if os.path.isdir(target):
        try:
            shutil.rmtree(target)
        except Exception as e:
            print(f"rm: cannot remove '{target}': {e}")
    else:
        try:
            os.remove(target)
        except FileNotFoundError:
            print(f"rm: cannot remove '{target}': No such file or directory")


def cmd_monitor(args):
    cpu = psutil.cpu_percent(interval=1)
    mem = psutil.virtual_memory()
    print(f"CPU Usage: {cpu}%")
    print(f"Memory Usage: {mem.percent}%")


def cmd_help(args):
    print("Available commands:")
    for cmd in commands.keys():
        print(f" - {cmd}")
    if ai_enabled:
        print(" - ai (natural language queries)")


# ========== AI Command ==========
def cmd_ai(args):
    if not ai_enabled:
        print("AI features not available (transformers not installed).")
        return
    if not args:
        print("ai: missing query")
        return
    query = " ".join(args)
    print(f"AI Query: {query}")
    try:
        result = nlp(query, max_length=100)[0]['generated_text']
        print("AI Suggestion:", result)
    except Exception as e:
        print(f"AI error: {e}")


# ========== Command Map ==========
commands = {
    "ls": cmd_ls,
    "cd": cmd_cd,
    "pwd": cmd_pwd,
    "mkdir": cmd_mkdir,
    "rm": cmd_rm,
    "monitor": cmd_monitor,
    "help": cmd_help,
    "ai": cmd_ai,
}


# ========== Autocomplete ==========
def completer(text, state):
    options = [cmd for cmd in commands.keys() if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    return None

if readline:
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer)


# ========== Main Loop ==========
def main():
    print("Python Terminal Emulator (type 'help' for commands, 'exit' to quit)")
    while True:
        try:
            user_input = input(f"{os.getcwd()} $ ").strip()
            if not user_input:
                continue
            if user_input.lower() in ["exit", "quit"]:
                print("Exiting terminal.")
                break

            parts = user_input.split()
            cmd, args = parts[0], parts[1:]

            if cmd in commands:
                commands[cmd](args)
            else:
                print(f"{cmd}: command not found. Type 'help' for available commands.")
        except KeyboardInterrupt:
            print("\nUse 'exit' to quit.")
        except Exception as e:
            print("Error:", e)


if __name__ == "__app__":
    main()