본문으로 바로가기

(Python) PAPAGO OCR번역 API코드

category Python 2024. 6. 7. 00:33

개요

papago api를 사용해 이미지를 자동번역하기위한 코드이다.

 

확장자로 이미지 검색 후 가져오기

names = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif", ".webp"]
TITLE = "폴더의 제목" # 번역할 이미지가 들어있는 폴더의 제목을 넣어준다.

API_KEY_ID = "Client ID를 넣어준다"
API_KEY = "Client Secret을 넣어준다"

 

폴더 생성 함수

import os

def createFolder(directory, ROOTPATH = ''):
    '''
    directory = 폴더명, ROOTPATH = 절대경로를 지정할 때 사용하면 좋습니다.
    생성된 폴더의 절대(존재한다면)경로를 directory명 + _PATH 변수로 반환합니다.
    '''
    try:
        if not os.path.exists(directory):
            os.makedirs(ROOTPATH + directory)
            globals()["{}_PATH".format(directory)] = ROOTPATH + directory
    except OSError:
        print (directory, "폴더를 생성할 수 없습니다.")

 

이미지들의 경로 가져오기

import glob
import natsort

# folder_path = "이미지 폴더의 경로" ## 절대경로로 이미지를 찾을 사람을 위한 코드

output = []

for i in names:
    output += glob.glob(f'{folder_path}\\{TITLE}\\*{i}')
after_order_list = natsort.natsorted(output)
print(after_order_list)
print(len(after_order_list))

 

webp파일 png파일로 컨버팅하기

- webp 파일은 번역할 수 없기 때문에 png 파일로 컨버팅해준다

# webp을 png로 변경

from PIL import Image
import os
from tqdm import tqdm

if len(output) >= 1: 
    for i in tqdm(after_order_list):
        im = Image.open(i).convert("RGB")
        im.save(i[:-4] + "png", "png")
    [os.remove(f) for f in glob.glob(f'{folder_path}\\{TITLE}\\*.webp')]
    after_order_list = glob.glob(f'{folder_path}\\{TITLE}\\*png')
    print(after_order_list)

 

해상도 맞춰주기

- 가로길이 또는 세로길이가 1960px을 넘어가면 번역이 불가능하기 때문에 1960으로 맞춰준다.

# 해상도 변경

import shutil

shutil.copytree(f"{folder_path}" + str(TITLE), f"{folder_path}" + str(TITLE) + "temp")

from PIL import Image
from tqdm import tqdm

after_order_list = glob.glob(f'{folder_path}\\{TITLE}temp\\*png')

for i in tqdm(after_order_list):
    img = Image.open(i)

    if (img.width > 1960) & (img.width > img.height):
        img_resize = img.resize((int(1960), int(img.height * 1960 / img.width)))
    elif (img.height > 1960) & (img.width < img.height):
        img_resize = img.resize((int(img.width * 1960 / img.height), int(1960)))
    elif (img.width > 1960) & (img.width == img.height):
        img_resize = img.resize((int(1960), int(1960)))
    else:
        img_resize = img.resize((int(img.width), int(img.height)))
    img_resize.save(i)

 

번역

언어 code
한국어 ko
영어 en
일본어 ja
중국어 간체 zh-CN
중국어 번체 zh-TW
베트남어 vi
태국어 th
인도네시아 id
프랑스 fr
스페인 es
러시아 ru
독일 de
이탈리아 it
import requests
from requests_toolbelt import MultipartEncoder
import uuid
import json
import base64
from tqdm import tqdm
import shutil

data_list = []

createFolder(TITLE + "translated", ROOTPATH = f"{folder_path}")
count = 0
temp = after_order_list
except_count = 0

# for n in tqdm(temp):
  data = {
    'source': 'auto',
    'target': 'ko',
    'image': (n, open(n, 'rb'), 'application/octet-stream', {'Content-Transfer-Encoding': 'binary'})
  }
  m = MultipartEncoder(data, boundary=uuid.uuid4())

  headers = {
    "Content-Type": m.content_type,
    "X-NCP-APIGW-API-KEY-ID": API_KEY_ID,
    "X-NCP-APIGW-API-KEY": API_KEY
  }
  try:
    url = "https://naveropenapi.apigw.ntruss.com/image-to-image/v1/translate"
    res = requests.post(url, headers=headers, data=m.to_string())
    # print(res.text)

    # renderedImage -> 이미지 파일로 출력
    resObj = json.loads(res.text)
    imageStr = resObj.get("data").get("renderedImage")
    imgdata = base64.b64decode(imageStr)

    data_list.append(data)

    if count < 10:
      filename = f'{folder_path}\\{TITLE}translated\\000{count}.png'
      count += 1
      with open(filename, 'wb') as f:
          f.write(imgdata)
    elif count < 100:
      filename = f'{folder_path}\\{TITLE}translated\\00{count}.png'
      count += 1
      with open(filename, 'wb') as f:
          f.write(imgdata)
    elif count < 1000:
      filename = f'{folder_path}\\{TITLE}translated\\0{count}.png'
      count += 1
      with open(filename, 'wb') as f:
          f.write(imgdata)
    else:
      filename = f'{folder_path}\\{TITLE}translated\\{count}.png'
      count += 1
      with open(filename, 'wb') as f:
          f.write(imgdata)
  except:
     except_count += 1
     if count < 10:
      destination = f'{folder_path}\\{TITLE}translated\\000{count}.png'
      shutil.copyfile(n, destination)
     elif count < 100:
      destination = f'{folder_path}\\{TITLE}translated\\00{count}.png'
      shutil.copyfile(n, destination)
     elif count < 1000:
      destination = f'{folder_path}\\{TITLE}translated\\0{count}.png'
      shutil.copyfile(n, destination)
     else:
      destination = f'{folder_path}\\{TITLE}translated\\{count}.png'
      shutil.copyfile(n, destination)
     count += 1
print(len(temp), except_count)
if os.path.exists(f"{folder_path}" + str(TITLE) + "temp"):
    shutil.rmtree(f"{folder_path}" + str(TITLE) + "temp")