acecalisto3 commited on
Commit
8363049
1 Parent(s): 2bfabfb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -72
app.py CHANGED
@@ -1,74 +1,165 @@
1
- import streamlit as st
2
  import os
3
  import subprocess
4
- import time
5
-
6
- st.set_page_config(page_title="Code Interpreter & Terminal Chat", page_icon="🤖")
7
-
8
- st.title("Code Interpreter & Terminal Chat")
9
- st.markdown("Ask questions, write code, and run terminal commands!")
10
-
11
- chat_history = []
12
-
13
- def chat_with_code(user_input):
14
- """
15
- Handles user input and processes it through code interpreter and terminal.
16
- """
17
- chat_history.append((user_input, None)) # Add user input to history
18
-
19
- try:
20
- # Attempt to execute code
21
- if user_input.startswith("```") and user_input.endswith("```"):
22
- code = user_input[3:-3].strip()
23
- output = execute_code(code)
24
- else:
25
- # Attempt to execute terminal command
26
- output = execute_terminal(user_input)
27
-
28
- chat_history[-1] = (user_input, output) # Update history with output
29
- except Exception as e:
30
- chat_history[-1] = (user_input, f"Error: {e}")
31
-
32
- return chat_history
33
-
34
- def execute_code(code):
35
- """
36
- Executes Python code and returns the output.
37
- """
38
- try:
39
- exec(code)
40
- except Exception as e:
41
- return f"Error: {e}"
42
-
43
- return "Code executed successfully!"
44
-
45
- def execute_terminal(command):
46
- """
47
- Executes a terminal command and returns the output.
48
- """
49
- process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
50
- stdout, stderr = process.communicate()
51
- output = stdout.decode("utf-8").strip()
52
- if stderr:
53
- output += f"\nError: {stderr.decode('utf-8').strip()}"
54
- return output
55
-
56
- # Display chat history
57
- for message in chat_history:
58
- with st.chat_message(message[0]):
59
- if message[1]:
60
- st.write(message[1])
61
-
62
- # User input area
63
- def handle_input(user_input):
64
- chat_history = chat_with_code(user_input)
65
-
66
- # Display updated chat history
67
- for message in chat_history:
68
- with st.chat_message(message[0]):
69
- if message[1]:
70
- st.write(message[1])
71
-
72
- st.session_state.input = "" # Clear the input field
73
-
74
- user_input = st.text_input("Enter your message or code:", key="input", on_change=handle_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
  import os
3
  import subprocess
4
+ import random
5
+ import string
6
+ from huggingface_hub import cached_download, hf_hub_url
7
+ from transformers import pipeline
8
+
9
+ # Define functions for each feature
10
+
11
+ # 1. Chat Interface
12
+ def chat_interface(input_text, history):
13
+ """Handles user input in the chat interface.
14
+
15
+ Args:
16
+ input_text: User's input text.
17
+ history: Chat history.
18
+
19
+ Returns:
20
+ A tuple containing the updated chat history and the chatbot's response.
21
+ """
22
+ # Load the appropriate language model from Hugging Face
23
+ model_name = 'google/flan-t5-xl' # Choose a suitable model
24
+ model_url = hf_hub_url(repo_id=model_name, revision='main', filename='config.json')
25
+ model_path = cached_download(model_url)
26
+ generator = pipeline('text-generation', model=model_path)
27
+
28
+ # Generate chatbot response
29
+ response = generator(input_text, max_length=50, num_return_sequences=1, do_sample=True)[0]['generated_text']
30
+
31
+ # Update chat history
32
+ history.append((input_text, response))
33
+ return history, response
34
+
35
+ # 2. Terminal
36
+ def terminal_interface(command, history):
37
+ """Executes commands in the terminal.
38
+
39
+ Args:
40
+ command: User's command.
41
+ history: Terminal command history.
42
+
43
+ Returns:
44
+ A tuple containing the updated command history and the terminal output.
45
+ """
46
+ # Execute command
47
+ try:
48
+ process = subprocess.run(command.split(), capture_output=True, text=True)
49
+ output = process.stdout
50
+ except Exception as e:
51
+ output = f'Error: {e}'
52
+
53
+ # Update command history
54
+ history.append((command, output))
55
+ return history, output
56
+
57
+ # 3. Code Editor
58
+ def code_editor_interface(code):
59
+ """Provides code completion, formatting, and linting in the code editor.
60
+
61
+ Args:
62
+ code: User's code.
63
+
64
+ Returns:
65
+ Formatted and linted code.
66
+ """
67
+ # Implement code completion, formatting, and linting using appropriate libraries
68
+ # For example, you can use the 'black' library for code formatting
69
+ # and 'pylint' for linting
70
+ # ...
71
+ return code
72
+
73
+ # 4. Workspace
74
+ def workspace_interface(project_name, history):
75
+ """Manages projects, files, and resources in the workspace.
76
+
77
+ Args:
78
+ project_name: Name of the new project.
79
+ history: Workspace history.
80
+
81
+ Returns:
82
+ A tuple containing the updated workspace history and project creation status.
83
+ """
84
+ # Create project directory
85
+ try:
86
+ os.makedirs(os.path.join('projects', project_name))
87
+ status = f'Project \"{project_name}\" created successfully.'
88
+ except FileExistsError:
89
+ status = f'Project \"{project_name}\" already exists.'
90
+
91
+ # Update workspace history
92
+ history.append((project_name, status))
93
+ return history, status
94
+
95
+ # 5. AI-Infused Tools
96
+
97
+ # Define custom AI-powered tools using Hugging Face models
98
+
99
+ # Example: Text summarization tool
100
+ def summarize_text(text):
101
+ """Summarizes a given text using a Hugging Face model.
102
+
103
+ Args:
104
+ text: Text to be summarized.
105
+
106
+ Returns:
107
+ Summarized text.
108
+ """
109
+ summarizer = pipeline('summarization', model='facebook/bart-large-cnn')
110
+ summary = summarizer(text, max_length=100, min_length=30)[0]['summary_text']
111
+ return summary
112
+
113
+ # 6. Hugging Face Integration
114
+
115
+ # Define functions for accessing, training, and deploying models
116
+
117
+ # Example: Load a pre-trained model
118
+ def load_model(model_name):
119
+ """Loads a pre-trained model from Hugging Face.
120
+
121
+ Args:
122
+ model_name: Name of the model to be loaded.
123
+
124
+ Returns:
125
+ The loaded model.
126
+ """
127
+ model_url = hf_hub_url(repo_id=model_name, revision='main')
128
+ model = cached_download(model_url)
129
+ return model
130
+
131
+ # Create Gradio interface
132
+ with gr.Blocks() as demo:
133
+ # Chat interface
134
+ chat_history = gr.State([]) # Initialize chat history
135
+ chat_input = gr.Textbox(label="Chat with CodeCraft", lines=5)
136
+ chat_output = gr.Textbox(label="CodeCraft Response", lines=5)
137
+ chat_button = gr.Button(value="Send")
138
+ chat_button.click(chat_interface, inputs=[chat_input, chat_history], outputs=[chat_history, chat_output])
139
+
140
+ # Terminal interface
141
+ terminal_history = gr.State([]) # Initialize terminal history
142
+ terminal_input = gr.Textbox(label="Enter Command", lines=1)
143
+ terminal_output = gr.Textbox(label="Terminal Output", lines=5)
144
+ terminal_button = gr.Button(value="Run")
145
+ terminal_button.click(terminal_interface, inputs=[terminal_input, terminal_history], outputs=[terminal_history, terminal_output])
146
+
147
+ # Code editor interface
148
+ code_editor = gr.Code(label="Code Editor", lines=10, language="python")
149
+ code_editor.change(code_editor_interface, inputs=code_editor, outputs=code_editor)
150
+
151
+ # Workspace interface
152
+ workspace_history = gr.State([]) # Initialize workspace history
153
+ workspace_input = gr.Textbox(label="Project Name", lines=1)
154
+ workspace_output = gr.Textbox(label="Workspace Data", lines=5)
155
+ workspace_button = gr.Button(value="Create Project")
156
+ workspace_button.click(workspace_interface, inputs=[workspace_input, workspace_history], outputs=[workspace_history, workspace_output])
157
+
158
+ # AI-Infused Tools
159
+ text_input = gr.Textbox(label="Enter text to summarize")
160
+ summary_output = gr.Textbox(label="Summarized Text")
161
+ summarize_button = gr.Button(value="Summarize")
162
+ summarize_button.click(summarize_text, inputs=text_input, outputs=summary_output)
163
+
164
+ # Launch Gradio app
165
+ demo.launch(share=True, server_name='0.0.0.0')