acecalisto3 commited on
Commit
272fc39
·
verified ·
1 Parent(s): 58547fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -113
app.py CHANGED
@@ -8,8 +8,6 @@ from io import StringIO
8
  import sys
9
  import torch
10
  from huggingface_hub import hf_hub_url, cached_download, HfApi
11
- import re
12
- from typing import List, Dict
13
 
14
  # Access Hugging Face API key from secrets
15
  hf_token = st.secrets["hf_token"]
@@ -30,34 +28,36 @@ if 'workspace_projects' not in st.session_state:
30
  st.session_state.workspace_projects = {}
31
  if 'available_agents' not in st.session_state:
32
  st.session_state.available_agents = []
 
 
33
 
34
  # AI Guide Toggle
35
  ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
36
 
37
  class AIAgent:
38
- def __init__(self, name: str, description: str, skills: List[str]):
39
  self.name = name
40
  self.description = description
41
  self.skills = skills
42
  self._hf_api = HfApi() # Initialize HfApi here
43
 
44
- def create_agent_prompt(self) -> str:
45
  skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
46
  agent_prompt = f"""
47
  As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
48
  {skills_str}
 
49
  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.
50
  """
51
  return agent_prompt
52
 
53
- def autonomous_build(self, chat_history: List[tuple[str, str]], workspace_projects: Dict[str, Dict],
54
- project_name: str, selected_model: str, hf_token: str) -> tuple[str, str]:
55
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
56
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
57
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
58
  return summary, next_step
59
 
60
- def deploy_built_space_to_hf(self, project_name: str) -> str:
61
  # Assuming you have a function that generates the space content
62
  space_content = generate_space_content(project_name)
63
  repository = self._hf_api.create_repo(
@@ -74,26 +74,24 @@ I am confident that I can leverage my expertise to assist you in developing and
74
  repo_type="space",
75
  token=hf_token
76
  )
77
- return repository.name
78
 
79
- def has_valid_hf_token(self) -> bool:
80
  return self._hf_api.whoami(token=hf_token) is not None
81
 
82
- def process_input(input_text: str) -> str:
83
- # Load the DialoGPT tokenizer explicitly
84
- chatbot_tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium", clean_up_tokenization_spaces=True)
85
- chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", tokenizer=chatbot_tokenizer)
86
  response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
87
  return response
88
 
89
- def run_code(code: str) -> str:
90
  try:
91
  result = subprocess.run(code, shell=True, capture_output=True, text=True)
92
  return result.stdout
93
  except Exception as e:
94
  return str(e)
95
 
96
- def workspace_interface(project_name: str) -> str:
97
  project_path = os.path.join(PROJECT_ROOT, project_name)
98
  if not os.path.exists(project_path):
99
  os.makedirs(project_path)
@@ -102,7 +100,7 @@ def workspace_interface(project_name: str) -> str:
102
  else:
103
  return f"Project '{project_name}' already exists."
104
 
105
- def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
106
  project_path = os.path.join(PROJECT_ROOT, project_name)
107
  if not os.path.exists(project_path):
108
  return f"Project '{project_name}' does not exist."
@@ -113,69 +111,34 @@ def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
113
  st.session_state.workspace_projects[project_name]['files'].append(file_name)
114
  return f"Code added to '{file_name}' in project '{project_name}'."
115
 
116
- def display_chat_history(chat_history: List[tuple[str, str]]) -> str:
117
  return "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
118
 
119
- def display_workspace_projects(workspace_projects: Dict[str, Dict]) -> str:
120
  return "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
121
 
122
- def generate_space_content(project_name: str) -> str:
123
  # Logic to generate the Streamlit app content based on project_name
124
  # ... (This is where you'll need to implement the actual code generation)
125
  return "import streamlit as st\nst.title('My Streamlit App')\nst.write('Hello, world!')"
126
 
127
- # Function to display the AI Guide chat
128
- def display_ai_guide_chat(chat_history: List[tuple[str, str]]):
129
- st.markdown("<div class='chat-history'>", unsafe_allow_html=True)
130
- for user_message, agent_message in chat_history:
131
- st.markdown(f"<div class='chat-message user'>{user_message}</div>", unsafe_allow_html=True)
132
- st.markdown(f"<div class='chat-message agent'>{agent_message}</div>", unsafe_allow_html=True)
133
- st.markdown("</div>", unsafe_allow_html=True)
134
-
135
- # Load the CodeGPT tokenizer explicitly
136
- code_generator_tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
137
- # Load the CodeGPT model for code completion
138
- code_generator = pipeline("text-generation", model="microsoft/CodeGPT-small-py", tokenizer=code_generator_tokenizer)
139
-
140
- def analyze_code(code: str) -> List[str]:
141
- hints = []
142
-
143
- # Example pointer: Suggest using list comprehensions
144
- if re.search(r'for .* in .*:\n\s+.*\.append\(', code):
145
- hints.append("Consider using a list comprehension instead of a loop for appending to a list.")
146
-
147
- # Example pointer: Recommend using f-strings for string formatting
148
- if re.search(r'\".*\%s\"|\'.*\%s\'', code) or re.search(r'\".*\%d\"|\'.*\%d\'', code):
149
- hints.append("Consider using f-strings for cleaner and more efficient string formatting.")
150
-
151
- # Example pointer: Avoid using global variables
152
- if re.search(r'\bglobal\b', code):
153
- hints.append("Avoid using global variables. Consider passing parameters or using classes.")
154
-
155
- # Example pointer: Recommend using `with` statement for file operations
156
- if re.search(r'open\(.+\)', code) and not re.search(r'with open\(.+\)', code):
157
- hints.append("Consider using the `with` statement when opening files to ensure proper resource management.")
158
-
159
- return hints
160
-
161
- def get_code_completion(prompt: str) -> str:
162
- # Generate code completion based on the current code input
163
- # Use max_new_tokens instead of max_length
164
- completions = code_generator(prompt, max_new_tokens=max_new_tokens, num_return_sequences=1)
165
- return completions[0]['generated_text']
166
-
167
- def lint_code(code: str) -> List[str]:
168
- # Capture pylint output
169
- pylint_output = StringIO()
170
- sys.stdout = pylint_output
171
-
172
- # Run pylint on the provided code
173
- pylint.lint.Run(['--from-stdin'], do_exit=False, argv=[], stdin=StringIO(code))
174
-
175
- # Reset stdout and fetch lint results
176
- sys.stdout = sys.__stdout__
177
- lint_results = pylint_output.getvalue().splitlines()
178
- return lint_results
179
 
180
  if __name__ == "__main__":
181
  st.sidebar.title("Navigation")
@@ -192,12 +155,12 @@ if __name__ == "__main__":
192
  if st.button("Run"):
193
  output = run_code(terminal_input)
194
  st.session_state.terminal_history.append((terminal_input, output))
195
- st.code(output, language="bash", "java", "html","python", "solidity", "typescript", "streamlit", "gradio", "css", "xcode", "sql", "svg", "rust")
196
  if ai_guide_level != "No Assistance":
197
- st.write("Run commands here to add packages to your project. For example: pip install <package-name>.")
198
  if terminal_input and "install" in terminal_input:
199
  package_name = terminal_input.split("install")[-1].strip()
200
- st.write(f"Package {package_name} will be added to your project.")
201
 
202
  elif app_mode == "Explorer":
203
  st.header("Explorer")
@@ -228,38 +191,16 @@ if __name__ == "__main__":
228
  # Logic to save code
229
  pass
230
  if ai_guide_level != "No Assistance":
231
- st.write("The function foo() requires the bar package. Add it to requirements.txt.")
232
-
233
- # Analyze code and provide real-time hints
234
- hints = analyze_code(code_editor)
235
- if hints:
236
- st.write("**Helpful Hints:**")
237
- for hint in hints:
238
- st.write(f"- {hint}")
239
-
240
- if st.button("Get Code Suggestion"):
241
- # Provide a predictive code completion
242
- completion = get_code_completion(code_editor)
243
- st.write("**Suggested Code Completion:**")
244
- st.code(completion, language="python")
245
-
246
- if st.button("Check Code"):
247
- # Analyze the code for errors and warnings
248
- lint_results = lint_code(code_editor)
249
-
250
- if lint_results:
251
- st.write("**Errors and Warnings:**")
252
- for result in lint_results:
253
- st.write(result)
254
- else:
255
- st.write("No issues found! Your code is clean.")
256
 
257
  elif app_mode == "Build & Deploy":
258
  st.header("Build & Deploy")
259
  project_name_input = st.text_input("Enter Project Name for Automation:")
 
 
260
  if st.button("Automate"):
261
  selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
262
- selected_model = st.selectbox("Select a code-generative model", AVAILABLE_CODE_GENERATIVE_MODELS)
263
  agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
264
  summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name_input, selected_model, hf_token)
265
  st.write("Autonomous Build Summary:")
@@ -267,22 +208,17 @@ if __name__ == "__main__":
267
  st.write("Next Step:")
268
  st.write(next_step)
269
  if agent._hf_api and agent.has_valid_hf_token():
270
- repository_name = agent.deploy_built_space_to_hf(project_name_input)
271
  st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")
272
- st.markdown(f"[Check out your new Space here](hf.co/{repository_name})")
273
 
274
- # AI Guide Chat
275
  if ai_guide_level != "No Assistance":
276
- display_ai_guide_chat(st.session_state.chat_history)
277
- # Add a text input for user to interact with the AI Guide
278
- user_input = st.text_input("Ask the AI Guide a question:", key="user_input")
279
- if st.button("Send"):
280
- if user_input:
281
- # Process the user's input and get a response from the AI Guide
282
- agent_response = process_input(user_input)
283
- st.session_state.chat_history.append((user_input, agent_response))
284
- # Clear the user input field
285
- st.session_state.user_input = ""
286
 
287
  # CSS for styling
288
  st.markdown("""
@@ -295,14 +231,17 @@ if __name__ == "__main__":
295
  margin: 0;
296
  padding: 0;
297
  }
 
298
  h1, h2, h3, h4, h5, h6 {
299
  color: #333;
300
  }
 
301
  .container {
302
  width: 90%;
303
  margin: 0 auto;
304
  padding: 20px;
305
  }
 
306
  /* Navigation Sidebar */
307
  .sidebar {
308
  background-color: #2c3e50;
@@ -315,21 +254,25 @@ if __name__ == "__main__":
315
  width: 250px;
316
  overflow-y: auto;
317
  }
 
318
  .sidebar a {
319
  color: #ecf0f1;
320
  text-decoration: none;
321
  display: block;
322
  padding: 10px 0;
323
  }
 
324
  .sidebar a:hover {
325
  background-color: #34495e;
326
  border-radius: 5px;
327
  }
 
328
  /* Main Content */
329
  .main-content {
330
  margin-left: 270px;
331
  padding: 20px;
332
  }
 
333
  /* Buttons */
334
  button {
335
  background-color: #3498db;
@@ -340,9 +283,11 @@ if __name__ == "__main__":
340
  cursor: pointer;
341
  font-size: 16px;
342
  }
 
343
  button:hover {
344
  background-color: #2980b9;
345
  }
 
346
  /* Text Areas and Inputs */
347
  textarea, input[type="text"] {
348
  width: 100%;
@@ -352,10 +297,12 @@ if __name__ == "__main__":
352
  border-radius: 5px;
353
  box-sizing: border-box;
354
  }
 
355
  textarea:focus, input[type="text"]:focus {
356
  border-color: #3498db;
357
  outline: none;
358
  }
 
359
  /* Terminal Output */
360
  .code-output {
361
  background-color: #1e1e1e;
@@ -364,6 +311,7 @@ if __name__ == "__main__":
364
  border-radius: 5px;
365
  font-family: 'Courier New', Courier, monospace;
366
  }
 
367
  /* Chat History */
368
  .chat-history {
369
  background-color: #ecf0f1;
@@ -372,17 +320,21 @@ if __name__ == "__main__":
372
  max-height: 300px;
373
  overflow-y: auto;
374
  }
 
375
  .chat-message {
376
  margin-bottom: 10px;
377
  }
 
378
  .chat-message.user {
379
  text-align: right;
380
  color: #3498db;
381
  }
 
382
  .chat-message.agent {
383
  text-align: left;
384
  color: #e74c3c;
385
  }
 
386
  /* Project Management */
387
  .project-list {
388
  background-color: #ecf0f1;
@@ -391,13 +343,16 @@ if __name__ == "__main__":
391
  max-height: 300px;
392
  overflow-y: auto;
393
  }
 
394
  .project-item {
395
  margin-bottom: 10px;
396
  }
 
397
  .project-item a {
398
  color: #3498db;
399
  text-decoration: none;
400
  }
 
401
  .project-item a:hover {
402
  text-decoration: underline;
403
  }
 
8
  import sys
9
  import torch
10
  from huggingface_hub import hf_hub_url, cached_download, HfApi
 
 
11
 
12
  # Access Hugging Face API key from secrets
13
  hf_token = st.secrets["hf_token"]
 
28
  st.session_state.workspace_projects = {}
29
  if 'available_agents' not in st.session_state:
30
  st.session_state.available_agents = []
31
+ if 'selected_language' not in st.session_state:
32
+ st.session_state.selected_language = "Python"
33
 
34
  # AI Guide Toggle
35
  ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
36
 
37
  class AIAgent:
38
+ def __init__(self, name, description, skills):
39
  self.name = name
40
  self.description = description
41
  self.skills = skills
42
  self._hf_api = HfApi() # Initialize HfApi here
43
 
44
+ def create_agent_prompt(self):
45
  skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
46
  agent_prompt = f"""
47
  As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
48
  {skills_str}
49
+
50
  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.
51
  """
52
  return agent_prompt
53
 
54
+ def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model, hf_token):
 
55
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
56
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
57
  next_step = "Based on the current state, the next logical step is to implement the main application logic."
58
  return summary, next_step
59
 
60
+ def deploy_built_space_to_hf(self):
61
  # Assuming you have a function that generates the space content
62
  space_content = generate_space_content(project_name)
63
  repository = self._hf_api.create_repo(
 
74
  repo_type="space",
75
  token=hf_token
76
  )
77
+ return repository
78
 
79
+ def has_valid_hf_token(self):
80
  return self._hf_api.whoami(token=hf_token) is not None
81
 
82
+ def process_input(input_text):
83
+ chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", tokenizer="microsoft/DialoGPT-medium")
 
 
84
  response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
85
  return response
86
 
87
+ def run_code(code):
88
  try:
89
  result = subprocess.run(code, shell=True, capture_output=True, text=True)
90
  return result.stdout
91
  except Exception as e:
92
  return str(e)
93
 
94
+ def workspace_interface(project_name):
95
  project_path = os.path.join(PROJECT_ROOT, project_name)
96
  if not os.path.exists(project_path):
97
  os.makedirs(project_path)
 
100
  else:
101
  return f"Project '{project_name}' already exists."
102
 
103
+ def add_code_to_workspace(project_name, code, file_name):
104
  project_path = os.path.join(PROJECT_ROOT, project_name)
105
  if not os.path.exists(project_path):
106
  return f"Project '{project_name}' does not exist."
 
111
  st.session_state.workspace_projects[project_name]['files'].append(file_name)
112
  return f"Code added to '{file_name}' in project '{project_name}'."
113
 
114
+ def display_chat_history(chat_history):
115
  return "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
116
 
117
+ def display_workspace_projects(workspace_projects):
118
  return "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
119
 
120
+ def generate_space_content(project_name):
121
  # Logic to generate the Streamlit app content based on project_name
122
  # ... (This is where you'll need to implement the actual code generation)
123
  return "import streamlit as st\nst.title('My Streamlit App')\nst.write('Hello, world!')"
124
 
125
+ def get_code_generation_model(language):
126
+ # Return the code generation model based on the selected language
127
+ if language == "Python":
128
+ return "bigcode/starcoder"
129
+ elif language == "Java":
130
+ return "Salesforce/codegen-350M-mono"
131
+ elif language == "JavaScript":
132
+ return "microsoft/CodeGPT-small"
133
+ else:
134
+ return "bigcode/starcoder"
135
+
136
+ def generate_code(input_text, language):
137
+ # Use the selected code generation model to generate code
138
+ model_name = get_code_generation_model(language)
139
+ model = pipeline("text2text-generation", model=model_name)
140
+ response = model(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
141
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  if __name__ == "__main__":
144
  st.sidebar.title("Navigation")
 
155
  if st.button("Run"):
156
  output = run_code(terminal_input)
157
  st.session_state.terminal_history.append((terminal_input, output))
158
+ st.code(output, language="bash")
159
  if ai_guide_level != "No Assistance":
160
+ st.write("Run commands here to add packages to your project. For example: `pip install <package-name>`.")
161
  if terminal_input and "install" in terminal_input:
162
  package_name = terminal_input.split("install")[-1].strip()
163
+ st.write(f"Package `{package_name}` will be added to your project.")
164
 
165
  elif app_mode == "Explorer":
166
  st.header("Explorer")
 
191
  # Logic to save code
192
  pass
193
  if ai_guide_level != "No Assistance":
194
+ st.write("The function `foo()` requires the `bar` package. Add it to `requirements.txt`.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
  elif app_mode == "Build & Deploy":
197
  st.header("Build & Deploy")
198
  project_name_input = st.text_input("Enter Project Name for Automation:")
199
+ selected_language = st.selectbox("Select a programming language:", ["Python", "Java", "JavaScript"])
200
+ st.session_state.selected_language = selected_language
201
  if st.button("Automate"):
202
  selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
203
+ selected_model = get_code_generation_model(selected_language)
204
  agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
205
  summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name_input, selected_model, hf_token)
206
  st.write("Autonomous Build Summary:")
 
208
  st.write("Next Step:")
209
  st.write(next_step)
210
  if agent._hf_api and agent.has_valid_hf_token():
211
+ repository = agent.deploy_built_space_to_hf()
212
  st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")
213
+ st.markdown("[Check out your new Space here](hf.co/" + repository.name + ")")
214
 
215
+ # Code Generation
216
  if ai_guide_level != "No Assistance":
217
+ code_input = st.text_area("Enter code to generate:", height=300)
218
+ if st.button("Generate Code"):
219
+ language = st.session_state.selected_language
220
+ generated_code = generate_code(code_input, language)
221
+ st.code(generated_code, language=language)
 
 
 
 
 
222
 
223
  # CSS for styling
224
  st.markdown("""
 
231
  margin: 0;
232
  padding: 0;
233
  }
234
+
235
  h1, h2, h3, h4, h5, h6 {
236
  color: #333;
237
  }
238
+
239
  .container {
240
  width: 90%;
241
  margin: 0 auto;
242
  padding: 20px;
243
  }
244
+
245
  /* Navigation Sidebar */
246
  .sidebar {
247
  background-color: #2c3e50;
 
254
  width: 250px;
255
  overflow-y: auto;
256
  }
257
+
258
  .sidebar a {
259
  color: #ecf0f1;
260
  text-decoration: none;
261
  display: block;
262
  padding: 10px 0;
263
  }
264
+
265
  .sidebar a:hover {
266
  background-color: #34495e;
267
  border-radius: 5px;
268
  }
269
+
270
  /* Main Content */
271
  .main-content {
272
  margin-left: 270px;
273
  padding: 20px;
274
  }
275
+
276
  /* Buttons */
277
  button {
278
  background-color: #3498db;
 
283
  cursor: pointer;
284
  font-size: 16px;
285
  }
286
+
287
  button:hover {
288
  background-color: #2980b9;
289
  }
290
+
291
  /* Text Areas and Inputs */
292
  textarea, input[type="text"] {
293
  width: 100%;
 
297
  border-radius: 5px;
298
  box-sizing: border-box;
299
  }
300
+
301
  textarea:focus, input[type="text"]:focus {
302
  border-color: #3498db;
303
  outline: none;
304
  }
305
+
306
  /* Terminal Output */
307
  .code-output {
308
  background-color: #1e1e1e;
 
311
  border-radius: 5px;
312
  font-family: 'Courier New', Courier, monospace;
313
  }
314
+
315
  /* Chat History */
316
  .chat-history {
317
  background-color: #ecf0f1;
 
320
  max-height: 300px;
321
  overflow-y: auto;
322
  }
323
+
324
  .chat-message {
325
  margin-bottom: 10px;
326
  }
327
+
328
  .chat-message.user {
329
  text-align: right;
330
  color: #3498db;
331
  }
332
+
333
  .chat-message.agent {
334
  text-align: left;
335
  color: #e74c3c;
336
  }
337
+
338
  /* Project Management */
339
  .project-list {
340
  background-color: #ecf0f1;
 
343
  max-height: 300px;
344
  overflow-y: auto;
345
  }
346
+
347
  .project-item {
348
  margin-bottom: 10px;
349
  }
350
+
351
  .project-item a {
352
  color: #3498db;
353
  text-decoration: none;
354
  }
355
+
356
  .project-item a:hover {
357
  text-decoration: underline;
358
  }