Athagi commited on
Commit
ef280d5
·
verified ·
1 Parent(s): 06cfe95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -130
app.py CHANGED
@@ -1,131 +1,88 @@
1
- from flask import Flask, request, jsonify, render_template, send_from_directory
2
- import os
3
- import subprocess
4
- import tempfile
5
- import shutil
6
- import sys
7
- import torch
8
- import platform
9
- from huggingface_hub import InferenceClient
10
- import re
11
-
12
- app = Flask(__name__)
13
- temp_dir = tempfile.mkdtemp()
14
- current_dir = temp_dir
15
-
16
- # Initialize Hugging Face client
17
- client = InferenceClient(
18
- token=os.environ.get("HF_API_KEY", "hf_xxxxxxxxxxxxxxxxxxxxxxxx")
19
- )
20
-
21
- # System State
22
- AGI_STATE = {
23
- "active_processes": {},
24
- "tts_engine_loaded": False,
25
- "current_model": "google/gemma-2-2b-it"
26
- }
27
-
28
- def execute_command(command, cwd=None):
29
- process = subprocess.Popen(
30
- command,
31
- shell=True,
32
- stdout=subprocess.PIPE,
33
- stderr=subprocess.PIPE,
34
- text=True,
35
- cwd=cwd or current_dir
36
- )
37
- stdout, stderr = process.communicate()
38
- return stdout + stderr
39
-
40
- @app.route("/")
41
- def index():
42
- return render_template("index.html")
43
-
44
- @app.route("/execute", methods=["POST"])
45
- def execute_code():
46
- global current_dir
47
- command = request.json.get("code", "").strip()
48
- if not command:
49
- return jsonify({"result": "Error: No command provided."})
50
-
51
- try:
52
- if command.lower().startswith(("ai:", "/ai")):
53
- return handle_ai_command(command)
54
- elif command.lower().startswith(("tts:", "/tts")):
55
- return handle_tts_command(command)
56
- elif command.lower().startswith(("sys:", "/sys")):
57
- return handle_system_command(command)
58
- elif command.lower().startswith(("web:", "/web")):
59
- return handle_web_command(command)
60
- elif command.lower().startswith(("file:", "/file")):
61
- return handle_file_command(command)
62
- else:
63
- return jsonify({"result": execute_generic_command(command)})
64
 
65
- except Exception as e:
66
- return jsonify({"result": f"Error: {str(e)}"})
67
-
68
- def handle_ai_command(command):
69
- prompt = command.split(":", 1)[1].strip()
70
- response = client.text_generation(
71
- model=AGI_STATE["current_model"],
72
- prompt=f"{read_knowledge_base()}\n\nUser: {prompt}\nAssistant:",
73
- max_new_tokens=500
74
- )
75
- return jsonify({
76
- "result": response,
77
- "type": "ai_response"
78
- })
79
-
80
- def handle_tts_command(command):
81
- return jsonify({"result": "TTS functionality not implemented", "type": "error"})
82
-
83
- def handle_system_command(command):
84
- cmd = command.split(":", 1)[1].strip()
85
- if cmd == "processes":
86
- return jsonify({
87
- "type": "process_list",
88
- "processes": list(AGI_STATE["active_processes"].keys())
89
- })
90
- return jsonify({"result": "Unsupported system command", "type": "error"})
91
-
92
- def handle_web_command(command):
93
- return jsonify({"result": "Web functionality not implemented", "type": "error"})
94
-
95
- def handle_file_command(command):
96
- try:
97
- _, operation, *rest = command.split(":", 2)
98
- if operation == "list":
99
- return jsonify({
100
- "type": "file_list",
101
- "files": os.listdir(current_dir)
102
- })
103
- return jsonify({"result": "Unsupported file operation", "type": "error"})
104
- except Exception as e:
105
- return jsonify({"result": f"File error: {str(e)}", "type": "error"})
106
-
107
- def execute_generic_command(command):
108
- if command == "help":
109
- return format_help_response()
110
- elif command.startswith("!"):
111
- return execute_command(command[1:])
112
- return "Unrecognized command. Type 'help' for options."
113
-
114
- def format_help_response():
115
- return """
116
- Available Commands:
117
- /ai [prompt] - Get AI response
118
- /file:list - List files
119
- !command - Execute shell command
120
- """
121
-
122
- @app.route("/download/<path:filename>")
123
- def download_file(filename):
124
- return send_from_directory(current_dir, filename, as_attachment=True)
125
-
126
- def read_knowledge_base():
127
- with open('knowledge.txt') as f:
128
- return f.read()
129
-
130
- if __name__ == "__main__":
131
- app.run(host="0.0.0.0", port=7860)
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>AGI Terminal</title>
7
+ <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
8
+ </head>
9
+ <body>
10
+ <div class="terminal-container">
11
+ <div class="chat-output" id="chat">
12
+ <div class="message system">
13
+ 🤖 AGI Terminal Ready<br>
14
+ Available commands:<br>
15
+ - AI: [your question]<br>
16
+ - file:list<br>
17
+ - ![command]
18
+ </div>
19
+ </div>
20
+
21
+ <div class="input-container">
22
+ <div class="prompt">>></div>
23
+ <input type="text" id="command-input" autofocus>
24
+ <button onclick="executeCommand()">Execute</button>
25
+ </div>
26
+ </div>
27
+
28
+ <script>
29
+ const chat = document.getElementById('chat');
30
+ const input = document.getElementById('command-input');
31
+
32
+ async function executeCommand() {
33
+ const command = input.value.trim();
34
+ if (!command) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ addMessage(command, 'user');
37
+ input.value = '';
38
+
39
+ const loader = addLoader();
40
+
41
+ try {
42
+ const response = await fetch('/execute', {
43
+ method: 'POST',
44
+ headers: {'Content-Type': 'application/json'},
45
+ body: JSON.stringify({ code: command })
46
+ });
47
+
48
+ const data = await response.json();
49
+ loader.remove();
50
+
51
+ handleResponse(data);
52
+
53
+ } catch (error) {
54
+ loader.remove();
55
+ addMessage(`Error: ${error.message}`, 'error');
56
+ }
57
+ }
58
+
59
+ function handleResponse(data) {
60
+ let content = data.result;
61
+ if (data.type === 'code') {
62
+ content += `<br><a href="/download/${data.file}" download class="download-link">Download ${data.file}</a>`;
63
+ }
64
+ addMessage(content, data.type);
65
+ }
66
+
67
+ function addMessage(content, type) {
68
+ const div = document.createElement('div');
69
+ div.className = `message ${type}`;
70
+ div.innerHTML = content;
71
+ chat.appendChild(div);
72
+ chat.scrollTop = chat.scrollHeight;
73
+ }
74
+
75
+ function addLoader() {
76
+ const loader = document.createElement('div');
77
+ loader.className = 'message loader';
78
+ loader.innerHTML = '<div class="dot-flashing"></div>';
79
+ chat.appendChild(loader);
80
+ return loader;
81
+ }
82
+
83
+ input.addEventListener('keypress', (e) => {
84
+ if (e.key === 'Enter') executeCommand();
85
+ });
86
+ </script>
87
+ </body>
88
+ </html>