0

I want to manually select and upload a CSV or Excel file through gradio (tutorial of gradio), and display it on the UI interface. First, I wrote a function read_file() to read Excel or CSV files:

import gradio as gr
import csv
import pandas as pd

def read_file(file_path):
    if file_path.endswith('.csv'):
        data = pd.read_csv(file_path)
    elif file_path.endswith('.xlsx') or file_path.endswith('.xls'):
        data = pd.read_excel(file_path)
    else:
        raise ValueError('File type not supported. Please provide a CSV or Excel file.')
    return data

df = read_file('./test_data.csv')
print(df)

Out:

        date        M0
0    2009-07  34239.30
1    2009-08  34406.62
2    2009-09  36787.89
3    2009-10  35730.23
4    2009-11  36343.86
..       ...       ...

As you can see, this function can read the test CSV file correctly, but when I pass it to gr.Blocks, an error will appear:

with gr.Blocks() as demo:
    a = gr.File()
    a.change(fn=read_file, inputs=[a], outputs=[])

demo.launch(debug=True)

The error message indicates that _io.BufferedRandom object has no attribute endswith:

AttributeError: '_io.BufferedRandom' object has no attribute 'endswith'

How can I solve this problem? Thanks.

ah bon
  • 9,293
  • 12
  • 65
  • 148

1 Answers1

0

If we use gr.Interface instead of insisting on gr.Blocks, the following code will work:

import gradio as gr
import csv
import pandas as pd

def read_excel_file(file_path):
    if file_path.name.endswith('.csv'):
        data = pd.read_csv(file_path.name)
    elif file_path.name.endswith('.xlsx') or file_path.name.endswith('.xls'):
        data = pd.read_excel(file_path.name)
    else:
        raise ValueError('File type not supported. Please provide a CSV or Excel file.')
    return data

file_input = gr.inputs.File(label="Upload Excel File")
output = gr.outputs.Dataframe(type='pandas')

interface = gr.Interface(fn=read_excel_file, inputs=file_input, outputs=output)
interface.launch()
ah bon
  • 9,293
  • 12
  • 65
  • 148