File size: 1,088 Bytes
caa6138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
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
34
35
36
37
38
39
40
41
42
import streamlit as st
import torch
import numpy as np
import io
import sys

# Function to execute the input code and capture print statements
def execute_code(code):
    # Redirect stdout to capture print statements
    old_stdout = sys.stdout
    sys.stdout = mystdout = io.StringIO()
    
    global_vars = {"torch": torch, "np": np}
    local_vars = {}
    try:
        exec(code, global_vars, local_vars)
        output = mystdout.getvalue()
    except Exception as e:
        output = str(e)
    finally:
        # Reset redirect.
        sys.stdout = old_stdout
    
    return output, local_vars

st.title('PyTorch Code Runner')

# Text area for inputting the PyTorch code
code_input = st.text_area("Enter your PyTorch code here", height=300)

# Button to execute the code
if st.button("Run Code"):
    # Prepend the import statement
    code_to_run = "import torch\nimport numpy as np\n" + code_input
    
    # Execute the code and capture the output
    output, variables = execute_code(code_to_run)
    
    # Display the output
    st.subheader('Output')
    st.text(output)