• Gradio 最快创建Web 界面部署到服务器并演示机器学习模型,本文提供教学案例以及部署方法,避免使用繁琐的django


    最近学习hugging face里面的物体检测模型,发现一个方便快捷的工具!

    Gradio 是通过友好的 Web 界面演示机器学习模型的最快方式,以便任何人都可以在任何地方使用它!

    一、核心优势:

    使用这个开发这种演示机器学习模型的web界面会比django会快上不少!
    只需要一个py文件即可实现模型界面创建,部署模型到服务器及时间响应所有功能。

    二、重要参考连接:

    官网如下:

    Gradio

    别人的部署到hugging face的space服务器案例如下:(可全网任意访问-)

    https://huggingface.co/spaces/ClassCat/DETR-Object-Detection

    案例对应的代码如下:

    https://huggingface.co/spaces/ClassCat/DETR-Object-Detection/tree/main

    三、自己本地服务器部署的案例

    自己的物检测及体识别的代码(亲测成功):

    1. import torch
    2. from transformers import pipeline
    3. from PIL import Image
    4. import matplotlib.pyplot as plt
    5. import matplotlib.patches as patches
    6. from random import choice
    7. import io
    8. detector50 = pipeline(model="facebook/detr-resnet-50")#自动下载模型,大约200MB
    9. # detector101 = pipeline(model="facebook/detr-resnet-101")
    10. import gradio as gr
    11. COLORS = ["#ff7f7f", "#ff7fbf", "#ff7fff", "#bf7fff",
    12. "#7f7fff", "#7fbfff", "#7fffff", "#7fffbf",
    13. "#7fff7f", "#bfff7f", "#ffff7f", "#ffbf7f"]
    14. fdic = {
    15. "family" : "Arial",
    16. "style" : "italic",
    17. "size" : 15,
    18. "color" : "yellow",
    19. "weight" : "bold"
    20. }
    21. def get_figure(in_pil_img, in_results):
    22. plt.figure(figsize=(16, 10))
    23. plt.imshow(in_pil_img)
    24. #pyplot.gcf()
    25. ax = plt.gca()
    26. for prediction in in_results:
    27. selected_color = choice(COLORS)
    28. x, y = prediction['box']['xmin'], prediction['box']['ymin'],
    29. w, h = prediction['box']['xmax'] - prediction['box']['xmin'], prediction['box']['ymax'] - prediction['box']['ymin']
    30. ax.add_patch(plt.Rectangle((x, y), w, h, fill=False, color=selected_color, linewidth=3))
    31. ax.text(x, y, f"{prediction['label']}: {round(prediction['score']*100, 1)}%", fontdict=fdic)
    32. plt.axis("off")
    33. return plt.gcf()
    34. def infer(model, in_pil_img):
    35. results = None
    36. if model == "detr-resnet-101":
    37. results = detector101(in_pil_img)
    38. else:
    39. results = detector50(in_pil_img)
    40. figure = get_figure(in_pil_img, results)
    41. buf = io.BytesIO()
    42. figure.savefig(buf, bbox_inches='tight')
    43. buf.seek(0)
    44. output_pil_img = Image.open(buf)
    45. return output_pil_img
    46. with gr.Blocks(title="DETR Object Detection - ClassCat",
    47. css=".gradio-container {background:lightyellow;}"
    48. ) as demo:
    49. #sample_index = gr.State([])
    50. gr.HTML("""
      DETR Object Detection
      """
      )
    51. gr.HTML("""

      1. Select a model.

      """
      )
    52. model = gr.Radio(["detr-resnet-50", "detr-resnet-101"], value="detr-resnet-50", label="Model name")
    53. gr.HTML("""
      """
      )
    54. gr.HTML("""

      2-a. Select an example by clicking a thumbnail below.

      """
      )
    55. gr.HTML("""

      2-b. Or upload an image by clicking on the canvas.

      """
      )
    56. with gr.Row():
    57. input_image = gr.Image(label="Input image", type="pil")
    58. output_image = gr.Image(label="Output image with predicted instances", type="pil")
    59. gr.Examples(['samples/cats.jpg', 'samples/detectron2.png'], inputs=input_image)
    60. gr.HTML("""
      """
      )
    61. gr.HTML("""

      3. Then, click "Infer" button to predict object instances. It will take about 10 seconds (on cpu)

      """
      )
    62. send_btn = gr.Button("Infer")
    63. send_btn.click(fn=infer, inputs=[model, input_image], outputs=[output_image])
    64. gr.HTML("""
      """
      )
    65. gr.HTML("""

      Reference参考链接

      """
      )
    66. gr.HTML("""
        """)
    67. gr.HTML("""
    68. Hands-on tutorial for DETR""")
  • gr.HTML("""
""")
  • #demo.queue()
  • demo.launch(debug=True)
  • 界面及功能都正常,展示如下:

    tips1:运行上述代码,如果报代理错误:

    在终端使用如下代码再重新启动jupyter-noterbook,使用下面命令即可解决:

    (base) jie@dell:~/桌面$ unset all_proxy; unset ALL_PROXY
    

    tip2:如果拖动自己的图片在预测框显示错误,原因是点击预测太快了。需要等图片上传完后点预测才能成功,点太快会出现错误两字。不限制图片尺寸。

    四、入门gradio案例:

    1. import gradio as gr
    2. def greet(name):
    3. return "Hello " + name + "!"
    4. demo = gr.Interface(fn=greet, inputs="text", outputs="text")
    5. demo.launch()

    实现对姓名打招呼的功能,本地服务器的界面如下:

    四、尝试在远程服务器上搭建(重要)

    本人项目链接:https://huggingface.co/spaces/wuqi57/facebook-detr-resnet-50

    在远程服务器上需要下载包和上传模型文件,官方提供了api:

    https://huggingface.co/facebook/detr-resnet-50/tree/main?inference_api=true

    以及打包好的space环境 

    https://huggingface.co/facebook/detr-resnet-50/tree/main?space_deploy=true

    上面两种方式就可以直接使用,直接创建一个app.py文件就可以运行,避免了上传大量的模型文件和下载相应的库。(实例见本人上面的项目链接)

  • 相关阅读:
    行业洞察 | 你的耳机能进行骨传导声纹识别吗?
    同样做软件测试,为什么有人月入3k-5k,有人能拿到17-20k?
    使用react-router-dom在新标签页打开链接,而不是本页跳转
    【数据结构】一篇深入理解二叉树计算
    【Java初阶】面向对象三大特性之封装
    软考-网络信息安全概述
    全文解读 | 五部委印发:元宇宙产业创新发展三年行动计划(2023-2025年)
    铜陵市省重点实验室、省工程技术研究中心认定奖励补贴和申报认定条件流程归集
    云备份——数据信息管理模块
    在CentOS下安装MySQL
  • 原文地址:https://blog.csdn.net/weixin_44162814/article/details/138153029