응답을 저장해놓으면 돌릴때마다 api call을 안해도 되서 좋습니다.(횟수 초과 과금방지) response_body = json.loads(response.text) "> 응답을 저장해놓으면 돌릴때마다 api call을 안해도 되서 좋습니다.(횟수 초과 과금방지) response_body = json.loads(response.text) "> 응답을 저장해놓으면 돌릴때마다 api call을 안해도 되서 좋습니다.(횟수 초과 과금방지) response_body = json.loads(response.text) ">
#api key 입력
api_url = '<https://mtrekq4jam.apigw.ntruss.com/custom/v1/22408/ddaf31abb4e57d9a918aef4215fd37bcd52eaf59e25cfb4582271a5819528eeb/document/receipt>'
secret_key = 'R3FzanNtWERQTUtkUVhsV3hjR1BvUFljRHJFUHlMQm4='

import requests
import uuid
import time
import json

#로컬에 저장된 사진입니다.
image_file = '영수증_2.jpeg' 

#api
request_json = {
  "version": "V2",
  "requestId": "string",
  "timestamp": 0,
  "images": [
    {
      "format": "jpg",
      "name": "test 1",
      "data": "data"
    }
  ]
}

payload = {'message': json.dumps(request_json).encode('UTF-8')}
files = [
  ('file', open(image_file,'rb'))
]
headers = {
  'X-OCR-SECRET': secret_key
}
#요청과 응답을 저장
response = requests.request("POST", api_url, headers=headers, data=payload, files=files)
#응답을 텍스트로 저장 -> 응답을 저장해놓으면 돌릴때마다 api call을 안해도 되서 좋습니다.(횟수 초과 과금방지)
response_body = json.loads(response.text)

images = response_body['images']
images_receipt = images[0].get("receipt")

#가게정보와 결제정보등은 내부에 배열이 하나씩있어서 이름으로 인덱싱이 간단함
receipt_memo = images_receipt['result']['storeInfo']['name']['text']
receipt_date = images_receipt['result']['paymentInfo']['date']['text']
receipt_price = images_receipt['result']['totalPrice']['price']['text']

#상품명에 경우 같은 이름이 없고 같은 배열이 여러개가 있어서 숫자로 나눠주어야함
my_list = images_receipt['result']['subResults'][0]['items']

for i in range(len(my_list)):
    print(images_receipt['result']['subResults'][0]['items'][i]['name']['text']
         ,"\\n\\t\\t 수량 : ",
          images_receipt['result']['subResults'][0]['items'][i]['count']['text']
         ,"\\n"
          
)
#구조 설명
subResults: [
{
    items: [#이렇게 {}로 묶인 경우 떄문에 숫자로 인덱스를 해야합니다.
        {3 items}, ->아래 내부 구조 A 설명
        {3 items},
        {3 items},
        {3 items}
    ]
    }
],

A 설명 items 첫번째{} 내부 구조

{
    name: {
        text: "씨그램 레몬350ml",
        formatted: {1 item},
        boundingBoxes: [2 items]
    },
    count: {3 items},
    priceInfo: {2 items}
},

images_receipt['result']['subResults'][0]['items']의 사이즈를 for문으로 돌림 -> 4개
4개의 아이템 내부 ['name']['text']를 출력

api로 사진을 보내기 위한 로컬 테스트를 진행을 했다. ec2로 넘어가는 사진을 저장하는 것을 확인하기 위함인데 프론트 엔드의 역할은 사용자의 이미지를 api로 넘기는 역할이다.

아주 기본적이 api 통신을 해본다. 로컬에서 api가 잘 요청이 되고 반환이 된다.

Untitled

Untitled