acecalisto3 commited on
Commit
e8fb655
·
verified ·
1 Parent(s): 94e4b2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -79
app.py CHANGED
@@ -1,7 +1,15 @@
1
  import os
 
2
  import subprocess
3
  import streamlit as st
4
- from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoConfig, AutoModel
 
 
 
 
 
 
 
5
 
6
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
7
  PROJECT_ROOT = "projects"
@@ -44,33 +52,24 @@ I am confident that I can leverage my expertise to assist you in developing and
44
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
45
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
46
 
47
- # Analyze chat history and workspace projects to suggest actions
48
- # Example:
49
- # - Check if the user has requested to create a new file
50
- # - Check if the user has requested to install a package
51
- # - Check if the user has requested to run a command
52
- # - Check if the user has requested to generate code
53
- # - Check if the user has requested to translate code
54
- # - Check if the user has requested to summarize text
55
- # - Check if the user has requested to analyze sentiment
56
-
57
- # Generate a response based on the analysis
58
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
59
 
60
  return summary, next_step
61
 
62
- def load_hf_token():
63
- return 'YOUR_HF_TOKEN'
64
-
65
  def save_agent_to_file(agent):
66
- """Saves the agent's prompt to a file."""
67
  if not os.path.exists(AGENT_DIRECTORY):
68
  os.makedirs(AGENT_DIRECTORY)
69
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
 
70
  with open(file_path, "w") as file:
71
  file.write(agent.create_agent_prompt())
 
 
72
  st.session_state.available_agents.append(agent.name)
73
 
 
 
74
  def load_agent_prompt(agent_name):
75
  """Loads an agent prompt from a file."""
76
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
@@ -87,116 +86,162 @@ def create_agent_from_text(name, text):
87
  save_agent_to_file(agent)
88
  return agent.create_agent_prompt()
89
 
 
90
  def chat_interface_with_agent(input_text, agent_name):
91
  agent_prompt = load_agent_prompt(agent_name)
92
  if agent_prompt is None:
93
  return f"Agent {agent_name} not found."
94
 
95
- model_name = "Bin12345/AutoCoder_S_6.7B"
 
96
  try:
97
- model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=load_hf_token())
98
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=load_hf_token())
99
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
100
  except EnvironmentError as e:
101
  return f"Error loading model: {e}"
102
 
 
103
  combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
104
 
105
- input_ids = tokenizer.encode(combined_input, return_tensors="pt")
106
  max_input_length = 900
 
107
  if input_ids.shape[1] > max_input_length:
108
  input_ids = input_ids[:, :max_input_length]
109
 
 
110
  outputs = model.generate(
111
- input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True,
112
- pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
113
  )
114
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
115
  return response
116
 
117
- # Terminal interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def terminal_interface(command, project_name=None):
119
  if project_name:
120
  project_path = os.path.join(PROJECT_ROOT, project_name)
121
  if not os.path.exists(project_path):
122
  return f"Project {project_name} does not exist."
123
- result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)
124
  else:
125
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
126
- return result.stdout
 
 
 
 
 
127
 
128
- # Code editor interface
129
  def code_editor_interface(code):
130
  try:
131
  formatted_code = black.format_str(code, mode=black.FileMode())
132
  except black.NothingChanged:
133
  formatted_code = code
134
-
135
  result = StringIO()
136
  sys.stdout = result
137
  sys.stderr = result
138
-
139
  (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
140
  sys.stdout = sys.__stdout__
141
  sys.stderr = sys.__stderr__
142
-
143
  lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
144
-
 
145
  return formatted_code, lint_message
146
 
147
- # Text summarization tool
148
  def summarize_text(text):
149
- summarizer = pipeline("summarization", model="t5-base", use_auth_token=load_hf_token())
150
- summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
 
151
  return summary[0]['summary_text']
152
 
153
- # Sentiment analysis tool
154
  def sentiment_analysis(text):
155
- analyzer = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment", use_auth_token=load_hf_token())
156
- result = analyzer(text)
157
- return result[0]['label']
158
-
159
- # Text translation tool (code translation)
160
- def translate_code(code, source_language, target_language):
161
- # Use a Hugging Face translation model instead of OpenAI
162
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es", use_auth_token=load_hf_token()) # Example: English to Spanish
163
- translated_code = translator(code, target_lang=target_language)[0]['translation_text']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  return translated_code
165
 
166
  def generate_code(code_idea):
167
- # Use a Hugging Face code generation model instead of OpenAI
168
- generator = pipeline('text-generation', model='bigcode/starcoder', use_auth_token=load_hf_token())
169
- generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
 
 
 
 
 
 
170
  return generated_code
171
 
172
- def chat_interface(input_text):
173
- """Handles general chat interactions with the user."""
174
- # Use a Hugging Face chatbot model or your own logic
175
- chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", use_auth_token=load_hf_token())
176
- response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
177
- return response
178
-
179
- # Workspace interface
180
- def workspace_interface(project_name):
181
- project_path = os.path.join(PROJECT_ROOT, project_name)
182
- if not os.path.exists(project_path):
183
- os.makedirs(project_path)
184
- st.session_state.workspace_projects[project_name] = {'files': []}
185
- return f"Project '{project_name}' created successfully."
186
- else:
187
- return f"Project '{project_name}' already exists."
188
-
189
- # Add code to workspace
190
- def add_code_to_workspace(project_name, code, file_name):
191
- project_path = os.path.join(PROJECT_ROOT, project_name)
192
- if not os.path.exists(project_path):
193
- return f"Project '{project_name}' does not exist."
194
-
195
- file_path = os.path.join(project_path, file_name)
196
- with open(file_path, "w") as file:
197
- file.write(code)
198
- st.session_state.workspace_projects[project_name]['files'].append(file_name)
199
- return f"Code added to '{file_name}' in project '{project_name}'."
200
 
201
  # Streamlit App
202
  st.title("AI Agent Creator")
@@ -225,7 +270,12 @@ elif app_mode == "Tool Box":
225
  st.subheader("Chat with CodeCraft")
226
  chat_input = st.text_area("Enter your message:")
227
  if st.button("Send"):
228
- chat_response = chat_interface(chat_input)
 
 
 
 
 
229
  st.session_state.chat_history.append((chat_input, chat_response))
230
  st.write(f"CodeCraft: {chat_response}")
231
 
@@ -262,8 +312,8 @@ elif app_mode == "Tool Box":
262
  # Text Translation Tool (Code Translation)
263
  st.subheader("Translate Code")
264
  code_to_translate = st.text_area("Enter code to translate:")
265
- source_language = st.text_input("Enter source language (e.g., 'Python'):")
266
- target_language = st.text_input("Enter target language (e.g., 'JavaScript'):")
267
  if st.button("Translate Code"):
268
  translated_code = translate_code(code_to_translate, source_language, target_language)
269
  st.code(translated_code, language=target_language.lower())
@@ -275,6 +325,20 @@ elif app_mode == "Tool Box":
275
  generated_code = generate_code(code_idea)
276
  st.code(generated_code, language="python")
277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  elif app_mode == "Workspace Chat App":
279
  # Workspace Chat App
280
  st.header("Workspace Chat App")
@@ -289,7 +353,7 @@ elif app_mode == "Workspace Chat App":
289
  # Add Code to Workspace
290
  st.subheader("Add Code to Workspace")
291
  code_to_add = st.text_area("Enter code to add to workspace:")
292
- file_name = st.text_input("Enter file name (e.g., 'app.py'):")
293
  if st.button("Add Code"):
294
  add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
295
  st.success(add_code_status)
@@ -345,4 +409,8 @@ elif app_mode == "Workspace Chat App":
345
  st.write("Autonomous Build Summary:")
346
  st.write(summary)
347
  st.write("Next Step:")
348
- st.write(next_step)
 
 
 
 
 
1
  import os
2
+ import sys
3
  import subprocess
4
  import streamlit as st
5
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
6
+ import black
7
+ from pylint import lint
8
+ from io import StringIO
9
+ import openai
10
+
11
+ # Set your OpenAI API key here
12
+ openai.api_key = "YOUR_OPENAI_API_KEY"
13
 
14
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
15
  PROJECT_ROOT = "projects"
 
52
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
53
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
54
 
 
 
 
 
 
 
 
 
 
 
 
55
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
56
 
57
  return summary, next_step
58
 
 
 
 
59
  def save_agent_to_file(agent):
60
+ """Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""
61
  if not os.path.exists(AGENT_DIRECTORY):
62
  os.makedirs(AGENT_DIRECTORY)
63
  file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
64
+ config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
65
  with open(file_path, "w") as file:
66
  file.write(agent.create_agent_prompt())
67
+ with open(config_path, "w") as file:
68
+ file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
69
  st.session_state.available_agents.append(agent.name)
70
 
71
+ commit_and_push_changes(f"Add agent {agent.name}")
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")
 
86
  save_agent_to_file(agent)
87
  return agent.create_agent_prompt()
88
 
89
+ # Chat interface using a selected agent
90
  def chat_interface_with_agent(input_text, agent_name):
91
  agent_prompt = load_agent_prompt(agent_name)
92
  if agent_prompt is None:
93
  return f"Agent {agent_name} not found."
94
 
95
+ # Load the GPT-2 model which is compatible with AutoModelForCausalLM
96
+ model_name = "gpt2"
97
  try:
98
+ model = AutoModelForCausalLM.from_pretrained(model_name)
99
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
100
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
101
  except EnvironmentError as e:
102
  return f"Error loading model: {e}"
103
 
104
+ # Combine the agent prompt with user input
105
  combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
106
 
107
+ # Truncate input text to avoid exceeding the model's maximum length
108
  max_input_length = 900
109
+ input_ids = tokenizer.encode(combined_input, return_tensors="pt")
110
  if input_ids.shape[1] > max_input_length:
111
  input_ids = input_ids[:, :max_input_length]
112
 
113
+ # Generate chatbot response
114
  outputs = model.generate(
115
+ 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
 
116
  )
117
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
118
  return response
119
 
120
+ def workspace_interface(project_name):
121
+ project_path = os.path.join(PROJECT_ROOT, project_name)
122
+ if not os.path.exists(PROJECT_ROOT):
123
+ os.makedirs(PROJECT_ROOT)
124
+ if not os.path.exists(project_path):
125
+ os.makedirs(project_path)
126
+ st.session_state.workspace_projects[project_name] = {"files": []}
127
+ st.session_state.current_state['workspace_chat']['project_name'] = project_name
128
+ commit_and_push_changes(f"Create project {project_name}")
129
+ return f"Project {project_name} created successfully."
130
+ else:
131
+ return f"Project {project_name} already exists."
132
+
133
+ def add_code_to_workspace(project_name, code, file_name):
134
+ project_path = os.path.join(PROJECT_ROOT, project_name)
135
+ if os.path.exists(project_path):
136
+ file_path = os.path.join(project_path, file_name)
137
+ with open(file_path, "w") as file:
138
+ file.write(code)
139
+ st.session_state.workspace_projects[project_name]["files"].append(file_name)
140
+ st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
141
+ commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
142
+ return f"Code added to {file_name} in project {project_name} successfully."
143
+ else:
144
+ return f"Project {project_name} does not exist."
145
+
146
  def terminal_interface(command, project_name=None):
147
  if project_name:
148
  project_path = os.path.join(PROJECT_ROOT, project_name)
149
  if not os.path.exists(project_path):
150
  return f"Project {project_name} does not exist."
151
+ result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
152
  else:
153
  result = subprocess.run(command, shell=True, capture_output=True, text=True)
154
+ if result.returncode == 0:
155
+ st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
156
+ return result.stdout
157
+ else:
158
+ st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
159
+ return result.stderr
160
 
 
161
  def code_editor_interface(code):
162
  try:
163
  formatted_code = black.format_str(code, mode=black.FileMode())
164
  except black.NothingChanged:
165
  formatted_code = code
 
166
  result = StringIO()
167
  sys.stdout = result
168
  sys.stderr = result
 
169
  (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
170
  sys.stdout = sys.__stdout__
171
  sys.stderr = sys.__stderr__
 
172
  lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
173
+ st.session_state.current_state['toolbox']['formatted_code'] = formatted_code
174
+ st.session_state.current_state['toolbox']['lint_message'] = lint_message
175
  return formatted_code, lint_message
176
 
 
177
  def summarize_text(text):
178
+ summarizer = pipeline("summarization")
179
+ summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
180
+ st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
181
  return summary[0]['summary_text']
182
 
 
183
  def sentiment_analysis(text):
184
+ analyzer = pipeline("sentiment-analysis")
185
+ sentiment = analyzer(text)
186
+ st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
187
+ return sentiment[0]
188
+
189
+ def translate_code(code, input_language, output_language):
190
+ # Define a dictionary to map programming languages to their corresponding file extensions
191
+ language_extensions = {
192
+ # ignore the specific languages right now, and continue to EOF
193
+ }
194
+
195
+ # Add code to handle edge cases such as invalid input and unsupported programming languages
196
+ if input_language not in language_extensions:
197
+ raise ValueError(f"Invalid input language: {input_language}")
198
+ if output_language not in language_extensions:
199
+ raise ValueError(f"Invalid output language: {output_language}")
200
+
201
+ # Use the dictionary to map the input and output languages to their corresponding file extensions
202
+ input_extension = language_extensions[input_language]
203
+ output_extension = language_extensions[output_language]
204
+
205
+ # Translate the code using the OpenAI API
206
+ prompt = f"Translate this code from {input_language} to {output_language}:\n\n{code}"
207
+ response = openai.ChatCompletion.create(
208
+ model="gpt-4",
209
+ messages=[
210
+ {"role": "system", "content": "You are an expert software developer."},
211
+ {"role": "user", "content": prompt}
212
+ ]
213
+ )
214
+ translated_code = response.choices[0].message['content'].strip()
215
+
216
+ # Return the translated code
217
+ translated_code = response.choices[0].message['content'].strip()
218
+ st.session_state.current_state['toolbox']['translated_code'] = translated_code
219
  return translated_code
220
 
221
  def generate_code(code_idea):
222
+ response = openai.ChatCompletion.create(
223
+ model="gpt-4",
224
+ messages=[
225
+ {"role": "system", "content": "You are an expert software developer."},
226
+ {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
227
+ ]
228
+ )
229
+ generated_code = response.choices[0].message['content'].strip()
230
+ st.session_state.current_state['toolbox']['generated_code'] = generated_code
231
  return generated_code
232
 
233
+ def commit_and_push_changes(commit_message):
234
+ """Commits and pushes changes to the Hugging Face repository."""
235
+ commands = [
236
+ "git add .",
237
+ f"git commit -m '{commit_message}'",
238
+ "git push"
239
+ ]
240
+ for command in commands:
241
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
242
+ if result.returncode != 0:
243
+ st.error(f"Error executing command '{command}': {result.stderr}")
244
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  # Streamlit App
247
  st.title("AI Agent Creator")
 
270
  st.subheader("Chat with CodeCraft")
271
  chat_input = st.text_area("Enter your message:")
272
  if st.button("Send"):
273
+ if chat_input.startswith("@"):
274
+ agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
275
+ chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
276
+ chat_response = chat_interface_with_agent(chat_input, agent_name)
277
+ else:
278
+ chat_response = chat_interface(chat_input)
279
  st.session_state.chat_history.append((chat_input, chat_response))
280
  st.write(f"CodeCraft: {chat_response}")
281
 
 
312
  # Text Translation Tool (Code Translation)
313
  st.subheader("Translate Code")
314
  code_to_translate = st.text_area("Enter code to translate:")
315
+ source_language = st.text_input("Enter source language (e.g. 'Python'):")
316
+ target_language = st.text_input("Enter target language (e.g. 'JavaScript'):")
317
  if st.button("Translate Code"):
318
  translated_code = translate_code(code_to_translate, source_language, target_language)
319
  st.code(translated_code, language=target_language.lower())
 
325
  generated_code = generate_code(code_idea)
326
  st.code(generated_code, language="python")
327
 
328
+ # Display Preset Commands
329
+ st.subheader("Preset Commands")
330
+ preset_commands = {
331
+ "Create a new project": "create_project('project_name')",
332
+ "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
333
+ "Run terminal command": "terminal_interface('command', 'project_name')",
334
+ "Generate code": "generate_code('code_idea')",
335
+ "Summarize text": "summarize_text('text')",
336
+ "Analyze sentiment": "sentiment_analysis('text')",
337
+ "Translate code": "translate_code('code', 'source_language', 'target_language')",
338
+ }
339
+ for command_name, command in preset_commands.items():
340
+ st.write(f"{command_name}: `{command}`")
341
+
342
  elif app_mode == "Workspace Chat App":
343
  # Workspace Chat App
344
  st.header("Workspace Chat App")
 
353
  # Add Code to Workspace
354
  st.subheader("Add Code to Workspace")
355
  code_to_add = st.text_area("Enter code to add to workspace:")
356
+ file_name = st.text_input("Enter file name (e.g. 'app.py'):")
357
  if st.button("Add Code"):
358
  add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
359
  st.success(add_code_status)
 
409
  st.write("Autonomous Build Summary:")
410
  st.write(summary)
411
  st.write("Next Step:")
412
+ st.write(next_step)
413
+
414
+ # Display current state for debugging
415
+ st.sidebar.subheader("Current State")
416
+ st.sidebar.json(st.session_state.current_state)