acecalisto3 commited on
Commit
67963cb
·
verified ·
1 Parent(s): d8a967c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +274 -224
app.py CHANGED
@@ -1,159 +1,72 @@
1
  import os
2
- import sys
3
  import subprocess
4
- import base64
5
- import json
6
- from io import StringIO
7
- from typing import Dict, List
8
-
9
  import streamlit as st
10
- import torch
11
- from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer, HfApi
12
- from pylint import lint
13
  import black
 
 
14
 
15
- from setuptools import setup, Extension
16
- from Cython.Build import cythonize
17
-
18
- extensions = [
19
- Extension("app", ["app.pyx"]),
20
- ]
21
-
22
- setup(
23
- ext_modules=cythonize(extensions),
24
- )
25
-
26
- # Add your Hugging Face API token here
27
- hf_token = st.secrets["huggingface"]
28
-
29
- # Constants
30
- PROJECT_ROOT = "./projects"
31
- AGENT_DIRECTORY = "./agents"
32
- AVAILABLE_CODE_GENERATIVE_MODELS = ["codegen", "gpt-neo", "codeparrot"]
33
 
34
- # Global state management
35
- if "chat_history" not in st.session_state:
36
  st.session_state.chat_history = []
37
- if "terminal_history" not in st.session_state:
38
  st.session_state.terminal_history = []
39
- if "workspace_projects" not in st.session_state:
40
  st.session_state.workspace_projects = {}
41
- if "available_agents" not in st.session_state:
42
  st.session_state.available_agents = []
43
-
44
- # Load pre-trained models
45
- @st.cache(allow_output_mutation=True)
46
- def load_models():
47
- rag_retriever = pipeline("question-answering", model="facebook/rag-token-nq")
48
- chat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium")
49
- tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
50
- return rag_retriever, chat_model, tokenizer
51
-
52
- rag_retriever, chat_model, tokenizer = load_models()
53
-
54
- def process_input(user_input: str) -> str:
55
- # Input pipeline: Tokenize and preprocess user input
56
- input_ids = tokenizer(user_input, return_tensors="pt").input_ids
57
- attention_mask = tokenizer(user_input, return_tensors="pt").attention_mask
58
-
59
- # RAG model: Generate response
60
- with torch.no_grad():
61
- rag_output = rag_retriever(question=user_input, context=user_input)
62
- rag_answer = rag_output['answer']
63
-
64
- # Chat model: Refine response
65
- chat_input = tokenizer(rag_answer, return_tensors="pt")
66
- with torch.no_grad():
67
- chat_output = chat_model.generate(**chat_input)
68
- refined_response = tokenizer.decode(chat_output[0], skip_special_tokens=True)
69
-
70
- return refined_response
71
 
72
  class AIAgent:
73
- def __init__(self, name: str, description: str, skills: List[str], hf_api=None):
74
  self.name = name
75
  self.description = description
76
  self.skills = skills
77
- self._hf_api = hf_api
78
- self._hf_token = hf_token
79
-
80
- @property
81
- def hf_api(self):
82
- if not self._hf_api and self.has_valid_hf_token():
83
- self._hf_api = HfApi(token=self._hf_token)
84
- return self._hf_api
85
-
86
- def has_valid_hf_token(self):
87
- return bool(self._hf_token)
88
 
89
  def create_agent_prompt(self):
90
- return f"Name: {self.name}\nDescription: {self.description}\nSkills:\n" + "\n".join(self.skills)
 
 
 
 
 
 
91
 
92
- async def autonomous_build(self, chat_history: List[str], workspace_projects: Dict[str, str], project_name: str, selected_model: str):
93
- summary = "Chat History:\n" + "\n".join(chat_history)
94
- summary += "\n\nWorkspace Projects:\n" + "\n".join(workspace_projects.items())
 
 
 
95
 
96
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
97
 
98
- project_path = os.path.join(PROJECT_ROOT, project_name)
99
- if not os.path.exists(project_path):
100
- os.makedirs(project_path)
101
-
102
- requirements_file = os.path.join(project_path, "requirements.txt")
103
- if not os.path.exists(requirements_file):
104
- with open(requirements_file, "w") as f:
105
- f.write("# Add your project's dependencies here\n")
106
-
107
- app_file = os.path.join(project_path, "app.py")
108
- if not os.path.exists(app_file):
109
- with open(app_file, "w") as f:
110
- f.write("# Your project's main application logic goes here\n")
111
-
112
- if "create a gui" in summary.lower():
113
- gui_code = generate_code(
114
- "Create a simple GUI for this application", selected_model)
115
- with open(app_file, "a") as f:
116
- f.write(gui_code)
117
-
118
- build_command = "pip install -r requirements.txt && python app.py"
119
- try:
120
- result = subprocess.run(
121
- build_command, shell=True, capture_output=True, text=True, cwd=project_path)
122
- st.write(f"Build Output:\n{result.stdout}")
123
- if result.stderr:
124
- st.error(f"Build Errors:\n{result.stderr}")
125
- except Exception as e:
126
- st.error(f"Build Error: {e}")
127
-
128
  return summary, next_step
129
 
130
- def deploy_built_space_to_hf(self):
131
- if not self.has_valid_hf_token():
132
- st.error("Invalid Hugging Face token. Please check your configuration.")
133
- return
134
-
135
- try:
136
- files = get_built_space_files()
137
- create_space_on_hugging_face(self.hf_api, self.name, self.description, True, files)
138
- st.success(f"Successfully deployed {self.name} to Hugging Face Spaces!")
139
- except Exception as e:
140
- st.error(f"Error deploying to Hugging Face Spaces: {str(e)}")
141
-
142
- def get_built_space_files() -> Dict[str, str]:
143
- return {
144
- "app.py": "# Your Streamlit app code here",
145
- "requirements.txt": "streamlit\ntransformers"
146
- }
147
-
148
- def save_agent_to_file(agent: AIAgent):
149
  if not os.path.exists(AGENT_DIRECTORY):
150
  os.makedirs(AGENT_DIRECTORY)
151
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
 
152
  with open(file_path, "w") as file:
153
  file.write(agent.create_agent_prompt())
 
 
154
  st.session_state.available_agents.append(agent.name)
155
 
156
- def load_agent_prompt(agent_name: str) -> str:
 
 
 
157
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
158
  if os.path.exists(file_path):
159
  with open(file_path, "r") as file:
@@ -162,127 +75,177 @@ def load_agent_prompt(agent_name: str) -> str:
162
  else:
163
  return None
164
 
165
- def create_agent_from_text(name: str, text: str) -> str:
166
- skills = text.split("\n")
167
  agent = AIAgent(name, "AI agent created from text input.", skills)
168
  save_agent_to_file(agent)
169
  return agent.create_agent_prompt()
170
 
171
- def chat_interface_with_agent(input_text: str, agent_name: str) -> str:
 
172
  agent_prompt = load_agent_prompt(agent_name)
173
  if agent_prompt is None:
174
  return f"Agent {agent_name} not found."
175
 
176
- model_name = "microsoft/DialoGPT-medium"
 
177
  try:
178
- generator = pipeline("text-generation", model=model_name)
179
- generated_response = generator(
180
- f"{agent_prompt}\n\nUser: {input_text}\nAgent:", max_length=100, do_sample=True, top_k=50)[0]["generated_text"]
181
- return generated_response
182
- except Exception as e:
183
  return f"Error loading model: {e}"
184
 
185
- def terminal_interface(command: str, project_name: str = None) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  if project_name:
187
  project_path = os.path.join(PROJECT_ROOT, project_name)
188
  if not os.path.exists(project_path):
189
  return f"Project {project_name} does not exist."
190
- result = subprocess.run(
191
- command, shell=True, capture_output=True, text=True, cwd=project_path)
192
  else:
193
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
194
- return result.stdout
195
-
196
- def code_editor_interface(code: str) -> str:
197
- try:
198
- formatted_code = black.format_str(code, mode=black.FileMode())
199
- except black.NothingChanged:
200
- formatted_code = code
201
-
202
- result = StringIO()
203
- sys.stdout = result
204
- sys.stderr = result
205
-
206
- lint.Run(['--rcfile=/dev/null', '-'], exit=False)
207
- lint_message = result.getvalue()
208
-
209
- sys.stdout = sys.__stdout__
210
- sys.stderr = sys.__stderr__
211
-
212
- return formatted_code, lint_message
213
 
214
- def summarize_text(text: str) -> str:
215
  summarizer = pipeline("summarization")
216
- summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
 
217
  return summary[0]['summary_text']
218
 
219
- def sentiment_analysis(text: str) -> str:
220
  analyzer = pipeline("sentiment-analysis")
221
- result = analyzer(text)
222
- return result[0]['label']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
- def translate_code(code: str, source_language: str, target_language: str) -> str:
225
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ROMANCE")
226
- translated_code = translator(code, max_length=512)[0]['translation_text']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  return translated_code
228
 
229
- def generate_code(code_idea: str, model_name: str) -> str:
230
- try:
231
- generator = pipeline('text-generation', model=model_name)
232
- generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
233
- return generated_code
234
- except Exception as e:
235
- return f"Error generating code: {e}"
236
-
237
- def chat_interface(input_text: str) -> str:
238
- chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
239
- response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
240
- return response
241
-
242
- def workspace_interface(project_name: str) -> str:
243
- project_path = os.path.join(PROJECT_ROOT, project_name)
244
- if not os.path.exists(project_path):
245
- os.makedirs(project_path)
246
- st.session_state.workspace_projects[project_name] = {'files': []}
247
- return f"Project '{project_name}' created successfully."
248
- else:
249
- return f"Project '{project_name}' already exists."
250
-
251
- def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
252
- project_path = os.path.join(PROJECT_ROOT, project_name)
253
- if not os.path.exists(project_path):
254
- return f"Project '{project_name}' does not exist."
255
-
256
- file_path = os.path.join(project_path, file_name)
257
- with open(file_path, "w") as file:
258
- file.write(code)
259
- st.session_state.workspace_projects[project_name]['files'].append(file_name)
260
- return f"Code added to '{file_name}' in project '{project_name}'."
261
-
262
- def create_space_on_hugging_face(api, name, description, public, files, entrypoint="app.py"):
263
- try:
264
- repo = api.create_repo(name, exist_ok=True, private=not public)
265
- for filename, content in files.items():
266
- api.upload_file(
267
- path_or_fileobj=content.encode(),
268
- path_in_repo=filename,
269
- repo_id=repo.repo_id,
270
- repo_type="space",
271
- )
272
- return repo
273
- except Exception as e:
274
- st.error(f"Error creating Hugging Face Space: {str(e)}")
275
- return None
276
 
277
  # Streamlit App
278
  st.title("AI Agent Creator")
279
 
280
  # Sidebar navigation
281
  st.sidebar.title("Navigation")
282
- app_mode = st.sidebar.selectbox(
283
- "Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
284
 
285
  if app_mode == "AI Agent Creator":
 
286
  st.header("Create an AI Agent from Text")
287
 
288
  st.subheader("From Text")
@@ -294,23 +257,31 @@ if app_mode == "AI Agent Creator":
294
  st.session_state.available_agents.append(agent_name)
295
 
296
  elif app_mode == "Tool Box":
 
297
  st.header("AI-Powered Tools")
298
 
 
299
  st.subheader("Chat with CodeCraft")
300
  chat_input = st.text_area("Enter your message:")
301
  if st.button("Send"):
302
- chat_response = chat_interface(chat_input)
 
 
 
 
 
303
  st.session_state.chat_history.append((chat_input, chat_response))
304
  st.write(f"CodeCraft: {chat_response}")
305
 
 
306
  st.subheader("Terminal")
307
  terminal_input = st.text_input("Enter a command:")
308
  if st.button("Run"):
309
  terminal_output = terminal_interface(terminal_input)
310
- st.session_state.terminal_history.append(
311
- (terminal_input, terminal_output))
312
  st.code(terminal_output, language="bash")
313
 
 
314
  st.subheader("Code Editor")
315
  code_editor = st.text_area("Write your code:", height=300)
316
  if st.button("Format & Lint"):
@@ -318,42 +289,121 @@ elif app_mode == "Tool Box":
318
  st.code(formatted_code, language="python")
319
  st.info(lint_message)
320
 
 
321
  st.subheader("Summarize Text")
322
  text_to_summarize = st.text_area("Enter text to summarize:")
323
  if st.button("Summarize"):
324
  summary = summarize_text(text_to_summarize)
325
  st.write(f"Summary: {summary}")
326
 
 
327
  st.subheader("Sentiment Analysis")
328
  sentiment_text = st.text_area("Enter text for sentiment analysis:")
329
  if st.button("Analyze Sentiment"):
330
  sentiment = sentiment_analysis(sentiment_text)
331
  st.write(f"Sentiment: {sentiment}")
332
 
 
333
  st.subheader("Translate Code")
334
  code_to_translate = st.text_area("Enter code to translate:")
335
- source_language = st.text_input("Enter source language (e.g., 'Python'):")
336
- target_language = st.text_input(
337
- "Enter target language (e.g., 'JavaScript'):")
338
  if st.button("Translate Code"):
339
- translated_code = translate_code(
340
- code_to_translate, source_language, target_language)
341
  st.code(translated_code, language=target_language.lower())
342
 
 
343
  st.subheader("Code Generation")
344
  code_idea = st.text_input("Enter your code idea:")
345
  if st.button("Generate Code"):
346
- generated_code = generate_code(code_idea, "gpt2")
347
  st.code(generated_code, language="python")
348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  elif app_mode == "Workspace Chat App":
 
350
  st.header("Workspace Chat App")
351
 
 
352
  st.subheader("Create a New Project")
353
  project_name = st.text_input("Enter project name:")
354
  if st.button("Create Project"):
355
  workspace_status = workspace_interface(project_name)
356
  st.success(workspace_status)
357
 
 
358
  st.subheader("Add Code to Workspace")
359
- code_to_add = st.text_area("Enter code to add to workspace:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
  class AIAgent:
29
+ def __init__(self, name, description, skills):
30
  self.name = name
31
  self.description = description
32
  self.skills = skills
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  def create_agent_prompt(self):
35
+ skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
36
+ agent_prompt = f"""
37
+ As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
38
+ {skills_str}
39
+ 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.
40
+ """
41
+ return agent_prompt
42
 
43
+ def autonomous_build(self, chat_history, workspace_projects):
44
+ """
45
+ Autonomous build logic that continues based on the state of chat history and workspace projects.
46
+ """
47
+ summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
48
+ summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
49
 
50
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  return summary, next_step
53
 
54
+ def save_agent_to_file(agent):
55
+ """Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  if not os.path.exists(AGENT_DIRECTORY):
57
  os.makedirs(AGENT_DIRECTORY)
58
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
59
+ config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
60
  with open(file_path, "w") as file:
61
  file.write(agent.create_agent_prompt())
62
+ with open(config_path, "w") as file:
63
+ file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
64
  st.session_state.available_agents.append(agent.name)
65
 
66
+ commit_and_push_changes(f"Add agent {agent.name}")
67
+
68
+ def load_agent_prompt(agent_name):
69
+ """Loads an agent prompt from a file."""
70
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
71
  if os.path.exists(file_path):
72
  with open(file_path, "r") as file:
 
75
  else:
76
  return None
77
 
78
+ def create_agent_from_text(name, text):
79
+ skills = text.split('\n')
80
  agent = AIAgent(name, "AI agent created from text input.", skills)
81
  save_agent_to_file(agent)
82
  return agent.create_agent_prompt()
83
 
84
+ # Chat interface using a selected agent
85
+ def chat_interface_with_agent(input_text, agent_name):
86
  agent_prompt = load_agent_prompt(agent_name)
87
  if agent_prompt is None:
88
  return f"Agent {agent_name} not found."
89
 
90
+ # Load the GPT-2 model which is compatible with AutoModelForCausalLM
91
+ model_name = "gpt2"
92
  try:
93
+ model = AutoModelForCausalLM.from_pretrained(model_name)
94
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
95
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
96
+ except EnvironmentError as e:
 
97
  return f"Error loading model: {e}"
98
 
99
+ # Combine the agent prompt with user input
100
+ combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
101
+
102
+ # Truncate input text to avoid exceeding the model's maximum length
103
+ max_input_length = 900
104
+ input_ids = tokenizer.encode(combined_input, return_tensors="pt")
105
+ if input_ids.shape[1] > max_input_length:
106
+ input_ids = input_ids[:, :max_input_length]
107
+
108
+ # Generate chatbot response
109
+ outputs = model.generate(
110
+ input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True, pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
111
+ )
112
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
113
+ return response
114
+
115
+ def workspace_interface(project_name):
116
+ project_path = os.path.join(PROJECT_ROOT, project_name)
117
+ if not os.path.exists(PROJECT_ROOT):
118
+ os.makedirs(PROJECT_ROOT)
119
+ if not os.path.exists(project_path):
120
+ os.makedirs(project_path)
121
+ st.session_state.workspace_projects[project_name] = {"files": []}
122
+ st.session_state.current_state['workspace_chat']['project_name'] = project_name
123
+ commit_and_push_changes(f"Create project {project_name}")
124
+ return f"Project {project_name} created successfully."
125
+ else:
126
+ return f"Project {project_name} already exists."
127
+
128
+ def add_code_to_workspace(project_name, code, file_name):
129
+ project_path = os.path.join(PROJECT_ROOT, project_name)
130
+ if os.path.exists(project_path):
131
+ file_path = os.path.join(project_path, file_name)
132
+ with open(file_path, "w") as file:
133
+ file.write(code)
134
+ st.session_state.workspace_projects[project_name]["files"].append(file_name)
135
+ st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
136
+ commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
137
+ return f"Code added to {file_name} in project {project_name} successfully."
138
+ else:
139
+ return f"Project {project_name} does not exist."
140
+
141
+ def terminal_interface(command, project_name=None):
142
  if project_name:
143
  project_path = os.path.join(PROJECT_ROOT, project_name)
144
  if not os.path.exists(project_path):
145
  return f"Project {project_name} does not exist."
146
+ result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
 
147
  else:
148
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
149
+ if result.returncode == 0:
150
+ st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
151
+ return result.stdout
152
+ else:
153
+ st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
154
+ return result.stderr
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
+ def summarize_text(text):
157
  summarizer = pipeline("summarization")
158
+ summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
159
+ st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
160
  return summary[0]['summary_text']
161
 
162
+ def sentiment_analysis(text):
163
  analyzer = pipeline("sentiment-analysis")
164
+ sentiment = analyzer(text)
165
+ st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
166
+ return sentiment[0]
167
+
168
+ # ... [rest of the translate_code function, but remove the OpenAI API call and replace it with your own logic] ...
169
+
170
+ def generate_code(code_idea):
171
+ # Replace this with a call to a Hugging Face model or your own logic
172
+ # For example, using a text-generation pipeline:
173
+ generator = pipeline('text-generation', model='gpt4o')
174
+ generated_code = generator(code_idea, max_length=10000, num_return_sequences=1)[0]['generated_text']
175
+ messages=[
176
+ {"role": "system", "content": "You are an expert software developer."},
177
+ {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
178
+ ]
179
+ st.session_state.current_state['toolbox']['generated_code'] = generated_code
180
+
181
+ return generated_code
182
+
183
+ def translate_code(code, input_language, output_language):
184
+ # Define a dictionary to map programming languages to their corresponding file extensions
185
+ language_extensions = {
186
+
187
+ }
188
 
189
+ # Add code to handle edge cases such as invalid input and unsupported programming languages
190
+ if input_language not in language_extensions:
191
+ raise ValueError(f"Invalid input language: {input_language}")
192
+ if output_language not in language_extensions:
193
+ raise ValueError(f"Invalid output language: {output_language}")
194
+
195
+ # Use the dictionary to map the input and output languages to their corresponding file extensions
196
+ input_extension = language_extensions[input_language]
197
+ output_extension = language_extensions[output_language]
198
+
199
+ # Translate the code using the OpenAI API
200
+ prompt = f"Translate this code from {input_language} to {output_language}:\n\n{code}"
201
+ response = openai.ChatCompletion.create(
202
+ model="gpt-4",
203
+ messages=[
204
+ {"role": "system", "content": "You are an expert software developer."},
205
+ {"role": "user", "content": prompt}
206
+ ]
207
+ )
208
+ translated_code = response.choices[0].message['content'].strip()
209
+
210
+ # Return the translated code
211
+ translated_code = response.choices[0].message['content'].strip()
212
+ st.session_state.current_state['toolbox']['translated_code'] = translated_code
213
  return translated_code
214
 
215
+ def generate_code(code_idea):
216
+ response = openai.ChatCompletion.create(
217
+ model="gpt-4",
218
+ messages=[
219
+ {"role": "system", "content": "You are an expert software developer."},
220
+ {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
221
+ ]
222
+ )
223
+ generated_code = response.choices[0].message['content'].strip()
224
+ st.session_state.current_state['toolbox']['generated_code'] = generated_code
225
+ return generated_code
226
+
227
+ def commit_and_push_changes(commit_message):
228
+ """Commits and pushes changes to the Hugging Face repository."""
229
+ commands = [
230
+ "git add .",
231
+ f"git commit -m '{commit_message}'",
232
+ "git push"
233
+ ]
234
+ for command in commands:
235
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
236
+ if result.returncode != 0:
237
+ st.error(f"Error executing command '{command}': {result.stderr}")
238
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
  # Streamlit App
241
  st.title("AI Agent Creator")
242
 
243
  # Sidebar navigation
244
  st.sidebar.title("Navigation")
245
+ app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
 
246
 
247
  if app_mode == "AI Agent Creator":
248
+ # AI Agent Creator
249
  st.header("Create an AI Agent from Text")
250
 
251
  st.subheader("From Text")
 
257
  st.session_state.available_agents.append(agent_name)
258
 
259
  elif app_mode == "Tool Box":
260
+ # Tool Box
261
  st.header("AI-Powered Tools")
262
 
263
+ # Chat Interface
264
  st.subheader("Chat with CodeCraft")
265
  chat_input = st.text_area("Enter your message:")
266
  if st.button("Send"):
267
+ if chat_input.startswith("@"):
268
+ agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
269
+ chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
270
+ chat_response = chat_interface_with_agent(chat_input, agent_name)
271
+ else:
272
+ chat_response = chat_interface(chat_input)
273
  st.session_state.chat_history.append((chat_input, chat_response))
274
  st.write(f"CodeCraft: {chat_response}")
275
 
276
+ # Terminal Interface
277
  st.subheader("Terminal")
278
  terminal_input = st.text_input("Enter a command:")
279
  if st.button("Run"):
280
  terminal_output = terminal_interface(terminal_input)
281
+ st.session_state.terminal_history.append((terminal_input, terminal_output))
 
282
  st.code(terminal_output, language="bash")
283
 
284
+ # Code Editor Interface
285
  st.subheader("Code Editor")
286
  code_editor = st.text_area("Write your code:", height=300)
287
  if st.button("Format & Lint"):
 
289
  st.code(formatted_code, language="python")
290
  st.info(lint_message)
291
 
292
+ # Text Summarization Tool
293
  st.subheader("Summarize Text")
294
  text_to_summarize = st.text_area("Enter text to summarize:")
295
  if st.button("Summarize"):
296
  summary = summarize_text(text_to_summarize)
297
  st.write(f"Summary: {summary}")
298
 
299
+ # Sentiment Analysis Tool
300
  st.subheader("Sentiment Analysis")
301
  sentiment_text = st.text_area("Enter text for sentiment analysis:")
302
  if st.button("Analyze Sentiment"):
303
  sentiment = sentiment_analysis(sentiment_text)
304
  st.write(f"Sentiment: {sentiment}")
305
 
306
+ # Text Translation Tool (Code Translation)
307
  st.subheader("Translate Code")
308
  code_to_translate = st.text_area("Enter code to translate:")
309
+ source_language = st.text_input("Enter source language (e.g. 'Python'):")
310
+ target_language = st.text_input("Enter target language (e.g. 'JavaScript'):")
 
311
  if st.button("Translate Code"):
312
+ translated_code = translate_code(code_to_translate, source_language, target_language)
 
313
  st.code(translated_code, language=target_language.lower())
314
 
315
+ # Code Generation
316
  st.subheader("Code Generation")
317
  code_idea = st.text_input("Enter your code idea:")
318
  if st.button("Generate Code"):
319
+ generated_code = generate_code(code_idea)
320
  st.code(generated_code, language="python")
321
 
322
+ # Display Preset Commands
323
+ st.subheader("Preset Commands")
324
+ preset_commands = {
325
+ "Create a new project": "create_project('project_name')",
326
+ "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
327
+ "Run terminal command": "terminal_interface('command', 'project_name')",
328
+ "Generate code": "generate_code('code_idea')",
329
+ "Summarize text": "summarize_text('text')",
330
+ "Analyze sentiment": "sentiment_analysis('text')",
331
+ "Translate code": "translate_code('code', 'source_language', 'target_language')",
332
+ }
333
+ for command_name, command in preset_commands.items():
334
+ st.write(f"{command_name}: `{command}`")
335
+
336
  elif app_mode == "Workspace Chat App":
337
+ # Workspace Chat App
338
  st.header("Workspace Chat App")
339
 
340
+ # Project Workspace Creation
341
  st.subheader("Create a New Project")
342
  project_name = st.text_input("Enter project name:")
343
  if st.button("Create Project"):
344
  workspace_status = workspace_interface(project_name)
345
  st.success(workspace_status)
346
 
347
+ # Add Code to Workspace
348
  st.subheader("Add Code to Workspace")
349
+ code_to_add = st.text_area("Enter code to add to workspace:")
350
+ file_name = st.text_input("Enter file name (e.g. 'app.py'):")
351
+ if st.button("Add Code"):
352
+ add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
353
+ st.success(add_code_status)
354
+
355
+ # Terminal Interface with Project Context
356
+ st.subheader("Terminal (Workspace Context)")
357
+ terminal_input = st.text_input("Enter a command within the workspace:")
358
+ if st.button("Run Command"):
359
+ terminal_output = terminal_interface(terminal_input, project_name)
360
+ st.code(terminal_output, language="bash")
361
+
362
+ # Chat Interface for Guidance
363
+ st.subheader("Chat with CodeCraft for Guidance")
364
+ chat_input = st.text_area("Enter your message for guidance:")
365
+ if st.button("Get Guidance"):
366
+ chat_response = chat_interface(chat_input)
367
+ st.session_state.chat_history.append((chat_input, chat_response))
368
+ st.write(f"CodeCraft: {chat_response}")
369
+
370
+ # Display Chat History
371
+ st.subheader("Chat History")
372
+ for user_input, response in st.session_state.chat_history:
373
+ st.write(f"User: {user_input}")
374
+ st.write(f"CodeCraft: {response}")
375
+
376
+ # Display Terminal History
377
+ st.subheader("Terminal History")
378
+ for command, output in st.session_state.terminal_history:
379
+ st.write(f"Command: {command}")
380
+ st.code(output, language="bash")
381
+
382
+ # Display Projects and Files
383
+ st.subheader("Workspace Projects")
384
+ for project, details in st.session_state.workspace_projects.items():
385
+ st.write(f"Project: {project}")
386
+ for file in details['files']:
387
+ st.write(f" - {file}")
388
+
389
+ # Chat with AI Agents
390
+ st.subheader("Chat with AI Agents")
391
+ selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
392
+ agent_chat_input = st.text_area("Enter your message for the agent:")
393
+ if st.button("Send to Agent"):
394
+ agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
395
+ st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
396
+ st.write(f"{selected_agent}: {agent_chat_response}")
397
+
398
+ # Automate Build Process
399
+ st.subheader("Automate Build Process")
400
+ if st.button("Automate"):
401
+ agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
402
+ summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
403
+ st.write("Autonomous Build Summary:")
404
+ st.write(summary)
405
+ st.write("Next Step:")
406
+ st.write(next_step)
407
+
408
+ # Display current state for debugging
409
+ st.sidebar.subheader("Current State")