DEMO 2-2: Diverse Data Display and File Interaction App
import gradio as grimport pandas as pdfrom PIL import Imagefrom pathlib import Path# Function to square the input numberdef change_number(x):return x**2# Function to download the imagedef download_image(x): img=x['composite'][:, :, :3] print(img.shape) rgb_image=Image.fromarray(img) tempdir='./mydraw.jpg' rgb_image.save(tempdir)print(tempdir, Path(tempdir).stem)return gr.DownloadButton(label=f"Download {Path(tempdir).stem}", value=tempdir, visible=True)# Function to get the file path and plot the data from a CSV filedef getfilepath(x): path=x[0] df_read=pd.read_csv(path) plot=gr.LinePlot( df_read, x="band", y="Reflectance", color="Symbol", color_legend_position="bottom", title="Spectra of Different Materials", tooltip=["band", "Reflectance", "Symbol"], height=250, width=500, container=False,)return plot# Function to plot the data from a CSV file uploaded by the userdef getpath(x): path=x.name df_read=pd.read_csv(path) plot=gr.LinePlot( df_read, x="band", y="Reflectance", color="Symbol", color_legend_position="bottom", title="Spectra of Different Materials", tooltip=["band", "Reflectance", "Symbol"], height=250, width=500, container=False,)return plot# Create a Gradio interface with the "soft" themewith gr.Blocks(theme="soft") as demo: gr.Markdown("# Web app interface design") csvfile=gr.update(value='')with gr.Tab("Get numbers"): ## The first sub appwith gr.Accordion("Readme", open=False): gr.Markdown(" Square of the input number")with gr.Row():with gr.Column(): temp_slider = gr.Slider(minimum=0.0,maximum=10,step=1,interactive=True,label="Slide me",)with gr.Column(): out_slider=gr.Textbox()with gr.Tab("Draw a picture"): ## The second sub app image_input = gr.ImageEditor(type="numpy",show_download_button=False,label="Draw a Picture") #dict:'background','layers', 'composite' image_button=gr.DownloadButton("Download",visible=True,variant='primary')with gr.Tab("Plot a figure"): ## The third sub appwith gr.Row():with gr.Column(): file_explore=gr.FileExplorer(root_dir="./data")with gr.Column():file=gr.File(file_count="single",scale=1,label="Upload the csv file")with gr.Row(): plot=gr.LinePlot() temp_slider.change(change_number,inputs=temp_slider,outputs=out_slider) # Link the slider's change event to the change_number function image_input.change(download_image, inputs=[image_input], outputs=image_button) # Link the ImageEditor's change event to the download_image function file_explore.change(getfilepath, inputs=file_explore, outputs=plot) # Link the FileExplorer's change event to the getfilepath functionfile.change(getpath, inputs=file, outputs=plot) # Link the File's change event to the getpath functionif__name__=="__main__": demo.launch()