Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,10 +2,29 @@ import os
|
|
| 2 |
import subprocess
|
| 3 |
import streamlit as st
|
| 4 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 5 |
-
import
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from io import StringIO
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
|
| 10 |
PROJECT_ROOT = "projects"
|
| 11 |
AGENT_DIRECTORY = "agents"
|
|
@@ -25,387 +44,269 @@ if 'current_state' not in st.session_state:
|
|
| 25 |
'workspace_chat': {}
|
| 26 |
}
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
"""
|
| 48 |
-
summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
| 49 |
-
summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
| 50 |
-
|
| 51 |
-
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
| 52 |
-
|
| 53 |
-
return summary, next_step
|
| 54 |
-
|
| 55 |
-
def save_agent_to_file(agent):
|
| 56 |
-
"""Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""
|
| 57 |
-
if not os.path.exists(AGENT_DIRECTORY):
|
| 58 |
-
os.makedirs(AGENT_DIRECTORY)
|
| 59 |
-
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
|
| 60 |
-
config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
|
| 61 |
-
with open(file_path, "w") as file:
|
| 62 |
-
file.write(agent.create_agent_prompt())
|
| 63 |
-
with open(config_path, "w") as file:
|
| 64 |
-
file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
|
| 65 |
-
st.session_state.available_agents.append(agent.name)
|
| 66 |
-
|
| 67 |
-
commit_and_push_changes(f"Add agent {agent.name}")
|
| 68 |
-
|
| 69 |
-
def load_agent_prompt(agent_name):
|
| 70 |
-
"""Loads an agent prompt from a file."""
|
| 71 |
-
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
| 72 |
-
if os.path.exists(file_path):
|
| 73 |
-
with open(file_path, "r") as file:
|
| 74 |
-
agent_prompt = file.read()
|
| 75 |
-
return agent_prompt
|
| 76 |
else:
|
| 77 |
-
return
|
| 78 |
-
|
| 79 |
-
def
|
| 80 |
-
|
| 81 |
-
agent = AIAgent(name, "AI agent created from text input.", skills)
|
| 82 |
-
save_agent_to_file(agent)
|
| 83 |
-
return agent.create_agent_prompt()
|
| 84 |
-
|
| 85 |
-
# Chat interface using a selected agent
|
| 86 |
-
def chat_interface_with_agent(input_text, agent_name):
|
| 87 |
-
agent_prompt = load_agent_prompt(agent_name)
|
| 88 |
-
if agent_prompt is None:
|
| 89 |
-
return f"Agent {agent_name} not found."
|
| 90 |
-
|
| 91 |
-
# Load the GPT-2 model which is compatible with AutoModelForCausalLM
|
| 92 |
-
model_name = "gpt2"
|
| 93 |
try:
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
input_ids = input_ids[:, :max_input_length]
|
| 108 |
-
|
| 109 |
-
# Generate chatbot response
|
| 110 |
-
outputs = model.generate(
|
| 111 |
-
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
|
| 112 |
-
)
|
| 113 |
-
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 114 |
-
return response
|
| 115 |
-
|
| 116 |
-
def workspace_interface(project_name):
|
| 117 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
| 118 |
-
if not os.path.exists(PROJECT_ROOT):
|
| 119 |
-
os.makedirs(PROJECT_ROOT)
|
| 120 |
-
if not os.path.exists(project_path):
|
| 121 |
-
os.makedirs(project_path)
|
| 122 |
-
st.session_state.workspace_projects[project_name] = {"files": []}
|
| 123 |
-
st.session_state.current_state['workspace_chat']['project_name'] = project_name
|
| 124 |
-
commit_and_push_changes(f"Create project {project_name}")
|
| 125 |
-
return f"Project {project_name} created successfully."
|
| 126 |
-
else:
|
| 127 |
-
return f"Project {project_name} already exists."
|
| 128 |
-
|
| 129 |
-
def add_code_to_workspace(project_name, code, file_name):
|
| 130 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
| 131 |
-
if os.path.exists(project_path):
|
| 132 |
-
file_path = os.path.join(project_path, file_name)
|
| 133 |
-
with open(file_path, "w") as file:
|
| 134 |
-
file.write(code)
|
| 135 |
-
st.session_state.workspace_projects[project_name]["files"].append(file_name)
|
| 136 |
-
st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
|
| 137 |
-
commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
|
| 138 |
-
return f"Code added to {file_name} in project {project_name} successfully."
|
| 139 |
-
else:
|
| 140 |
-
return f"Project {project_name} does not exist."
|
| 141 |
-
|
| 142 |
-
def terminal_interface(command, project_name=None):
|
| 143 |
-
if project_name:
|
| 144 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
| 145 |
-
if not os.path.exists(project_path):
|
| 146 |
-
return f"Project {project_name} does not exist."
|
| 147 |
-
result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
|
| 148 |
-
else:
|
| 149 |
-
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
| 150 |
-
if result.returncode == 0:
|
| 151 |
-
st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
|
| 152 |
-
return result.stdout
|
| 153 |
-
else:
|
| 154 |
-
st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
|
| 155 |
-
return result.stderr
|
| 156 |
-
|
| 157 |
-
def summarize_text(text):
|
| 158 |
-
summarizer = pipeline("summarization")
|
| 159 |
-
summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
|
| 160 |
-
st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
|
| 161 |
-
return summary[0]['summary_text']
|
| 162 |
-
|
| 163 |
-
def sentiment_analysis(text):
|
| 164 |
-
analyzer = pipeline("sentiment-analysis")
|
| 165 |
-
sentiment = analyzer(text)
|
| 166 |
-
st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
|
| 167 |
-
return sentiment[0]
|
| 168 |
-
|
| 169 |
-
# ... [rest of the translate_code function, but remove the OpenAI API call and replace it with your own logic] ...
|
| 170 |
-
|
| 171 |
-
def generate_code(code_idea):
|
| 172 |
-
# Replace this with a call to a Hugging Face model or your own logic
|
| 173 |
-
# For example, using a text-generation pipeline:
|
| 174 |
-
generator = pipeline('text-generation', model='gpt4o')
|
| 175 |
-
generated_code = generator(code_idea, max_length=10000, num_return_sequences=1)[0]['generated_text']
|
| 176 |
-
messages=[
|
| 177 |
-
{"role": "system", "content": "You are an expert software developer."},
|
| 178 |
-
{"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
|
| 179 |
-
]
|
| 180 |
-
st.session_state.current_state['toolbox']['generated_code'] = generated_code
|
| 181 |
-
|
| 182 |
-
return generated_code
|
| 183 |
-
|
| 184 |
-
def translate_code(code, input_language, output_language):
|
| 185 |
-
# Define a dictionary to map programming languages to their corresponding file extensions
|
| 186 |
-
language_extensions = {
|
| 187 |
-
|
| 188 |
-
}
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
]
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
st.session_state.current_state['toolbox']['translated_code'] = translated_code
|
| 214 |
-
return translated_code
|
| 215 |
-
|
| 216 |
-
def generate_code(code_idea):
|
| 217 |
-
response = openai.ChatCompletion.create(
|
| 218 |
-
model="gpt-4",
|
| 219 |
-
messages=[
|
| 220 |
-
{"role": "system", "content": "You are an expert software developer."},
|
| 221 |
-
{"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
|
| 222 |
]
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
-
def
|
| 229 |
-
"""
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
]
|
| 235 |
-
for command in commands:
|
| 236 |
-
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
| 237 |
-
if result.returncode != 0:
|
| 238 |
-
st.error(f"Error executing command '{command}': {result.stderr}")
|
| 239 |
-
break
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
else:
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 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 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
#
|
| 317 |
-
st.
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
st.
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
st.
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
st.write(f"User: {user_input}")
|
| 375 |
-
st.write(f"CodeCraft: {response}")
|
| 376 |
-
|
| 377 |
-
# Display Terminal History
|
| 378 |
-
st.subheader("Terminal History")
|
| 379 |
-
for command, output in st.session_state.terminal_history:
|
| 380 |
-
st.write(f"Command: {command}")
|
| 381 |
-
st.code(output, language="bash")
|
| 382 |
-
|
| 383 |
-
# Display Projects and Files
|
| 384 |
-
st.subheader("Workspace Projects")
|
| 385 |
-
for project, details in st.session_state.workspace_projects.items():
|
| 386 |
-
st.write(f"Project: {project}")
|
| 387 |
-
for file in details['files']:
|
| 388 |
-
st.write(f" - {file}")
|
| 389 |
-
|
| 390 |
-
# Chat with AI Agents
|
| 391 |
-
st.subheader("Chat with AI Agents")
|
| 392 |
-
selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
|
| 393 |
-
agent_chat_input = st.text_area("Enter your message for the agent:")
|
| 394 |
-
if st.button("Send to Agent"):
|
| 395 |
-
agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
|
| 396 |
-
st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
|
| 397 |
-
st.write(f"{selected_agent}: {agent_chat_response}")
|
| 398 |
-
|
| 399 |
-
# Automate Build Process
|
| 400 |
-
st.subheader("Automate Build Process")
|
| 401 |
-
if st.button("Automate"):
|
| 402 |
-
agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
|
| 403 |
-
summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
|
| 404 |
-
st.write("Autonomous Build Summary:")
|
| 405 |
-
st.write(summary)
|
| 406 |
-
st.write("Next Step:")
|
| 407 |
-
st.write(next_step)
|
| 408 |
-
|
| 409 |
-
# Display current state for debugging
|
| 410 |
-
st.sidebar.subheader("Current State")
|
| 411 |
-
st.sidebar.json(st.session_state.current_state)
|
|
|
|
| 2 |
import subprocess
|
| 3 |
import streamlit as st
|
| 4 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
from langchain_community.llms import HuggingFaceHub
|
| 6 |
+
from langchain_community.embeddings import HuggingFaceHubEmbeddings
|
| 7 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 8 |
+
from langchain_community.vectorstores import FAISS
|
| 9 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 10 |
+
from langchain.chains.question_answering import load_qa_chain
|
| 11 |
+
from llama_cpp import Llama, LlamaCppPythonProvider, LlamaCppAgent
|
| 12 |
+
from llama_cpp.llama_cpp_agent import get_messages_formatter_type, get_context_by_model
|
| 13 |
from io import StringIO
|
| 14 |
+
import tempfile
|
| 15 |
+
|
| 16 |
+
# --- Global Variables ---
|
| 17 |
+
CURRENT_PROJECT = {} # Store project data (code, packages, etc.)
|
| 18 |
+
MODEL_OPTIONS = {
|
| 19 |
+
"CodeQwen": "Qwen/CodeQwen1.5-7B-Chat-GGUF",
|
| 20 |
+
"Codestral": "bartowski/Codestral-22B-v0.1-GGUF",
|
| 21 |
+
"AutoCoder": "bartowski/AutoCoder-GGUF",
|
| 22 |
+
}
|
| 23 |
+
MODEL_FILENAMES = {
|
| 24 |
+
"CodeQwen": "codeqwen-1_5-7b-chat-q6_k.gguf",
|
| 25 |
+
"Codestral": "Codestral-22B-v0.1-Q6_K.gguf",
|
| 26 |
+
"AutoCoder": "AutoCoder-Q6_K.gguf",
|
| 27 |
+
}
|
| 28 |
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
|
| 29 |
PROJECT_ROOT = "projects"
|
| 30 |
AGENT_DIRECTORY = "agents"
|
|
|
|
| 44 |
'workspace_chat': {}
|
| 45 |
}
|
| 46 |
|
| 47 |
+
# --- Load NLP Pipelines ---
|
| 48 |
+
classifier = pipeline("text-classification", model="facebook/bart-large-mnli")
|
| 49 |
+
|
| 50 |
+
# --- Load the model and tokenizer ---
|
| 51 |
+
model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1", use_auth_token=os.environ.get("huggingface_token"))
|
| 52 |
+
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1", use_auth_token=os.environ.get("huggingface_token"))
|
| 53 |
+
|
| 54 |
+
# --- Utility Functions ---
|
| 55 |
+
def install_and_import(package_name):
|
| 56 |
+
"""Installs a package using pip and imports it."""
|
| 57 |
+
subprocess.check_call(["pip", "install", package_name])
|
| 58 |
+
return importlib.import_module(package_name)
|
| 59 |
+
|
| 60 |
+
def extract_package_name(input_str):
|
| 61 |
+
"""Extracts the package name from a PyPI URL or pip command."""
|
| 62 |
+
if input_str.startswith("https://pypi.org/project/"):
|
| 63 |
+
return input_str.split("/")[-2]
|
| 64 |
+
elif input_str.startswith("pip install "):
|
| 65 |
+
return input_str.split(" ")[2]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
else:
|
| 67 |
+
return input_str
|
| 68 |
+
|
| 69 |
+
def create_interface_from_input(input_str):
|
| 70 |
+
"""Creates a Gradio interface with buttons for functions from a package."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
+
package_name = extract_package_name(input_str)
|
| 73 |
+
module = install_and_import(package_name)
|
| 74 |
+
|
| 75 |
+
# Handle Flask application context if needed
|
| 76 |
+
if 'flask' in sys.modules or 'flask_restful' in sys.modules:
|
| 77 |
+
app = Flask(__name__)
|
| 78 |
+
with app.app_context():
|
| 79 |
+
functions = [getattr(module, name) for name in dir(module) if callable(getattr(module, name))]
|
| 80 |
+
else:
|
| 81 |
+
functions = [getattr(module, name) for name in dir(module) if callable(getattr(module, name))]
|
| 82 |
+
|
| 83 |
+
function_list = [(func.__name__, func) for func in functions if not func.__name__.startswith("_")]
|
| 84 |
+
return function_list, f"Interface for `{package_name}` created."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return [], str(e)
|
| 88 |
+
|
| 89 |
+
def execute_pip_command(command, add_message):
|
| 90 |
+
"""Executes a pip command and streams the output."""
|
| 91 |
+
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 92 |
+
while True:
|
| 93 |
+
output = process.stdout.readline()
|
| 94 |
+
if output == '' and process.poll() is not None:
|
| 95 |
+
break
|
| 96 |
+
if output:
|
| 97 |
+
add_message("System", f"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
\n{output.strip()}\n
|
| 101 |
+
|
| 102 |
+
time.sleep(0.1) # Simulate delay for more realistic streaming
|
| 103 |
+
rc = process.poll()
|
| 104 |
+
return rc
|
| 105 |
+
|
| 106 |
+
def generate_text(input_text):
|
| 107 |
+
"""Generates text using the loaded language model."""
|
| 108 |
+
inputs = tokenizer(input_text, return_tensors="pt")
|
| 109 |
+
output = model.generate(**inputs, max_length=500, num_return_sequences=1)
|
| 110 |
+
return tokenizer.decode(output[0], skip_special_tokens=True)
|
| 111 |
+
|
| 112 |
+
# --- AI Agent Functions ---
|
| 113 |
+
def analyze_user_intent(user_input):
|
| 114 |
+
"""Classifies the user's intent based on their input."""
|
| 115 |
+
classification = classifier(user_input)
|
| 116 |
+
return classification[0]['label']
|
| 117 |
+
|
| 118 |
+
def generate_mini_app_ideas(theme):
|
| 119 |
+
"""Generates mini-app ideas based on the user's theme."""
|
| 120 |
+
if theme.lower() == "productivity":
|
| 121 |
+
return [
|
| 122 |
+
"Idea-to-Codebase Generator",
|
| 123 |
+
"Automated GitHub Repo Manager",
|
| 124 |
+
"AI-Powered IDE"
|
| 125 |
]
|
| 126 |
+
elif theme.lower() == "creativity":
|
| 127 |
+
return [
|
| 128 |
+
"Brainstorming Assistant",
|
| 129 |
+
"Mood Board Generator",
|
| 130 |
+
"Writing Assistant"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
]
|
| 132 |
+
elif theme.lower() == "well-being":
|
| 133 |
+
return [
|
| 134 |
+
"Meditation Guide",
|
| 135 |
+
"Mood Tracker",
|
| 136 |
+
"Sleep Tracker"
|
| 137 |
+
]
|
| 138 |
+
else:
|
| 139 |
+
return ["No matching mini-apps found. Try a different theme."]
|
| 140 |
|
| 141 |
+
def generate_app_code(app_name, app_description, model_name, history):
|
| 142 |
+
"""Generates code for the selected mini-app using the specified GGUF model."""
|
| 143 |
+
prompt = f"Write a Python script for a {app_description} named {app_name} using Gradio and Streamlit:"
|
| 144 |
+
agent = get_agent(model_name)
|
| 145 |
+
generated_code = agent.chat(prompt, history)
|
| 146 |
+
return generated_code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
+
def execute_terminal_command(command):
|
| 149 |
+
"""Executes a terminal command and returns the output."""
|
| 150 |
+
try:
|
| 151 |
+
result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True)
|
| 152 |
+
return result.strip(), None
|
| 153 |
+
except subprocess.CalledProcessError as e:
|
| 154 |
+
return e.output.strip(), str(e)
|
| 155 |
+
|
| 156 |
+
def install_package(package_name):
|
| 157 |
+
"""Installs a package using pip."""
|
| 158 |
+
output, error = execute_terminal_command(f"pip install {package_name}")
|
| 159 |
+
if error:
|
| 160 |
+
return f"Error installing package: {error}"
|
| 161 |
+
else:
|
| 162 |
+
return f"Package `{package_name}` installed successfully."
|
| 163 |
+
|
| 164 |
+
def get_project_data():
|
| 165 |
+
"""Returns the current project data."""
|
| 166 |
+
return CURRENT_PROJECT
|
| 167 |
+
|
| 168 |
+
def update_project_data(key, value):
|
| 169 |
+
"""Updates the project data."""
|
| 170 |
+
CURRENT_PROJECT[key] = value
|
| 171 |
+
|
| 172 |
+
def handle_chat(input_text, history):
|
| 173 |
+
"""Handles user input in the chat interface."""
|
| 174 |
+
def add_message(sender, message):
|
| 175 |
+
history.append((sender, message))
|
| 176 |
+
|
| 177 |
+
add_message("User", input_text)
|
| 178 |
+
|
| 179 |
+
if input_text.startswith("pip install ") or input_text.startswith("https://pypi.org/project/"):
|
| 180 |
+
package_name = extract_package_name(input_text)
|
| 181 |
+
add_message("System", f"Installing `{package_name}`...")
|
| 182 |
+
result = install_package(package_name)
|
| 183 |
+
add_message("System", result)
|
| 184 |
+
update_project_data("packages", CURRENT_PROJECT.get("packages", []) + [package_name])
|
| 185 |
+
return history, dynamic_functions
|
| 186 |
+
|
| 187 |
+
# --- AI Agent Interaction ---
|
| 188 |
+
if USER_INTENT is None:
|
| 189 |
+
add_message("System", analyze_user_intent(input_text))
|
| 190 |
+
add_message("System", "What kind of mini-app do you have in mind?")
|
| 191 |
+
elif not MINI_APPS:
|
| 192 |
+
add_message("System", "Here are some ideas:")
|
| 193 |
+
for idea in generate_mini_app_ideas(input_text):
|
| 194 |
+
add_message("System", f"- {idea}")
|
| 195 |
+
add_message("System", "Which one would you like to build?")
|
| 196 |
+
elif CURRENT_APP["name"] is None:
|
| 197 |
+
selected_app = input_text
|
| 198 |
+
app_description = next((app for app in MINI_APPS if selected_app in app), None)
|
| 199 |
+
if app_description:
|
| 200 |
+
add_message("System", f"Generating code for {app_description}...")
|
| 201 |
+
code = generate_app_code(selected_app, app_description, "CodeQwen", history) # Use CodeQwen by default
|
| 202 |
+
add_message("System", f"
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
python\n{code}\n
|
| 206 |
+
|
| 207 |
+
add_message("System", "Code generated! What else can I do for you?")
|
| 208 |
+
update_project_data("code", code)
|
| 209 |
+
update_project_data("app_name", selected_app)
|
| 210 |
+
update_project_data("app_description", app_description)
|
| 211 |
else:
|
| 212 |
+
add_message("System", "Please choose from the provided mini-app ideas.")
|
| 213 |
+
else:
|
| 214 |
+
add_message("System", "You already have an app in progress. Do you want to start over?")
|
| 215 |
+
|
| 216 |
+
return history, dynamic_functions
|
| 217 |
+
|
| 218 |
+
# --- Prebuilt Tools ---
|
| 219 |
+
def generate_code_tool(input_text, history):
|
| 220 |
+
"""Prebuilt tool for code generation."""
|
| 221 |
+
code = generate_app_code("MyTool", "A tool to do something", "CodeQwen", history) # Use CodeQwen by default
|
| 222 |
+
return f"
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
python\n{code}\n
|
| 226 |
+
|
| 227 |
+
def analyze_code_tool(input_text, history):
|
| 228 |
+
"""Prebuilt tool for code analysis."""
|
| 229 |
+
agent = get_agent("Codestral")
|
| 230 |
+
analysis = agent.chat(input_text, history)
|
| 231 |
+
return analysis
|
| 232 |
+
|
| 233 |
+
# --- Streamlit Interface ---
|
| 234 |
+
st.title("AI4ME: Your Personal AI App Workshop")
|
| 235 |
+
st.markdown("## Let's build your dream app together! 🤖")
|
| 236 |
+
|
| 237 |
+
# --- Hugging Face Token Input ---
|
| 238 |
+
huggingface_token = st.text_input("Enter your Hugging Face Token", type="password", key="huggingface_token")
|
| 239 |
+
os.environ["huggingface_token"] = huggingface_token
|
| 240 |
+
|
| 241 |
+
# --- Chat Interface ---
|
| 242 |
+
chat_history = []
|
| 243 |
+
chat_input = st.text_input("Tell me your idea...", key="chat_input")
|
| 244 |
+
if chat_input:
|
| 245 |
+
chat_history, dynamic_functions = handle_chat(chat_input, chat_history)
|
| 246 |
+
for sender, message in chat_history:
|
| 247 |
+
st.markdown(f"**{sender}:** {message}")
|
| 248 |
+
|
| 249 |
+
# --- Code Execution and Deployment ---
|
| 250 |
+
if CURRENT_APP["code"]:
|
| 251 |
+
st.markdown("## Your App Code:")
|
| 252 |
+
code_area = st.text_area("Your App Code", value=CURRENT_APP["code"], key="code_area")
|
| 253 |
+
|
| 254 |
+
st.markdown("## Deploy Your App (Coming Soon!)")
|
| 255 |
+
# Add deployment functionality here using Streamlit's deployment features.
|
| 256 |
+
# For example, you could use Streamlit's `st.button` to trigger deployment.
|
| 257 |
+
|
| 258 |
+
# --- Code Execution ---
|
| 259 |
+
st.markdown("## Run Your App:")
|
| 260 |
+
if st.button("Execute Code"):
|
| 261 |
+
try:
|
| 262 |
+
# Use Hugging Face's text-generation pipeline for code execution
|
| 263 |
+
inputs = tokenizer(code_area, return_tensors="pt")
|
| 264 |
+
output = model.generate(**inputs, max_length=500, num_return_sequences=1)
|
| 265 |
+
output = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 266 |
+
st.success(f"Code executed successfully!\n{output}")
|
| 267 |
+
except Exception as e:
|
| 268 |
+
st.error(f"Error executing code: {e}")
|
| 269 |
+
|
| 270 |
+
# --- Code Editing ---
|
| 271 |
+
st.markdown("## Edit Your Code:")
|
| 272 |
+
if st.button("Edit Code"):
|
| 273 |
+
try:
|
| 274 |
+
# Use Hugging Face's text-generation pipeline for code editing
|
| 275 |
+
prompt = f"Improve the following Python code:\n
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
python\n{code_area}\n
|
| 279 |
+
|
| 280 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 281 |
+
output = model.generate(**inputs, max_length=500, num_return_sequences=1)
|
| 282 |
+
edited_code = tokenizer.decode(output[0], skip_special_tokens=True).split("
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
python\n")[1].split("\n
|
| 286 |
+
|
| 287 |
+
st.success(f"Code edited successfully!\n{edited_code}")
|
| 288 |
+
update_project_data("code", edited_code)
|
| 289 |
+
code_area.value = edited_code
|
| 290 |
+
except Exception as e:
|
| 291 |
+
st.error(f"Error editing code: {e}")
|
| 292 |
+
|
| 293 |
+
# --- Prebuilt Tools ---
|
| 294 |
+
st.markdown("## Prebuilt Tools:")
|
| 295 |
+
with st.expander("Generate Code"):
|
| 296 |
+
code_input = st.text_area("Enter your code request:", key="code_input")
|
| 297 |
+
if st.button("Generate"):
|
| 298 |
+
code_output = generate_code_tool(code_input, chat_history)
|
| 299 |
+
st.markdown(code_output)
|
| 300 |
+
|
| 301 |
+
with st.expander("Analyze Code"):
|
| 302 |
+
code_input = st.text_area("Enter your code:", key="analyze_code_input")
|
| 303 |
+
if st.button("Analyze"):
|
| 304 |
+
analysis_output = analyze_code_tool(code_input, chat_history)
|
| 305 |
+
st.markdown(analysis_output)
|
| 306 |
+
|
| 307 |
+
# --- Additional Features ---
|
| 308 |
+
# Add features like:
|
| 309 |
+
# - Code editing
|
| 310 |
+
# - Integration with external APIs
|
| 311 |
+
# - Advanced AI agents for more complex tasks
|
| 312 |
+
# - User account management
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|