acecalisto3 commited on
Commit
3748d81
1 Parent(s): bd04abe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -340
app.py CHANGED
@@ -1,356 +1,110 @@
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
- import together
9
- import sys
10
-
11
- HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
12
- PROJECT_ROOT = "projects"
13
- AGENT_DIRECTORY = "agents"
14
-
15
- # Global state to manage communication between Tool Box and Workspace Chat App
16
- if 'chat_history' not in st.session_state:
17
- st.session_state.chat_history = []
18
- if 'terminal_history' not in st.session_state:
19
- st.session_state.terminal_history = []
20
- if 'workspace_projects' not in st.session_state:
21
- st.session_state.workspace_projects = {}
22
- if 'available_agents' not in st.session_state:
23
- st.session_state.available_agents = []
24
- if 'current_state' not in st.session_state:
25
- st.session_state.current_state = {
26
- 'toolbox': {},
27
- 'workspace_chat': {}
28
- }
29
-
30
- class AIAgent:
31
- def __init__(self, name, description, skills):
32
- self.name = name
33
- self.description = description
34
- self.skills = skills
35
-
36
- def create_agent_prompt(self):
37
- skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
38
- agent_prompt = (
39
- f"""
40
- As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
41
- {skills_str}
42
- 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.
43
- """
44
- )
45
- return agent_prompt
46
 
47
- def autonomous_build(self, chat_history, workspace_projects):
48
- """
49
- Autonomous build logic that continues based on the state of chat history and workspace projects.
50
- """
51
- summary = (
52
- "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
53
- )
54
- summary += (
55
- "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
56
- )
57
 
58
- # Analyze chat history and workspace projects to suggest actions
59
- # Example:
60
- # - Check if the user has requested to create a new file
61
- # - Check if the user has requested to install a package
62
- # - Check if the user has requested to run a command
63
- # - Check if the user has requested to generate code
64
- # - Check if the user has requested to translate code
65
- # - Check if the user has requested to summarize text
66
- # - Check if the user has requested to analyze sentiment
67
 
68
- # Generate a response based on the analysis
69
- next_step = (
70
- "Based on the current state, the next logical step is to implement the main application logic."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  )
72
 
73
- return summary, next_step
74
-
75
- def save_agent_to_file(agent):
76
- """Saves the agent's prompt to a file."""
77
- if not os.path.exists(AGENT_DIRECTORY):
78
- os.makedirs(AGENT_DIRECTORY)
79
- file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
80
- with open(file_path, "w") as file:
81
- file.write(agent.create_agent_prompt())
82
- st.session_state.available_agents.append(agent.name)
83
 
84
- def load_agent_prompt(agent_name):
85
- """Loads an agent prompt from a file."""
86
- file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
87
- if os.path.exists(file_path):
88
- with open(file_path, "r") as file:
89
- agent_prompt = file.read()
90
- return agent_prompt
91
- else:
92
- return None
93
 
94
- def create_agent_from_text(name, text):
95
- skills = text.split('\n')
96
- agent = AIAgent(name, "AI agent created from text input.", skills)
97
- save_agent_to_file(agent)
98
- return agent.create_agent_prompt()
99
 
100
- def chat_interface_with_agent(input_text, agent_name):
101
- agent_prompt = load_agent_prompt(agent_name)
102
- if agent_prompt is None:
103
- return f"Agent {agent_name} not found."
104
 
105
- model_name = "Bin12345/AutoCoder_S_6.7B"
106
  try:
107
- model = AutoModelForCausalLM.from_pretrained(model_name)
108
- tokenizer = AutoTokenizer.from_pretrained(model_name)
109
- generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
110
- except EnvironmentError as e:
111
- return f"Error loading model: {e}"
112
-
113
- combined_input = (
114
- f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
 
 
 
 
 
 
 
 
 
 
 
115
  )
116
 
117
- input_ids = tokenizer.encode(combined_input, return_tensors="pt")
118
- max_input_length = 900
119
- if input_ids.shape[1] > max_input_length:
120
- input_ids = input_ids[:, :max_input_length]
121
-
122
- outputs = model.generate(
123
- input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True,
124
- pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
125
- )
126
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
127
- return response
128
 
129
- # Terminal interface
130
- def terminal_interface(command, project_name=None):
131
- if project_name:
132
- project_path = os.path.join(PROJECT_ROOT, project_name)
133
- if not os.path.exists(project_path):
134
- return f"Project {project_name} does not exist."
135
- result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)
136
- else:
137
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
138
- return result.stdout
139
 
140
- # Code editor interface
141
- def code_editor_interface(code):
142
  try:
143
- formatted_code = black.format_str(code, mode=black.FileMode())
144
- except black.NothingChanged:
145
- formatted_code = code
146
-
147
- result = StringIO()
148
- sys.stdout = result
149
- sys.stderr = result
150
-
151
- (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
152
- sys.stdout = sys.__stdout__
153
- sys.stderr = sys.__stderr__
154
-
155
- lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
156
-
157
- return formatted_code, lint_message
158
-
159
- # Text summarization tool
160
- def summarize_text(text):
161
- summarizer = pipeline("summarization", model="t5-base")
162
- summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
163
- return summary[0]['summary_text']
164
-
165
- # Sentiment analysis tool
166
- def sentiment_analysis(text):
167
- analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
168
- result = analyzer(text)
169
- return result[0]['label']
170
-
171
- # Text translation tool (code translation)
172
- def translate_code(code, source_language, target_language):
173
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es") # Example: English to Spanish
174
- translated_code = translator(code, target_lang=target_language)[0]['translation_text']
175
- return translated_code
176
-
177
- def generate_code(code_idea):
178
- generator = pipeline('text-generation', model='bigcode/starcoder')
179
- generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
180
- return generated_code
181
-
182
- def chat_interface(input_text):
183
- chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
184
- response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
185
- return response
186
-
187
- # Workspace interface
188
- def workspace_interface(project_name):
189
- project_path = os.path.join(PROJECT_ROOT, project_name)
190
- if not os.path.exists(project_path):
191
- os.makedirs(project_path)
192
- st.session_state.workspace_projects[project_name] = {'files': []}
193
- return f"Project '{project_name}' created successfully."
194
- else:
195
- return f"Project '{project_name}' already exists."
196
-
197
- # Add code to workspace
198
- def add_code_to_workspace(project_name, code, file_name):
199
- project_path = os.path.join(PROJECT_ROOT, project_name)
200
- if not os.path.exists(project_path):
201
- return f"Project '{project_name}' does not exist."
202
-
203
- file_path = os.path.join(project_path, file_name)
204
- with open(file_path, "w") as file:
205
- file.write(code)
206
- st.session_state.workspace_projects[project_name]['files'].append(file_name)
207
- return f"Code added to '{file_name}' in project '{project_name}'."
208
-
209
- # Streamlit App
210
- st.title("AI Agent Creator")
211
-
212
- # Sidebar navigation
213
- st.sidebar.title("Navigation")
214
- app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
215
-
216
- if app_mode == "AI Agent Creator":
217
- # AI Agent Creator
218
- st.header("Create an AI Agent from Text")
219
-
220
- st.subheader("From Text")
221
- agent_name = st.text_input("Enter agent name:")
222
- text_input = st.text_area("Enter skills (one per line):")
223
- if st.button("Create Agent"):
224
- agent_prompt = create_agent_from_text(agent_name, text_input)
225
- st.success(f"Agent '{agent_name}' created and saved successfully.")
226
- st.session_state.available_agents.append(agent_name)
227
-
228
- elif app_mode == "Tool Box":
229
- # Tool Box
230
- st.header("AI-Powered Tools")
231
-
232
- # Chat Interface
233
- st.subheader("Chat with CodeCraft")
234
- chat_input = st.text_area("Enter your message:")
235
- if st.button("Send"):
236
- chat_response = chat_interface(chat_input)
237
- st.session_state.chat_history.append((chat_input, chat_response))
238
- st.write((f"CodeCraft: {chat_response}"))
239
-
240
- # Terminal Interface
241
- st.subheader("Terminal")
242
- terminal_input = st.text_input("Enter a command:")
243
- if st.button("Run"):
244
- terminal_output = terminal_interface(terminal_input)
245
- st.session_state.terminal_history.append((terminal_input, terminal_output))
246
- st.code(terminal_output, language="bash")
247
-
248
- # Code Editor Interface
249
- st.subheader("Code Editor")
250
- code_editor = st.text_area("Write your code:", height=300)
251
- if st.button("Format & Lint"):
252
- formatted_code, lint_message = code_editor_interface(code_editor)
253
- st.code(formatted_code, language="python")
254
- st.info(lint_message)
255
-
256
- # Text Summarization Tool
257
- st.subheader("Summarize Text")
258
- text_to_summarize = st.text_area("Enter text to summarize:")
259
- if st.button("Summarize"):
260
- summary = summarize_text(text_to_summarize)
261
- st.write((f"Summary: {summary}"))
262
-
263
- # Sentiment Analysis Tool
264
- st.subheader("Sentiment Analysis")
265
- sentiment_text = st.text_area("Enter text for sentiment analysis:")
266
- if st.button("Analyze Sentiment"):
267
- sentiment = sentiment_analysis(sentiment_text)
268
- st.write((f"Sentiment: {sentiment}"))
269
-
270
- # Text Translation Tool (Code Translation)
271
- st.subheader("Translate Code")
272
- code_to_translate = st.text_area("Enter code to translate:")
273
- source_language = st.text_input("Enter source language (e.g., 'Python'):")
274
- target_language = st.text_input("Enter target language (e.g., 'JavaScript'):")
275
- if st.button("Translate Code"):
276
- translated_code = translate_code(code_to_translate, source_language, target_language)
277
- st.code(translated_code, language=target_language.lower())
278
-
279
- # Code Generation
280
- st.subheader("Code Generation")
281
- code_idea = st.text_input("Enter your code idea:")
282
- if st.button("Generate Code"):
283
- generated_code = generate_code(code_idea)
284
- st.code(generated_code, language="python")
285
-
286
- elif app_mode == "Workspace Chat App":
287
- # Workspace Chat App
288
- st.header("Workspace Chat App")
289
-
290
- # Project Workspace Creation
291
- st.subheader("Create a New Project")
292
- project_name = st.text_input("Enter project name:")
293
- if st.button("Create Project"):
294
- workspace_status = workspace_interface(project_name)
295
- st.success(workspace_status)
296
-
297
- # Add Code to Workspace
298
- st.subheader("Add Code to Workspace")
299
- code_to_add = st.text_area("Enter code to add to workspace:")
300
- file_name = st.text_input("Enter file name (e.g., 'app.py'):")
301
- if st.button("Add Code"):
302
- add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
303
- st.success(add_code_status)
304
-
305
- # Terminal Interface with Project Context
306
- st.subheader("Terminal (Workspace Context)")
307
- terminal_input = st.text_input("Enter a command within the workspace:")
308
- if st.button("Run Command"):
309
- terminal_output = terminal_interface(terminal_input, project_name)
310
- st.code(terminal_output, language="bash")
311
-
312
- # Chat Interface for Guidance
313
- st.subheader("Chat with CodeCraft for Guidance")
314
- chat_input = st.text_area("Enter your message for guidance:")
315
- if st.button("Get Guidance"):
316
- chat_response = chat_interface(chat_input)
317
- st.session_state.chat_history.append((chat_input, chat_response))
318
- st.write((f"CodeCraft: {chat_response}"))
319
-
320
- # Display Chat History
321
- st.subheader("Chat History")
322
- for user_input, response in st.session_state.chat_history:
323
- st.write((f"User: {user_input}"))
324
- st.write((f"CodeCraft: {response}"))
325
-
326
- # Display Terminal History
327
- st.subheader("Terminal History")
328
- for command, output in st.session_state.terminal_history:
329
- st.write((f"Command: {command}"))
330
- st.code(output, language="bash")
331
-
332
- # Display Projects and Files
333
- st.subheader("Workspace Projects")
334
- for project, details in st.session_state.workspace_projects.items():
335
- st.write((f"Project: {project}"))
336
- for file in details['files']:
337
- st.write((f" - {file}"))
338
-
339
- # Chat with AI Agents
340
- st.subheader("Chat with AI Agents")
341
- selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
342
- agent_chat_input = st.text_area("Enter your message for the agent:")
343
- if st.button("Send to Agent"):
344
- agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
345
- st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
346
- st.write((f"{selected_agent}: {agent_chat_response}"))
347
-
348
- # Automate Build Process
349
- st.subheader("Automate Build Process")
350
- if st.button("Automate"):
351
- agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
352
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
353
- st.write("Autonomous Build Summary:")
354
- st.write(summary)
355
- st.write("Next Step:")
356
- st.write(next_step)
 
 
 
1
  import streamlit as st
2
+ import gradio as gr
3
+ from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer
4
+ import subprocess
5
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Initialize Hugging Face pipelines
8
+ text_generator = pipeline("text-generation", model="gpt2")
9
+ code_generator = pipeline("text2text-generation", model="microsoft/CodeGPT-small-py")
 
 
 
 
 
 
 
10
 
11
+ # Streamlit App
12
+ st.title("AI Dev Tool Kit")
 
 
 
 
 
 
 
13
 
14
+ # Sidebar for Navigation
15
+ st.sidebar.title("Navigation")
16
+ app_mode = st.sidebar.selectbox("Choose the app mode", ["Explorer", "In-Chat Terminal", "Tool Box"])
17
+
18
+ if app_mode == "Explorer":
19
+ st.header("Explorer")
20
+ st.write("Explore files and projects here.")
21
+ # Implement your explorer functionality here
22
+
23
+ elif app_mode == "In-Chat Terminal":
24
+ st.header("In-Chat Terminal")
25
+
26
+ def run_terminal_command(command):
27
+ try:
28
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
29
+ return result.stdout if result.returncode == 0 else result.stderr
30
+ except Exception as e:
31
+ return str(e)
32
+
33
+ def terminal_interface(command):
34
+ response = run_terminal_command(command)
35
+ return response
36
+
37
+ def nlp_code_interpreter(text):
38
+ response = code_generator(text, max_length=150)
39
+ code = response[0]['generated_text']
40
+ return code, run_terminal_command(code)
41
+
42
+ with gr.Blocks() as iface:
43
+ terminal_input = gr.Textbox(label="Enter Command or Code")
44
+ terminal_output = gr.Textbox(label="Terminal Output", lines=10)
45
+ terminal_button = gr.Button("Run")
46
+
47
+ terminal_button.click(
48
+ nlp_code_interpreter,
49
+ inputs=terminal_input,
50
+ outputs=[terminal_output, terminal_output]
51
  )
52
 
53
+ iface.launch()
 
 
 
 
 
 
 
 
 
54
 
55
+ st.write("Use the terminal to execute commands or interpret natural language into code.")
 
 
 
 
 
 
 
 
56
 
57
+ elif app_mode == "Tool Box":
58
+ st.header("Tool Box")
59
+ st.write("Access various AI development tools here.")
60
+ # Implement your tool box functionality here
 
61
 
62
+ # Deploy to Hugging Face Spaces
63
+ def deploy_to_huggingface(app_name):
64
+ code = f"""
65
+ import gradio as gr
66
 
67
+ def run_terminal_command(command):
68
  try:
69
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
70
+ return result.stdout if result.returncode == 0 else result.stderr
71
+ except Exception as e:
72
+ return str(e)
73
+
74
+ def nlp_code_interpreter(text):
75
+ response = code_generator(text, max_length=150)
76
+ code = response[0]['generated_text']
77
+ return code, run_terminal_command(code)
78
+
79
+ with gr.Blocks() as iface:
80
+ terminal_input = gr.Textbox(label="Enter Command or Code")
81
+ terminal_output = gr.Textbox(label="Terminal Output", lines=10)
82
+ terminal_button = gr.Button("Run")
83
+
84
+ terminal_button.click(
85
+ nlp_code_interpreter,
86
+ inputs=terminal_input,
87
+ outputs=[terminal_output, terminal_output]
88
  )
89
 
90
+ iface.launch()
91
+ """
 
 
 
 
 
 
 
 
 
92
 
93
+ with open("app.py", "w") as f:
94
+ f.write(code)
 
 
 
 
 
 
 
 
95
 
 
 
96
  try:
97
+ subprocess.run(["huggingface-cli", "repo", "create", "--type", "space", "--space_sdk", "gradio", app_name], check=True)
98
+ subprocess.run(["git", "init"], cwd=f"./{app_name}", check=True)
99
+ subprocess.run(["git", "add", "."], cwd=f"./{app_name}", check=True)
100
+ subprocess.run(['git', 'commit', '-m', '"Initial commit"'], cwd=f'./{app_name}', check=True)
101
+ subprocess.run(["git", "push", "https://huggingface.co/spaces/" + app_name, "main"], cwd=f'./{app_name}', check=True)
102
+ return f"Successfully deployed to Hugging Face Spaces: https://huggingface.co/spaces/{app_name}"
103
+ except Exception as e:
104
+ return f"Error deploying to Hugging Face Spaces: {e}"
105
+
106
+ # Example usage
107
+ if st.button("Deploy to Hugging Face"):
108
+ app_name = "ai-dev-toolkit"
109
+ deploy_status = deploy_to_huggingface(app_name)
110
+ st.write(deploy_status)