acecalisto3 commited on
Commit
a35ba6f
·
verified ·
1 Parent(s): 5cbfe4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +295 -349
app.py CHANGED
@@ -1,360 +1,306 @@
1
- import streamlit as st
2
- from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, RagRetriever, AutoModelForSeq2SeqLM
3
- import os
4
- import subprocess
5
- import black
6
- from pylint import lint
7
- from io import StringIO
8
- import sys
9
- import torch
10
- from huggingface_hub import hf_hub_url, cached_download, HfApi
11
-
12
- # Access Hugging Face API key from secrets
13
- hf_token = st.secrets["hf_token"]
14
- if not hf_token:
15
- st.error("Hugging Face API key not found. Please make sure it is set in the secrets.")
16
-
17
- HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
18
- PROJECT_ROOT = "projects"
19
- AGENT_DIRECTORY = "agents"
20
- AVAILABLE_CODE_GENERATIVE_MODELS = ["bigcode/starcoder", "Salesforce/codegen-350M-mono", "microsoft/CodeGPT-small"]
21
-
22
- # Global state to manage communication between Tool Box and Workspace Chat App
23
- if 'chat_history' not in st.session_state:
24
- st.session_state.chat_history = []
25
- if 'terminal_history' not in st.session_state:
26
- st.session_state.terminal_history = []
27
- if 'workspace_projects' not in st.session_state:
28
- st.session_state.workspace_projects = {}
29
- if 'available_agents' not in st.session_state:
30
- st.session_state.available_agents = []
31
- if 'selected_language' not in st.session_state:
32
- st.session_state.selected_language = "Python"
33
-
34
- # AI Guide Toggle
35
- ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
36
-
37
- class AIAgent:
38
- def __init__(self, name, description, skills):
39
- self.name = name
40
- self.description = description
41
- self.skills = skills
42
- self._hf_api = HfApi() # Initialize HfApi here
43
-
44
- def create_agent_prompt(self):
45
- skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
46
- agent_prompt = f"""
47
- As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
48
- {skills_str}
49
-
50
- 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.
51
- """
52
- return agent_prompt
53
-
54
- def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model, hf_token):
55
- summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
56
- summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
57
- next_step = "Based on the current state, the next logical step is to implement the main application logic."
58
- return summary, next_step
59
-
60
- def deploy_built_space_to_hf(self, project_name):
61
- # Assuming you have a function that generates the space content
62
- space_content = generate_space_content(project_name)
63
- repository = self._hf_api.create_repo(
64
- repo_id=project_name,
65
- private=True,
66
- token=hf_token,
67
- exist_ok=True,
68
- space_sdk="streamlit"
69
- )
70
- self._hf_api.upload_file(
71
- path_or_fileobj=space_content,
72
- path_in_repo="app.py",
73
- repo_id=project_name,
74
- repo_type="space",
75
- token=hf_token
76
- )
77
- return repository
78
-
79
- def has_valid_hf_token(self):
80
- return self._hf_api.whoami(token=hf_token) is not None
81
-
82
- def process_input(input_text):
83
- chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", tokenizer="microsoft/DialoGPT-medium")
84
- response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
85
- return response
86
-
87
- def run_code(code):
88
- try:
89
- result = subprocess.run(code, shell=True, capture_output=True, text=True)
90
- return result.stdout
91
- except Exception as e:
92
- return str(e)
93
-
94
- def workspace_interface(project_name):
95
- project_path = os.path.join(PROJECT_ROOT, project_name)
96
- if not os.path.exists(project_path):
97
- os.makedirs(project_path)
98
- st.session_state.workspace_projects[project_name] = {'files': []}
99
- return f"Project '{project_name}' created successfully."
100
- else:
101
- return f"Project '{project_name}' already exists."
102
 
103
- def add_code_to_workspace(project_name, code, file_name):
104
- project_path = os.path.join(PROJECT_ROOT, project_name)
105
- if not os.path.exists(project_path):
106
- return f"Project '{project_name}' does not exist."
107
-
108
- file_path = os.path.join(project_path, file_name)
109
- with open(file_path, "w") as file:
110
- file.write(code)
111
- st.session_state.workspace_projects[project_name]['files'].append(file_name)
112
- return f"Code added to '{file_name}' in project '{project_name}'."
113
-
114
- def display_chat_history(chat_history):
115
- return "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
116
-
117
- def display_workspace_projects(workspace_projects):
118
- return "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
119
-
120
- def generate_space_content(project_name):
121
- # Logic to generate the Streamlit app content based on project_name
122
- #... (This is where you'll need to implement the actual code generation)
123
- return "import streamlit as st\nst.title('My Streamlit App')\nst.write('Hello, world!')"
124
-
125
- def get_code_generation_model(language):
126
- # Return the code generation model based on the selected language
127
- if language == "Python":
128
- return "bigcode/starcoder"
129
- elif language == "Java":
130
- return "Salesforce/codegen-350M-mono"
131
- elif language == "JavaScript":
132
- return "microsoft/CodeGPT-small"
133
- else:
134
- return "bigcode/starcoder"
135
 
136
- def generate_code(input_text, language):
137
- # Use the selected code generation model to generate code
138
- model_name = get_code_generation_model(language)
139
- model = pipeline("text2text-generation", model=model_name)
140
- response = model(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
141
- return response
 
 
 
 
 
 
142
 
143
- if __name__ == "__main__":
144
- st.sidebar.title("Navigation")
145
- app_mode = st.sidebar.selectbox("Choose the app mode", ["Home", "Terminal", "Explorer", "Code Editor", "Build & Deploy"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  if app_mode == "Home":
148
  st.title("Welcome to AI-Guided Development")
149
- st.write("This application helps you build and deploy applications with the assistance of an AI Guide.")
150
- st.write("Toggle the AI Guide from the sidebar to choose the level of assistance you need.")
151
 
152
- elif app_mode == "Terminal":
153
- st.header("Terminal")
154
- terminal_input = st.text_input("Enter a command:")
155
- if st.button("Run"):
156
- output = run_code(terminal_input)
157
- st.session_state.terminal_history.append((terminal_input, output))
158
- st.code(output, language="bash")
159
- if ai_guide_level!= "No Assistance":
160
- st.write("Run commands here to add packages to your project. For example: `pip install <package-name>`.")
161
- if terminal_input and "install" in terminal_input:
162
- package_name = terminal_input.split("install")[-1].strip()
163
- st.write(f"Package `{package_name}` will be added to your project.")
164
-
165
- elif app_mode == "Explorer":
166
- st.header("Explorer")
167
- uploaded_file = st.file_uploader("Upload a file", type=["py"])
168
- if uploaded_file:
169
- file_details = {"FileName": uploaded_file.name, "FileType": uploaded_file.type}
170
- st.write(file_details)
171
- save_path = os.path.join(PROJECT_ROOT, uploaded_file.name)
172
- with open(save_path, "wb") as f:
173
- f.write(uploaded_file.getbuffer())
174
- st.success(f"File {uploaded_file.name} saved successfully!")
175
-
176
- st.write("Drag and drop files into the 'app' folder.")
177
- for project, details in st.session_state.workspace_projects.items():
178
- st.write(f"Project: {project}")
179
- for file in details['files']:
180
- st.write(f" - {file}")
181
- if st.button(f"Move {file} to app folder"):
182
- # Logic to move file to 'app' folder
183
- pass
184
- if ai_guide_level!= "No Assistance":
185
- st.write("You can upload files and move them into the 'app' folder for building your application.")
186
 
187
  elif app_mode == "Code Editor":
188
- st.header("Code Editor")
189
- code_editor = st.text_area("Write your code:", height=300)
190
- if st.button("Save Code"):
191
- # Logic to save code
192
- pass
193
- if ai_guide_level!= "No Assistance":
194
- st.write("The function `foo()` requires the `bar` package. Add it to `requirements.txt`.")
195
 
196
  elif app_mode == "Build & Deploy":
197
- st.header("Build & Deploy")
198
- project_name_input = st.text_input("Enter Project Name for Automation:")
199
- selected_language = st.selectbox("Select a programming language:", ["Python", "Java", "JavaScript"])
200
- st.session_state.selected_language = selected_language
201
- if st.button("Automate"):
202
- selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
203
- selected_model = get_code_generation_model(selected_language)
204
- agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
205
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name_input, selected_model, hf_token)
206
- st.write("Autonomous Build Summary:")
207
- st.write(summary)
208
- st.write("Next Step:")
209
- st.write(next_step)
210
- if agent._hf_api and agent.has_valid_hf_token():
211
- repository = agent.deploy_built_space_to_hf(project_name_input)
212
- st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")
213
- st.markdown("[Check out your new Space here](hf.co/" + repository.name + ")")
214
-
215
- # Code Generation
216
- if ai_guide_level!= "No Assistance":
217
- code_input = st.text_area("Enter code to generate:", height=300)
218
- if st.button("Generate Code"):
219
- language = st.session_state.selected_language
220
- generated_code = generate_code(code_input, language)
221
- st.code(generated_code, language=language)
222
-
223
- # CSS for styling
224
- st.markdown("""
225
- <style>
226
- /* Advanced and Accommodating CSS */
227
- body {
228
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
229
- background-color: #f4f4f9;
230
- color: #333;
231
- margin: 0;
232
- padding: 0;
233
- }
234
-
235
- h1, h2, h3, h4, h5, h6 {
236
- color: #333;
237
- }
238
-
239
- .container {
240
- width: 90%;
241
- margin: 0 auto;
242
- padding: 20px;
243
- }
244
-
245
- /* Navigation Sidebar */
246
- .sidebar {
247
- background-color: #2c3e50;
248
- color: #ecf0f1;
249
- padding: 20px;
250
- height: 100vh;
251
- position: fixed;
252
- top: 0;
253
- left: 0;
254
- width: 250px;
255
- overflow-y: auto;
256
- }
257
-
258
- .sidebar a {
259
- color: #ecf0f1;
260
- text-decoration: none;
261
- display: block;
262
- padding: 10px 0;
263
- }
264
-
265
- .sidebar a:hover {
266
- background-color: #34495e;
267
- border-radius: 5px;
268
- }
269
-
270
- /* Main Content */
271
- .main-content {
272
- margin-left: 270px;
273
- padding: 20px;
274
- }
275
-
276
- /* Buttons */
277
- button {
278
- background-color: #3498db;
279
- color: #fff;
280
- border: none;
281
- padding: 10px 20px;
282
- border-radius: 5px;
283
- cursor: pointer;
284
- font-size: 16px;
285
- }
286
-
287
- button:hover {
288
- background-color: #2980b9;
289
- }
290
-
291
- /* Text Areas and Inputs */
292
- textarea, input[type="text"] {
293
- width: 100%;
294
- padding: 10px;
295
- margin: 10px 0;
296
- border: 1px solid #ddd;
297
- border-radius: 5px;
298
- box-sizing: border-box;
299
- }
300
-
301
- textarea:focus, input[type="text"]:focus {
302
- border-color: #3498db;
303
- outline: none;
304
- }
305
-
306
- /* Terminal Output */
307
- .code-output {
308
- background-color: #1e1e1e;
309
- color: #dcdcdc;
310
- padding: 20px;
311
- border-radius: 5px;
312
- font-family: 'Courier New', Courier, monospace;
313
- }
314
-
315
- /* Chat History */
316
- .chat-history {
317
- background-color: #ecf0f1;
318
- padding: 20px;
319
- border-radius: 5px;
320
- max-height: 300px;
321
- overflow-y: auto;
322
- }
323
-
324
- .chat-message {
325
- margin-bottom: 10px;
326
- }
327
-
328
- .chat-message.user {
329
- text-align: right;
330
- color: #3498db;
331
- }
332
-
333
- .chat-message.agent {
334
- text-align: left;
335
- color: #e74c3c;
336
- }
337
-
338
- /* Project Management */
339
- .project-list {
340
- background-color: #ecf0f1;
341
- padding: 20px;
342
- border-radius: 5px;
343
- max-height: 300px;
344
- overflow-y: auto;
345
- }
346
-
347
- .project-item {
348
- margin-bottom: 10px;
349
- }
350
-
351
- .project-item a {
352
- color: #3498db;
353
- text-decoration: none;
354
- }
355
-
356
- .project-item a:hover {
357
- text-decoration: underline;
358
- }
359
- </style>
360
- """, unsafe_allow_html=True)
 
1
+ You are absolutely right! I apologize for the oversight. It seems I'm still learning and sometimes miss those crucial details.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ Here's the corrected code, with the missing closing parenthesis added:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ ```python
6
+ import streamlit as st
7
+ from flask import Flask, jsonify, request
8
+ from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
9
+ from flask_sqlalchemy import SQLAlchemy
10
+ from werkzeug.security import generate_password_hash, check_password_hash
11
+ import pdb
12
+ import subprocess
13
+ import docker
14
+ from huggingface_hub import HfApi, create_repo
15
+ import importlib
16
+ import os
17
 
18
+ # Initialize Flask app
19
+ app = Flask(__name__)
20
+ app.config['SECRET_KEY'] = 'your-secret-key'
21
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
22
+ db = SQLAlchemy(app)
23
+ login_manager = LoginManager()
24
+ login_manager.init_app(app)
25
+
26
+ # User and Project models (as defined earlier)
27
+
28
+ class User(UserMixin, db.Model):
29
+ id = db.Column(db.Integer, primary_key=True)
30
+ username = db.Column(db.String(100), unique=True, nullable=False)
31
+ password_hash = db.Column(db.String(100), nullable=False)
32
+ projects = db.relationship('Project', backref='user', lazy=True)
33
+
34
+ class Project(db.Model):
35
+ id = db.Column(db.Integer, primary_key=True)
36
+ name = db.Column(db.String(100), nullable=False)
37
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
38
+
39
+ @login_manager.user_loader
40
+ def load_user(user_id):
41
+ return User.query.get(int(user_id))
42
+
43
+ # Authentication routes (as defined earlier)
44
+
45
+ @app.route('/register', methods=['POST'])
46
+ def register():
47
+ data = request.get_json()
48
+ username = data.get('username')
49
+ password = data.get('password')
50
+ if User.query.filter_by(username=username).first():
51
+ return jsonify({'message': 'Username already exists'}), 400
52
+ new_user = User(username=username, password_hash=generate_password_hash(password))
53
+ db.session.add(new_user)
54
+ db.session.commit()
55
+ return jsonify({'message': 'User registered successfully'}), 201
56
+
57
+ @app.route('/login', methods=['POST'])
58
+ def login():
59
+ data = request.get_json()
60
+ username = data.get('username')
61
+ password = data.get('password')
62
+ user = User.query.filter_by(username=username).first()
63
+ if user and check_password_hash(user.password_hash, password):
64
+ login_user(user)
65
+ return jsonify({'message': 'Logged in successfully'}), 200
66
+ return jsonify({'message': 'Invalid username or password'}), 401
67
+
68
+ @app.route('/logout')
69
+ @login_required
70
+ def logout():
71
+ logout_user()
72
+ return jsonify({'message': 'Logged out successfully'}), 200
73
+
74
+ @app.route('/create_project', methods=['POST'])
75
+ @login_required
76
+ def create_project():
77
+ data = request.get_json()
78
+ project_name = data.get('project_name')
79
+ new_project = Project(name=project_name, user_id=current_user.id)
80
+ db.session.add(new_project)
81
+ db.session.commit()
82
+ return jsonify({'message': 'Project created successfully'}), 201
83
+
84
+ @app.route('/get_projects')
85
+ @login_required
86
+ def get_projects():
87
+ projects = Project.query.filter_by(user_id=current_user.id).all()
88
+ return jsonify({'projects': [project.name for project in projects]}), 200
89
+
90
+ # Plugin system
91
+ class PluginManager:
92
+ def __init__(self, plugin_dir):
93
+ self.plugin_dir = plugin_dir
94
+ self.plugins = {}
95
+
96
+ def load_plugins(self):
97
+ for filename in os.listdir(self.plugin_dir):
98
+ if filename.endswith('.py'):
99
+ module_name = filename[:-3]
100
+ spec = importlib.util.spec_from_file_location(module_name, os.path.join(self.plugin_dir, filename))
101
+ module = importlib.util.module_from_spec(spec)
102
+ spec.loader.exec_module(module)
103
+ if hasattr(module, 'register_plugin'):
104
+ plugin = module.register_plugin()
105
+ self.plugins[plugin.name] = plugin
106
+
107
+ def get_plugin(self, name):
108
+ return self.plugins.get(name)
109
+
110
+ def list_plugins(self):
111
+ return list(self.plugins.keys())
112
+
113
+ # Example plugin
114
+ # save this as a .py file in your plugin directory
115
+ def register_plugin():
116
+ return ExamplePlugin()
117
+
118
+ class ExamplePlugin:
119
+ name = "example_plugin"
120
+
121
+ def run(self, input_data):
122
+ return f"Plugin processed: {input_data}"
123
+
124
+ plugin_manager = PluginManager('./plugins')
125
+ plugin_manager.load_plugins()
126
+
127
+ def main():
128
+ st.sidebar.title("AI-Guided Development")
129
+ app_mode = st.sidebar.selectbox("Choose the app mode",
130
+ ["Home", "Login/Register", "File Explorer", "Code Editor", "Terminal",
131
+ "Build & Deploy", "AI Assistant", "Plugins"])
132
+
133
+ # AI Guide Toggle
134
+ ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
135
 
136
  if app_mode == "Home":
137
  st.title("Welcome to AI-Guided Development")
138
+ st.write("Select a mode from the sidebar to get started.")
 
139
 
140
+ elif app_mode == "Login/Register":
141
+ login_register_page()
142
+
143
+ elif app_mode == "File Explorer":
144
+ file_explorer_page()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  elif app_mode == "Code Editor":
147
+ code_editor_page()
148
+
149
+ elif app_mode == "Terminal":
150
+ terminal_page()
 
 
 
151
 
152
  elif app_mode == "Build & Deploy":
153
+ build_and_deploy_page()
154
+
155
+ elif app_mode == "AI Assistant":
156
+ ai_assistant_page()
157
+
158
+ elif app_mode == "Plugins":
159
+ plugins_page()
160
+
161
+ @login_required
162
+ def file_explorer_page():
163
+ st.header("File Explorer")
164
+ # File explorer code (as before)
165
+
166
+ @login_required
167
+ def code_editor_page():
168
+ st.header("Code Editor")
169
+ # Code editor with Monaco integration
170
+ st.components.v1.html(
171
+ """
172
+ <div id="monaco-editor" style="width:800px;height:600px;border:1px solid grey"></div>
173
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/loader.min.js"></script>
174
+ <script>
175
+ require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs' }});
176
+ require(['vs/editor/editor.main'], function() {
177
+ var editor = monaco.editor.create(document.getElementById('monaco-editor'), {
178
+ value: 'print("Hello, World!")',
179
+ language: 'python'
180
+ });
181
+ });
182
+ </script>
183
+ """,
184
+ height=650,
185
+ )
186
+
187
+ if st.button("Run Code"):
188
+ code = st.session_state.get('code', '') # Get code from Monaco editor
189
+ output = run_code(code)
190
+ st.code(output)
191
+
192
+ if st.button("Debug Code"):
193
+ code = st.session_state.get('code', '')
194
+ st.write("Debugging mode activated. Check your console for the debugger.")
195
+ debug_code(code)
196
+
197
+ @login_required
198
+ def terminal_page():
199
+ st.header("Terminal")
200
+ # Terminal code (as before)
201
+
202
+ @login_required
203
+ def build_and_deploy_page():
204
+ st.header("Build & Deploy")
205
+ project_name = st.text_input("Enter project name:")
206
+
207
+ if st.button("Build Docker Image"):
208
+ image, logs = build_docker_image(project_name)
209
+ st.write(f"Docker image built: {image.tags}")
210
+
211
+ if st.button("Run Docker Container"):
212
+ port = st.number_input("Enter port number:", value=8501)
213
+ container = run_docker_container(project_name, port)
214
+ st.write(f"Docker container running: {container.id}")
215
+
216
+ if st.button("Deploy to Hugging Face Spaces"):
217
+ token = st.text_input("Enter your Hugging Face token:", type="password")
218
+ if token:
219
+ repo_url = deploy_to_hf_spaces(project_name, token)
220
+ st.write(f"Deployed to Hugging Face Spaces: {repo_url}")
221
+
222
+ @login_required
223
+ def ai_assistant_page():
224
+ st.header("AI Assistant")
225
+ # AI assistant code (as before)
226
+
227
+ @login_required
228
+ def plugins_page():
229
+ st.header("Plugins")
230
+ st.write("Available plugins:")
231
+ for plugin_name in plugin_manager.list_plugins():
232
+ st.write(f"- {plugin_name}")
233
+
234
+ selected_plugin = st.selectbox("Select a plugin to run:", plugin_manager.list_plugins())
235
+ input_data = st.text_input("Enter input for the plugin:")
236
+
237
+ if st.button("Run Plugin"):
238
+ plugin = plugin_manager.get_plugin(selected_plugin)
239
+ if plugin:
240
+ result = plugin.run(input_data)
241
+ st.write(f"Plugin output: {result}")
242
+
243
+ def login_register_page():
244
+ st.header("Login/Register")
245
+ action = st.radio("Choose action:", ["Login", "Register"])
246
+
247
+ username = st.text_input("Username:")
248
+ password = st.text_input("Password:", type="password")
249
+
250
+ if action == "Login":
251
+ if st.button("Login"):
252
+ user = User.query.filter_by(username=username).first()
253
+ if user and check_password_hash(user.password_hash, password):
254
+ login_user(user)
255
+ st.success("Logged in successfully!")
256
+ else:
257
+ st.error("Invalid username or password")
258
+ else:
259
+ if st.button("Register"):
260
+ if User.query.filter_by(username=username).first():
261
+ st.error("Username already exists")
262
+ else:
263
+ new_user = User(username=username, password_hash=generate_password_hash(password))
264
+ db.session.add(new_user)
265
+ db.session.commit()
266
+ st.success("User registered successfully!")
267
+
268
+ def debug_code(code):
269
+ try:
270
+ pdb.run(code)
271
+ except Exception as e:
272
+ return str(e)
273
+
274
+ def run_code(code):
275
+ try:
276
+ result = subprocess.run(['python', '-c', code], capture_output=True, text=True, timeout=10)
277
+ return result.stdout
278
+ except subprocess.TimeoutExpired:
279
+ return "Code execution timed out"
280
+ except Exception as e:
281
+ return str(e)
282
+
283
+ def build_docker_image(project_name):
284
+ client = docker.from_env()
285
+ image, build_logs = client.images.build(path=".", tag=project_name)
286
+ return image, build_logs
287
+
288
+ def run_docker_container(image_name, port):
289
+ client = docker.from_env()
290
+ container = client.containers.run(image_name, detach=True, ports={f'{port}/tcp': port})
291
+ return container
292
+
293
+ def deploy_to_hf_spaces(project_name, token):
294
+ api = HfApi()
295
+ repo_url = create_repo(project_name, repo_type="space", space_sdk="streamlit", token=token)
296
+ api.upload_folder(
297
+ folder_path=".",
298
+ repo_id=project_name,
299
+ repo_type="space",
300
+ token=token
301
+ )
302
+ return repo_url
303
+
304
+ if __name__ == "__main__":
305
+ db.create_all() # Create the database tables if they don't exist
306
+ main()