import os
import oss2

def get_model(name):
    os.makedirs(os.path.join(os.path.dirname(__file__), "model"), exist_ok=True)
    fn = os.path.join(os.path.dirname(__file__), "model", name)
    if os.path.exists(fn):
        return fn
    with open(fn + ".tmp", 'wb') as tf:
        print(f"Downloading {name}...")
        tf.write(oss_get(name, "emblem-models"))
        print(f"Downloaded {name}")
    os.rename(fn + ".tmp", fn)
    return fn

def oss_get(name, bucket=None):
    try:
        return oss_bucket(bucket).get_object(name).read()
    except oss2.exceptions.NoSuchKey:
        return None

def oss_bucket(bucketname):
    auth = oss2.Auth('LTAI5tC2qXGxwHZUZP7DoD1A', 'qPo9O6ZvEfqo4t8oflGEm0DoxLHJhm')
    bucket = oss2.Bucket(auth, 'oss-rg-china-mainland.aliyuncs.com', bucketname)
    return bucket

if __name__ == "__main__":
    print(get_model('sr.prototxt'))
