Spaces:
Build error
Build error
acecalisto3
commited on
Commit
•
ecbc10f
1
Parent(s):
d3b7eee
Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import subprocess
|
3 |
-
import
|
4 |
-
|
5 |
-
from
|
|
|
6 |
import torch
|
7 |
-
from datetime import datetime
|
8 |
from huggingface_hub import hf_hub_url, cached_download, HfApi
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
# Constants
|
12 |
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
|
13 |
PROJECT_ROOT = "projects"
|
14 |
AGENT_DIRECTORY = "agents"
|
15 |
-
AVAILABLE_CODE_GENERATIVE_MODELS = [
|
16 |
-
"bigcode/starcoder", # Popular and powerful
|
17 |
-
"Salesforce/codegen-350M-mono", # Smaller, good for quick tasks
|
18 |
-
"microsoft/CodeGPT-small", # Smaller, good for quick tasks
|
19 |
-
"google/flan-t5-xl", # Powerful, good for complex tasks
|
20 |
-
"facebook/bart-large-cnn", # Good for text-to-code tasks
|
21 |
-
]
|
22 |
-
|
23 |
-
# Load environment variables
|
24 |
-
load_dotenv()
|
25 |
-
HF_TOKEN = os.getenv("HUGGING_FACE_API_KEY")
|
26 |
-
|
27 |
-
# Initialize logger
|
28 |
-
logging.basicConfig(level=logging.INFO)
|
29 |
|
30 |
# Global state to manage communication between Tool Box and Workspace Chat App
|
31 |
if 'chat_history' not in st.session_state:
|
@@ -36,296 +34,374 @@ if 'workspace_projects' not in st.session_state:
|
|
36 |
st.session_state.workspace_projects = {}
|
37 |
if 'available_agents' not in st.session_state:
|
38 |
st.session_state.available_agents = []
|
39 |
-
if 'current_state' not in st.session_state:
|
40 |
-
st.session_state.current_state = {
|
41 |
-
'toolbox': {},
|
42 |
-
'workspace_chat': {}
|
43 |
-
}
|
44 |
-
|
45 |
-
# Load pre-trained RAG retriever
|
46 |
-
rag_retriever = RagRetriever.from_pretrained("facebook/rag-token-base") # Use a Hugging Face RAG model
|
47 |
-
|
48 |
-
# Load pre-trained chat model
|
49 |
-
chat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium") # Use a Hugging Face chat model
|
50 |
|
51 |
-
#
|
52 |
-
|
53 |
|
54 |
-
# Define a class for the AI Agent
|
55 |
class AIAgent:
|
56 |
-
def __init__(self, name, description, skills):
|
57 |
self.name = name
|
58 |
self.description = description
|
59 |
self.skills = skills
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
|
62 |
-
def process_input(user_input):
|
63 |
-
# Input pipeline: Tokenize and preprocess user input
|
64 |
-
input_ids = tokenizer(user_input, return_tensors="pt").input_ids
|
65 |
-
attention_mask = tokenizer(user_input, return_tensors="pt").attention_mask
|
66 |
-
|
67 |
-
# RAG model: Generate response
|
68 |
-
output = rag_retriever(input_ids, attention_mask=attention_mask)
|
69 |
-
response = output.generator_outputs[0].sequences[0]
|
70 |
-
|
71 |
-
# Chat model: Refine response
|
72 |
-
chat_input = tokenizer(response, return_tensors="pt")
|
73 |
-
chat_input["input_ids"] = chat_input["input_ids"].unsqueeze(0)
|
74 |
-
chat_input["attention_mask"] = chat_input["attention_mask"].unsqueeze(0)
|
75 |
-
output = chat_model(**chat_input)
|
76 |
-
refined_response = output.sequences[0]
|
77 |
-
|
78 |
-
# Output pipeline: Return final response
|
79 |
-
return refined_response
|
80 |
-
|
81 |
-
# Define a function to create a new project
|
82 |
-
def create_project(project_name):
|
83 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
84 |
-
if os.path.exists(project_path):
|
85 |
-
return f"Project '{project_name}' already exists."
|
86 |
-
else:
|
87 |
os.makedirs(project_path)
|
88 |
st.session_state.workspace_projects[project_name] = {'files': []}
|
89 |
return f"Project '{project_name}' created successfully."
|
|
|
|
|
90 |
|
91 |
-
|
92 |
-
def add_code_to_project(project_name, code, file_name):
|
93 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
94 |
if not os.path.exists(project_path):
|
95 |
return f"Project '{project_name}' does not exist."
|
96 |
-
|
97 |
file_path = os.path.join(project_path, file_name)
|
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 |
-
for
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
git_repo_url = hf_hub_url(repository_name)
|
167 |
-
git = subprocess.Popen(["git", "init"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=project_path)
|
168 |
-
git.communicate()
|
169 |
-
|
170 |
-
git = subprocess.Popen(["git", "add", "-A"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=project_path)
|
171 |
-
git.communicate()
|
172 |
-
|
173 |
-
for file in files:
|
174 |
-
filename = "temp.txt"
|
175 |
-
with open("temp.txt", "wb") as temp_file:
|
176 |
-
temp_file.write(file)
|
177 |
-
git = subprocess.Popen(["git", "add", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=project_path)
|
178 |
-
git.communicate()
|
179 |
-
os.remove("temp.txt")
|
180 |
-
|
181 |
-
git = subprocess.Popen(["git", "commit", "-m", "Initial commit"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=project_path)
|
182 |
-
git.communicate()
|
183 |
-
|
184 |
-
return git.returncode == 0
|
185 |
-
|
186 |
-
# Define a function to publish a space
|
187 |
-
def publish_space(repository_name, hf_token):
|
188 |
-
api = HfApi(token=hf_token)
|
189 |
-
api.create_model(repository_name, files=[], push_to_hub=True)
|
190 |
-
|
191 |
-
# Define a function to handle autonomous build
|
192 |
-
def handle_autonomous_build():
|
193 |
-
if not st.session_state.workspace_projects or not st.session_state.available_agents:
|
194 |
-
st.error("No projects or agents available to build.")
|
195 |
-
return
|
196 |
-
|
197 |
-
project_name = list(st.session_state.workspace_projects.keys())[0]
|
198 |
-
selected_agent = st.session_state.available_agents[0]
|
199 |
-
code_idea = st.session_state.current_state["workspace_chat"]["user_input"]
|
200 |
-
code_generative_model = next((model for model in AVAILABLE_CODE_GENERATIVE_MODELS if model in st.session_state.current_state["toolbox"]["selected_models"]), None)
|
201 |
|
202 |
-
|
203 |
-
st.error("No code-generative model selected.")
|
204 |
-
return
|
205 |
-
|
206 |
-
logging.info(f"Building project '{project_name}' with agent '{selected_agent}' and model '{code_generative_model}'.")
|
207 |
-
|
208 |
-
try:
|
209 |
-
# TODO: Add code to run the build process here
|
210 |
-
# This could include generating code, running it, and updating the workspace projects
|
211 |
-
# The build process should also update the UI with the build summary and next steps
|
212 |
-
summary, next_step = build_project(project_name, selected_agent, code_idea, code_generative_model)
|
213 |
-
st.write(f"Build summary: {summary}")
|
214 |
-
st.write(f"Next step: {next_step}")
|
215 |
-
|
216 |
-
if next_step == "Deploy to Hugging Face Hub":
|
217 |
-
deploy_response = deploy_space_to_hf(project_name, HF_TOKEN)
|
218 |
-
st.write(deploy_response)
|
219 |
-
except Exception as e:
|
220 |
-
logging.error(f"Error during build process: {e}")
|
221 |
-
st.error("Error during build process.")
|
222 |
-
|
223 |
-
# Define a function to build a project
|
224 |
-
def build_project(project_name, agent, code_idea, code_generative_model):
|
225 |
-
# TODO: Add code to build the project here
|
226 |
-
# This could include generating code, running it, and updating the workspace projects
|
227 |
-
# The build process should also return a summary and next step
|
228 |
-
summary = "Project built successfully."
|
229 |
-
next_step = ""
|
230 |
-
return summary, next_step
|
231 |
-
|
232 |
-
# Define the main function
|
233 |
-
def main():
|
234 |
-
# Initialize the app
|
235 |
-
st.title("AI Agent Creator")
|
236 |
-
|
237 |
-
# Sidebar navigation
|
238 |
st.sidebar.title("Navigation")
|
239 |
-
app_mode = st.sidebar.selectbox("Choose the app mode", ["
|
240 |
-
|
241 |
-
if app_mode == "AI Agent Creator":
|
242 |
-
# AI Agent Creator
|
243 |
-
st.header("Create an AI Agent from Text")
|
244 |
-
|
245 |
-
st.subheader("From Text")
|
246 |
-
agent_name = st.text_input("Enter agent name:")
|
247 |
-
text_input = st.text_area("Enter skills (one per line):")
|
248 |
-
if st.button("Create Agent"):
|
249 |
-
skills = text_input.split('\n')
|
250 |
-
try:
|
251 |
-
agent = AIAgent(agent_name, "AI agent created from text input", skills)
|
252 |
-
st.session_state.available_agents.append(agent_name)
|
253 |
-
st.success(f"Agent '{agent_name}' created and saved successfully.")
|
254 |
-
except Exception as e:
|
255 |
-
st.error(f"Error creating agent: {e}")
|
256 |
-
|
257 |
-
elif app_mode == "Tool Box":
|
258 |
-
# Tool Box
|
259 |
-
st.header("AI-Powered Tools")
|
260 |
-
|
261 |
-
# Chat Interface
|
262 |
-
st.subheader("Chat with CodeCraft")
|
263 |
-
chat_input = st.text_area("Enter your message:")
|
264 |
-
if st.button("Send"):
|
265 |
-
response = process_input(chat_input)
|
266 |
-
st.session_state.chat_history.append((chat_input, response))
|
267 |
-
st.write(f"CodeCraft: {response}")
|
268 |
|
269 |
-
|
270 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
271 |
terminal_input = st.text_input("Enter a command:")
|
272 |
if st.button("Run"):
|
273 |
output = run_code(terminal_input)
|
274 |
st.session_state.terminal_history.append((terminal_input, output))
|
275 |
st.code(output, language="bash")
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
st.
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
if
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
st.
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
st.write(
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
st.code(
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
if
|
331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
🧠
|
2 |
+
gemini-1.5-flash-latest
|
3 |
+
import streamlit as st
|
4 |
+
from streamlit_ace import st_ace
|
5 |
+
from streamlit_jupyter import st_jupyter
|
6 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
7 |
import os
|
8 |
import subprocess
|
9 |
+
import black
|
10 |
+
from pylint import lint
|
11 |
+
from io import StringIO
|
12 |
+
import sys
|
13 |
import torch
|
|
|
14 |
from huggingface_hub import hf_hub_url, cached_download, HfApi
|
15 |
+
import re
|
16 |
+
from typing import List, Dict
|
17 |
+
|
18 |
+
# Access Hugging Face API key from secrets
|
19 |
+
hf_token = st.secrets["hf_token"]
|
20 |
+
if not hf_token:
|
21 |
+
st.error("Hugging Face API key not found. Please make sure it is set in the secrets.")
|
22 |
|
|
|
23 |
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
|
24 |
PROJECT_ROOT = "projects"
|
25 |
AGENT_DIRECTORY = "agents"
|
26 |
+
AVAILABLE_CODE_GENERATIVE_MODELS = ["bigcode/starcoder", "Salesforce/codegen-350M-mono", "microsoft/CodeGPT-small"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
# Global state to manage communication between Tool Box and Workspace Chat App
|
29 |
if 'chat_history' not in st.session_state:
|
|
|
34 |
st.session_state.workspace_projects = {}
|
35 |
if 'available_agents' not in st.session_state:
|
36 |
st.session_state.available_agents = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
+
# AI Guide Toggle
|
39 |
+
ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
|
40 |
|
|
|
41 |
class AIAgent:
|
42 |
+
def __init__(self, name: str, description: str, skills: List[str]):
|
43 |
self.name = name
|
44 |
self.description = description
|
45 |
self.skills = skills
|
46 |
+
self._hf_api = HfApi() # Initialize HfApi here
|
47 |
+
|
48 |
+
def create_agent_prompt(self) -> str:
|
49 |
+
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
50 |
+
agent_prompt = f"""
|
51 |
+
As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
|
52 |
+
{skills_str}
|
53 |
+
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.
|
54 |
+
"""
|
55 |
+
return agent_prompt
|
56 |
+
|
57 |
+
def autonomous_build(self, chat_history: List[tuple[str, str]], workspace_projects: Dict[str, Dict],
|
58 |
+
project_name: str, selected_model: str, hf_token: str) -> tuple[str, str]:
|
59 |
+
summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
60 |
+
summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
61 |
+
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
62 |
+
return summary, next_step
|
63 |
+
|
64 |
+
def deploy_built_space_to_hf(self, project_name: str) -> str:
|
65 |
+
# Assuming you have a function that generates the space content
|
66 |
+
space_content = generate_space_content(project_name)
|
67 |
+
repository = self._hf_api.create_repo(
|
68 |
+
repo_id=project_name,
|
69 |
+
private=True,
|
70 |
+
token=hf_token,
|
71 |
+
exist_ok=True,
|
72 |
+
space_sdk="streamlit"
|
73 |
+
)
|
74 |
+
self._hf_api.upload_file(
|
75 |
+
path_or_fileobj=space_content,
|
76 |
+
path_in_repo="app.py",
|
77 |
+
repo_id=project_name,
|
78 |
+
repo_type="space",
|
79 |
+
token=hf_token
|
80 |
+
)
|
81 |
+
return repository.name
|
82 |
+
|
83 |
+
def has_valid_hf_token(self) -> bool:
|
84 |
+
return self._hf_api.whoami(token=hf_token) is not None
|
85 |
+
|
86 |
+
def process_input(input_text: str) -> str:
|
87 |
+
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", tokenizer="microsoft/DialoGPT-medium", clean_up_tokenization_spaces=True)
|
88 |
+
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
89 |
+
return response
|
90 |
+
|
91 |
+
def run_code(code: str) -> str:
|
92 |
+
try:
|
93 |
+
result = subprocess.run(code, shell=True, capture_output=True, text=True)
|
94 |
+
return result.stdout
|
95 |
+
except Exception as e:
|
96 |
+
return str(e)
|
97 |
|
98 |
+
def workspace_interface(project_name: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
100 |
+
if not os.path.exists(project_path):
|
|
|
|
|
101 |
os.makedirs(project_path)
|
102 |
st.session_state.workspace_projects[project_name] = {'files': []}
|
103 |
return f"Project '{project_name}' created successfully."
|
104 |
+
else:
|
105 |
+
return f"Project '{project_name}' already exists."
|
106 |
|
107 |
+
def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
|
|
|
108 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
109 |
if not os.path.exists(project_path):
|
110 |
return f"Project '{project_name}' does not exist."
|
111 |
+
|
112 |
file_path = os.path.join(project_path, file_name)
|
113 |
+
with open(file_path, "w") as file:
|
114 |
+
file.write(code)
|
115 |
+
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
116 |
+
return f"Code added to '{file_name}' in project '{project_name}'."
|
117 |
+
|
118 |
+
def display_chat_history(chat_history: List[tuple[str, str]]) -> str:
|
119 |
+
return "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
120 |
+
|
121 |
+
def display_workspace_projects(workspace_projects: Dict[str, Dict]) -> str:
|
122 |
+
return "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
123 |
+
|
124 |
+
def generate_space_content(project_name: str) -> str:
|
125 |
+
# Logic to generate the Streamlit app content based on project_name
|
126 |
+
# ... (This is where you'll need to implement the actual code generation)
|
127 |
+
return "import streamlit as st\nst.title('My Streamlit App')\nst.write('Hello, world!')"
|
128 |
+
|
129 |
+
# Function to display the AI Guide chat
|
130 |
+
def display_ai_guide_chat(chat_history: List[tuple[str, str]]):
|
131 |
+
st.markdown("<div class='chat-history'>", unsafe_allow_html=True)
|
132 |
+
for user_message, agent_message in chat_history:
|
133 |
+
st.markdown(f"<div class='chat-message user'>{user_message}</div>", unsafe_allow_html=True)
|
134 |
+
st.markdown(f"<div class='chat-message agent'>{agent_message}</div>", unsafe_allow_html=True)
|
135 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
136 |
+
|
137 |
+
# Load the CodeGPT tokenizer explicitly
|
138 |
+
code_generator_tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
|
139 |
+
# Load the CodeGPT model for code completion
|
140 |
+
code_generator = pipeline("text-generation", model="microsoft/CodeGPT-small-py", tokenizer=code_generator_tokenizer)
|
141 |
+
|
142 |
+
def analyze_code(code: str) -> List[str]:
|
143 |
+
hints = []
|
144 |
+
|
145 |
+
# Example pointer: Suggest using list comprehensions
|
146 |
+
if re.search(r'for .* in .*:\n\s+.*\.append\(', code):
|
147 |
+
hints.append("Consider using a list comprehension instead of a loop for appending to a list.")
|
148 |
+
|
149 |
+
# Example pointer: Recommend using f-strings for string formatting
|
150 |
+
if re.search(r'\".*\%s\"|\'.*\%s\'', code) or re.search(r'\".*\%d\"|\'.*\%d\'', code):
|
151 |
+
hints.append("Consider using f-strings for cleaner and more efficient string formatting.")
|
152 |
+
|
153 |
+
# Example pointer: Avoid using global variables
|
154 |
+
if re.search(r'\bglobal\b', code):
|
155 |
+
hints.append("Avoid using global variables. Consider passing parameters or using classes.")
|
156 |
+
|
157 |
+
# Example pointer: Recommend using `with` statement for file operations
|
158 |
+
if re.search(r'open\(.+\)', code) and not re.search(r'with open\(.+\)', code):
|
159 |
+
hints.append("Consider using the `with` statement when opening files to ensure proper resource management.")
|
160 |
+
|
161 |
+
return hints
|
162 |
+
|
163 |
+
def get_code_completion(prompt: str) -> str:
|
164 |
+
# Generate code completion based on the current code input
|
165 |
+
# Use max_new_tokens instead of max_length
|
166 |
+
completions = code_generator(prompt, max_new_tokens=50, num_return_sequences=1)
|
167 |
+
return completions[0]['generated_text']
|
168 |
+
|
169 |
+
def lint_code(code: str) -> List[str]:
|
170 |
+
# Capture pylint output
|
171 |
+
pylint_output = StringIO()
|
172 |
+
sys.stdout = pylint_output
|
173 |
+
|
174 |
+
# Run pylint on the provided code
|
175 |
+
pylint.lint.Run(['--from-stdin'], do_exit=False, argv=[], stdin=StringIO(code))
|
176 |
+
|
177 |
+
# Reset stdout and fetch lint results
|
178 |
+
sys.stdout = sys.__stdout__
|
179 |
+
lint_results = pylint_output.getvalue().splitlines()
|
180 |
+
return lint_results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
|
182 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
st.sidebar.title("Navigation")
|
184 |
+
app_mode = st.sidebar.selectbox("Choose the app mode", ["Home", "Terminal", "Explorer", "Code Editor", "Build & Deploy"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
|
186 |
+
if app_mode == "Home":
|
187 |
+
st.title("Welcome to AI-Guided Development")
|
188 |
+
st.write("This application helps you build and deploy applications with the assistance of an AI Guide.")
|
189 |
+
st.write("Toggle the AI Guide from the sidebar to choose the level of assistance you need.")
|
190 |
+
|
191 |
+
elif app_mode == "Terminal":
|
192 |
+
st.header("Terminal")
|
193 |
terminal_input = st.text_input("Enter a command:")
|
194 |
if st.button("Run"):
|
195 |
output = run_code(terminal_input)
|
196 |
st.session_state.terminal_history.append((terminal_input, output))
|
197 |
st.code(output, language="bash")
|
198 |
+
if ai_guide_level != "No Assistance":
|
199 |
+
st.write("Run commands here to add packages to your project. For example: pip install <package-name>.")
|
200 |
+
if terminal_input and "install" in terminal_input:
|
201 |
+
package_name = terminal_input.split("install")[-1].strip()
|
202 |
+
st.write(f"Package {package_name} will be added to your project.")
|
203 |
+
|
204 |
+
elif app_mode == "Explorer":
|
205 |
+
st.header("Explorer")
|
206 |
+
uploaded_file = st.file_uploader("Upload a file", type=["py"])
|
207 |
+
if uploaded_file:
|
208 |
+
file_details = {"FileName": uploaded_file.name, "FileType": uploaded_file.type}
|
209 |
+
st.write(file_details)
|
210 |
+
save_path = os.path.join(PROJECT_ROOT, uploaded_file.name)
|
211 |
+
with open(save_path, "wb") as f:
|
212 |
+
f.write(uploaded_file.getbuffer())
|
213 |
+
st.success(f"File {uploaded_file.name} saved successfully!")
|
214 |
+
|
215 |
+
st.write("Drag and drop files into the 'app' folder.")
|
216 |
+
for project, details in st.session_state.workspace_projects.items():
|
217 |
+
st.write(f"Project: {project}")
|
218 |
+
for file in details['files']:
|
219 |
+
st.write(f" - {file}")
|
220 |
+
if st.button(f"Move {file} to app folder"):
|
221 |
+
# Logic to move file to 'app' folder
|
222 |
+
pass
|
223 |
+
if ai_guide_level != "No Assistance":
|
224 |
+
st.write("You can upload files and move them into the 'app' folder for building your application.")
|
225 |
+
|
226 |
+
elif app_mode == "Code Editor":
|
227 |
+
st.header("Code Editor")
|
228 |
+
code_editor = st.text_area("Write your code:", height=300)
|
229 |
+
if st.button("Save Code"):
|
230 |
+
# Logic to save code
|
231 |
+
pass
|
232 |
+
if ai_guide_level != "No Assistance":
|
233 |
+
st.write("The function foo() requires the bar package. Add it to requirements.txt.")
|
234 |
+
|
235 |
+
# Analyze code and provide real-time hints
|
236 |
+
hints = analyze_code(code_editor)
|
237 |
+
if hints:
|
238 |
+
st.write("**Helpful Hints:**")
|
239 |
+
for hint in hints:
|
240 |
+
st.write(f"- {hint}")
|
241 |
+
|
242 |
+
if st.button("Get Code Suggestion"):
|
243 |
+
# Provide a predictive code completion
|
244 |
+
completion = get_code_completion(code_editor)
|
245 |
+
st.write("**Suggested Code Completion:**")
|
246 |
+
st.code(completion, language="python")
|
247 |
+
|
248 |
+
if st.button("Check Code"):
|
249 |
+
# Analyze the code for errors and warnings
|
250 |
+
lint_results = lint_code(code_editor)
|
251 |
+
|
252 |
+
if lint_results:
|
253 |
+
st.write("**Errors and Warnings:**")
|
254 |
+
for result in lint_results:
|
255 |
+
st.write(result)
|
256 |
+
else:
|
257 |
+
st.write("No issues found! Your code is clean.")
|
258 |
+
|
259 |
+
elif app_mode == "Build & Deploy":
|
260 |
+
st.header("Build & Deploy")
|
261 |
+
project_name_input = st.text_input("Enter Project Name for Automation:")
|
262 |
+
if st.button("Automate"):
|
263 |
+
selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
|
264 |
+
selected_model = st.selectbox("Select a code-generative model", AVAILABLE_CODE_GENERATIVE_MODELS)
|
265 |
+
agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
|
266 |
+
summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name_input, selected_model, hf_token)
|
267 |
+
st.write("Autonomous Build Summary:")
|
268 |
+
st.write(summary)
|
269 |
+
st.write("Next Step:")
|
270 |
+
st.write(next_step)
|
271 |
+
if agent._hf_api and agent.has_valid_hf_token():
|
272 |
+
repository_name = agent.deploy_built_space_to_hf(project_name_input)
|
273 |
+
st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")
|
274 |
+
st.markdown(f"[Check out your new Space here](hf.co/{repository_name})")
|
275 |
+
|
276 |
+
# AI Guide Chat
|
277 |
+
if ai_guide_level != "No Assistance":
|
278 |
+
display_ai_guide_chat(st.session_state.chat_history)
|
279 |
+
# Add a text input for user to interact with the AI Guide
|
280 |
+
user_input = st.text_input("Ask the AI Guide a question:", key="user_input")
|
281 |
+
if st.button("Send"):
|
282 |
+
if user_input:
|
283 |
+
# Process the user's input and get a response from the AI Guide
|
284 |
+
agent_response = process_input(user_input)
|
285 |
+
st.session_state.chat_history.append((user_input, agent_response))
|
286 |
+
# Clear the user input field
|
287 |
+
st.session_state.user_input = ""
|
288 |
+
|
289 |
+
# CSS for styling
|
290 |
+
st.markdown("""
|
291 |
+
<style>
|
292 |
+
/* Advanced and Accommodating CSS */
|
293 |
+
body {
|
294 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
295 |
+
background-color: #f4f4f9;
|
296 |
+
color: #333;
|
297 |
+
margin: 0;
|
298 |
+
padding: 0;
|
299 |
+
}
|
300 |
+
h1, h2, h3, h4, h5, h6 {
|
301 |
+
color: #333;
|
302 |
+
}
|
303 |
+
.container {
|
304 |
+
width: 90%;
|
305 |
+
margin: 0 auto;
|
306 |
+
padding: 20px;
|
307 |
+
}
|
308 |
+
/* Navigation Sidebar */
|
309 |
+
.sidebar {
|
310 |
+
background-color: #2c3e50;
|
311 |
+
color: #ecf0f1;
|
312 |
+
padding: 20px;
|
313 |
+
height: 100vh;
|
314 |
+
position: fixed;
|
315 |
+
top: 0;
|
316 |
+
left: 0;
|
317 |
+
width: 250px;
|
318 |
+
overflow-y: auto;
|
319 |
+
}
|
320 |
+
.sidebar a {
|
321 |
+
color: #ecf0f1;
|
322 |
+
text-decoration: none;
|
323 |
+
display: block;
|
324 |
+
padding: 10px 0;
|
325 |
+
}
|
326 |
+
.sidebar a:hover {
|
327 |
+
background-color: #34495e;
|
328 |
+
border-radius: 5px;
|
329 |
+
}
|
330 |
+
/* Main Content */
|
331 |
+
.main-content {
|
332 |
+
margin-left: 270px;
|
333 |
+
padding: 20px;
|
334 |
+
}
|
335 |
+
/* Buttons */
|
336 |
+
button {
|
337 |
+
background-color: #3498db;
|
338 |
+
color: #fff;
|
339 |
+
border: none;
|
340 |
+
padding: 10px 20px;
|
341 |
+
border-radius: 5px;
|
342 |
+
cursor: pointer;
|
343 |
+
font-size: 16px;
|
344 |
+
}
|
345 |
+
button:hover {
|
346 |
+
background-color: #2980b9;
|
347 |
+
}
|
348 |
+
/* Text Areas and Inputs */
|
349 |
+
textarea, input[type="text"] {
|
350 |
+
width: 100%;
|
351 |
+
padding: 10px;
|
352 |
+
margin: 10px 0;
|
353 |
+
border: 1px solid #ddd;
|
354 |
+
border-radius: 5px;
|
355 |
+
box-sizing: border-box;
|
356 |
+
}
|
357 |
+
textarea:focus, input[type="text"]:focus {
|
358 |
+
border-color: #3498db;
|
359 |
+
outline: none;
|
360 |
+
}
|
361 |
+
/* Terminal Output */
|
362 |
+
.code-output {
|
363 |
+
background-color: #1e1e1e;
|
364 |
+
color: #dcdcdc;
|
365 |
+
padding: 20px;
|
366 |
+
border-radius: 5px;
|
367 |
+
font-family: 'Courier New', Courier, monospace;
|
368 |
+
}
|
369 |
+
/* Chat History */
|
370 |
+
.chat-history {
|
371 |
+
background-color: #ecf0f1;
|
372 |
+
padding: 20px;
|
373 |
+
border-radius: 5px;
|
374 |
+
max-height: 300px;
|
375 |
+
overflow-y: auto;
|
376 |
+
}
|
377 |
+
.chat-message {
|
378 |
+
margin-bottom: 10px;
|
379 |
+
}
|
380 |
+
.chat-message.user {
|
381 |
+
text-align: right;
|
382 |
+
color: #3498db;
|
383 |
+
}
|
384 |
+
.chat-message.agent {
|
385 |
+
text-align: left;
|
386 |
+
color: #e74c3c;
|
387 |
+
}
|
388 |
+
/* Project Management */
|
389 |
+
.project-list {
|
390 |
+
background-color: #ecf0f1;
|
391 |
+
padding: 20px;
|
392 |
+
border-radius: 5px;
|
393 |
+
max-height: 300px;
|
394 |
+
overflow-y: auto;
|
395 |
+
}
|
396 |
+
.project-item {
|
397 |
+
margin-bottom: 10px;
|
398 |
+
}
|
399 |
+
.project-item a {
|
400 |
+
color: #3498db;
|
401 |
+
text-decoration: none;
|
402 |
+
}
|
403 |
+
.project-item a:hover {
|
404 |
+
text-decoration: underline;
|
405 |
+
}
|
406 |
+
</style>
|
407 |
+
""", unsafe_allow_html=True)
|