1. 필요한 모듈 install

https://zzsza.github.io/mlops/2021/02/07/python-streamlit-dashboard/

https://github.com/zzsza/Boostcamp-AI-Tech-Product-Serving#contributors-

pip install streamlit
# 등등

2. 코드 작성

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()

3. streamlit 외부 접속

# 외부 접속을 하려고 할 때, 아래 그림과 같이 할당된 포트 번호 중 하나를 넣어준다.
# 위의 코드를 app.py에 작성하였을 경우
# stage.ai 서버 터미널에서 실행해야 함!!!
ex) streamlit run app.py --server.port 30001

Untitled

Untitled

Untitled

<aside> 💡 짜잔

</aside>

모피어스.jpg

모피어스.jpg

import streamlit as st
import io
from PIL import Image
import time
import random
import requests
import pandas as pd
import csv
import pymysql
import numpy as np
import base64
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)
    conn = pymysql.connect(
        user='root', 
        passwd='0000', 
        host='localhost', 
        db='pills', 
        charset='utf8'
    )
    cursor = conn.cursor()
    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')
    sql = '''
        SELECT  품목명,큰제품이미지,성상, feature
        from pills_table
        where 색상앞 = '연두' 
        and 의약품제형 = '원형'
    '''
    if uploaded_file_front and uploaded_file_back :
    
        random_feature = np.random.rand(1024)
        if st.button("예측 시작") :
            cursor.execute(sql) 
            res = cursor.fetchall() 
            st.write("예측 완료!")
        
            # 임의로 결과 생성 및 출력
            cols = st.columns(5)
            for i in range(5):

                response = requests.get(res[i][1])
                img = Image.open(io.BytesIO(response.content))

                cols[i].write(f"{i+1}. {res[i][0]}")
                cols[i].image(img)
                cols[i].write(f"성상: {res[i][2]}")  
                feat = np.frombuffer(base64.b64decode(res[i][3].encode('utf-8')), dtype=np.float64)
                cols[i].write(f"점수: {np.dot(feat,random_feature)/(np.dot(feat,feat)*np.dot(random_feature,random_feature) ** 0.5)}")

main()