Machine Learning Web App

107 阅读2分钟

machine_learning_web_app: buiding a machine learning web app with streamlit, fastapi and docker (gitee.com)

Principle

image.png

  • frontend: streamlit

Its goal is to enable data scientists to release applications without requiring the assistance of a development team.

Streamlit allows to build an app making predictions using a trained model, with very few lines of code handling the user interface and controls, and almost no design efforts.

app.py

import streamlit as st

import numpy as np
import pandas as pd

st.markdown("""# This is a header
## This is a sub header
This is text""")

df = pd.DataFrame({
          'first column': list(range(1, 11)),
          'second column': np.arange(10, 101, 10)
        })

# this slider allows the user to select a number of lines
# to display in the dataframe
# the selected value is returned by st.slider
line_count = st.slider('Select a line count', 1, 10, 3)

# and used in order to select the displayed lines
head_df = df.head(line_count)

head_df
streamlit run app.py
  • backend: fastapi

FastAPI uses python decorators in order to link the routes that the developers will query to the code of the endpoints. The code of the decorated function will be called whenever an HTTP request is received. The response will be returned as a JSON object to the code querying the API.

  • uvicorn

Unicorn is a lightning fast web server for python.

Uvicorn listens to all the HTTP requests and calls the code decorated for the corresponding FastAPI endpoints.

uvicorn simple:app --reload

配置云服务器

在本地terminal中运行 ssh-keygen and type .\ssh\id_rsa.pub,会生成密钥

在云服务器的root的terminal中运行:(在.ssh文件夹中) echo "密钥" >> authorized_keys

cat authorized_keys

就可以在本地terminal登录了

ssh root@<弹性ip>

Configure security group

入口规则:TCP 改为5000-9999(否则之后的8000端口没法访问) ICMP

ping <弹性ip>

Linux命令

mkdir gitee

cd gitee

git clone <source link>

在云服务器安装所需要的包

如果你希望使用 pip 安装,确保你的系统已经安装了 libuv 库。你可以使用以下命令安装 libuv:

sudo apt-get install libuv1-dev # 对于Debian/Ubuntu

sudo yum install libuv-devel # 对于CentOS/RHEL

然后就可以使用 pip 安装

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

nohup使terminal关闭也可访问

nohup uvicorn backend:app --host 0.0.0.0 --port 8000 > nohup_log.tx t

nohup streamlit run frontend.py > nohup.txt &

使用docker部署

在linux安装docker

依据Dockerfile文件build镜像

docker build -t harryandjack/webapp .

RUN 后端

docker run -p 8888:8888 harryandjack/webapp

nohup docker run -p 8888:8888 harryandjack/webapp > nohup.txt & / docker run -d -p 8888:8888 harryandjack/webapp

访问124.71.176.65:8888

前端

killall streamlit

nohup streamlit frontend.py > nohup.txt &

访问124.71.176.65:8501