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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# model_loader.py
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import glob
|
| 6 |
+
from huggingface_hub import hf_hub_download, list_repo_files
|
| 7 |
+
|
| 8 |
+
# --- Globale Konfiguration und Variablen ---
|
| 9 |
+
# Diese Variablen werden von app.py importiert.
|
| 10 |
+
MODEL_CONFIG_FILE = "models.json"
|
| 11 |
+
DEFAULT_LOCAL_DIR = "./models"
|
| 12 |
+
MODEL_DROPDOWN_CHOICES = []
|
| 13 |
+
MODEL_FILE_MAPPING = {}
|
| 14 |
+
|
| 15 |
+
os.makedirs(DEFAULT_LOCAL_DIR, exist_ok=True)
|
| 16 |
+
# ----------------------------------------------------------------------
|
| 17 |
+
|
| 18 |
+
def download_models():
|
| 19 |
+
"""Liest models.json, lädt Modelldateien mit HF_TOKEN herunter und füllt die globale Map."""
|
| 20 |
+
global MODEL_DROPDOWN_CHOICES
|
| 21 |
+
global MODEL_FILE_MAPPING
|
| 22 |
+
|
| 23 |
+
# Sicherstellen, dass die Listen/Maps leer sind, falls die Funktion mehrfach aufgerufen wird
|
| 24 |
+
MODEL_DROPDOWN_CHOICES.clear()
|
| 25 |
+
MODEL_FILE_MAPPING.clear()
|
| 26 |
+
|
| 27 |
+
hf_token = os.environ.get('HF_TOKEN')
|
| 28 |
+
if not hf_token:
|
| 29 |
+
print("⚠️ HF_TOKEN not found")
|
| 30 |
+
else:
|
| 31 |
+
print(f"🔑 HF_TOKEN found")
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
with open(MODEL_CONFIG_FILE, 'r') as f:
|
| 35 |
+
config = json.load(f)
|
| 36 |
+
except FileNotFoundError:
|
| 37 |
+
print(f"❌ ERROR: '{MODEL_CONFIG_FILE}' not found.")
|
| 38 |
+
MODEL_DROPDOWN_CHOICES.append("ERROR: models.json missing")
|
| 39 |
+
return
|
| 40 |
+
except json.JSONDecodeError as e:
|
| 41 |
+
print(f"❌ ERROR: {MODEL_CONFIG_FILE} is not a valid JSON. Error: {e}")
|
| 42 |
+
MODEL_DROPDOWN_CHOICES.append("ERROR: models.json invalid")
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
local_dir = config.get('local_dir', DEFAULT_LOCAL_DIR)
|
| 46 |
+
if not os.path.exists(local_dir):
|
| 47 |
+
os.makedirs(local_dir, exist_ok=True)
|
| 48 |
+
print(f"Local directory {local_dir} created.")
|
| 49 |
+
|
| 50 |
+
models_list = config.get('models', [])
|
| 51 |
+
|
| 52 |
+
print(f"✨ Starting download of {len(models_list)} configured models...")
|
| 53 |
+
|
| 54 |
+
for model_entry in models_list:
|
| 55 |
+
name = model_entry.get('name')
|
| 56 |
+
repo_id = model_entry.get('repo_id')
|
| 57 |
+
file_name = model_entry.get('file_name')
|
| 58 |
+
folder_name = model_entry.get('folder_name')
|
| 59 |
+
meta_repo = model_entry.get('meta_repo')
|
| 60 |
+
meta_file = model_entry.get('meta_file')
|
| 61 |
+
|
| 62 |
+
if not name or not repo_id:
|
| 63 |
+
print(f"⚠️ WARNING: Entry without 'name' or 'repo_id' found: {model_entry}")
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
MODEL_DROPDOWN_CHOICES.append(name)
|
| 67 |
+
|
| 68 |
+
# Single File(s) (file_name)
|
| 69 |
+
if file_name:
|
| 70 |
+
print(f" -> Downloading single file for '{name}': {file_name}")
|
| 71 |
+
try:
|
| 72 |
+
# Check if file_name contains wildcards
|
| 73 |
+
if '*' in file_name or '?' in file_name or '[' in file_name:
|
| 74 |
+
all_files = list_repo_files(repo_id=repo_id, token=hf_token)
|
| 75 |
+
matching_files = []
|
| 76 |
+
for f in all_files:
|
| 77 |
+
if glob.fnmatch.fnmatch(f, file_name):
|
| 78 |
+
matching_files.append(f)
|
| 79 |
+
|
| 80 |
+
if not matching_files:
|
| 81 |
+
print(f" ⚎ No files matched pattern: {file_name}")
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
# Download all matching files
|
| 85 |
+
for matching_file in matching_files:
|
| 86 |
+
print(f" - Downloading {matching_file}")
|
| 87 |
+
hf_hub_download(
|
| 88 |
+
repo_id=repo_id,
|
| 89 |
+
filename=matching_file,
|
| 90 |
+
local_dir=local_dir,
|
| 91 |
+
token=hf_token
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# Store the first matching file path for model initialization
|
| 95 |
+
MODEL_FILE_MAPPING[name] = os.path.join(local_dir, matching_files[0])
|
| 96 |
+
print(f" -> Downloaded {len(matching_files)} files for {name}")
|
| 97 |
+
else:
|
| 98 |
+
# Regular file download
|
| 99 |
+
hf_hub_download(
|
| 100 |
+
repo_id=repo_id,
|
| 101 |
+
filename=file_name,
|
| 102 |
+
local_dir=local_dir,
|
| 103 |
+
token=hf_token
|
| 104 |
+
)
|
| 105 |
+
# Store the full path (relative to installation)
|
| 106 |
+
MODEL_FILE_MAPPING[name] = os.path.join(local_dir, file_name)
|
| 107 |
+
print(f" -> Downloaded: {name}")
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"❌ ERROR during download of {name} ({file_name}): {e}")
|
| 110 |
+
|
| 111 |
+
# Folder Download (folder_name)
|
| 112 |
+
elif folder_name:
|
| 113 |
+
print(f" -> Downloading folder for '{name}': {folder_name}")
|
| 114 |
+
try:
|
| 115 |
+
all_files = list_repo_files(repo_id=repo_id, token=hf_token)
|
| 116 |
+
files_to_download = sorted([
|
| 117 |
+
filename
|
| 118 |
+
for filename in all_files
|
| 119 |
+
if filename.startswith(f"{folder_name}/")
|
| 120 |
+
])
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"❌ ERROR during listing files in repo {repo_id}: {e}")
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
if not files_to_download:
|
| 126 |
+
print(f"⚠️ WARNING: No files found in folder '{folder_name}'.")
|
| 127 |
+
continue
|
| 128 |
+
|
| 129 |
+
first_part_filename = files_to_download[0]
|
| 130 |
+
|
| 131 |
+
for filename in files_to_download:
|
| 132 |
+
print(f" - Downloading {filename}")
|
| 133 |
+
try:
|
| 134 |
+
hf_hub_download(
|
| 135 |
+
repo_id=repo_id,
|
| 136 |
+
filename=filename,
|
| 137 |
+
local_dir=local_dir,
|
| 138 |
+
token=hf_token
|
| 139 |
+
)
|
| 140 |
+
except Exception as e:
|
| 141 |
+
print(f"❌ ERROR during download of {filename}: {e}")
|
| 142 |
+
|
| 143 |
+
# For Llama-CPP-Initialization store the path to the first part
|
| 144 |
+
# Path: <local_dir>/<folder_name>/<first_file_part>
|
| 145 |
+
MODEL_FILE_MAPPING[name] = os.path.join(local_dir, first_part_filename)
|
| 146 |
+
print(f" -> Downloaded folder: {name}. First part: {MODEL_FILE_MAPPING[name]}")
|
| 147 |
+
|
| 148 |
+
# Meta File Download (meta_file and meta_repo)
|
| 149 |
+
elif meta_repo and meta_file:
|
| 150 |
+
print(f" -> Downloading meta file for '{name}': {meta_file} from {meta_repo}")
|
| 151 |
+
try:
|
| 152 |
+
# Debug: Print the download parameters
|
| 153 |
+
print(f" Debug: Downloading meta file from repo {meta_repo} with filename {meta_file}")
|
| 154 |
+
|
| 155 |
+
# Download meta file from meta_repo
|
| 156 |
+
hf_hub_download(
|
| 157 |
+
repo_id=meta_repo,
|
| 158 |
+
filename=meta_file,
|
| 159 |
+
local_dir=local_dir,
|
| 160 |
+
token=hf_token
|
| 161 |
+
)
|
| 162 |
+
# Store the meta file path for model initialization
|
| 163 |
+
MODEL_FILE_MAPPING[name] = os.path.join(local_dir, meta_file)
|
| 164 |
+
print(f" -> Downloaded meta file: {name}")
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"❌ ERROR during download of meta file {name} ({meta_file}): {e}")
|
| 167 |
+
# Try to print more details about the error
|
| 168 |
+
import traceback
|
| 169 |
+
traceback.print_exc()
|
| 170 |
+
|
| 171 |
+
else:
|
| 172 |
+
print(f"⚠️ WARNING: For '{name}' neither 'file_name', 'folder_name' nor 'meta_file' was given.")
|
| 173 |
+
|
| 174 |
+
print("--- Download process completed. ---")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# --- Global Downloads once started ---
|
| 178 |
+
download_models()
|
| 179 |
+
# ----------------------------------------
|