GGUF-Splitter / src /hf_utils.py
Felladrin's picture
Initial commit
2de2584
"""Hugging Face API utilities"""
import re
from typing import Optional
from huggingface_hub import HfApi
from huggingface_hub.errors import RepositoryNotFoundError
from huggingface_hub.utils import validate_repo_id
try:
from huggingface_hub import repo_exists as hf_repo_exists
_use_official_repo_exists = True
except ImportError:
hf_repo_exists = None
_use_official_repo_exists = False
def extract_quantization(filename: str) -> str:
"""Extract quantization from GGUF filename"""
match = re.search(r"((?:B?F16)|Q[0-9]+(?:_[0-9]+)?(?:_[A-Z]+)*)", filename, re.IGNORECASE)
return match.group(1) if match else "Unknown"
def check_repo_exists(repo_id: str, api: HfApi) -> bool:
"""Check if a Hugging Face repository exists"""
if _use_official_repo_exists and hf_repo_exists:
return hf_repo_exists(repo_id, token=getattr(api, "token", None))
try:
api.list_repo_files(repo_id)
return True
except RepositoryNotFoundError:
return False
except Exception:
return False
def get_gguf_files_from_repo(repo_id: str, api: HfApi) -> list:
"""Get list of .gguf files from a repository"""
try:
return [
path
for path in api.list_repo_files(repo_id)
if isinstance(path, str) and path.endswith(".gguf")
]
except Exception:
return []
def extract_username(user_info: object) -> Optional[str]:
"""Extract username from HF user info object"""
if isinstance(user_info, dict):
return user_info.get("name") or user_info.get("username")
return getattr(user_info, "name", None) or getattr(user_info, "username", None)