acecalisto3 commited on
Commit
9cf63c4
β€’
1 Parent(s): ac242b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -16
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import os
2
- import subprocess
3
  import streamlit as st
 
4
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoModel, RagRetriever, AutoModelForSeq2SeqLM
5
  import black
6
  from pylint import lint
@@ -8,9 +8,12 @@ from io import StringIO
8
  import sys
9
  import torch
10
  from huggingface_hub import hf_hub_url, cached_download, HfApi
 
11
 
12
  # Set your Hugging Face API key here
13
- hf_token = "YOUR_HUGGING_FACE_API_KEY" # Replace with your actual token
 
 
14
 
15
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
16
  PROJECT_ROOT = "projects"
@@ -71,24 +74,25 @@ def process_input(user_input):
71
  return refined_response
72
 
73
  class AIAgent:
74
- def __init__(self, name, description, skills):
75
  self.name = name
76
  self.description = description
77
  self.skills = skills
 
 
78
 
79
- def create_agent_prompt(self):
80
- skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
81
- agent_prompt = f"""
82
- As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
83
- {skills_str}
84
- 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.
85
- """
86
- return agent_prompt
87
 
88
- def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model):
89
- """
90
- Autonomous build logic that continues based on the state of chat history and workspace projects.
91
- """
92
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
93
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
94
 
@@ -139,6 +143,30 @@ I am confident that I can leverage my expertise to assist you in developing and
139
  st.error(f"Build Error: {e}")
140
 
141
  return summary, next_step
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  def save_agent_to_file(agent):
144
  """Saves the agent's prompt to a file."""
@@ -280,6 +308,31 @@ def add_code_to_workspace(project_name, code, file_name):
280
  st.session_state.workspace_projects[project_name]['files'].append(file_name)
281
  return f"Code added to '{file_name}' in project '{project_name}'."
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  # Streamlit App
284
  st.title("AI Agent Creator")
285
 
@@ -363,7 +416,56 @@ elif app_mode == "Tool Box":
363
  elif app_mode == "Workspace Chat App":
364
  # Workspace Chat App
365
  st.header("Workspace Chat App")
 
 
 
 
 
 
 
 
 
 
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  # Project Workspace Creation
368
  st.subheader("Create a New Project")
369
  project_name = st.text_input("Enter project name:")
@@ -456,7 +558,19 @@ elif app_mode == "Workspace Chat App":
456
  st.write(summary)
457
  st.write("Next Step:")
458
  st.write(next_step)
459
-
 
 
 
 
 
 
 
 
 
 
 
 
460
  # Use the hf_token to interact with the Hugging Face API
461
  api = HfApi(token=hf_token)
462
  # Function to create a Space on Hugging Face
 
1
  import os
 
2
  import streamlit as st
3
+ import subprocess
4
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoModel, RagRetriever, AutoModelForSeq2SeqLM
5
  import black
6
  from pylint import lint
 
8
  import sys
9
  import torch
10
  from huggingface_hub import hf_hub_url, cached_download, HfApi
11
+ import base64
12
 
13
  # Set your Hugging Face API key here
14
+ # hf_token = "YOUR_HUGGING_FACE_API_KEY" # Replace with your actual token
15
+ # Get Hugging Face token from secrets.toml - this line should already be in the main code
16
+ hf_token = st.secrets["huggingface"]["hf_token"]
17
 
18
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
19
  PROJECT_ROOT = "projects"
 
74
  return refined_response
75
 
76
  class AIAgent:
77
+ def __init__(self, name, description, skills, hf_api=None):
78
  self.name = name
79
  self.description = description
80
  self.skills = skills
81
+ self._hf_api = hf_api
82
+ self._hf_token = hf_token # Store the token here
83
 
84
+ @property
85
+ def hf_api(self):
86
+ if not self._hf_api and self.has_valid_hf_token():
87
+ self._hf_api = HfApi(token=self._hf_token)
88
+ return self._hf_api
89
+
90
+ def has_valid_hf_token(self):
91
+ return bool(self._hf_token)
92
 
93
+ async def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model, hf_token):
94
+ self._hf_token = hf_token
95
+ # Continuation of previous methods
 
96
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
97
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
98
 
 
143
  st.error(f"Build Error: {e}")
144
 
145
  return summary, next_step
146
+
147
+ def deploy_built_space_to_hf(self):
148
+ if not self._hf_api or not self._hf_token:
149
+ raise ValueError("Cannot deploy the Space since no valid Hugoging Face API connection was established.")
150
+
151
+ # Assuming you have a function to get the files for your Space
152
+ repository_name = f"my-awesome-space_{datetime.now().timestamp()}"
153
+ files = get_built_space_files() # Placeholder - you'll need to define this function
154
+
155
+ # Create the Space
156
+ create_space(self.hf_api, repository_name, "Description", True, files)
157
+
158
+ st.markdown("## Congratulations! Successfully deployed Space πŸš€ ##")
159
+ st.markdown(f"[Check out your new Space here](https://huggingface.co/spaces/{repository_name})")
160
+
161
+
162
+ # Add any missing functions from your original code (e.g., get_built_space_files)
163
+ def get_built_space_files():
164
+ # Replace with your logic to gather the files you want to deploy
165
+ return {
166
+ "app.py": "# Your Streamlit app code here",
167
+ "requirements.txt": "streamlit\ntransformers"
168
+ # Add other files as needed
169
+ }
170
 
171
  def save_agent_to_file(agent):
172
  """Saves the agent's prompt to a file."""
 
308
  st.session_state.workspace_projects[project_name]['files'].append(file_name)
309
  return f"Code added to '{file_name}' in project '{project_name}'."
310
 
311
+ def create_space(api, name, description, public, files, entrypoint="launch.py"):
312
+ url = f"{hf_hub_url()}spaces/{name}/prepare-repo"
313
+ headers = {"Authorization": f"Bearer {api.access_token}"}
314
+ payload = {
315
+ "public": public,
316
+ "gitignore_template": "web",
317
+ "default_branch": "main",
318
+ "archived": False,
319
+ "files": []
320
+ }
321
+ for filename, contents in files.items():
322
+ data = {
323
+ "content": contents,
324
+ "path": filename,
325
+ "encoding": "utf-8",
326
+ "mode": "overwrite" if "#\{random.randint(0, 1)\}" not in contents else "merge",
327
+ }
328
+ payload["files"].append(data)
329
+ response = requests.post(url, json=payload, headers=headers)
330
+ response.raise_for_status()
331
+ location = response.headers.get("Location")
332
+ # wait_for_processing(location, api) # You might need to implement this if it's not already defined
333
+
334
+ return Repository(name=name, api=api)
335
+
336
  # Streamlit App
337
  st.title("AI Agent Creator")
338
 
 
416
  elif app_mode == "Workspace Chat App":
417
  # Workspace Chat App
418
  st.header("Workspace Chat App")
419
+ def get_built_space_files():
420
+ """
421
+ Gathers the necessary files for the Hugging Face Space,
422
+ handling different project structures and file types.
423
+ """
424
+ files = {}
425
+
426
+ # Get the current project name (adjust as needed)
427
+ project_name = st.session_state.get('project_name', 'my_project')
428
+ project_path = os.path.join(PROJECT_ROOT, project_name)
429
 
430
+ # Define a list of files/directories to search for
431
+ targets = [
432
+ "app.py",
433
+ "requirements.txt",
434
+ "Dockerfile",
435
+ "docker-compose.yml", # Example YAML file
436
+ "src", # Example subdirectory
437
+ "assets" # Another example subdirectory
438
+ ]
439
+
440
+ # Iterate through the targets
441
+ for target in targets:
442
+ target_path = os.path.join(project_path, target)
443
+
444
+ # If the target is a file, add it to the files dictionary
445
+ if os.path.isfile(target_path):
446
+ add_file_to_dictionary(files, target_path)
447
+
448
+ # If the target is a directory, recursively search for files within it
449
+ elif os.path.isdir(target_path):
450
+ for root, _, filenames in os.walk(target_path):
451
+ for filename in filenames:
452
+ file_path = os.path.join(root, filename)
453
+ add_file_to_dictionary(files, file_path)
454
+
455
+ return files
456
+
457
+ def add_file_to_dictionary(files, file_path):
458
+ """Helper function to add a file to the files dictionary."""
459
+ filename = os.path.relpath(file_path, PROJECT_ROOT) # Get relative path
460
+
461
+ # Handle text and binary files
462
+ if filename.endswith((".py", ".txt", ".json", ".html", ".css", ".yml", ".yaml")):
463
+ with open(file_path, "r") as f:
464
+ files[filename] = f.read()
465
+ else:
466
+ with open(file_path, "rb") as f:
467
+ file_content = f.read()
468
+ files[filename] = base64.b64encode(file_content).decode("utf-8")
469
  # Project Workspace Creation
470
  st.subheader("Create a New Project")
471
  project_name = st.text_input("Enter project name:")
 
558
  st.write(summary)
559
  st.write("Next Step:")
560
  st.write(next_step)
561
+
562
+ # Using the modified and extended class and functions, update the callback for the 'Automate' button in the Streamlit UI:
563
+ if st.button("Automate", args=(hf_token,)):
564
+ agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
565
+ summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model, hf_token)
566
+ st.write("Autonomous Build Summary:")
567
+ st.write(summary)
568
+ st.write("Next Step:")
569
+ st.write(next_step)
570
+
571
+ # If everything went well, proceed to deploy the Space
572
+ if agent._hf_api and agent.has_valid_hf_token():
573
+ agent.deploy_built_space_to_hf()
574
  # Use the hf_token to interact with the Hugging Face API
575
  api = HfApi(token=hf_token)
576
  # Function to create a Space on Hugging Face