Spaces:
Sleeping
Sleeping
acecalisto3
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,302 +1,348 @@
|
|
|
|
1 |
import sys
|
2 |
import subprocess
|
3 |
-
|
4 |
-
|
5 |
-
from
|
6 |
-
from
|
7 |
-
|
8 |
-
import tempfile
|
9 |
-
import os
|
10 |
-
import importlib
|
11 |
-
|
12 |
-
class AppType(Enum):
|
13 |
-
WEB_APP = auto()
|
14 |
-
GRADIO_APP = auto()
|
15 |
-
STREAMLIT_APP = auto()
|
16 |
-
REACT_APP = auto()
|
17 |
-
|
18 |
-
@dataclass(frozen=True)
|
19 |
-
class Code:
|
20 |
-
content: str
|
21 |
-
language: str
|
22 |
-
|
23 |
-
@dataclass(frozen=True)
|
24 |
-
class Prompt:
|
25 |
-
content: str
|
26 |
-
|
27 |
-
@dataclass(frozen=True)
|
28 |
-
class Space:
|
29 |
-
content: str
|
30 |
-
|
31 |
-
@dataclass(frozen=True)
|
32 |
-
class Tutorial:
|
33 |
-
content: str
|
34 |
-
|
35 |
-
@dataclass(frozen=True)
|
36 |
-
class File:
|
37 |
-
name: str
|
38 |
-
content: str
|
39 |
-
language: str
|
40 |
-
|
41 |
-
@dataclass(frozen=True)
|
42 |
-
class AppInfo:
|
43 |
-
name: str
|
44 |
-
description: str
|
45 |
-
features: Tuple[str, ...]
|
46 |
-
dependencies: Tuple[str, ...]
|
47 |
-
space: Optional[Space] = None
|
48 |
-
tutorial: Optional[Tutorial] = None
|
49 |
-
|
50 |
-
@dataclass(frozen=True)
|
51 |
-
class App:
|
52 |
-
code: Code
|
53 |
-
|
54 |
-
def run(self):
|
55 |
-
raise NotImplementedError("Subclasses must implement run method")
|
56 |
-
|
57 |
-
@dataclass(frozen=True)
|
58 |
-
class WebApp(App):
|
59 |
-
def run(self):
|
60 |
-
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.html') as f:
|
61 |
-
f.write(self.code.content)
|
62 |
-
webbrowser.open('file://' + f.name)
|
63 |
-
print(f"Opened WebApp in default browser. Temporary file: {f.name}")
|
64 |
-
|
65 |
-
@dataclass(frozen=True)
|
66 |
-
class GradioApp(App):
|
67 |
-
def run(self):
|
68 |
-
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as f:
|
69 |
-
f.write(self.code.content)
|
70 |
-
try:
|
71 |
-
subprocess.run([sys.executable, f.name], check=True)
|
72 |
-
except subprocess.CalledProcessError:
|
73 |
-
print("Error running Gradio app. Make sure Gradio is installed: pip install gradio")
|
74 |
-
finally:
|
75 |
-
os.unlink(f.name)
|
76 |
-
|
77 |
-
@dataclass(frozen=True)
|
78 |
-
class StreamlitApp(App):
|
79 |
-
def run(self):
|
80 |
-
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as f:
|
81 |
-
f.write(self.code.content)
|
82 |
-
try:
|
83 |
-
subprocess.run([sys.executable, "-m", "streamlit", "run", f.name], check=True)
|
84 |
-
except subprocess.CalledProcessError:
|
85 |
-
print("Error running Streamlit app. Make sure Streamlit is installed: pip install streamlit")
|
86 |
-
finally:
|
87 |
-
os.unlink(f.name)
|
88 |
-
|
89 |
-
|
90 |
-
@dataclass(frozen=True)
|
91 |
-
class ReactApp(App):
|
92 |
-
def run(self):
|
93 |
-
print("To run a React app, you need to set up a proper React environment.")
|
94 |
-
print("Here's how you might typically run a React app:")
|
95 |
-
print("1. Make sure you have Node.js and npm installed")
|
96 |
-
print("2. Create a new React app: npx create-react-app my-app")
|
97 |
-
print("3. Replace the contents of src/App.js with the generated code")
|
98 |
-
print("4. Run the app: npm start")
|
99 |
-
print("\nHere's the code for your App.js:")
|
100 |
-
print(self.code.content)
|
101 |
-
|
102 |
-
class AppFactory:
|
103 |
-
@staticmethod
|
104 |
-
@lru_cache(maxsize=128)
|
105 |
-
def create_prompt(app_type: AppType, app_info: AppInfo) -> Prompt:
|
106 |
-
return Prompt(
|
107 |
-
content=f"""
|
108 |
-
Create a {app_type.name} web application with the following details:
|
109 |
-
Name: {app_info.name}
|
110 |
-
Description: {app_info.description}
|
111 |
-
Features: {', '.join(app_info.features)}
|
112 |
-
Dependencies: {', '.join(app_info.dependencies)}
|
113 |
-
Space: {app_info.space.content if app_info.space else 'N/A'}
|
114 |
-
Tutorial: {app_info.tutorial.content if app_info.tutorial else 'N/A'}
|
115 |
-
Please generate the code for this application.
|
116 |
-
"""
|
117 |
-
)
|
118 |
-
|
119 |
-
@staticmethod
|
120 |
-
@lru_cache(maxsize=128)
|
121 |
-
def create_space(app_info: AppInfo) -> Space:
|
122 |
-
return Space(
|
123 |
-
content=f"""
|
124 |
-
{app_info.name}
|
125 |
-
{app_info.description}
|
126 |
-
Features: {', '.join(app_info.features)}
|
127 |
-
Dependencies: {', '.join(app_info.dependencies)}
|
128 |
-
"""
|
129 |
-
)
|
130 |
-
|
131 |
-
@staticmethod
|
132 |
-
@lru_cache(maxsize=128)
|
133 |
-
def create_app_type_prompt(app_type: AppType, app_info: AppInfo) -> Prompt:
|
134 |
-
return Prompt(
|
135 |
-
content=f"""
|
136 |
-
Is the following web application a {app_type.name}?
|
137 |
-
{app_info.name}
|
138 |
-
{app_info.description}
|
139 |
-
Features: {', '.join(app_info.features)}
|
140 |
-
Dependencies: {', '.join(app_info.dependencies)}
|
141 |
-
Please answer with either "Yes" or "No".
|
142 |
-
"""
|
143 |
-
)
|
144 |
-
|
145 |
-
@staticmethod
|
146 |
-
def get_app(app_type: AppType, app_info: AppInfo) -> App:
|
147 |
-
app_creators = {
|
148 |
-
AppType.WEB_APP: AppFactory._create_web_app,
|
149 |
-
AppType.GRADIO_APP: AppFactory._create_gradio_app,
|
150 |
-
AppType.STREAMLIT_APP: AppFactory._create_streamlit_app,
|
151 |
-
AppType.REACT_APP: AppFactory._create_react_app,
|
152 |
-
}
|
153 |
-
return app_creators[app_type](app_info)
|
154 |
-
|
155 |
-
@staticmethod
|
156 |
-
@lru_cache(maxsize=128)
|
157 |
-
def _create_web_app(app_info: AppInfo) -> WebApp:
|
158 |
-
code = Code(
|
159 |
-
content=f"""
|
160 |
-
<!DOCTYPE html>
|
161 |
-
<html lang="en">
|
162 |
-
<head>
|
163 |
-
<meta charset="UTF-8">
|
164 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
165 |
-
<title>{app_info.name}</title>
|
166 |
-
</head>
|
167 |
-
<body>
|
168 |
-
<h1>{app_info.name}</h1>
|
169 |
-
<p>{app_info.description}</p>
|
170 |
-
</body>
|
171 |
-
</html>
|
172 |
-
""",
|
173 |
-
language="html"
|
174 |
-
)
|
175 |
-
return WebApp(code=code)
|
176 |
-
|
177 |
-
@staticmethod
|
178 |
-
@lru_cache(maxsize=128)
|
179 |
-
def _create_gradio_app(app_info: AppInfo) -> GradioApp:
|
180 |
-
code = Code(
|
181 |
-
content="""
|
182 |
-
import gradio as gr
|
183 |
-
|
184 |
-
def greet(name):
|
185 |
-
return f"Hello, {name}!"
|
186 |
-
|
187 |
-
demo = gr.Interface(greet, "text", "text")
|
188 |
-
|
189 |
-
if __name__ == "__main__":
|
190 |
-
demo.launch()
|
191 |
-
""",
|
192 |
-
language="python"
|
193 |
-
)
|
194 |
-
return GradioApp(code=code)
|
195 |
-
|
196 |
-
@staticmethod
|
197 |
-
@lru_cache(maxsize=128)
|
198 |
-
def _create_streamlit_app(app_info: AppInfo) -> StreamlitApp:
|
199 |
-
code = Code(
|
200 |
-
content=f"""
|
201 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
|
203 |
-
st.title('{app_info.name}')
|
204 |
-
st.write('{app_info.description}')
|
205 |
-
""",
|
206 |
-
language="python"
|
207 |
-
)
|
208 |
-
return StreamlitApp(code=code)
|
209 |
-
|
210 |
-
@staticmethod
|
211 |
-
@lru_cache(maxsize=128)
|
212 |
-
def _create_react_app(app_info: AppInfo) -> ReactApp:
|
213 |
-
code = Code(
|
214 |
-
content=f"""
|
215 |
-
import React from 'react';
|
216 |
-
|
217 |
-
function App() {{
|
218 |
-
return (
|
219 |
-
<div className="App">
|
220 |
-
<h1>{app_info.name}</h1>
|
221 |
-
<p>{app_info.description}</p>
|
222 |
-
</div>
|
223 |
-
);
|
224 |
-
}}
|
225 |
-
|
226 |
-
export default App;
|
227 |
-
""",
|
228 |
-
language="javascript"
|
229 |
-
)
|
230 |
-
return ReactApp(code=code)
|
231 |
-
|
232 |
-
@staticmethod
|
233 |
-
@lru_cache(maxsize=128)
|
234 |
-
def parse_tutorial(app_info: AppInfo) -> Tutorial:
|
235 |
-
return Tutorial(
|
236 |
-
content=f"""
|
237 |
-
## {app_info.name} Tutorial
|
238 |
-
**Introduction**
|
239 |
-
{app_info.description}
|
240 |
-
**Prerequisites**
|
241 |
-
* Basic knowledge of web development
|
242 |
-
* Familiarity with {', '.join(app_info.dependencies)}
|
243 |
-
**Steps**
|
244 |
-
{chr(10).join(f"{i+1}. {feature}" for i, feature in enumerate(app_info.features))}
|
245 |
-
**Conclusion**
|
246 |
-
Congratulations! You have successfully created a {app_info.name} application.
|
247 |
-
"""
|
248 |
-
)
|
249 |
-
|
250 |
-
@staticmethod
|
251 |
-
def generate_files(app_type: AppType, app_info: AppInfo) -> List[File]:
|
252 |
-
app = AppFactory.get_app(app_type, app_info)
|
253 |
-
file_name = {
|
254 |
-
AppType.WEB_APP: "index.html",
|
255 |
-
AppType.GRADIO_APP: "app.py",
|
256 |
-
AppType.STREAMLIT_APP: "app.py",
|
257 |
-
AppType.REACT_APP: "App.js",
|
258 |
-
}[app_type]
|
259 |
-
return [File(name=file_name, content=app.code.content, language=app.code.language)]
|
260 |
-
|
261 |
-
@staticmethod
|
262 |
-
def run_app(app: App):
|
263 |
-
app.run()
|
264 |
-
|
265 |
-
if __name__ == "__main__":
|
266 |
-
app_info = AppInfo(
|
267 |
-
name="My Cool App",
|
268 |
-
description="A simple web application",
|
269 |
-
features=("Feature 1", "Feature 2", "Feature 3"),
|
270 |
-
dependencies=("Python", "JavaScript"),
|
271 |
-
)
|
272 |
-
|
273 |
-
# Check if required packages are installed
|
274 |
-
required_packages = ['gradio', 'streamlit']
|
275 |
-
missing_packages = []
|
276 |
-
for package in required_packages:
|
277 |
try:
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Add your Hugging Face API token here
|
16 |
+
hf_token = st.secrets["huggingface"]
|
17 |
+
|
18 |
+
# Constants
|
19 |
+
PROJECT_ROOT = "./projects"
|
20 |
+
AGENT_DIRECTORY = "./agents"
|
21 |
+
AVAILABLE_CODE_GENERATIVE_MODELS = ["codegen", "gpt-neo", "codeparrot"]
|
22 |
+
|
23 |
+
# Global state management
|
24 |
+
if "chat_history" not in st.session_state:
|
25 |
+
st.session_state.chat_history = []
|
26 |
+
if "terminal_history" not in st.session_state:
|
27 |
+
st.session_state.terminal_history = []
|
28 |
+
if "workspace_projects" not in st.session_state:
|
29 |
+
st.session_state.workspace_projects = {}
|
30 |
+
if "available_agents" not in st.session_state:
|
31 |
+
st.session_state.available_agents = []
|
32 |
+
|
33 |
+
# Load pre-trained models
|
34 |
+
@st.cache(allow_output_mutation=True)
|
35 |
+
def load_models():
|
36 |
+
rag_retriever = pipeline("question-answering", model="facebook/rag-token-nq")
|
37 |
+
chat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium")
|
38 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
39 |
+
return rag_retriever, chat_model, tokenizer
|
40 |
+
|
41 |
+
rag_retriever, chat_model, tokenizer = load_models()
|
42 |
+
|
43 |
+
def process_input(user_input: str) -> str:
|
44 |
+
# Input pipeline: Tokenize and preprocess user input
|
45 |
+
input_ids = tokenizer(user_input, return_tensors="pt").input_ids
|
46 |
+
attention_mask = tokenizer(user_input, return_tensors="pt").attention_mask
|
47 |
+
|
48 |
+
# RAG model: Generate response
|
49 |
+
with torch.no_grad():
|
50 |
+
rag_output = rag_retriever(question=user_input, context=user_input)
|
51 |
+
rag_answer = rag_output['answer']
|
52 |
+
|
53 |
+
# Chat model: Refine response
|
54 |
+
chat_input = tokenizer(rag_answer, return_tensors="pt")
|
55 |
+
with torch.no_grad():
|
56 |
+
chat_output = chat_model.generate(**chat_input)
|
57 |
+
refined_response = tokenizer.decode(chat_output[0], skip_special_tokens=True)
|
58 |
+
|
59 |
+
return refined_response
|
60 |
+
|
61 |
+
class AIAgent:
|
62 |
+
def __init__(self, name: str, description: str, skills: List[str], hf_api=None):
|
63 |
+
self.name = name
|
64 |
+
self.description = description
|
65 |
+
self.skills = skills
|
66 |
+
self._hf_api = hf_api
|
67 |
+
self._hf_token = hf_token
|
68 |
+
|
69 |
+
@property
|
70 |
+
def hf_api(self):
|
71 |
+
if not self._hf_api and self.has_valid_hf_token():
|
72 |
+
self._hf_api = HfApi(token=self._hf_token)
|
73 |
+
return self._hf_api
|
74 |
+
|
75 |
+
def has_valid_hf_token(self):
|
76 |
+
return bool(self._hf_token)
|
77 |
+
|
78 |
+
def create_agent_prompt(self):
|
79 |
+
return f"Name: {self.name}\nDescription: {self.description}\nSkills:\n" + "\n".join(self.skills)
|
80 |
+
|
81 |
+
async def autonomous_build(self, chat_history: List[str], workspace_projects: Dict[str, str], project_name: str, selected_model: str):
|
82 |
+
summary = "Chat History:\n" + "\n".join(chat_history)
|
83 |
+
summary += "\n\nWorkspace Projects:\n" + "\n".join(workspace_projects.items())
|
84 |
+
|
85 |
+
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
86 |
+
|
87 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
88 |
+
if not os.path.exists(project_path):
|
89 |
+
os.makedirs(project_path)
|
90 |
+
|
91 |
+
requirements_file = os.path.join(project_path, "requirements.txt")
|
92 |
+
if not os.path.exists(requirements_file):
|
93 |
+
with open(requirements_file, "w") as f:
|
94 |
+
f.write("# Add your project's dependencies here\n")
|
95 |
+
|
96 |
+
app_file = os.path.join(project_path, "app.py")
|
97 |
+
if not os.path.exists(app_file):
|
98 |
+
with open(app_file, "w") as f:
|
99 |
+
f.write("# Your project's main application logic goes here\n")
|
100 |
+
|
101 |
+
if "create a gui" in summary.lower():
|
102 |
+
gui_code = generate_code(
|
103 |
+
"Create a simple GUI for this application", selected_model)
|
104 |
+
with open(app_file, "a") as f:
|
105 |
+
f.write(gui_code)
|
106 |
+
|
107 |
+
build_command = "pip install -r requirements.txt && python app.py"
|
108 |
+
try:
|
109 |
+
result = subprocess.run(
|
110 |
+
build_command, shell=True, capture_output=True, text=True, cwd=project_path)
|
111 |
+
st.write(f"Build Output:\n{result.stdout}")
|
112 |
+
if result.stderr:
|
113 |
+
st.error(f"Build Errors:\n{result.stderr}")
|
114 |
+
except Exception as e:
|
115 |
+
st.error(f"Build Error: {e}")
|
116 |
+
|
117 |
+
return summary, next_step
|
118 |
+
|
119 |
+
def deploy_built_space_to_hf(self):
|
120 |
+
if not self.has_valid_hf_token():
|
121 |
+
st.error("Invalid Hugging Face token. Please check your configuration.")
|
122 |
+
return
|
123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
try:
|
125 |
+
files = get_built_space_files()
|
126 |
+
create_space_on_hugging_face(self.hf_api, self.name, self.description, True, files)
|
127 |
+
st.success(f"Successfully deployed {self.name} to Hugging Face Spaces!")
|
128 |
+
except Exception as e:
|
129 |
+
st.error(f"Error deploying to Hugging Face Spaces: {str(e)}")
|
130 |
+
|
131 |
+
def get_built_space_files() -> Dict[str, str]:
|
132 |
+
return {
|
133 |
+
"app.py": "# Your Streamlit app code here",
|
134 |
+
"requirements.txt": "streamlit\ntransformers"
|
135 |
+
}
|
136 |
+
|
137 |
+
def save_agent_to_file(agent: AIAgent):
|
138 |
+
if not os.path.exists(AGENT_DIRECTORY):
|
139 |
+
os.makedirs(AGENT_DIRECTORY)
|
140 |
+
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
|
141 |
+
with open(file_path, "w") as file:
|
142 |
+
file.write(agent.create_agent_prompt())
|
143 |
+
st.session_state.available_agents.append(agent.name)
|
144 |
+
|
145 |
+
def load_agent_prompt(agent_name: str) -> str:
|
146 |
+
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
147 |
+
if os.path.exists(file_path):
|
148 |
+
with open(file_path, "r") as file:
|
149 |
+
agent_prompt = file.read()
|
150 |
+
return agent_prompt
|
151 |
+
else:
|
152 |
+
return None
|
153 |
+
|
154 |
+
def create_agent_from_text(name: str, text: str) -> str:
|
155 |
+
skills = text.split("\n")
|
156 |
+
agent = AIAgent(name, "AI agent created from text input.", skills)
|
157 |
+
save_agent_to_file(agent)
|
158 |
+
return agent.create_agent_prompt()
|
159 |
+
|
160 |
+
def chat_interface_with_agent(input_text: str, agent_name: str) -> str:
|
161 |
+
agent_prompt = load_agent_prompt(agent_name)
|
162 |
+
if agent_prompt is None:
|
163 |
+
return f"Agent {agent_name} not found."
|
164 |
+
|
165 |
+
model_name = "microsoft/DialoGPT-medium"
|
166 |
+
try:
|
167 |
+
generator = pipeline("text-generation", model=model_name)
|
168 |
+
generated_response = generator(
|
169 |
+
f"{agent_prompt}\n\nUser: {input_text}\nAgent:", max_length=100, do_sample=True, top_k=50)[0]["generated_text"]
|
170 |
+
return generated_response
|
171 |
+
except Exception as e:
|
172 |
+
return f"Error loading model: {e}"
|
173 |
+
|
174 |
+
def terminal_interface(command: str, project_name: str = None) -> str:
|
175 |
+
if project_name:
|
176 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
177 |
+
if not os.path.exists(project_path):
|
178 |
+
return f"Project {project_name} does not exist."
|
179 |
+
result = subprocess.run(
|
180 |
+
command, shell=True, capture_output=True, text=True, cwd=project_path)
|
181 |
+
else:
|
182 |
+
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
183 |
+
return result.stdout
|
184 |
+
|
185 |
+
def code_editor_interface(code: str) -> str:
|
186 |
+
try:
|
187 |
+
formatted_code = black.format_str(code, mode=black.FileMode())
|
188 |
+
except black.NothingChanged:
|
189 |
+
formatted_code = code
|
190 |
+
|
191 |
+
result = StringIO()
|
192 |
+
sys.stdout = result
|
193 |
+
sys.stderr = result
|
194 |
+
|
195 |
+
lint.Run(['--rcfile=/dev/null', '-'], exit=False)
|
196 |
+
lint_message = result.getvalue()
|
197 |
+
|
198 |
+
sys.stdout = sys.__stdout__
|
199 |
+
sys.stderr = sys.__stderr__
|
200 |
+
|
201 |
+
return formatted_code, lint_message
|
202 |
+
|
203 |
+
def summarize_text(text: str) -> str:
|
204 |
+
summarizer = pipeline("summarization")
|
205 |
+
summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
|
206 |
+
return summary[0]['summary_text']
|
207 |
+
|
208 |
+
def sentiment_analysis(text: str) -> str:
|
209 |
+
analyzer = pipeline("sentiment-analysis")
|
210 |
+
result = analyzer(text)
|
211 |
+
return result[0]['label']
|
212 |
+
|
213 |
+
def translate_code(code: str, source_language: str, target_language: str) -> str:
|
214 |
+
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ROMANCE")
|
215 |
+
translated_code = translator(code, max_length=512)[0]['translation_text']
|
216 |
+
return translated_code
|
217 |
+
|
218 |
+
def generate_code(code_idea: str, model_name: str) -> str:
|
219 |
+
try:
|
220 |
+
generator = pipeline('text-generation', model=model_name)
|
221 |
+
generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
|
222 |
+
return generated_code
|
223 |
+
except Exception as e:
|
224 |
+
return f"Error generating code: {e}"
|
225 |
+
|
226 |
+
def chat_interface(input_text: str) -> str:
|
227 |
+
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
|
228 |
+
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
229 |
+
return response
|
230 |
+
|
231 |
+
def workspace_interface(project_name: str) -> str:
|
232 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
233 |
+
if not os.path.exists(project_path):
|
234 |
+
os.makedirs(project_path)
|
235 |
+
st.session_state.workspace_projects[project_name] = {'files': []}
|
236 |
+
return f"Project '{project_name}' created successfully."
|
237 |
+
else:
|
238 |
+
return f"Project '{project_name}' already exists."
|
239 |
+
|
240 |
+
def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
|
241 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
242 |
+
if not os.path.exists(project_path):
|
243 |
+
return f"Project '{project_name}' does not exist."
|
244 |
+
|
245 |
+
file_path = os.path.join(project_path, file_name)
|
246 |
+
with open(file_path, "w") as file:
|
247 |
+
file.write(code)
|
248 |
+
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
249 |
+
return f"Code added to '{file_name}' in project '{project_name}'."
|
250 |
+
|
251 |
+
def create_space_on_hugging_face(api, name, description, public, files, entrypoint="app.py"):
|
252 |
+
try:
|
253 |
+
repo = api.create_repo(name, exist_ok=True, private=not public)
|
254 |
+
for filename, content in files.items():
|
255 |
+
api.upload_file(
|
256 |
+
path_or_fileobj=content.encode(),
|
257 |
+
path_in_repo=filename,
|
258 |
+
repo_id=repo.repo_id,
|
259 |
+
repo_type="space",
|
260 |
+
)
|
261 |
+
return repo
|
262 |
+
except Exception as e:
|
263 |
+
st.error(f"Error creating Hugging Face Space: {str(e)}")
|
264 |
+
return None
|
265 |
+
|
266 |
+
# Streamlit App
|
267 |
+
st.title("AI Agent Creator")
|
268 |
+
|
269 |
+
# Sidebar navigation
|
270 |
+
st.sidebar.title("Navigation")
|
271 |
+
app_mode = st.sidebar.selectbox(
|
272 |
+
"Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
|
273 |
+
|
274 |
+
if app_mode == "AI Agent Creator":
|
275 |
+
st.header("Create an AI Agent from Text")
|
276 |
+
|
277 |
+
st.subheader("From Text")
|
278 |
+
agent_name = st.text_input("Enter agent name:")
|
279 |
+
text_input = st.text_area("Enter skills (one per line):")
|
280 |
+
if st.button("Create Agent"):
|
281 |
+
agent_prompt = create_agent_from_text(agent_name, text_input)
|
282 |
+
st.success(f"Agent '{agent_name}' created and saved successfully.")
|
283 |
+
st.session_state.available_agents.append(agent_name)
|
284 |
+
|
285 |
+
elif app_mode == "Tool Box":
|
286 |
+
st.header("AI-Powered Tools")
|
287 |
+
|
288 |
+
st.subheader("Chat with CodeCraft")
|
289 |
+
chat_input = st.text_area("Enter your message:")
|
290 |
+
if st.button("Send"):
|
291 |
+
chat_response = chat_interface(chat_input)
|
292 |
+
st.session_state.chat_history.append((chat_input, chat_response))
|
293 |
+
st.write(f"CodeCraft: {chat_response}")
|
294 |
+
|
295 |
+
st.subheader("Terminal")
|
296 |
+
terminal_input = st.text_input("Enter a command:")
|
297 |
+
if st.button("Run"):
|
298 |
+
terminal_output = terminal_interface(terminal_input)
|
299 |
+
st.session_state.terminal_history.append(
|
300 |
+
(terminal_input, terminal_output))
|
301 |
+
st.code(terminal_output, language="bash")
|
302 |
+
|
303 |
+
st.subheader("Code Editor")
|
304 |
+
code_editor = st.text_area("Write your code:", height=300)
|
305 |
+
if st.button("Format & Lint"):
|
306 |
+
formatted_code, lint_message = code_editor_interface(code_editor)
|
307 |
+
st.code(formatted_code, language="python")
|
308 |
+
st.info(lint_message)
|
309 |
+
|
310 |
+
st.subheader("Summarize Text")
|
311 |
+
text_to_summarize = st.text_area("Enter text to summarize:")
|
312 |
+
if st.button("Summarize"):
|
313 |
+
summary = summarize_text(text_to_summarize)
|
314 |
+
st.write(f"Summary: {summary}")
|
315 |
+
|
316 |
+
st.subheader("Sentiment Analysis")
|
317 |
+
sentiment_text = st.text_area("Enter text for sentiment analysis:")
|
318 |
+
if st.button("Analyze Sentiment"):
|
319 |
+
sentiment = sentiment_analysis(sentiment_text)
|
320 |
+
st.write(f"Sentiment: {sentiment}")
|
321 |
+
|
322 |
+
st.subheader("Translate Code")
|
323 |
+
code_to_translate = st.text_area("Enter code to translate:")
|
324 |
+
source_language = st.text_input("Enter source language (e.g., 'Python'):")
|
325 |
+
target_language = st.text_input(
|
326 |
+
"Enter target language (e.g., 'JavaScript'):")
|
327 |
+
if st.button("Translate Code"):
|
328 |
+
translated_code = translate_code(
|
329 |
+
code_to_translate, source_language, target_language)
|
330 |
+
st.code(translated_code, language=target_language.lower())
|
331 |
+
|
332 |
+
st.subheader("Code Generation")
|
333 |
+
code_idea = st.text_input("Enter your code idea:")
|
334 |
+
if st.button("Generate Code"):
|
335 |
+
generated_code = generate_code(code_idea, "gpt2")
|
336 |
+
st.code(generated_code, language="python")
|
337 |
+
|
338 |
+
elif app_mode == "Workspace Chat App":
|
339 |
+
st.header("Workspace Chat App")
|
340 |
+
|
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 |
+
st.subheader("Add Code to Workspace")
|
348 |
+
code_to_add = st.text_area("Enter code to add to workspace:")
|