[Python, Gradio.io] How to Output Downloadable file after processing?

Specification

  • gr.__version__ --> '3.16.2'
  • I want to create a gradio tab in my gradio app
  • Disregard TAB 1, I am only working on tab2
  • where I upload an excel file
  • save name of the excel fie to a variable
  • process that excel file take data out of it 2 numbers (1 and 2)
  • Load data from the excel file to a pandas dataframe and add 1 to both of the numbers
  • Turn dataframe to excel gain and output it to the user to be able to download the output excel file
  • The output file is named as the original uploaded file
    "

MY CURRENT Code

import gradio as gr
import pandas as pd


# def func1():
#     #....
#     pass

def func2(name, file):
    file_name = name
    file_x = file
    # use this function to retrieve the file_x without modification for gradio.io output
    # excel to dataframe
    df = pd.read_excel(file_x)
    # add 1 to both numbers
    df['1'] = df['1'] + 1
    df['2'] = df['2'] + 1
    # dataframe to excel
    # returnt the exported excel fiel with the same name as the original file
    return df.to_excel(file_x, index=False)


# GRADIO APP
with gr.Blocks() as demo:
    gr.Markdown("BI App")


    ''' #1.TAB '''
    # with gr.Tab("Tab1"):
    #      #.... unimportant code
    #     with gr.Column():
    #         file_obj = gr.File(label="Input File", 
    #             file_count="single", 
    #             file_types=["", ".", ".csv",".xls",".xlsx"]),
    #         # extract the filename from gradio.io file object
    #         # keyfile_name = gr.Interface(file_name_reader, inputs="file", outputs=None)
    #         keyfile_name = 'nothing'
    #         tab1_inputs = [keyfile_name, file_obj]

    #     with gr.Column():
    #         # output excel file with gradio.io
    #         tab1_outputs = [gr.File(label="Output File", 
    #             file_count="single", 
    #             file_types=["", ".", ".csv",".xls",".xlsx"])]
        
    #     tab1_submit_button = gr.Button("Submit")


    ''' #2.TAB - I EDIT THIS TAB'''
    with gr.Tab("Tab2"):
        admitad_invoice_approvals_button = gr.Button("Submit")

        def file_name_reader(file):
            file_name = file.name  # extract the file name from the uploaded file
            return file_name
        
        # iface = gr.Interface(file_name_reader, inputs="file", outputs=None)

        with gr.Column():
            file_obj = gr.File(label="Input File", 
                file_count="single", 
                file_types=["", ".", ".csv",".xls",".xlsx"]),
            # extract the filename from gradio.io file object
            keyfile_name = gr.Interface(file_name_reader, inputs="file", outputs=None)
            tab2_inputs = [keyfile_name, file_obj]

        with gr.Column():
            # output excel file with gradio.io
            tab2_outputs = [gr.File(label="Output File", 
                file_count="single", 
                file_types=["", ".", ".csv",".xls",".xlsx"])]

        tab2_submit_button = gr.Button("Submit")


    '''1 button for each of the tabs to execute the GUI TASK'''
    # tab1_submit_button.click(func1,
    #                         inputs=tab1_inputs,
    #                         outputs=tab1_outputs)
    
    tab2_submit_button.click(func2,
                            inputs=tab2_inputs,
                            outputs=tab2_outputs)
    

''' EXECUTING THE APP'''
demo.launch(debug=True, share=True) ## PRODUCTION TESTING

ERROR:

Output exceeds the [size limit](command:workbench.action.openSettings?%5B%22notebook.output.textLineLimit%22%5D). Open the full output data [in a text editor](command:workbench.action.openLargeOutput?89dc72e0-7589-43f5-bbdb-7c4dec432955)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[7], line 95
     90     '''1 button for each of the tabs to execute the GUI TASK'''
     91     # tab1_submit_button.click(func1,
     92     #                         inputs=tab1_inputs,
     93     #                         outputs=tab1_outputs)
---> 95     tab2_submit_button.click(func2,
     96                             inputs=tab2_inputs,
     97                             outputs=tab2_outputs)
    100 ''' EXECUTING THE APP'''
    101 demo.launch(debug=True, share=True) ## PRODUCTION TESTING

File [~/.local/lib/python3.8/site-packages/gradio/events.py:145](https://vscode-remote+ssh-002dremote-002bbi3.vscode-resource.vscode-cdn.net/home/ubuntu/airflow/~/.local/lib/python3.8/site-packages/gradio/events.py:145), in Clickable.click(self, fn, inputs, outputs, api_name, status_tracker, scroll_to_output, show_progress, queue, batch, max_batch_size, preprocess, postprocess, cancels, every, _js)
    140 if status_tracker:
    141     warnings.warn(
    142         "The 'status_tracker' parameter has been deprecated and has no effect."
    143     )
--> 145 dep = self.set_event_trigger(
    146     "click",
    147     fn,
    148     inputs,
    149     outputs,
    150     preprocess=preprocess,
    151     postprocess=postprocess,
    152     scroll_to_output=scroll_to_output,
    153     show_progress=show_progress,
    154     api_name=api_name,
    155     js=_js,
    156     queue=queue,
    157     batch=batch,
    158     max_batch_size=max_batch_size,
    159     every=every,
    160 )
    161 set_cancel_events(self, "click", cancels)
    162 return dep

File [~/.local/lib/python3.8/site-packages/gradio/blocks.py:225](https://vscode-remote+ssh-002dremote-002bbi3.vscode-resource.vscode-cdn.net/home/ubuntu/airflow/~/.local/lib/python3.8/site-packages/gradio/blocks.py:225), in Block.set_event_trigger(self, event_name, fn, inputs, outputs, preprocess, postprocess, scroll_to_output, show_progress, api_name, js, no_target, queue, batch, max_batch_size, cancels, every)
    217         warnings.warn(
    218             "api_name {} already exists, using {}".format(api_name, api_name_)
    219         )
    220         api_name = api_name_
    222 dependency = {
    223     "targets": [self._id] if not no_target else [],
    224     "trigger": event_name,
...
    237 }
    238 Context.root_block.dependencies.append(dependency)
    239 return dependency

AttributeError: 'tuple' object has no attribute '_id'

Tried

  • I have looked in to Gradio Docs but the output file generation is not clean especially regarding applying it to my case

Instead of

        with gr.Column():
            file_obj = gr.File(label="Input File"
# no any other arguments
)
            keyfile_name = gr.Interface(file_name_reader, inputs="file", outputs=None)
            input= file_obj

Just have

        with gr.Column():
            file_obj = gr.File(label="Input File")
            input= file_obj

1 Like