boostcampaitech3 / final-project-level3-cv-16

👀 너의 알약이 보여 💊 : 알약 이미지 분류 프로젝트
5 stars 6 forks source link

[Dev][Enhancement] Implementing a webpage view using streamlit #11

Closed ghost closed 2 years ago

ghost commented 2 years ago

What

streamlit을 사용한 웹페이지 뷰 구성

Why

사용자가 보기 편하면서, 동시에 구현하기 쉽기 때문에 streamlit으로 작성

How

ghost commented 2 years ago
import streamlit as st
import io
from PIL import Image
import time
import random
import requests
import pandas as pd
import csv

st.set_page_config(page_title = "빨간 알약 줄까? 파란 알약 줄까?", layout="centered", page_icon = "pill")

def main():

    st.image(Image.open('모피어스.jpg'))

    st.sidebar.title("사용법")
    st.sidebar.subheader("1. 알아보고 싶은 알약의 앞면과 뒷면이 잘 보이도록 사진을 각각 한 장씩 찍습니다.")
    st.sidebar.subheader("2. 찍은 알약의 앞면 사진을 상단에, 뒷면 사진을 하단에 업로드합니다.")
    st.sidebar.subheader("3. 앞면 사진과 뒷면 사진을 업로드하였다면 아래의 버튼을 눌러줍니다.")
    st.sidebar.subheader("4. 업로드한 사진과 유사한 알약을 k개까지 웹페이지 상으로 보여줍니다.")

    col1, col2 = st.columns(2)
    col3, col4 = st.columns(2)

    uploaded_file_front = col1.file_uploader("알약 앞면 사진을 올려주세요.", type=["jpg", "jpeg", "png"])

    if uploaded_file_front:
        image_bytes = uploaded_file_front.getvalue()
        image = Image.open(io.BytesIO(image_bytes))
        col3.image(image, caption='Pill front')

    uploaded_file_back = col2.file_uploader("알약 뒷면 사진을 올려주세요.", type=["jpg", "jpeg", "png"])

    if uploaded_file_back:
        image_bytes = uploaded_file_back.getvalue()
        image = Image.open(io.BytesIO(image_bytes))
        col4.image(image, caption='Pill back')

    if uploaded_file_front and uploaded_file_back :

        pill_data = pd.read_csv('./pill_info.csv', encoding = 'UTF-8')

        if st.button("예측 시작") :
            with st.spinner("Please wait..."):
                time.sleep(5)
            st.write("예측 완료!")

            # 임의로 결과 생성 및 출력
            cols = st.columns(5)
            rand_num = random.sample(range(24318), 5)
            for i in range(5):
                result_pill = pill_data.iloc[rand_num[i]]

                response = requests.get(result_pill[5])
                img = Image.open(io.BytesIO(response.content))

                cols[i].write(f"{i+1}. {result_pill[1]}")
                cols[i].image(img)
                cols[i].write(f"성상: {result_pill[4]}")

main()

아래에 있는 다빈님의 "알약 csv 파일 데이터를 받아와서 출력하는 기능"을 추가하였습니다. + random 그리고 변수명을 uploaded_file1에서 uploaded_file_front로, uploaded_file2에서 uploaded_file_back으로 변경하였습니다. (다빈님 코드와 동일하게 설정)

기능 추가 시, 해당 comment의 코드도 업데이트 예정입니다.

ghost commented 2 years ago

image

우선 뷰는 이런 느낌입니다! 이것도 마찬가지로 코드 변경 시 해당 comment도 업데이트 하겠습니다!

SSANGYOON commented 2 years ago

혹시 모피어스 사진을 추가해주실 수 있을까요?(손만 나와도 됩니다)

ghost commented 2 years ago

streamlit 외부 접속 구현하였고, 해당 내용은 https://seoulsky-field.notion.site/streamlit-c4b6bf6faad346119fb2c789a083a0ce 에 정리하였습니다. 그리고 모피어스.jpg는 아래에 업로드 하겠습니다. 자막은 추후에 시간이 되면 추가하도록 하겠습니다. 모피어스

sodabeans commented 2 years ago

알약 csv 파일 데이터를 받아와서 출력하도록 해봤습니다. 아직 모델을 추가하지 않아서 임의로 선택한 5개의 알약 정보를 받아오도록 했습니다. 아래 코드는 main함수 일부입니다. 이미지 업로드 다음 부분에 해당됩니다. 변수명은 위에 @tnsgh9603 이 작성해주신 코드와 다릅니다! (eg. uploaded_file1 == uploaded_file_front)

import streamlit as st
import random
import csv
import io
import requests
from PIL import Image
import pandas as pd

...

# in main function
pill_data = pd.read_csv('pill_info.csv', encoding = 'UTF-8')
if uploaded_file_front and uploaded_file_back:
        if st.button("시작"):
            st.write("분석중...")
            # TODO: 모델 예측 결과 가져오기
            st.write("분석 완료!")

            # 임의로 결과 생성 및 출력
            cols = st.columns(5)
            rand_num = random.sample(range(24318), 5)
            for i in range(5):
                result_pill = pill_data.iloc[rand_num[i]]

                response = requests.get(result_pill[5])
                img = Image.open(io.BytesIO(response.content))

                cols[i].write(f"{i+1}. {result_pill[1]}")
                cols[i].image(img)
                cols[i].write(f"성상: {result_pill[4]}")