Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,383 +1,436 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
from flask import Flask, jsonify, request
|
3 |
-
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
|
4 |
-
from flask_sqlalchemy import SQLAlchemy
|
5 |
-
from werkzeug.security import generate_password_hash, check_password_hash
|
6 |
-
import pdb
|
7 |
-
import subprocess
|
8 |
-
import docker
|
9 |
-
from huggingface_hub import HfApi, create_repo
|
10 |
-
import importlib
|
11 |
import os
|
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 |
-
def
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
@app.route('/logout')
|
63 |
-
@login_required
|
64 |
-
def logout():
|
65 |
-
logout_user()
|
66 |
-
return jsonify({'message': 'Logged out successfully'}), 200
|
67 |
-
|
68 |
-
@app.route('/create_project', methods=['POST'])
|
69 |
-
@login_required
|
70 |
-
def create_project():
|
71 |
-
data = request.get_json()
|
72 |
-
project_name = data.get('project_name')
|
73 |
-
new_project = Project(name=project_name, user_id=current_user.id)
|
74 |
-
db.session.add(new_project)
|
75 |
-
db.session.commit()
|
76 |
-
return jsonify({'message': 'Project created successfully'}), 201
|
77 |
-
|
78 |
-
@app.route('/get_projects')
|
79 |
-
@login_required
|
80 |
-
def get_projects():
|
81 |
-
projects = Project.query.filter_by(user_id=current_user.id).all()
|
82 |
-
return jsonify({'projects': [project.name for project in projects]}), 200
|
83 |
-
|
84 |
-
# Plugin system
|
85 |
-
class PluginManager:
|
86 |
-
def __init__(self):
|
87 |
-
self.plugin_dir = './plugins'
|
88 |
-
self.plugins = {}
|
89 |
-
|
90 |
-
def load_plugins(self):
|
91 |
-
for filename in os.listdir(self.plugin_dir):
|
92 |
-
if filename.endswith('.py'):
|
93 |
-
module_name = filename[:-3]
|
94 |
-
spec = importlib.util.spec_from_file_location(module_name, os.path.join(self.plugin_dir, filename))
|
95 |
-
module = importlib.util.module_from_spec(spec)
|
96 |
-
spec.loader.exec_module(module)
|
97 |
-
if hasattr(module, 'register_plugin'):
|
98 |
-
plugin = module.register_plugin()
|
99 |
-
self.plugins[plugin.name] = plugin
|
100 |
-
|
101 |
-
def get_plugin(self, name):
|
102 |
-
return self.plugins.get(name)
|
103 |
-
|
104 |
-
def list_plugins(self):
|
105 |
-
return list(self.plugins.keys())
|
106 |
-
|
107 |
-
# Example plugin
|
108 |
-
def register_plugin():
|
109 |
-
return ExamplePlugin()
|
110 |
-
|
111 |
-
class ExamplePlugin:
|
112 |
-
name = "example_plugin"
|
113 |
-
|
114 |
-
def run(self, input_data):
|
115 |
-
return f"Plugin processed: {input_data}"
|
116 |
-
|
117 |
-
plugin_manager = PluginManager()
|
118 |
-
plugin_manager.load_plugins()
|
119 |
-
|
120 |
-
# Load the tokenizer explicitly
|
121 |
-
tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
|
122 |
-
|
123 |
-
# Initialize the model
|
124 |
-
model = AutoModelForCausalLM.from_pretrained("microsoft/CodeGPT-small-py") # Use a public model
|
125 |
-
|
126 |
-
# Initialize the pipeline
|
127 |
-
code_generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
128 |
-
|
129 |
-
# AI Assistant
|
130 |
-
hf_api = HfApi()
|
131 |
-
|
132 |
-
def model_menu():
|
133 |
-
models = ["distilbert", "t5", "codellama-7b", "geminai-1.5b"]
|
134 |
-
selected_model = st.sidebar.selectbox("Select a model:", models)
|
135 |
-
|
136 |
-
# Add the code snippet here
|
137 |
-
try:
|
138 |
-
if selected_model == "distilbert":
|
139 |
-
model = pipeline("text-generation", model="distilbert-base-uncased")
|
140 |
-
elif selected_model == "t5":
|
141 |
-
model = pipeline("text-generation", model="t5-base")
|
142 |
-
elif selected_model == "codellama-7b":
|
143 |
-
model = AutoModelForSeq2SeqLM.from_pretrained("codegen-7B-mono")
|
144 |
-
tokenizer = AutoTokenizer.from_pretrained("codegen-7B-mono")
|
145 |
-
model = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
146 |
-
elif selected_model == "geminai-1.5b":
|
147 |
-
model = AutoModelForSeq2SeqLM.from_pretrained("geminai-1.5b")
|
148 |
-
tokenizer = AutoTokenizer.from_pretrained("geminai-1.5b")
|
149 |
-
model = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
150 |
-
else:
|
151 |
-
raise ValueError("Invalid model name")
|
152 |
-
return model
|
153 |
-
except Exception as e:
|
154 |
-
logging.error(f"Error importing model: {e}")
|
155 |
-
return None
|
156 |
|
157 |
-
|
158 |
|
159 |
-
|
160 |
-
# Extract key information from the user idea
|
161 |
-
# (You might want to use a more sophisticated NLP pipeline here)
|
162 |
-
summary = user_idea # For now, just use the user's input
|
163 |
|
164 |
-
# Create project directory if it doesn't exist
|
165 |
-
project_path = create_project(project_name)
|
166 |
|
167 |
-
|
168 |
-
|
169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
171 |
-
|
172 |
-
with open(os.path.join(project_path, "app.py"), "w") as f:
|
173 |
-
f.write(generated_code)
|
174 |
|
175 |
-
# Deploy the app to Hugging Face Spaces
|
176 |
-
deploy_app_to_hf_spaces(project_name, generated_code)
|
177 |
|
178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
|
180 |
-
def deploy_app_to_hf_spaces(project_name, generated_code):
|
181 |
-
repo_name = f"hf-{project_name}"
|
182 |
-
repo_id = hf_api.changelog.get_repo_id(repo_name)
|
183 |
|
184 |
-
|
185 |
-
|
186 |
-
|
|
|
|
|
187 |
|
188 |
-
# Save the generated code to a temporary file
|
189 |
-
temp_file = "temp_code.py"
|
190 |
-
with open(temp_file, "w") as f:
|
191 |
-
f.write(generated_code)
|
192 |
|
193 |
-
|
194 |
-
|
|
|
|
|
|
|
195 |
|
196 |
-
#
|
197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
198 |
|
199 |
-
# Print success message
|
200 |
-
st.write(f"App deployed successfully to Hugging Face Spaces: https://huggingface.co/spaces/{repo_name}")
|
201 |
|
202 |
-
|
203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
204 |
if not os.path.exists(project_path):
|
205 |
os.makedirs(project_path)
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
|
217 |
-
if app_mode == "Home":
|
218 |
-
st.title("Welcome to AI-Guided Development")
|
219 |
-
st.write("Select a mode from the sidebar to get started.")
|
220 |
|
221 |
-
|
222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
|
224 |
-
elif app_mode == "File Explorer":
|
225 |
-
file_explorer_page()
|
226 |
|
227 |
-
|
228 |
-
|
|
|
|
|
|
|
229 |
|
230 |
-
elif app_mode == "Terminal":
|
231 |
-
terminal_page()
|
232 |
|
233 |
-
|
234 |
-
|
|
|
|
|
|
|
235 |
|
236 |
-
elif app_mode == "AI Assistant":
|
237 |
-
ai_assistant_page()
|
238 |
|
239 |
-
|
240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
241 |
|
242 |
-
@login_required
|
243 |
-
def file_explorer_page():
|
244 |
-
st.header("File Explorer")
|
245 |
-
# File explorer code (as before)
|
246 |
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
# Code editor with Monaco integration
|
251 |
-
st.components.v1.html(
|
252 |
-
"""
|
253 |
-
<div id="monaco-editor" style="width:800px;height:600px;border:1px solid grey"></div>
|
254 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/loader.min.js"></script>
|
255 |
-
<script>
|
256 |
-
require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs' }});
|
257 |
-
require(['vs/editor/editor.main'], function() {
|
258 |
-
var editor = monaco.editor.create(document.getElementById('monaco-editor'), {
|
259 |
-
value: 'print("Hello, World!")',
|
260 |
-
language: 'python'
|
261 |
-
});
|
262 |
-
});
|
263 |
-
</script>
|
264 |
-
""",
|
265 |
-
height=650,
|
266 |
-
)
|
267 |
-
|
268 |
-
if st.button("Run Code"):
|
269 |
-
code = st.session_state.get('code', '') # Get code from Monaco editor
|
270 |
-
output = run_code(code)
|
271 |
-
st.code(output)
|
272 |
-
|
273 |
-
if st.button("Debug Code"):
|
274 |
-
code = st.session_state.get('code', '')
|
275 |
-
st.write("Debugging mode activated. Check your console for the debugger.")
|
276 |
-
debug_code(code)
|
277 |
-
|
278 |
-
@login_required
|
279 |
-
def terminal_page():
|
280 |
-
st.header("Terminal")
|
281 |
-
# Terminal code (as before)
|
282 |
-
|
283 |
-
@login_required
|
284 |
-
def build_and_deploy_page():
|
285 |
-
st.header("Build & Deploy")
|
286 |
-
project_name = st.text_input("Enter project name:")
|
287 |
-
|
288 |
-
if st.button("Build Docker Image"):
|
289 |
-
image, logs = build_docker_image(project_name)
|
290 |
-
st.write(f"Docker image built: {image.tags}")
|
291 |
-
|
292 |
-
if st.button("Run Docker Container"):
|
293 |
-
port = st.number_input("Enter port number:", value=8080)
|
294 |
-
container = run_docker_container(project_name, port)
|
295 |
-
st.write(f"Docker container running: {container.id}")
|
296 |
-
|
297 |
-
if st.button("Deploy to Hugging Face Spaces"):
|
298 |
-
token = st.text_input("Enter your Hugging Face token:", type="password")
|
299 |
-
if token:
|
300 |
-
repo_url = deploy_to_hf_spaces(project_name, token)
|
301 |
-
st.write(f"Deployed to Hugging Face Spaces: {repo_url}")
|
302 |
-
|
303 |
-
@login_required
|
304 |
-
def ai_assistant_page():
|
305 |
-
st.header("AI Assistant")
|
306 |
-
user_idea = st.text_area("Describe your app idea:")
|
307 |
-
project_name = st.text_input("Enter project name:")
|
308 |
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
st.write(f"Project directory: {project_path}")
|
313 |
-
|
314 |
-
@login_required
|
315 |
-
def plugins_page():
|
316 |
-
st.header("Plugins")
|
317 |
-
st.write("Available plugins:")
|
318 |
-
for plugin_name in plugin_manager.list_plugins():
|
319 |
-
st.write(f"- {plugin_name}")
|
320 |
-
|
321 |
-
selected_plugin = st.selectbox("Select a plugin to run:", plugin_manager.list_plugins())
|
322 |
-
input_data = st.text_input("Enter input for the plugin:")
|
323 |
-
|
324 |
-
if st.button("Run Plugin"):
|
325 |
-
plugin = plugin_manager.get_plugin(selected_plugin)
|
326 |
-
if plugin:
|
327 |
-
result = plugin.run(input_data)
|
328 |
-
st.write(f"Plugin output: {result}")
|
329 |
-
|
330 |
-
def login_register_page():
|
331 |
-
st.header("Login/Register")
|
332 |
-
action = st.radio("Choose action:", ["Login", "Register"])
|
333 |
-
|
334 |
-
username = st.text_input("Username:")
|
335 |
-
password = st.text_input("Password:", type="password")
|
336 |
-
|
337 |
-
if action == "Login":
|
338 |
-
if st.button("Login"):
|
339 |
-
user = User.query.filter_by(username=username).first()
|
340 |
-
if user and check_password_hash(user.password_hash, password):
|
341 |
-
login_user(user)
|
342 |
-
st.success("Logged in successfully!")
|
343 |
-
else:
|
344 |
-
st.error("Invalid username or password")
|
345 |
-
else:
|
346 |
-
if st.button("Register"):
|
347 |
-
if User.query.filter_by(username=username).first():
|
348 |
-
st.error("Username already exists")
|
349 |
-
else:
|
350 |
-
new_user = User(username=username, password_hash=generate_password_hash(password))
|
351 |
-
db.session.add(new_user)
|
352 |
-
db.session.commit()
|
353 |
-
st.success("User registered successfully!")
|
354 |
-
|
355 |
-
def debug_code(code):
|
356 |
try:
|
357 |
-
|
|
|
|
|
|
|
358 |
except Exception as e:
|
359 |
-
return
|
360 |
|
361 |
-
|
|
|
|
|
362 |
try:
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
367 |
except Exception as e:
|
368 |
-
return
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
if
|
381 |
-
|
382 |
-
|
383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import subprocess
|
3 |
+
import streamlit as st
|
4 |
+
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
5 |
+
import black
|
6 |
+
from pylint import lint
|
7 |
+
from io import StringIO
|
8 |
+
|
9 |
+
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
|
10 |
+
PROJECT_ROOT = "projects"
|
11 |
+
AGENT_DIRECTORY = "agents"
|
12 |
+
|
13 |
+
# Global state to manage communication between Tool Box and Workspace Chat App
|
14 |
+
if 'chat_history' not in st.session_state:
|
15 |
+
st.session_state.chat_history = []
|
16 |
+
if 'terminal_history' not in st.session_state:
|
17 |
+
st.session_state.terminal_history = []
|
18 |
+
if 'workspace_projects' not in st.session_state:
|
19 |
+
st.session_state.workspace_projects = {}
|
20 |
+
if 'available_agents' not in st.session_state:
|
21 |
+
st.session_state.available_agents = []
|
22 |
+
if 'current_state' not in st.session_state:
|
23 |
+
st.session_state.current_state = {
|
24 |
+
'toolbox': {},
|
25 |
+
'workspace_chat': {}
|
26 |
+
}
|
27 |
+
|
28 |
+
|
29 |
+
class AIAgent:
|
30 |
+
def __init__(self, name, description, skills):
|
31 |
+
self.name = name
|
32 |
+
self.description = description
|
33 |
+
self.skills = skills
|
34 |
+
|
35 |
+
def create_agent_prompt(self):
|
36 |
+
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
37 |
+
agent_prompt = f"""
|
38 |
+
As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
|
39 |
+
{skills_str}
|
40 |
+
I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications. Please feel free to ask any questions or present any challenges you may encounter.
|
41 |
+
"""
|
42 |
+
return agent_prompt
|
43 |
+
|
44 |
+
def autonomous_build(self, chat_history, workspace_projects):
|
45 |
+
"""
|
46 |
+
Autonomous build logic that continues based on the state of chat history and workspace projects.
|
47 |
+
This is a placeholder and needs to be implemented based on your specific needs.
|
48 |
+
"""
|
49 |
+
summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
50 |
+
summary += "\n\nWorkspace Projects:\n" + "\n".join(
|
51 |
+
[f"{p}: {details}" for p, details in workspace_projects.items()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
+
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
54 |
|
55 |
+
return summary, next_step
|
|
|
|
|
|
|
56 |
|
|
|
|
|
57 |
|
58 |
+
def save_agent_to_file(agent):
|
59 |
+
"""Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""
|
60 |
+
if not os.path.exists(AGENT_DIRECTORY):
|
61 |
+
os.makedirs(AGENT_DIRECTORY)
|
62 |
+
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
|
63 |
+
config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
|
64 |
+
with open(file_path, "w") as file:
|
65 |
+
file.write(agent.create_agent_prompt())
|
66 |
+
with open(config_path, "w") as file:
|
67 |
+
file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
|
68 |
+
st.session_state.available_agents.append(agent.name)
|
69 |
|
70 |
+
commit_and_push_changes(f"Add agent {agent.name}")
|
|
|
|
|
71 |
|
|
|
|
|
72 |
|
73 |
+
def load_agent_prompt(agent_name):
|
74 |
+
"""Loads an agent prompt from a file."""
|
75 |
+
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
76 |
+
if os.path.exists(file_path):
|
77 |
+
with open(file_path, "r") as file:
|
78 |
+
agent_prompt = file.read()
|
79 |
+
return agent_prompt
|
80 |
+
else:
|
81 |
+
return None
|
82 |
|
|
|
|
|
|
|
83 |
|
84 |
+
def create_agent_from_text(name, text):
|
85 |
+
skills = text.split('\n')
|
86 |
+
agent = AIAgent(name, "AI agent created from text input.", skills)
|
87 |
+
save_agent_to_file(agent)
|
88 |
+
return agent.create_agent_prompt()
|
89 |
|
|
|
|
|
|
|
|
|
90 |
|
91 |
+
# Chat interface using a selected agent
|
92 |
+
def chat_interface_with_agent(input_text, agent_name):
|
93 |
+
agent_prompt = load_agent_prompt(agent_name)
|
94 |
+
if agent_prompt is None:
|
95 |
+
return f"Agent {agent_name} not found."
|
96 |
|
97 |
+
# Load the GPT-2 model which is compatible with AutoModelForCausalLM
|
98 |
+
model_name = "gpt2"
|
99 |
+
try:
|
100 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
101 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
102 |
+
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
103 |
+
except EnvironmentError as e:
|
104 |
+
return f"Error loading model: {e}"
|
105 |
+
|
106 |
+
# Combine the agent prompt with user input
|
107 |
+
combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
|
108 |
+
|
109 |
+
# Truncate input text to avoid exceeding the model's maximum length
|
110 |
+
max_input_length = 900
|
111 |
+
input_ids = tokenizer.encode(combined_input, return_tensors="pt")
|
112 |
+
if input_ids.shape[1] > max_input_length:
|
113 |
+
input_ids = input_ids[:, :max_input_length]
|
114 |
+
|
115 |
+
# Generate chatbot response
|
116 |
+
outputs = model.generate(
|
117 |
+
input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True,
|
118 |
+
pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
|
119 |
+
)
|
120 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
121 |
+
return response
|
122 |
|
|
|
|
|
123 |
|
124 |
+
# Basic chat interface (no agent)
|
125 |
+
def chat_interface(input_text):
|
126 |
+
# Load the GPT-2 model
|
127 |
+
model_name = "gpt2"
|
128 |
+
try:
|
129 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
130 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
131 |
+
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
132 |
+
except EnvironmentError as e:
|
133 |
+
return f"Error loading model: {e}"
|
134 |
+
|
135 |
+
# Generate chatbot response
|
136 |
+
outputs = generator(input_text, max_new_tokens=50, num_return_sequences=1, do_sample=True)
|
137 |
+
response = outputs[0]['generated_text']
|
138 |
+
return response
|
139 |
+
|
140 |
+
|
141 |
+
def workspace_interface(project_name):
|
142 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
143 |
+
if not os.path.exists(PROJECT_ROOT):
|
144 |
+
os.makedirs(PROJECT_ROOT)
|
145 |
if not os.path.exists(project_path):
|
146 |
os.makedirs(project_path)
|
147 |
+
st.session_state.workspace_projects[project_name] = {"files": []}
|
148 |
+
st.session_state.current_state['workspace_chat']['project_name'] = project_name
|
149 |
+
commit_and_push_changes(f"Create project {project_name}")
|
150 |
+
return f"Project {project_name} created successfully."
|
151 |
+
else:
|
152 |
+
return f"Project {project_name} already exists."
|
153 |
+
|
154 |
+
|
155 |
+
def add_code_to_workspace(project_name, code, file_name):
|
156 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
157 |
+
if os.path.exists(project_path):
|
158 |
+
file_path = os.path.join(project_path, file_name)
|
159 |
+
with open(file_path, "w") as file:
|
160 |
+
file.write(code)
|
161 |
+
st.session_state.workspace_projects[project_name]["files"].append(file_name)
|
162 |
+
st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
|
163 |
+
commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
|
164 |
+
return f"Code added to {file_name} in project {project_name} successfully."
|
165 |
+
else:
|
166 |
+
return f"Project {project_name} does not exist."
|
167 |
|
|
|
|
|
|
|
168 |
|
169 |
+
def terminal_interface(command, project_name=None):
|
170 |
+
if project_name:
|
171 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
172 |
+
if not os.path.exists(project_path):
|
173 |
+
return f"Project {project_name} does not exist."
|
174 |
+
result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
|
175 |
+
else:
|
176 |
+
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
177 |
+
if result.returncode == 0:
|
178 |
+
st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
|
179 |
+
return result.stdout
|
180 |
+
else:
|
181 |
+
st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
|
182 |
+
return result.stderr
|
183 |
|
|
|
|
|
184 |
|
185 |
+
def summarize_text(text):
|
186 |
+
summarizer = pipeline("summarization")
|
187 |
+
summary = summarizer(text, max_length=100, min_length=25, do_sample=False)
|
188 |
+
st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
|
189 |
+
return summary[0]['summary_text']
|
190 |
|
|
|
|
|
191 |
|
192 |
+
def sentiment_analysis(text):
|
193 |
+
analyzer = pipeline("sentiment-analysis")
|
194 |
+
sentiment = analyzer(text)
|
195 |
+
st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
|
196 |
+
return sentiment[0]
|
197 |
|
|
|
|
|
198 |
|
199 |
+
def code_editor_interface(code):
|
200 |
+
"""Formats and lints Python code using black and pylint."""
|
201 |
+
try:
|
202 |
+
formatted_code = black.format_str(code, mode=black.FileMode())
|
203 |
+
lint_result = StringIO()
|
204 |
+
lint.Run([
|
205 |
+
'--disable=C0114,C0115,C0116', # Disable missing docstrings warnings
|
206 |
+
'--output-format=text',
|
207 |
+
'--reports=n', # Disable report generation
|
208 |
+
'-' # Read from stdin
|
209 |
+
], exit=False, do_exit=False)
|
210 |
+
lint_message = lint_result.getvalue()
|
211 |
+
return formatted_code, lint_message
|
212 |
+
except Exception as e:
|
213 |
+
return code, f"Error formatting or linting code: {e}"
|
214 |
|
|
|
|
|
|
|
|
|
215 |
|
216 |
+
def translate_code(code, input_language, output_language):
|
217 |
+
"""
|
218 |
+
Translates code using the Hugging Face translation pipeline.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
|
220 |
+
Note: This is a basic example and may not be suitable for all code translation tasks.
|
221 |
+
Consider using more specialized tools for complex code translation.
|
222 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
try:
|
224 |
+
translator = pipeline("translation", model=f"{input_language}-to-{output_language}")
|
225 |
+
translated_code = translator(code, max_length=10000)[0]['translation_text']
|
226 |
+
st.session_state.current_state['toolbox']['translated_code'] = translated_code
|
227 |
+
return translated_code
|
228 |
except Exception as e:
|
229 |
+
return f"Error translating code: {e}"
|
230 |
|
231 |
+
|
232 |
+
def generate_code(code_idea):
|
233 |
+
"""Generates code using the Hugging Face text-generation pipeline."""
|
234 |
try:
|
235 |
+
generator = pipeline('text-generation', model='gpt2') # You can replace 'gpt2' with a more suitable model
|
236 |
+
generated_code = generator(f"```python\n{code_idea}\n```", max_length=1000, num_return_sequences=1)[0][
|
237 |
+
'generated_text']
|
238 |
+
|
239 |
+
# Extract code from the generated text (assuming it's wrapped in ```python ... ```)
|
240 |
+
start_index = generated_code.find("```python") + len("```python")
|
241 |
+
end_index = generated_code.find("```", start_index)
|
242 |
+
if start_index != -1 and end_index != -1:
|
243 |
+
generated_code = generated_code[start_index:end_index].strip()
|
244 |
+
|
245 |
+
st.session_state.current_state['toolbox']['generated_code'] = generated_code
|
246 |
+
return generated_code
|
247 |
except Exception as e:
|
248 |
+
return f"Error generating code: {e}"
|
249 |
+
|
250 |
+
|
251 |
+
def commit_and_push_changes(commit_message):
|
252 |
+
"""Commits and pushes changes to the Hugging Face repository."""
|
253 |
+
commands = [
|
254 |
+
"git add .",
|
255 |
+
f"git commit -m '{commit_message}'",
|
256 |
+
"git push"
|
257 |
+
]
|
258 |
+
for command in commands:
|
259 |
+
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
260 |
+
if result.returncode != 0:
|
261 |
+
st.error(f"Error executing command '{command}': {result.stderr}")
|
262 |
+
break
|
263 |
+
|
264 |
+
|
265 |
+
# Streamlit App
|
266 |
+
st.title("AI Agent Creator")
|
267 |
+
|
268 |
+
# Sidebar navigation
|
269 |
+
st.sidebar.title("Navigation")
|
270 |
+
app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
|
271 |
+
|
272 |
+
if app_mode == "AI Agent Creator":
|
273 |
+
# AI Agent Creator
|
274 |
+
st.header("Create an AI Agent from Text")
|
275 |
+
|
276 |
+
st.subheader("From Text")
|
277 |
+
agent_name = st.text_input("Enter agent name:")
|
278 |
+
text_input = st.text_area("Enter skills (one per line):")
|
279 |
+
if st.button("Create Agent"):
|
280 |
+
agent_prompt = create_agent_from_text(agent_name, text_input)
|
281 |
+
st.success(f"Agent '{agent_name}' created and saved successfully.")
|
282 |
+
st.session_state.available_agents.append(agent_name)
|
283 |
+
|
284 |
+
elif app_mode == "Tool Box":
|
285 |
+
# Tool Box
|
286 |
+
st.header("AI-Powered Tools")
|
287 |
+
|
288 |
+
# Chat Interface
|
289 |
+
st.subheader("Chat with CodeCraft")
|
290 |
+
chat_input = st.text_area("Enter your message:")
|
291 |
+
if st.button("Send"):
|
292 |
+
if chat_input.startswith("@"):
|
293 |
+
agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
|
294 |
+
chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
|
295 |
+
chat_response = chat_interface_with_agent(chat_input, agent_name)
|
296 |
+
else:
|
297 |
+
chat_response = chat_interface(chat_input)
|
298 |
+
st.session_state.chat_history.append((chat_input, chat_response))
|
299 |
+
st.write(f"CodeCraft: {chat_response}")
|
300 |
+
|
301 |
+
# Terminal Interface
|
302 |
+
st.subheader("Terminal")
|
303 |
+
terminal_input = st.text_input("Enter a command:")
|
304 |
+
if st.button("Run"):
|
305 |
+
terminal_output = terminal_interface(terminal_input)
|
306 |
+
st.session_state.terminal_history.append((terminal_input, terminal_output))
|
307 |
+
st.code(terminal_output, language="bash")
|
308 |
+
|
309 |
+
# Code Editor Interface
|
310 |
+
st.subheader("Code Editor")
|
311 |
+
code_editor = st.text_area("Write your code:", height=300)
|
312 |
+
if st.button("Format & Lint"):
|
313 |
+
formatted_code, lint_message = code_editor_interface(code_editor)
|
314 |
+
st.code(formatted_code, language="python")
|
315 |
+
st.info(lint_message)
|
316 |
+
|
317 |
+
# Text Summarization Tool
|
318 |
+
st.subheader("Summarize Text")
|
319 |
+
text_to_summarize = st.text_area("Enter text to summarize:")
|
320 |
+
if st.button("Summarize"):
|
321 |
+
summary = summarize_text(text_to_summarize)
|
322 |
+
st.write(f"Summary: {summary}")
|
323 |
+
|
324 |
+
# Sentiment Analysis Tool
|
325 |
+
st.subheader("Sentiment Analysis")
|
326 |
+
sentiment_text = st.text_area("Enter text for sentiment analysis:")
|
327 |
+
if st.button("Analyze Sentiment"):
|
328 |
+
sentiment = sentiment_analysis(sentiment_text)
|
329 |
+
st.write(f"Sentiment: {sentiment}")
|
330 |
+
|
331 |
+
# Text Translation Tool (Code Translation)
|
332 |
+
st.subheader("Translate Code")
|
333 |
+
code_to_translate = st.text_area("Enter code to translate:")
|
334 |
+
source_language = st.selectbox("Source Language", ["en", "fr", "de", "es", "zh", "ja", "ko", "ru"]) # Add more languages as needed
|
335 |
+
target_language = st.selectbox("Target Language", ["en", "fr", "de", "es", "zh", "ja", "ko", "ru"]) # Add more languages as needed
|
336 |
+
if st.button("Translate Code"):
|
337 |
+
translated_code = translate_code(code_to_translate, source_language, target_language)
|
338 |
+
st.code(translated_code, language=target_language.lower())
|
339 |
+
|
340 |
+
# Code Generation
|
341 |
+
st.subheader("Code Generation")
|
342 |
+
code_idea = st.text_input("Enter your code idea:")
|
343 |
+
if st.button("Generate Code"):
|
344 |
+
generated_code = generate_code(code_idea)
|
345 |
+
st.code(generated_code, language="python")
|
346 |
+
|
347 |
+
# Display Preset Commands
|
348 |
+
st.subheader("Preset Commands")
|
349 |
+
preset_commands = {
|
350 |
+
"Create a new project": "create_project('project_name')",
|
351 |
+
"Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
|
352 |
+
"Run terminal command": "terminal_interface('command', 'project_name')",
|
353 |
+
"Generate code": "generate_code('code_idea')",
|
354 |
+
"Summarize text": "summarize_text('text')",
|
355 |
+
"Analyze sentiment": "sentiment_analysis('text')",
|
356 |
+
"Translate code": "translate_code('code', 'source_language', 'target_language')",
|
357 |
+
}
|
358 |
+
for command_name, command in preset_commands.items():
|
359 |
+
st.write(f"{command_name}: `{command}`")
|
360 |
+
|
361 |
+
elif app_mode == "Workspace Chat App":
|
362 |
+
# Workspace Chat App
|
363 |
+
st.header("Workspace Chat App")
|
364 |
+
|
365 |
+
# Project Workspace Creation
|
366 |
+
st.subheader("Create a New Project")
|
367 |
+
project_name = st.text_input("Enter project name:")
|
368 |
+
if st.button("Create Project"):
|
369 |
+
workspace_status = workspace_interface(project_name)
|
370 |
+
st.success(workspace_status)
|
371 |
+
|
372 |
+
# Add Code to Workspace
|
373 |
+
st.subheader("Add Code to Workspace")
|
374 |
+
code_to_add = st.text_area("Enter code to add to workspace:")
|
375 |
+
file_name = st.text_input("Enter file name (e.g. 'app.py'):")
|
376 |
+
if st.button("Add Code"):
|
377 |
+
add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
|
378 |
+
st.success(add_code_status)
|
379 |
+
|
380 |
+
# Terminal Interface with Project Context
|
381 |
+
st.subheader("Terminal (Workspace Context)")
|
382 |
+
terminal_input = st.text_input("Enter a command within the workspace:")
|
383 |
+
if st.button("Run Command"):
|
384 |
+
terminal_output = terminal_interface(terminal_input, project_name)
|
385 |
+
st.code(terminal_output, language="bash")
|
386 |
+
|
387 |
+
# Chat Interface for Guidance
|
388 |
+
st.subheader("Chat with CodeCraft for Guidance")
|
389 |
+
chat_input = st.text_area("Enter your message for guidance:")
|
390 |
+
if st.button("Get Guidance"):
|
391 |
+
chat_response = chat_interface(chat_input)
|
392 |
+
st.session_state.chat_history.append((chat_input, chat_response))
|
393 |
+
st.write(f"CodeCraft: {chat_response}")
|
394 |
+
|
395 |
+
# Display Chat History
|
396 |
+
st.subheader("Chat History")
|
397 |
+
for user_input, response in st.session_state.chat_history:
|
398 |
+
st.write(f"User: {user_input}")
|
399 |
+
st.write(f"CodeCraft: {response}")
|
400 |
+
|
401 |
+
# Display Terminal History
|
402 |
+
st.subheader("Terminal History")
|
403 |
+
for command, output in st.session_state.terminal_history:
|
404 |
+
st.write(f"Command: {command}")
|
405 |
+
st.code(output, language="bash")
|
406 |
+
|
407 |
+
# Display Projects and Files
|
408 |
+
st.subheader("Workspace Projects")
|
409 |
+
for project, details in st.session_state.workspace_projects.items():
|
410 |
+
st.write(f"Project: {project}")
|
411 |
+
for file in details['files']:
|
412 |
+
st.write(f" - {file}")
|
413 |
+
|
414 |
+
# Chat with AI Agents
|
415 |
+
st.subheader("Chat with AI Agents")
|
416 |
+
selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
|
417 |
+
agent_chat_input = st.text_area("Enter your message for the agent:")
|
418 |
+
if st.button("Send to Agent"):
|
419 |
+
agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
|
420 |
+
st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
|
421 |
+
st.write(f"{selected_agent}: {agent_chat_response}")
|
422 |
+
|
423 |
+
# Automate Build Process
|
424 |
+
st.subheader("Automate Build Process")
|
425 |
+
if st.button("Automate"):
|
426 |
+
agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
|
427 |
+
summary, next_step = agent.autonomous_build(st.session_state.chat_history,
|
428 |
+
st.session_state.workspace_projects)
|
429 |
+
st.write("Autonomous Build Summary:")
|
430 |
+
st.write(summary)
|
431 |
+
st.write("Next Step:")
|
432 |
+
st.write(next_step)
|
433 |
+
|
434 |
+
# Display current state for debugging
|
435 |
+
st.sidebar.subheader("Current State")
|
436 |
+
st.sidebar.json(st.session_state.current_state)
|