File size: 1,944 Bytes
9e43cb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import os
from pathlib import Path


os.environ['HF_OUTPUT_REPO'] = 'votepurchase/pony' # The name of the 'model' repo to upload to. private repo recommended.
# Set HF write token to HF_TOKEN as SECRET (never as environment)


def upload_to_repo(path, filename):
    from huggingface_hub import HfApi, hf_hub_url
    hf_token = os.environ.get("HF_TOKEN")
    repo_id = os.environ.get("HF_OUTPUT_REPO")
    api = HfApi()
    try:
        api.upload_file(path_or_fileobj=path, path_in_repo=filename, repo_id=repo_id, token=hf_token)
        url = hf_hub_url(repo_id=repo_id, filename=filename)
    except Exception as e:
        print(f"Error: Failed to upload to {repo_id}. ")
        return None
    return url

def upload_image(path, filename):
    url = upload_to_repo(path, filename)
    print(url) # for debug
    return url


def compose_image_url(repo_id, filename): # Can be used in local environment
    from huggingface_hub import hf_hub_url
    url = hf_hub_url(repo_id=repo_id, filename=filename)
    return url


def is_exists_image(filename): # Can be used in local environment
    from huggingface_hub import HfApi
    hf_token = os.environ.get("HF_TOKEN")
    repo_id = os.environ.get("HF_OUTPUT_REPO")
    api = HfApi()
    try:
        is_exists = api.file_exists(repo_id=repo_id, filename=filename, token=hf_token)
    except Exception as e:
        return None
    return is_exists


def download_image(filename): # Can be used in local environment
    from huggingface_hub import HfApi
    hf_token = os.environ.get("HF_TOKEN")
    repo_id = os.environ.get("HF_OUTPUT_REPO")
    api = HfApi()
    try:
        if is_exists_image:
            api.hf_hub_download(repo_id=repo_id, filename=filename, local_dir=".", token=hf_token)
    except Exception as e:
        return

#  HfApi Client Document: https://huggingface.co/docs/huggingface_hub/package_reference/hf_api