Use the File module of the gradio library to upload files and generate downloadable files

Use the File module of the gradio library to upload files and generate downloadable files

1. Background

When using Gradio to design and rewrite the AI ​​demo for effect review, I searched online and on the official website for how to use Gradio to generate a downloadable file, but to no avail. So I lay down for a while and recorded the process of lying down.

2. Introduction

1. Introduction to Gradio

Gradio is a powerful Python library for building interactive machine learning and deep learning applications. The File module provides the function of file upload and display.

2. Introduction to File module

The File module is a component in the gradio library that is used to create a file component that allows users to upload a generic file (used as input) or display a generic file (used as output).

When taken as input, the File module passes the uploaded file to the function as tempfile._TemporaryFileWrapper or List[tempfile._TemporaryFileWrapper], depending on the setting of the file_count parameter (or bytes/List[bytes], depending on the setting of the type parameter).

As output, the File module expects the function to return a path to a file (str type), or a list containing file paths (List[str])

3.tempfile module

The tempfile module is a module in the Python standard library for creating temporary files and directories. It provides a simple way to create temporary files and folders within a program that can be automatically deleted when the program ends, thus avoiding the need to manually clean up temporary files after the program ends.

The tempfile module provides many functions and classes for creating temporary files and folders in different scenarios. For example:

  • tempfile.TemporaryFile(): Creates a temporary file object that is automatically deleted when it is closed or the program ends.
  • tempfile.TemporaryDirectory(): Creates a temporary folder that is automatically deleted when closing or the program ends.
  • tempfile.NamedTemporaryFile(): Creates a temporary file object with the specified name, which is automatically deleted when it is closed or the program ends.
  • tempfile.mkstemp(): Creates a temporary file with a unique name and returns its file descriptor and path.
    You can use these functions and classes to create and process temporary files and folders and automatically delete them when the program ends to avoid the problem of residual files after the program ends.

3. File upload demo practice

1. Specific code

The following is the specific code implemented

import os

import gradio as gr
import tempfile
import shutil
def generate_file(file_obj):
    global tmpdir
    print('临时文件夹地址:{}'.format(tmpdir))
    print('上传文件的地址:{}'.format(file_obj.name)) # 输出上传后的文件在gradio中保存的绝对地址

    #获取到上传后的文件的绝对路径后,其余的操作就和平常一致了

    # 将文件复制到临时目录中
    shutil.copy(file_obj.name, tmpdir)

    # 获取上传Gradio的文件名称
    FileName=os.path.basename(file_obj.name)

    # 获取拷贝在临时目录的新的文件地址
    NewfilePath=os.path.join(tmpdir,FileName)
    print(NewfilePath)

    # 打开复制到新路径后的文件
    with open(NewfilePath, 'rb') as file_obj:

        #在本地电脑打开一个新的文件,并且将上传文件内容写入到新文件
        outputPath=os.path.join(tmpdir,"New"+FileName)
        with open(outputPath,'wb') as w:
            w.write(file_obj.read())

    # 返回新文件的的地址(注意这里)
    return outputPath
def main():
    global tmpdir
    with tempfile.TemporaryDirectory(dir='.') as tmpdir:
        # 定义输入和输出
        inputs = gr.components.File(label="上传文件")
        outputs = gr.components.File(label="下载文件")

        # 创建 Gradio 应用程序g
        app = gr.Interface(fn=generate_file, inputs=inputs, outputs=outputs,   title="文件上传、并生成可下载文件demo",
                      description="上传任何文件都可以,只要大小别超过你电脑的内存即可"
      )

        # 启动应用程序
        app.launch(share=True)
if __name__=="__main__":
    main()

2. Run the sample

Insert image description here
Insert image description here
You can test it on this Hugging Face website: https://huggingface.co/spaces/white520/testCreateFile

Guess you like

Origin blog.csdn.net/qq_51116518/article/details/132628392