# 图像质量增强
# client_id 为官网获取的AK， client_secret 为官网获取的SK
import requests
import base64
from loguru import logger
class ImgEnhance:
    def __init__(self):
        self.host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=SEVtEVlQPyqf55mgGt5u5Ad2&client_secret=0CNGhjMrgXRPmDE014S2IXyHLKCuTcfK'
        self.res_token = ''

    # 获取百度api的token
    def get_api_token(self):
        response = requests.get(self.host)
        if response:
            print(response.json())
            access_token = response.json()['access_token']
            self.res_token = access_token
            print(access_token)
            self.Work()
            # self.Img_enlarge()
    # 开始图片增强处理
    def Work(self):
        '''
        图像清晰度增强
        '''
        request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance"
        # 二进制方式打开图片文件
        f = open('./res_assets/test_10.jpg', 'rb')
        img = base64.b64encode(f.read())

        params = {"image": img}
        request_url = request_url + "?access_token=" + self.res_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            imgdata = base64.b64decode(response.json()["image"])
            file = open(r'./res_assets/test_10.jpg', 'wb')
            file.write(imgdata)
            file.close()

    # 图片无损放大
    def Img_enlarge(self):
        '''
        图片无损放大
        '''
        request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance"
        # 二进制方式打开图片文件
        f = open('./res_assets/test_10.jpg', 'rb')
        img = base64.b64encode(f.read())

        params = {"image": img}
        request_url = request_url + "?access_token=" + self.res_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            imgdata = base64.b64decode(response.json()["image"])
            file = open(r'./res_assets/test_10.jpg', 'wb')
            file.write(imgdata)
            file.close()

if __name__ == '__main__':
    Img = ImgEnhance()
    Img.get_api_token()
