import torch
import random
import numpy as np
import json
from PIL import Image
import os
from os import PathLike 

def setup_seed(seed):
     torch.manual_seed(seed)
     torch.cuda.manual_seed_all(seed)
     np.random.seed(seed)
     random.seed(seed)
     torch.backends.cudnn.deterministic = True


# with open("answer_BLIPOPT_relations.json","r+") as f:
#     predict = json.loads(f.read())


# for img in predict:
#     if predict[img]["gold"].strip().lower() == predict[img]["predict"].lower():
#         print(img, predict[img])



#判断文件是否为有效（完整）的图片
#输入参数为文件路径，或文件对象
def IsValidImage(file): 
    bValid = True
    if isinstance(file, (str, PathLike)):
        fileObj = open(file, 'rb')
    else:
        fileObj = file
    
    buf = fileObj.read()
    if buf[6:10] in (b'JFIF', b'Exif'):     #jpg图片
        if not buf.rstrip(b'\0\r\n').endswith(b'\xff\xd9'):
            bValid = False
    else:        
        try:  
            Image.open(fileObj).verify() 
        except:  
            bValid = False
         
    return bValid
     
     
#判断文件是否为有效（完整）的图片
#输入参数为bytes，如网络请求返回的二进制数据
def IsValidImage4Bytes(buf): 
    bValid = True
    try:  
        Image.open(io.BytesIO(buf)).verify() 
    except:  
        bValid = False
         
    return bValid
    
    
#判断文件是否为有效（完整）的图片
#输入参数为bytes，如网络请求返回的二进制数据
def IsValidImage4Bytes(buf): 
    bValid = True
    if buf[6:10] in (b'JFIF', b'Exif'):     #jpg图片
        if not buf.rstrip(b'\0\r\n').endswith(b'\xff\xd9'):
            bValid = False
    else:        
        try:  
            Image.open(io.BytesIO(buf)).verify() 
        except:  
            bValid = False
         
    return bValid

