Spaces:
Build error
Build error
acecalisto3
commited on
Commit
•
e5e0c8c
1
Parent(s):
d6eab59
Update app.py
Browse files
app.py
CHANGED
@@ -1,17 +1,16 @@
|
|
1 |
import streamlit as st
|
2 |
from streamlit_ace import st_ace
|
3 |
-
from transformers import pipeline, AutoTokenizer
|
4 |
import os
|
5 |
import subprocess
|
6 |
import black
|
7 |
from pylint import lint
|
8 |
from io import StringIO
|
9 |
import sys
|
10 |
-
import torch
|
11 |
-
from huggingface_hub import hf_hub_url, cached_download, HfApi
|
12 |
import re
|
13 |
from typing import List, Dict
|
14 |
from streamlit_jupyter import StreamlitPatcher, tqdm
|
|
|
15 |
|
16 |
# This line should be at the top of your script
|
17 |
StreamlitPatcher().jupyter() # This patches Streamlit to work in Jupyter
|
@@ -39,169 +38,11 @@ if 'available_agents' not in st.session_state:
|
|
39 |
# AI Guide Toggle
|
40 |
ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
|
41 |
|
42 |
-
class TextGenerationTool:
|
43 |
-
def __init__(self, llm: str):
|
44 |
-
self.llm = llm
|
45 |
-
self.tokenizer = AutoTokenizer.from_pretrained(llm)
|
46 |
-
self.model = AutoModelForCausalLM.from_pretrained(llm)
|
47 |
-
|
48 |
-
def generate_text(self, prompt: str, max_length: int = 50) -> str:
|
49 |
-
inputs = self.tokenizer(prompt, return_tensors="pt")
|
50 |
-
outputs = self.model.generate(**inputs, max_length=max_length)
|
51 |
-
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
52 |
-
|
53 |
-
class AIAgent:
|
54 |
-
def __init__(self, name: str, description: str, skills: List[str], llm: str):
|
55 |
-
self.name = name
|
56 |
-
self.description = description
|
57 |
-
self.skills = skills
|
58 |
-
self.text_gen_tool = TextGenerationTool(llm)
|
59 |
-
self._hf_api = HfApi() # Initialize HfApi here
|
60 |
-
|
61 |
-
def generate_agent_response(self, prompt: str) -> str:
|
62 |
-
return self.text_gen_tool.generate_text(prompt)
|
63 |
-
|
64 |
-
def create_agent_prompt(self) -> str:
|
65 |
-
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
66 |
-
agent_prompt = f"""
|
67 |
-
As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
|
68 |
-
{skills_str}
|
69 |
-
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.
|
70 |
-
"""
|
71 |
-
return agent_prompt
|
72 |
-
|
73 |
-
def autonomous_build(self, chat_history: List[tuple[str, str]], workspace_projects: Dict[str, Dict],
|
74 |
-
project_name: str, selected_model: str, hf_token: str) -> tuple[str, str]:
|
75 |
-
summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
76 |
-
summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
77 |
-
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
78 |
-
return summary, next_step
|
79 |
-
|
80 |
-
def deploy_built_space_to_hf(self, project_name: str) -> str:
|
81 |
-
space_content = generate_space_content(project_name)
|
82 |
-
repository = self._hf_api.create_repo(
|
83 |
-
repo_id=project_name,
|
84 |
-
private=True,
|
85 |
-
token=hf_token,
|
86 |
-
exist_ok=True,
|
87 |
-
space_sdk="streamlit"
|
88 |
-
)
|
89 |
-
self._hf_api.upload_file(
|
90 |
-
path_or_fileobj=space_content,
|
91 |
-
path_in_repo="app.py",
|
92 |
-
repo_id=project_name,
|
93 |
-
repo_type="space",
|
94 |
-
token=hf_token
|
95 |
-
)
|
96 |
-
return repository.name
|
97 |
-
|
98 |
-
def has_valid_hf_token(self) -> bool:
|
99 |
-
return self._hf_api.whoami(token=hf_token) is not None
|
100 |
-
|
101 |
-
def process_input(input_text: str) -> str:
|
102 |
-
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", tokenizer="microsoft/DialoGPT-medium", clean_up_tokenization_spaces=True)
|
103 |
-
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
104 |
-
return response
|
105 |
-
|
106 |
-
def run_code(code: str) -> str:
|
107 |
-
try:
|
108 |
-
result = subprocess.run(code, shell=True, capture_output=True, text=True)
|
109 |
-
return result.stdout
|
110 |
-
except Exception as e:
|
111 |
-
return str(e)
|
112 |
-
|
113 |
-
def workspace_interface(project_name: str) -> str:
|
114 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
115 |
-
if not os.path.exists(project_path):
|
116 |
-
os.makedirs(project_path)
|
117 |
-
st.session_state.workspace_projects[project_name] = {'files': []}
|
118 |
-
return f"Project '{project_name}' created successfully."
|
119 |
-
else:
|
120 |
-
return f"Project '{project_name}' already exists."
|
121 |
-
|
122 |
-
def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
|
123 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
124 |
-
if not os.path.exists(project_path):
|
125 |
-
return f"Project '{project_name}' does not exist."
|
126 |
-
|
127 |
-
file_path = os.path.join(project_path, file_name)
|
128 |
-
with open(file_path, "w") as file:
|
129 |
-
file.write(code)
|
130 |
-
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
131 |
-
return f"Code added to '{file_name}' in project '{project_name}'."
|
132 |
-
|
133 |
-
def display_chat_history(chat_history: List[tuple[str, str]]) -> str:
|
134 |
-
return "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
135 |
-
|
136 |
-
def display_workspace_projects(workspace_projects: Dict[str, Dict]) -> str:
|
137 |
-
return "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
138 |
-
|
139 |
-
def generate_space_content(project_name: str) -> str:
|
140 |
-
# Logic to generate the Streamlit app content based on project_name
|
141 |
-
# ... (This is where you'll need to implement the actual code generation)
|
142 |
-
return "import streamlit as st\nst.title('My Streamlit App')\nst.write('Hello, world!')"
|
143 |
-
|
144 |
-
# Function to display the AI Guide chat
|
145 |
-
def display_ai_guide_chat(chat_history: List[tuple[str, str]]):
|
146 |
-
st.markdown("<div class='chat-history'>", unsafe_allow_html=True)
|
147 |
-
for user_message, agent_message in chat_history:
|
148 |
-
st.markdown(f"<div class='chat-message user'>{user_message}</div>", unsafe_allow_html=True)
|
149 |
-
st.markdown(f"<div class='chat-message agent'>{agent_message}</div>", unsafe_allow_html=True)
|
150 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
151 |
-
|
152 |
# Load the CodeGPT tokenizer explicitly
|
153 |
code_generator_tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
|
154 |
# Load the CodeGPT model for code completion
|
155 |
code_generator = pipeline("text-generation", model="microsoft/CodeGPT-small-py", tokenizer=code_generator_tokenizer)
|
156 |
|
157 |
-
def analyze_code(code: str) -> List[str]:
|
158 |
-
hints = []
|
159 |
-
|
160 |
-
# Example pointer: Suggest using list comprehensions
|
161 |
-
if re.search(r'for .* in .*:\n\s+.*\.append\(', code):
|
162 |
-
hints.append("Consider using a list comprehension instead of a loop for appending to a list.")
|
163 |
-
|
164 |
-
# Example pointer: Recommend using f-strings for string formatting
|
165 |
-
if re.search(r'\".*\%s\"|\'.*\%s\'', code) or re.search(r'\".*\%d\"|\'.*\%d\'', code):
|
166 |
-
hints.append("Consider using f-strings for cleaner and more efficient string formatting.")
|
167 |
-
|
168 |
-
# Example pointer: Avoid using global variables
|
169 |
-
if re.search(r'\bglobal\b', code):
|
170 |
-
hints.append("Avoid using global variables. Consider passing parameters or using classes.")
|
171 |
-
|
172 |
-
# Example pointer: Recommend using `with` statement for file operations
|
173 |
-
if re.search(r'open\(.+\)', code) and not re.search(r'with open\(.+\)', code):
|
174 |
-
hints.append("Consider using the `with` statement when opening files to ensure proper resource management.")
|
175 |
-
|
176 |
-
return hints
|
177 |
-
|
178 |
-
def get_code_completion(prompt: str) -> str:
|
179 |
-
# Generate code completion based on the current code input
|
180 |
-
# Use max_new_tokens instead of max_length
|
181 |
-
completions = code_generator(prompt, max_new_tokens=50, num_return_sequences=1)
|
182 |
-
return completions[0]['generated_text']
|
183 |
-
|
184 |
-
def lint_code(code: str) -> List[str]:
|
185 |
-
# Capture pylint output
|
186 |
-
pylint_output = StringIO()
|
187 |
-
sys.stdout = pylint_output
|
188 |
-
|
189 |
-
# Run pylint on the provided code
|
190 |
-
pylint.lint.Run(['--from-stdin'], do_exit=False, input=code)
|
191 |
-
|
192 |
-
# Reset stdout
|
193 |
-
sys.stdout = sys.__stdout__
|
194 |
-
|
195 |
-
# Extract pylint messages
|
196 |
-
messages = pylint_output.getvalue().splitlines()
|
197 |
-
|
198 |
-
return messages
|
199 |
-
|
200 |
-
def format_code(code: str) -> str:
|
201 |
-
# Format code using Black
|
202 |
-
formatted_code = black.format_str(code, mode=black.FileMode())
|
203 |
-
return formatted_code
|
204 |
-
|
205 |
def main():
|
206 |
st.title("Streamlit Workspace")
|
207 |
|
@@ -266,94 +107,52 @@ def main():
|
|
266 |
))
|
267 |
elif ai_guide_level == "Partial Assistance":
|
268 |
guide_chat_history.append((
|
269 |
-
"
|
270 |
-
"
|
271 |
))
|
|
|
272 |
display_ai_guide_chat(guide_chat_history)
|
273 |
|
274 |
with workspace_tabs[1]:
|
275 |
# Tool Box Tab
|
276 |
st.subheader("Tool Box")
|
277 |
-
|
|
|
|
|
|
|
278 |
|
279 |
-
|
280 |
-
|
281 |
-
st.
|
282 |
-
code_editor = st_ace(
|
283 |
-
placeholder="Write your code here...",
|
284 |
-
height=300,
|
285 |
-
theme="monokai",
|
286 |
-
key="code_editor",
|
287 |
-
language="python",
|
288 |
-
auto_update=True
|
289 |
-
)
|
290 |
|
291 |
-
|
|
|
|
|
292 |
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
if completion_prompt:
|
297 |
-
completed_code = get_code_completion(completion_prompt)
|
298 |
-
st.write(f"**Completion:** {completed_code}")
|
299 |
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
terminal_input = st.text_input("Enter a command:")
|
304 |
-
|
305 |
-
if terminal_input:
|
306 |
-
st.session_state.terminal_history.append(terminal_input)
|
307 |
-
st.write(run_code(terminal_input))
|
308 |
-
terminal_input = "" # Clear the input field
|
309 |
-
|
310 |
-
# Display terminal history
|
311 |
-
st.markdown("\n".join(st.session_state.terminal_history))
|
312 |
-
|
313 |
-
with tool_tabs[2]:
|
314 |
-
# Code Analysis Tab
|
315 |
-
st.subheader("Code Analysis")
|
316 |
-
code_to_analyze = st.text_area("Enter code to analyze:")
|
317 |
-
if code_to_analyze:
|
318 |
-
# Analyze code
|
319 |
-
analysis_results = analyze_code(code_to_analyze)
|
320 |
-
if analysis_results:
|
321 |
-
st.write("**Code Analysis Results:**")
|
322 |
-
for hint in analysis_results:
|
323 |
-
st.write(f"- {hint}")
|
324 |
-
else:
|
325 |
-
st.write("No code analysis suggestions found.")
|
326 |
-
|
327 |
-
# Lint code
|
328 |
-
lint_results = lint_code(code_to_analyze)
|
329 |
-
if lint_results:
|
330 |
-
st.write("**Linting Results:**")
|
331 |
-
for message in lint_results:
|
332 |
-
st.write(f"- {message}")
|
333 |
-
else:
|
334 |
-
st.write("No linting issues found.")
|
335 |
-
|
336 |
-
# Format code
|
337 |
-
formatted_code = format_code(code_to_analyze)
|
338 |
-
st.write("**Formatted Code:**")
|
339 |
-
st.code(formatted_code, language="python")
|
340 |
|
341 |
with workspace_tabs[2]:
|
342 |
# Projects Tab
|
343 |
st.subheader("Projects")
|
344 |
-
project_name = st.text_input("
|
345 |
if st.button("Create Project"):
|
346 |
-
|
|
|
347 |
|
348 |
-
|
349 |
-
|
|
|
|
|
|
|
350 |
|
351 |
-
|
352 |
-
|
353 |
-
code_to_add = st.text_area("Enter code to add:")
|
354 |
-
file_name = st.text_input("Enter file name:")
|
355 |
-
if st.button("Add Code"):
|
356 |
-
st.write(add_code_to_workspace(selected_project, code_to_add, file_name))
|
357 |
|
358 |
if __name__ == "__main__":
|
359 |
main()
|
|
|
1 |
import streamlit as st
|
2 |
from streamlit_ace import st_ace
|
3 |
+
from transformers import pipeline, AutoTokenizer
|
4 |
import os
|
5 |
import subprocess
|
6 |
import black
|
7 |
from pylint import lint
|
8 |
from io import StringIO
|
9 |
import sys
|
|
|
|
|
10 |
import re
|
11 |
from typing import List, Dict
|
12 |
from streamlit_jupyter import StreamlitPatcher, tqdm
|
13 |
+
from agents import TextGenerationTool, AIAgent, process_input, run_code, workspace_interface, add_code_to_workspace, display_chat_history, display_workspace_projects, generate_space_content, analyze_code, get_code_completion, lint_code, format_code
|
14 |
|
15 |
# This line should be at the top of your script
|
16 |
StreamlitPatcher().jupyter() # This patches Streamlit to work in Jupyter
|
|
|
38 |
# AI Guide Toggle
|
39 |
ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
|
40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
# Load the CodeGPT tokenizer explicitly
|
42 |
code_generator_tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
|
43 |
# Load the CodeGPT model for code completion
|
44 |
code_generator = pipeline("text-generation", model="microsoft/CodeGPT-small-py", tokenizer=code_generator_tokenizer)
|
45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
def main():
|
47 |
st.title("Streamlit Workspace")
|
48 |
|
|
|
107 |
))
|
108 |
elif ai_guide_level == "Partial Assistance":
|
109 |
guide_chat_history.append((
|
110 |
+
"I'm building a Streamlit app to display data from a CSV file.",
|
111 |
+
"Great! Let's start by creating a new project in the workspace."
|
112 |
))
|
113 |
+
|
114 |
display_ai_guide_chat(guide_chat_history)
|
115 |
|
116 |
with workspace_tabs[1]:
|
117 |
# Tool Box Tab
|
118 |
st.subheader("Tool Box")
|
119 |
+
code_input = st_ace(language='python', theme='monokai', key='code_input')
|
120 |
+
if st.button("Run Code"):
|
121 |
+
output = run_code(code_input)
|
122 |
+
st.text_area("Output", output, height=200)
|
123 |
|
124 |
+
if st.button("Analyze Code"):
|
125 |
+
hints = analyze_code(code_input)
|
126 |
+
st.text_area("Hints", "\n".join(hints), height=200)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
+
if st.button("Format Code"):
|
129 |
+
formatted_code = format_code(code_input)
|
130 |
+
st_ace(value=formatted_code, language='python', theme='monokai', key='formatted_code')
|
131 |
|
132 |
+
if st.button("Lint Code"):
|
133 |
+
lint_messages = lint_code(code_input)
|
134 |
+
st.text_area("Lint Messages", "\n".join(lint_messages), height=200)
|
|
|
|
|
|
|
135 |
|
136 |
+
if st.button("Get Code Completion"):
|
137 |
+
completion = get_code_completion(code_input)
|
138 |
+
st_ace(value=completion, language='python', theme='monokai', key='code_completion')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
|
140 |
with workspace_tabs[2]:
|
141 |
# Projects Tab
|
142 |
st.subheader("Projects")
|
143 |
+
project_name = st.text_input("Project Name")
|
144 |
if st.button("Create Project"):
|
145 |
+
message = workspace_interface(project_name)
|
146 |
+
st.write(message)
|
147 |
|
148 |
+
file_name = st.text_input("File Name")
|
149 |
+
code_content = st_ace(language='python', theme='monokai', key='code_content')
|
150 |
+
if st.button("Add Code to Project"):
|
151 |
+
message = add_code_to_workspace(project_name, code_content, file_name)
|
152 |
+
st.write(message)
|
153 |
|
154 |
+
st.subheader("Workspace Projects")
|
155 |
+
st.markdown(display_workspace_projects(st.session_state.workspace_projects))
|
|
|
|
|
|
|
|
|
156 |
|
157 |
if __name__ == "__main__":
|
158 |
main()
|