Spaces:
Paused
Paused
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818215 unmodified lines98991001011021031041051061071081094 unmodified lines11411511611711811912012112212312427 unmodified lines1521531541551561571581591601611621631641651 unmodified line1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971982 unmodified lines2012022032042052062073 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226311 unmodified lines2752762772782792802812822832842852862872882892902912922932942952962972982993002 unmodified lines3033043053063073083093103113123133143153163172 unmodified lines3203213223233243253263273283293303313323333343353363373388 unmodified lines3473483493503513523538 unmodified lines36236336436536636736836937037124 unmodified lines39639739839940040140222 unmodified lines4254264274284294304314324336 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449518 unmodified lines5145155165175185195205211 unmodified line52352452552652752852925 unmodified lines5555565575585595605615625635645651 unmodified line5675685695705715725732 unmodified lines5765775785795805815825835845855865875885895905915921 unmodified line594595596597598599600601602603604import osimport subprocessfrom transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoModel, RagRetriever, AutoModelForSeq2SeqLMimport blackfrom pylint import lintfrom io import StringIOimport sysimport torchfrom huggingface_hub import hf_hub_url, cached_download, HfApi, InferenceClientimport base64import streamlit as st# Use a publicly available model that doesn't require authenticationrag_retriever = pipeline("retrieval-question-answering", model="distilbert-base-nq")st.write("Pipeline created successfully")# Add the new HTML code belowcustom_html = '''<div style='position:fixed;bottom:0;left:0;width:100%;'><iframe width="100%" scrolling="no" title="CodeGPT Widget" frameborder="0" allowtransparency sandbox="" allowfullscreen="" data-widget-id="c265505c-e667-4af2-b492-291da888ee7c" src="https://widget.codegpt.co/chat-widget.js"></iframe></div>'''# Update the markdown function to accept custom HTML codedef markdown_with_custom_html(md, html):md_content = mdif html:return f"{md_content}\n\n{html}"else:return md_contentmarkdown_text = "Compare model responses with me!"markdown_with_custom_html(markdown_text, custom_html)# Set your Hugging Face API key here# hf_token = "YOUR_HUGGING_FACE_API_KEY" # Replace with your actual token# Get Hugging Face token from secrets.toml - this line should already be in the main codehf_token = os.environ.get("HUGGINGFACE_TOKEN")("key")HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"PROJECT_ROOT = "projects"AGENT_DIRECTORY = "agents"# Global state to manage communication between Tool Box and Workspace Chat Appif 'chat_history' not in st.session_state:st.session_state.chat_history = []if 'terminal_history' not in st.session_state:st.session_state.terminal_history = []if 'workspace_projects' not in st.session_state:st.session_state.workspace_projects = {}if 'available_agents' not in st.session_state:st.session_state.available_agents = []if 'current_state' not in st.session_state:st.session_state.current_state = {'toolbox': {},'workspace_chat': {}}# List of top downloaded free code-generative models from Hugging Face HubAVAILABLE_CODE_GENERATIVE_MODELS = ["bigcode/starcoder", # Popular and powerful"Salesforce/codegen-350M-mono", # Smaller, good for quick tasks"microsoft/CodeGPT-small", # Smaller, good for quick tasks"google/flan-t5-xl", # Powerful, good for complex tasks"facebook/bart-large-cnn", # Good for text-to-code tasks]# Load pre-trained RAG retriever# rag_retriever = RagRetriever.from_pretrained("facebook/rag-token-base") # Use a Hugging Face RAG model# Load pre-trained chat modelchat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium") # Use a Hugging Face chat model# Load tokenizertokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")def process_input(user_input):# Input pipeline: Tokenize and preprocess user inputinput_ids = tokenizer(user_input, return_tensors="pt").input_idsattention_mask = tokenizer(user_input, return_tensors="pt").attention_mask15 unmodified linesreturn refined_responseclass AIAgent:def __init__(self, name, description, skills, hf_api=None):self.name = nameself.description = descriptionself.skills = skillsself._hf_api = hf_apiself._hf_token = hf_token # Store the token here@propertydef hf_api(self):4 unmodified linesdef has_valid_hf_token(self):return bool(self._hf_token)async def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model, hf_token):self._hf_token = hf_token# Continuation of previous methodssummary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])# Analyze chat history and workspace projects to suggest actions# Example:27 unmodified lines# Generate GUI code for app.py if requestedif "create a gui" in summary.lower():gui_code = generate_code("Create a simple GUI for this application", selected_model)with open(app_file, "a") as f:f.write(gui_code)# Run the default build processbuild_command = "pip install -r requirements.txt && python app.py"try:result = subprocess.run(build_command, shell=True, capture_output=True, text=True, cwd=project_path)st.write(f"Build Output:\n{result.stdout}")if result.stderr:st.error(f"Build Errors:\n{result.stderr}")1 unmodified linest.error(f"Build Error: {e}")return summary, next_stepdef deploy_built_space_to_hf(self):if not self._hf_api or not self._hf_token:raise ValueError("Cannot deploy the Space since no valid Hugoging Face API connection was established.")# Assuming you have a function to get the files for your Spacerepository_name = f"my-awesome-space_{datetime.now().timestamp()}"files = get_built_space_files() # Placeholder - you'll need to define this function# Create the Spacecreate_space(self.hf_api, repository_name, "Description", True, files)st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")st.markdown(f"[Check out your new Space here](https://huggingface.co/spaces/{repository_name})")# Add any missing functions from your original code (e.g., get_built_space_files)def get_built_space_files():# Replace with your logic to gather the files you want to deployreturn {"app.py": "# Your Streamlit app code here","requirements.txt": "streamlit\ntransformers"# Add other files as needed}def save_agent_to_file(agent):"""Saves the agent's prompt to a file."""if not os.path.exists(AGENT_DIRECTORY):os.makedirs(AGENT_DIRECTORY)2 unmodified linesfile.write(agent.create_agent_prompt())st.session_state.available_agents.append(agent.name)def load_agent_prompt(agent_name):"""Loads an agent prompt from a file."""file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")if os.path.exists(file_path):3 unmodified lineselse:return Nonedef create_agent_from_text(name, text):skills = text.split('\n')agent = AIAgent(name, "AI agent created from text input.", skills)save_agent_to_file(agent)return agent.create_agent_prompt()def chat_interface_with_agent(input_text, agent_name):agent_prompt = load_agent_prompt(agent_name)if agent_prompt is None:return f"Agent {agent_name} not found."model_name ="bigscience/T0_3B"try:from transformers import AutoModel, AutoTokenizer # Import AutoModel heremodel = ("bigscience/T0_3B")tokenizer = AutoTokenizer.from_pretrained(model_name)generator = pipeline("text-generation", model=model, tokenizer=tokenizer)except EnvironmentError as e:return f"Error loading model: {e}"combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"input_ids = tokenizer.encode(combined_input, return_tensors="pt")max_input_length = 900if input_ids.shape[1] > max_input_length:input_ids = input_ids[:, :max_input_length]outputs = model.generate(input_ids, max_new_tokens=1000, num_return_sequences=1, do_sample=True,pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id)response = tokenizer.decode(outputs[0], skip_special_tokens=True)return response# Terminal interfacedef terminal_interface(command, project_name=None):if project_name:project_path = os.path.join(PROJECT_ROOT, project_name)if not os.path.exists(project_path):return f"Project {project_name} does not exist."result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)else:result = subprocess.run(command, shell=True, capture_output=True, text=True)return result.stdout# Code editor interfacedef code_editor_interface(code):try:formatted_code = black.format_str(code, mode=black.FileMode())except black.NothingChanged:11 unmodified linesreturn formatted_code, lint_message# Text summarization tooldef summarize_text(text):summarizer = pipeline("summarization")summary = summarizer(text, max_length=130, min_length=30, do_sample=False)return summary[0]['summary_text']# Sentiment analysis tooldef sentiment_analysis(text):analyzer = pipeline("sentiment-analysis")result = analyzer(text)return result[0]['label']# Text translation tool (code translation)def translate_code(code, source_language, target_language):# Use a Hugging Face translation model instead of OpenAItranslator = pipeline("translation", model="bartowski/Codestral-22B-v0.1-GGUF") # Example: English to Spanishtranslated_code = translator(code, target_lang=target_language)[0]['translation_text']return translated_codedef generate_code(code_idea, model_name):"""Generates code using the selected model."""try:generator = pipeline('text-generation', model=model_name)2 unmodified linesexcept Exception as e:return f"Error generating code: {e}"def chat_interface(input_text):"""Handles general chat interactions with the user."""# Use a Hugging Face chatbot model or your own logicchatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']return response# Workspace interfacedef workspace_interface(project_name):project_path = os.path.join(PROJECT_ROOT, project_name)if not os.path.exists(project_path):os.makedirs(project_path)2 unmodified lineselse:return f"Project '{project_name}' already exists."# Add code to workspacedef add_code_to_workspace(project_name, code, file_name):project_path = os.path.join(PROJECT_ROOT, project_name)if not os.path.exists(project_path):return f"Project '{project_name}' does not exist."file_path = os.path.join(project_path, file_name)with open(file_path, "w") as file:file.write(code)st.session_state.workspace_projects[project_name]['files'].append(file_name)return f"Code added to '{file_name}' in project '{project_name}'."def create_space(api, name, description, public, files, entrypoint="launch.py"):url = f"{hf_hub_url()}spaces/{name}/prepare-repo"headers = {"Authorization": f"Bearer {api.access_token}"}payload = {8 unmodified lines"content": contents,"path": filename,"encoding": "utf-8","mode": "overwrite" if "#\{random.randint(0, 1)\}" not in contents else "merge",}payload["files"].append(data)response = requests.post(url, json=payload, headers=headers)8 unmodified lines# Sidebar navigationst.sidebar.title("Navigation")app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])# Get Hugging Face token from secrets.tomlhf_token = st.secrets["huggingface"]if app_mode == "AI Agent Creator":# AI Agent Creator24 unmodified linesterminal_input = st.text_input("Enter a command:")if st.button("Run"):terminal_output = terminal_interface(terminal_input)st.session_state.terminal_history.append((terminal_input, terminal_output))st.code(terminal_output, language="bash")# Code Editor Interface22 unmodified linesst.subheader("Translate Code")code_to_translate = st.text_area("Enter code to translate:")source_language = st.text_input("Enter source language (e.g., 'Python'):")target_language = st.text_input("Enter target language (e.g., 'JavaScript'):")if st.button("Translate Code"):translated_code = translate_code(code_to_translate, source_language, target_language)st.code(translated_code, language=target_language.lower())# Code Generation6 unmodified lineselif app_mode == "Workspace Chat App":# Workspace Chat Appst.header("Workspace Chat App")def get_built_space_files():"""Gathers the necessary files for the Hugging Face Space,handling different project structures and file types."""files = {}# Get the current project name (adjust as needed)project_name = st.session_state.get('project_name', 'my_project')project_path = os.path.join(PROJECT_ROOT, project_name)# Define a list of files/directories to search fortargets = ["app.py","requirements.txt","Dockerfile","docker-compose.yml", # Example YAML file"src", # Example subdirectory"assets" # Another example subdirectory]# Iterate through the targetsfor target in targets:target_path = os.path.join(project_path, target)# If the target is a file, add it to the files dictionaryif os.path.isfile(target_path):add_file_to_dictionary(files, target_path)# If the target is a directory, recursively search for files within itelif os.path.isdir(target_path):for root, _, filenames in os.walk(target_path):for filename in filenames:file_path = os.path.join(root, filename)add_file_to_dictionary(files, file_path)return filesdef add_file_to_dictionary(files, file_path):"""Helper function to add a file to the files dictionary."""filename = os.path.relpath(file_path, PROJECT_ROOT) # Get relative path# Handle text and binary filesif filename.endswith((".py", ".txt", ".json", ".html", ".css", ".yml", ".yaml")):with open(file_path, "r") as f:files[filename] = f.read()else:with open(file_path, "rb") as f:file_content = f.read()files[filename] = base64.b64encode(file_content).decode("utf-8")# Project Workspace Creationst.subheader("Create a New Project")project_name = st.text_input("Enter project name:")18 unmodified linescode_to_add = st.text_area("Enter code to add to workspace:")file_name = st.text_input("Enter file name (e.g., 'app.py'):")if st.button("Add Code"):add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)st.session_state.terminal_history.append((f"Add Code: {code_to_add}", add_code_status))st.success(add_code_status)# Terminal Interface with Project Context1 unmodified lineterminal_input = st.text_input("Enter a command within the workspace:")if st.button("Run Command"):terminal_output = terminal_interface(terminal_input, project_name)st.session_state.terminal_history.append((terminal_input, terminal_output))st.code(terminal_output, language="bash")# Chat Interface for Guidance25 unmodified lines# Chat with AI Agentsst.subheader("Chat with AI Agents")selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)agent_chat_input = st.text_area("Enter your message for the agent:")if st.button("Send to Agent"):agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)st.session_state.chat_history.append((agent_chat_input, agent_chat_response))st.write(f"{selected_agent}: {agent_chat_response}")# Code Generation1 unmodified linecode_idea = st.text_input("Enter your code idea:")# Model Selection Menuselected_model = st.selectbox("Select a code-generative model", AVAILABLE_CODE_GENERATIVE_MODELS)if st.button("Generate Code"):generated_code = generate_code(code_idea, selected_model)2 unmodified lines# Automate Build Processst.subheader("Automate Build Process")if st.button("Automate"):agent = AIAgent(selected_agent, "", []) # Load the agent without skills for nowsummary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model)st.write("Autonomous Build Summary:")st.write(summary)st.write("Next Step:")st.write(next_step)# Using the modified and extended class and functions, update the callback for the 'Automate' button in the Streamlit UI:if st.button("Automate", args=(hf_token,)):agent = AIAgent(selected_agent, "", []) # Load the agent without skills for nowsummary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model, hf_token)st.write("Autonomous Build Summary:")st.write(summary)st.write("Next Step:")1 unmodified line# If everything went well, proceed to deploy the Spaceif agent._hf_api and agent.has_valid_hf_token():agent.deploy_built_space_to_hf()# Use the hf_token to interact with the Hugging Face APIapi = HfApi(token="HUGGINGFACE_TOKEN")# Function to create a Space on Hugging Facedef create_space(api, name, description, public, files, entrypoint="launch.py"):url = f"{hf_hub_url()}spaces/{name}/prepare-repo"headers = {"Authorization": f"Bearer {api.access_token}"}12345678910111213141516171819202122232425262728293031323334353615 unmodified lines5253545556575859606162634 unmodified lines6869707172737475767727 unmodified lines1051061071081091101111121131141151161171181191201 unmodified line1221231241251261271281291301311321331341351361372 unmodified lines1401411421431441451463 unmodified lines15015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718811 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242 unmodified lines2272282292302312322332342352362372382392402 unmodified lines2432442452462472482492502512522532542552562572582592608 unmodified lines2692702712722732742758 unmodified lines28428528628728828929029124 unmodified lines31631731831932032132232322 unmodified lines3463473483493503513523533543553566 unmodified lines36336436536636736836918 unmodified lines3883893903913923933943953963971 unmodified line39940040140240340440540625 unmodified lines4324334344354364374384394404414424434444451 unmodified line4474484494504514524534542 unmodified lines4574584594604614624634644654661 unmodified line468469470471472473474import osimport sysimport subprocessimport base64import jsonfrom io import StringIOfrom typing import Dict, Listimport streamlit as stfrom transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizerfrom pylint import lint# Add your Hugging Face API token herehf_token = st.secrets["hf_token"]# Global state to manage communication between Tool Box and Workspace Chat Appif "chat_history" not in st.session_state:st.session_state.chat_history = []if "terminal_history" not in st.session_state:st.session_state.terminal_history = []if "workspace_projects" not in st.session_state:st.session_state.workspace_projects = {}# Load pre-trained RAG retrieverrag_retriever = pipeline("retrieval-question-answering", model="facebook/rag-token-base")# Load pre-trained chat modelchat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium")# Load tokenizertokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")def process_input(user_input: str) -> str:# Input pipeline: Tokenize and preprocess user inputinput_ids = tokenizer(user_input, return_tensors="pt").input_idsattention_mask = tokenizer(user_input, return_tensors="pt").attention_mask15 unmodified linesreturn refined_responseclass AIAgent:def __init__(self, name: str, description: str, skills: List[str], hf_api=None):self.name = nameself.description = descriptionself.skills = skillsself._hf_api = hf_apiself._hf_token = hf_token@propertydef hf_api(self):4 unmodified linesdef has_valid_hf_token(self):return bool(self._hf_token)async def autonomous_build(self, chat_history: List[str], workspace_projects: Dict[str, str], project_name: str, selected_model: str):# Continuation of previous methodssummary = "Chat History:\n" + "\n".join(chat_history)summary += "\n\nWorkspace Projects:\n" + "\n".join(workspace_projects.items())# Analyze chat history and workspace projects to suggest actions# Example:27 unmodified lines# Generate GUI code for app.py if requestedif "create a gui" in summary.lower():gui_code = generate_code("Create a simple GUI for this application", selected_model)with open(app_file, "a") as f:f.write(gui_code)# Run the default build processbuild_command = "pip install -r requirements.txt && python app.py"try:result = subprocess.run(build_command, shell=True, capture_output=True, text=True, cwd=project_path)st.write(f"Build Output:\n{result.stdout}")if result.stderr:st.error(f"Build Errors:\n{result.stderr}")1 unmodified linest.error(f"Build Error: {e}")return summary, next_stepdef get_built_space_files() -> Dict[str, str]:# Replace with your logic to gather the files you want to deployreturn {"app.py": "# Your Streamlit app code here","requirements.txt": "streamlit\ntransformers"# Add other files as needed}def save_agent_to_file(agent: AIAgent):"""Saves the agent's prompt to a file."""if not os.path.exists(AGENT_DIRECTORY):os.makedirs(AGENT_DIRECTORY)2 unmodified linesfile.write(agent.create_agent_prompt())st.session_state.available_agents.append(agent.name)def load_agent_prompt(agent_name: str) -> str:"""Loads an agent prompt from a file."""file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")if os.path.exists(file_path):3 unmodified lineselse:return Nonedef create_agent_from_text(name: str, text: str) -> str:skills = text.split("\n")agent = AIAgent(name, "AI agent created from text input.", skills)save_agent_to_file(agent)return agent.create_agent_prompt()def chat_interface_with_agent(input_text: str, agent_name: str) -> str:agent_prompt = load_agent_prompt(agent_name)if agent_prompt is None:return f"Agent {agent_name} not found."model_name = "MaziyarPanahi/Codestral-22B-v0.1-GGUF"try:generator = pipeline("text-generation", model=model_name)generator.tokenizer.pad_token = generator.tokenizer.eos_tokengenerated_response = generator(f"{agent_prompt}\n\nUser: {input_text}\nAgent:", max_length=100, do_sample=True, top_k=50)[0]["generated_text"]return generated_responseexcept Exception as e:return f"Error loading model: {e}"def terminal_interface(command: str, project_name: str = None) -> str:if project_name:project_path = os.path.join(PROJECT_ROOT, project_name)if not os.path.exists(project_path):return f"Project {project_name} does not exist."result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)else:result = subprocess.run(command, shell=True, capture_output=True, text=True)return result.stdoutdef code_editor_interface(code: str) -> str:try:formatted_code = black.format_str(code, mode=black.FileMode())except black.NothingChanged:11 unmodified linesreturn formatted_code, lint_messagedef summarize_text(text: str) -> str:summarizer = pipeline("summarization")summary = summarizer(text, max_length=130, min_length=30, do_sample=False)return summary[0]['summary_text']def sentiment_analysis(text: str) -> str:analyzer = pipeline("sentiment-analysis")result = analyzer(text)return result[0]['label']def translate_code(code: str, source_language: str, target_language: str) -> str:# Use a Hugging Face translation model instead of OpenAI# Example: English to Spanishtranslator = pipeline("translation", model="bartowski/Codestral-22B-v0.1-GGUF")translated_code = translator(code, target_lang=target_language)[0]['translation_text']return translated_codedef generate_code(code_idea: str, model_name: str) -> str:"""Generates code using the selected model."""try:generator = pipeline('text-generation', model=model_name)2 unmodified linesexcept Exception as e:return f"Error generating code: {e}"def chat_interface(input_text: str) -> str:"""Handles general chat interactions with the user."""# Use a Hugging Face chatbot model or your own logicchatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']return responsedef workspace_interface(project_name: str) -> str:project_path = os.path.join(PROJECT_ROOT, project_name)if not os.path.exists(project_path):os.makedirs(project_path)2 unmodified lineselse:return f"Project '{project_name}' already exists."def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:project_path = os.path.join(PROJECT_ROOT, project_name)if not os.path.exists(project_path):return f"Project '{project_name}' does not exist."file_path = os.path.join(project_path, file_name)with open(file_path, "w") as file:file.write(code)st.session_state.workspace_projects[project_name]['files'].append(file_name)return f"Code added to '{file_name}' in project '{project_name}'."def create_space_on_hugging_face(api, name, description, public, files, entrypoint="launch.py"):url = f"{hf_hub_url()}spaces/{name}/prepare-repo"headers = {"Authorization": f"Bearer {api.access_token}"}payload = {8 unmodified lines"content": contents,"path": filename,"encoding": "utf-8","mode": "overwrite"}payload["files"].append(data)response = requests.post(url, json=payload, headers=headers)8 unmodified lines# Sidebar navigationst.sidebar.title("Navigation")app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])if app_mode == "AI Agent Creator":# AI Agent Creator24 unmodified linesterminal_input = st.text_input("Enter a command:")if st.button("Run"):terminal_output = terminal_interface(terminal_input)st.session_state.terminal_history.append((terminal_input, terminal_output))st.code(terminal_output, language="bash")# Code Editor Interface22 unmodified linesst.subheader("Translate Code")code_to_translate = st.text_area("Enter code to translate:")source_language = st.text_input("Enter source language (e.g., 'Python'):")target_language = st.text_input("Enter target language (e.g., 'JavaScript'):")if st.button("Translate Code"):translated_code = translate_code(code_to_translate, source_language, target_language)st.code(translated_code, language=target_language.lower())# Code Generation6 unmodified lineselif app_mode == "Workspace Chat App":# Workspace Chat Appst.header("Workspace Chat App")# Project Workspace Creationst.subheader("Create a New Project")project_name = st.text_input("Enter project name:")18 unmodified linescode_to_add = st.text_area("Enter code to add to workspace:")file_name = st.text_input("Enter file name (e.g., 'app.py'):")if st.button("Add Code"):add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)st.session_state.terminal_history.append((f"Add Code: {code_to_add}", add_code_status))st.success(add_code_status)# Terminal Interface with Project Context1 unmodified lineterminal_input = st.text_input("Enter a command within the workspace:")if st.button("Run Command"):terminal_output = terminal_interface(terminal_input, project_name)st.session_state.terminal_history.append((terminal_input, terminal_output))st.code(terminal_output, language="bash")# Chat Interface for Guidance25 unmodified lines# Chat with AI Agentsst.subheader("Chat with AI Agents")selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)agent_chat_input = st.text_area("Enter your message for the agent:")if st.button("Send to Agent"):agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)st.session_state.chat_history.append((agent_chat_input, agent_chat_response))st.write(f"{selected_agent}: {agent_chat_response}")# Code Generation1 unmodified linecode_idea = st.text_input("Enter your code idea:")# Model Selection Menuselected_model = st.selectbox("Select a code-generative model", AVAILABLE_CODE_GENERATIVE_MODELS)if st.button("Generate Code"):generated_code = generate_code(code_idea, selected_model)2 unmodified lines# Automate Build Processst.subheader("Automate Build Process")if st.button("Automate"):# Load the agent without skills for nowagent = AIAgent(selected_agent, "", [])summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model)st.write("Autonomous Build Summary:")st.write(summary)st.write("Next Step:")1 unmodified line# If everything went well, proceed to deploy the Spaceif agent._hf_api and agent.has_valid_hf_token():agent.deploy_built_space_to_hf()# Use the hf_token to interact with the Hugging Face APIapi = HfApi(token="hf_token") # Function to create a Space on Hugging Facecreate_space_on_hugging_face(api, agent.name, agent.description, True, get_built_space_files())
app.py+84-214