Google Cloud Platform

Local환경 GCE 연동

GinaKim 2024. 4. 23. 11:25
728x90

키 파일 다운까지 완료한 상태에서 진행

 

BigQuery Local 환경 연동

인증키 생성 - API 및 서비스 > BigQuery - 사용자 인증정보 만들기 - 애플리케이션 데이터 선택 > 다음 > 서비스 아이디 입력 > 만들고 계속하기 > 역할 소유자로 선택 > 완료 - IAM 및 관리자 > 서비스계

didikimd.tistory.com

 

conda 가상환경 생성

- conda 가상환경 라이브러리 관리는 environment.yml 파일로 함

  • environment.yml
    • name에는 가상환경 이름, conda로 설치할 라이브러리는 dependencies, conda로 설치 안되는 라이브러리는 pip으로 설정
name: condagcp2
channels:
  - defaults
dependencies:
  - python=3.11
  - numpy
  - pandas
  - matplotlib
  - plotly
  - pip:
      - streamlit
      - google-cloud-bigquery 
      - pandas-gbq

 

- 아래 코드로 가상환경 설정 및 라이브러리 설치

conda env create -f .\environment.yml

 

- 설치 완료되면 conda 가상환경 접속

conda activate 가상환경이름

 

- streamlit app.py 파일 실행해서 가상환경 설치가 잘 되었는지, bigqurey 연동 잘 되었는지 확인

# -*- coding:utf-8 -*-

import streamlit as st 
import matplotlib.pyplot as plt 
from google.oauth2 import service_account
from google.cloud import bigquery
import plotly.express as px
import google.auth
from google.auth import compute_engine

# Local에 저장된 json 파일 불러오기
try:
    credentials = service_account.Credentials.from_service_account_file(r'.streamlit\mulcamp-project-ff28eff3ad75.json')
except:
    credentials, project_id = google.auth.default()
    credentials = compute_engine.Credentials(
        service_account_email=credentials.service_account_email)

# GCP 프로젝트
project_id = 'mulcamp-project'
client = bigquery.Client(credentials = credentials, project=project_id)

@st.cache_data(ttl=600)
def getData(query):
    data = client.query(query).to_dataframe()
    int64_columns = data.select_dtypes(include='Int64').columns
    data[int64_columns] = data[int64_columns].astype('float64')
    print(data.info())
    return data

def plotly_chart(data, feature):
    main_features = ['LotArea', 'GrLivArea', 'SalePrice']
    chart_features = main_features + [feature]
    DF = data[chart_features]

    # main plot (scatter)
    fig = px.scatter(DF,
                    x='GrLivArea',
                    y='SalePrice',
                    color=feature,
                    size='LotArea',
                    width=750,
                    height=400)

    # annotation (text)
    fig.add_annotation(text="Possible outliers",
                    xref="x", yref="y",
                    x=6200,y=160000,
                    showarrow = True,                   
                    yshift=30,
                    xshift=-60,
                    font=dict(
                        family="sans serif",
                        size=12,
                        color="LightSeaGreen"
                        )
                    )
    # annotation (box)
    fig.add_shape(type="rect",
                xref="x", yref="y",
                x0=4500, x1=5800, y0=100000, y1=250000,
                fillcolor="lightgray",    
                line_color="black",
                opacity=0.3
                )
    # update the plot
    fig.update_layout(title='<b>House Price vs GrLivArea<b>',
                    titlefont={'size': 24}
                    )
    st.plotly_chart(fig)

def main():
    st.title("Hello GCP from Local")
    fig, ax = plt.subplots(figsize=(10, 6))
    ax.plot([1, 2, 3, 4, 3, 2, 1])
    ax.set_title("Hello Plot from Local PC")
    st.pyplot(fig)
    
    st.markdown("<hr>", unsafe_allow_html = True)
    st.markdown("""
    <style>
    .gcp-font {
        font-size:32px !important;
    }
    </style>
    """, unsafe_allow_html=True)

    st.markdown('<p class="gcp-font">BigQuery with Streamlit</p>', unsafe_allow_html=True)

    query = '''
        SELECT * FROM `mulcamp-project.kaggle.train`
    '''

    data = getData(query)
    st.dataframe(data.head(3))

    object_feature = st.selectbox("Select....", ("OverallQual", "ExterQual", "RoofStyle"), index=0) 
    plotly_chart(data, object_feature)
    st.markdown('<p class="gcp-font">BigQuery with Streamlit in GCP 성공!!</p>', unsafe_allow_html=True)

    

if __name__ == "__main__":
    main()

 

- 문제없이 잘 되는 것 확인 후, git commit

(이미 git actions 설정을 해두었기에, SSH 클라우드에 자동으로 git pull 됨)

git add .
git commit -m "커밋메시지"
git push

 

- GCE에서도 동일하게 가상환경 생성 후, app.py 잘 실행되는지 확인

- 잘 실행되면 nohup 배포

nohup streamlit run app.py > streamlit.log 2>&1 &

 

- 외부 IP:8501해서 잘 보이는지 확인하면 성공!

728x90