node5265/virtual-try-on
0
1import json2import os3import re4from collections import defaultdict5from datetime import datetime, timedelta, timezone6 7import huggingface_hub8from huggingface_hub import ModelCard9from huggingface_hub.hf_api import ModelInfo10from transformers import AutoConfig11from transformers.models.auto.tokenization_auto import AutoTokenizer12 13def check_model_card(repo_id: str) -> tuple[bool, str]:14 """Checks if the model card and license exist and have been filled"""15 try:16 card = ModelCard.load(repo_id)17 except huggingface_hub.utils.EntryNotFoundError:18 return False, "Please add a model card to your model to explain how you trained/fine-tuned it."19 20 # Enforce license metadata21 if card.data.license is None:22 if not ("license_name" in card.data and "license_link" in card.data):23 return False, (24 "License not found. Please add a license to your model card using the `license` metadata or a"25 " `license_name`/`license_link` pair."26 )27 28 # Enforce card content29 if len(card.text) < 200:30 return False, "Please add a description to your model card, it is too short."31 32 return True, ""33 34def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:35 """Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""36 try:37 config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)38 if test_tokenizer:39 try:40 tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)41 except ValueError as e:42 return (43 False,44 f"uses a tokenizer which is not in a transformers release: {e}",45 None46 )47 except Exception as e:48 return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)49 return True, None, config50 51 except ValueError:52 return (53 False,54 "needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",55 None56 )57 58 except Exception as e:59 return False, "was not found on hub!", None60 61 62def get_model_size(model_info: ModelInfo, precision: str):63 """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""64 try:65 model_size = round(model_info.safetensors["total"] / 1e9, 3)66 except (AttributeError, TypeError):67 return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py68 69 size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 170 model_size = size_factor * model_size71 return model_size72 73def get_model_arch(model_info: ModelInfo):74 """Gets the model architecture from the configuration"""75 return model_info.config.get("architectures", "Unknown")76 77def already_submitted_models(requested_models_dir: str) -> set[str]:78 """Gather a list of already submitted models to avoid duplicates"""79 depth = 180 file_names = []81 users_to_submission_dates = defaultdict(list)82 83 for root, _, files in os.walk(requested_models_dir):84 current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)85 if current_depth == depth:86 for file in files:87 if not file.endswith(".json"):88 continue89 with open(os.path.join(root, file), "r") as f:90 info = json.load(f)91 file_names.append(f"{info['model']}_{info['revision']}_{info['precision']}")92 93 # Select organisation94 if info["model"].count("/") == 0 or "submitted_time" not in info:95 continue96 organisation, _ = info["model"].split("/")97 users_to_submission_dates[organisation].append(info["submitted_time"])98 99 return set(file_names), users_to_submission_dates100 