Spaces:
Running
Running
Commit
•
a98a37e
1
Parent(s):
c43dc09
Update app.py
Browse files
app.py
CHANGED
@@ -1,33 +1,54 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import os
|
3 |
+
import subprocess
|
4 |
+
import time
|
5 |
+
|
6 |
+
def chat_with_code(history, user_input):
|
7 |
+
"""
|
8 |
+
Handles user input and processes it through code interpreter and terminal.
|
9 |
+
"""
|
10 |
+
history.append((user_input, None)) # Add user input to history
|
11 |
+
|
12 |
+
try:
|
13 |
+
# Attempt to execute code
|
14 |
+
if user_input.startswith("```") and user_input.endswith("```"):
|
15 |
+
code = user_input[3:-3].strip()
|
16 |
+
output = execute_code(code)
|
17 |
+
else:
|
18 |
+
# Attempt to execute terminal command
|
19 |
+
output = execute_terminal(user_input)
|
20 |
+
|
21 |
+
history[-1] = (user_input, output) # Update history with output
|
22 |
+
except Exception as e:
|
23 |
+
history[-1] = (user_input, f"Error: {e}")
|
24 |
+
|
25 |
+
return history
|
26 |
+
|
27 |
+
def execute_code(code):
|
28 |
+
"""
|
29 |
+
Executes Python code and returns the output.
|
30 |
+
"""
|
31 |
+
try:
|
32 |
+
exec(code)
|
33 |
+
except Exception as e:
|
34 |
+
return f"Error: {e}"
|
35 |
+
|
36 |
+
return "Code executed successfully!"
|
37 |
+
|
38 |
+
def execute_terminal(command):
|
39 |
+
"""
|
40 |
+
Executes a terminal command and returns the output.
|
41 |
+
"""
|
42 |
+
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
43 |
+
stdout, stderr = process.communicate()
|
44 |
+
output = stdout.decode("utf-8").strip()
|
45 |
+
if stderr:
|
46 |
+
output += f"\nError: {stderr.decode('utf-8').strip()}"
|
47 |
+
return output
|
48 |
+
|
49 |
+
# Create Gradio interface
|
50 |
+
iface = gr.ChatInterface(chat_with_code,
|
51 |
+
title="Code Interpreter & Terminal Chat",
|
52 |
+
description="Ask questions, write code, and run terminal commands!")
|
53 |
+
|
54 |
+
iface.launch(share=True)
|