# shellcheck shell=dash

# get huggingface token from https://huggingface.co/settings/tokens

x log init huggingface

xrc:mod:lib     huggingface     ddgo

___x_cmd_huggingface___main(){
    [ "$#" -gt 0 ] ||   set - -h

    local op="$1"; shift
    case "$op" in
        -h|--help)          ___x_cmd help -m huggingface ;;
        model)              ___x_cmd_huggingface_model  "$@" ;;

        :|ddgo)             ___x_cmd_huggingface_ddgo   "$@" ;;

        --publicdownload)
            ___x_cmd_huggingface___"${op#--}" "$@" ;;
    esac
}

___x_cmd_huggingface___publicdownload(){
    local x_
    case "$1" in
        http://*|https://*)
            x_="$1" ;;
        *)
            ___x_cmd_huggingface___publicurl_;
            x_="$x_/${1#/}"
    esac
    local model_name;   local model_path
    model_path="$___X_CMD_ROOT_DATA/model"
    if [ -n "$2" ]; then
        model_name="${2##*/}"
        model_path="${2%/*}"
        [ "$model_name" != "$model_path" ] || model_path="$___X_CMD_ROOT_DATA/model"
    else
        model_name="${x_##*/}"
        model_path="$___X_CMD_ROOT_DATA/model"
    fi


    ___x_cmd mkdirp "$model_path"
    huggingface:info "download [model=$model_name]"
    ___x_cmd curl --fail -L -C - -o "$model_path/$model_name" "$x_" || return 1
}

# https://huggingface.co/jartine/phi-2-llamafile/resolve/main/phi-2.Q8_0.llamafile
___x_cmd_huggingface___publicurl_(){
    x_=https://huggingface.co
    ! ___x_cmd websrc is cn || x_=https://hf-mirror.com
}
