File size: 1,978 Bytes
ceb3ae8
3c6168b
ceb3ae8
8427805
 
 
 
 
ceb3ae8
 
 
3c6168b
 
ceb3ae8
3c6168b
 
 
 
 
 
 
 
 
 
ceb3ae8
3c6168b
 
 
 
 
 
 
 
 
 
8427805
6be19d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8427805
 
 
 
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import pandas as pd
import traceback


def load_excel(file):
    df = pd.read_excel(file)
    return file, df

def run_code(file, code):
    scope = {'pd': pd}
    if file:
        print('file ok')
        df = pd.read_excel(file)

        scope['df'] = df
        try:
            # Attempt to execute the user's code
            exec(code, scope, scope)
        except Exception as e:
            # Catch any exceptions that occur and print the error message
            error_msg = traceback.format_exc()
            print(f"Error executing user code: {error_msg}")
            scope['new_df'] = df  # Use the original df if error occurs
            return scope['new_df'], error_msg  # Return the error message along with the df

        print(scope.keys())
        if 'new_df' not in scope:
            print("new_df not defined")
            scope['new_df'] = df.copy()
        new_df = scope['new_df']
        
        return new_df, None  # Return None as the error message when execution is successful
    else:
        print("No file provided")
        return pd.DataFrame(), "No file provided"

def run_code_and_update_ui(file, code):
    df, error_msg = run_code(file, code)  # This is your updated run_code function.
    
    # Now, check if there's an error message and handle it appropriately.
    if error_msg:
        # You can update some error display component in Gradio here to show the error_msg.
        # Assuming you have a gr.Textbox to display errors:
        error_display.update(value=f"Error in code execution: {error_msg}")
        # Ensure you still return the original DataFrame or an empty one to satisfy the expected output type.
        return df
    else:
        # If no error, clear the error display and return the DataFrame as usual.
        error_display.update(value="")
        return df


def export_df(df, filename):
    filename = filename.replace('.xlsx', '_coded.xlsx')
    df.to_excel(filename, index=False)
    return filename