June's Story

Pytorch 모델 Google Cloud Storage에 올려서 사용하기 본문

프로그래밍

Pytorch 모델 Google Cloud Storage에 올려서 사용하기

Ikjunerd 2022. 4. 7. 11:11

Google Cloud Platform + PHP로 Telegram bot 만들기 에서 만든 봇에서

Telegram bot으로 보낸 사진 Google Cloud Storage에 저장하기 에서 만든 GCS 버킷에 사진을 전달하면 미리 업로드한 pytorch 모델을 가지고 사진을 처리하는 내용

1. Google Cloud Storage 버킷에 미리 트레인한 pytorch 모델 업로드

2. 모델을 실행할 Google Cloud Function 생성

  • 탐색 메뉴에서 Cloud Function 클릭 (메뉴에 없으면 모든 제품 보기로 가서 찾으면 됨)
  • Cloud Function 들어가서 함수 만들기 클릭

  • 함수 만들기 
    • 기본사항
      • 환경: 1세대
      • 함수이름: pytorch_model_test (아무거나 입력)
      • asia-northeast3 
    • 트리거 (버킷에 파일이 업로드 되면 실행하는 함수로 만들기 위해서 다음과 같이 설정)
      • 트리거 유형: Cloud Storage
      • Event type: 완료/생성 
      • 버킷: telegram_bot_test (전에 만든 버킷 이름)
    • 런타임
      • 할당 메모리: 1 GB 
  • 코드 입력 (런타임: Python 3.7)

requirement.txt

1
2
3
4
5
6
7
# Function dependencies, for example:
# package>=version
pillow
google-cloud-storage
--find-links https://download.pytorch.org/whl/torch_stable.html
torch==1.10.0+cpu
https://download.pytorch.org/whl/cpu/torchvision-0.11.0%2Bcpu-cp37-cp37m-linux_x86_64.whl
cs

main.py

BotToken과 버킷 이름을 자기것으로 바꿔서 올리면 됨

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from google.cloud import storage
import requests
from PIL import Image
import numpy as np
import torch
from torchvision import datasets, models, transforms
import torch.nn as nn
 
def hello_gcs(event, context):
     """Triggered by a change to a Cloud Storage bucket.
     Args:
          event (dict): Event payload.
          context (google.cloud.functions.Context): Metadata for the event.
     """
     file = event
     print(f"Processing file: {file['name']}.")
 
     file = event
     inputfilename = file['name']
     chatid = inputfilename.split('.')[0]
     url = 'https://api.telegram.org/bot5156495869:AAGq5jjsBvA_UaeN-eZUXxYgJq7RXzaXd3s/sendmessage'
 
     data = {'chat_id': chatid, 'text''사진 속 동물은...🤔''parse_mode''Markdown'
     res = requests.post(url, data=data)
 
     device = torch.device('cpu')
 
     model = models.resnet50(pretrained=False)
 
     model.fc = nn.Sequential(
          nn.Linear(2048128),
          nn.ReLU(),
          nn.Linear(12864),
          nn.ReLU(),
          nn.Linear(641)) 
 
     client = storage.Client()
     bucket = client.get_bucket('telegram_bot_test')
     blob = bucket.get_blob("cats-vs-dogs-model.pth")
     blob.download_to_filename("/tmp/model.pth")
 
     model.load_state_dict(torch.load('/tmp/model.pth',map_location=device))
 
     blob = bucket.get_blob(inputfilename)
     blob.download_to_filename('/tmp/'+inputfilename)
 
     testee_img = Image.open('/tmp/'+inputfilename)
 
     data_transforms = {
          'test': transforms.Compose([
               transforms.Resize((224224)),
               transforms.ToTensor(),
               transforms.Normalize([0.4850.4560.406], [0.2290.2240.225])
          ]),
     }
 
     testee_input = data_transforms['test'](testee_img)
     testee_batch = torch.stack([testee_input, testee_input])
 
     testee_batch = testee_batch.to(device)
     output = model(testee_batch)
 
     decisions = torch.sigmoid(output).cpu().data.numpy()
 
     prediction = decisions[0,0> 0.5
 
     feeling = '😉'
     if decisions[0,0> 0.6:
          feeling = '😀'
     else
          feeling = '🙄'
 
     text = '몰라요'
     if prediction:
          text = '개입니다. ' + feeling
     else:
          text = '고양이입니다. '  + feeling
 
     data = {'chat_id': chatid, 'text': text, 'parse_mode''Markdown'
     res = requests.post(url, data=data)    
cs

 

  • 와 같이 두 파일을 수정하고 배포 클릭 (배포 시간이 좀 걸림)
  • python 들여쓰기 잘 못돼서 오류 발생할 수 있는데, 오류 발생하면 로그 보기로 확인해서 그부분 수정하면 됨
    (Cloud function 오른쪽 끝에 점 세개 누르면 로그 보기 있음)
  • 배포 완료되면 다음과 같이 나옴

3. Telegram bot 에서 테스트

Comments