首頁  >  文章  >  後端開發  >  使用 Streamlit 製作 Web 應用程式是如此簡單

使用 Streamlit 製作 Web 應用程式是如此簡單

DDD
DDD原創
2024-10-23 21:25:02934瀏覽

Making a Webapp is so EASY with Streamlit

Streamlit 在資料科學家中很受歡迎,因為您通常不需要前端知識。

它們提供簡單且易於實現的元素和小部件,無需編寫太多程式碼。

我在 ML/AI 專案中多次使用了 Streamlit,體驗非常棒。你可以更專注於編寫邏輯,前端部分(設計、佈局等)由streamlit處理得很好。

我使用 Streamlit 和 Python 創建了一個演示 Web 應用程序,以便您可以理解我在說什麼。

網路應用程式

這個網頁應用程式是將圖像格式轉換為另一種格式,例如,如果您的圖像是PNG格式,您可以將其轉換為JPEG圖像。

以下程式碼製作了 web 應用程式的使用者介面。

import streamlit as st
from imgconvrtr import convert_img_format
from PIL import Image

# Webpage setup
st.set_page_config(page_title="Image Convrtr")
st.title("Image Converter")
st.write("Convert your images in one _click_")

# File uploader
uploaded_file = st.file_uploader(
    "Upload an image",
    type=["png", "jpg", "jpeg", "jfif", "bmp"]
)

if uploaded_file is not None:
    # Show the uploaded image
    img = Image.open(uploaded_file)
    st.image(img, caption="Uploaded Image", use_column_width=True)

    # Show original image format
    st.write(f"Original format: {img.format}")

    # Output format selection
    format_options = ["PNG", "JPEG", "JFIF", "BMP"]
    output_format = st.selectbox("Choose output format", format_options)

    # Convert the image
    if img.format != output_format:
        if st.button("Convert"):
            converted_img = convert_img_format(uploaded_file, output_format.lower())
            st.write(f"Image converted to {output_format}")

            # Download button
            st.download_button(
                label=f"Download as {output_format}",
                data=converted_img,
                file_name=f"image.{output_format.lower()}",
                mime=f"image/{output_format.lower()}"
            )
    else:
        st.write("Select a different format... Yo!")

現在您已經大致了解了這個網頁應用程式的用途。我們可以直接跳到討論此程式碼中使用的元件。

一開始,你可以看到 st.title 和 st.write 等頁面元素,分別用於設定頁面標題和在頁面上顯示文字。

接下來,您可以看到一個用於上傳檔案的小部件(在本例中用於上傳圖像)。了解建立文件上傳器是多麼容易。

st.image 用來顯示使用者上傳的圖片。

然後我們有一個下拉式選單來選擇使用選擇框(st.selectbox)小工具建立的各種格式。

現在,您可以看到我們有兩個按鈕(st.button 和 st.download_button)。它們都是一樣的,但都是為了方便。

st.button 顯示我們在這裡用於影像轉換的按鈕小工具。

當使用者需要直接從應用程式下載檔案時,st.download_button 非常有用。

Streamlit 提供了許多用於不同目的的元素和小部件。

現在如果你想嘗試這個網頁應用程序,你需要安裝所需的函式庫:

pip install streamlit pillow

這是影像轉換函數:

from PIL import Image
import io

# Function to convert image format
def convert_img_format(image_file, frmat):
    with Image.open(image_file) as img:
        output_img = io.BytesIO()
        img.save(output_img, format=frmat.upper())
        output_img.seek(0)
        return output_img

使用以下命令執行應用程式:

streamlit run <script_name>.py

替換為實際的腳本名稱。


現在就這些。
繼續編碼✌✌

以上是使用 Streamlit 製作 Web 應用程式是如此簡單的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn