webscout 7.6__py3-none-any.whl → 7.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (124) hide show
  1. webscout/AIutel.py +2 -1
  2. webscout/Bard.py +14 -11
  3. webscout/DWEBS.py +431 -415
  4. webscout/Extra/autocoder/autocoder_utiles.py +183 -47
  5. webscout/Extra/autocoder/rawdog.py +848 -649
  6. webscout/Extra/gguf.py +682 -652
  7. webscout/Provider/AI21.py +1 -1
  8. webscout/Provider/AISEARCH/DeepFind.py +2 -2
  9. webscout/Provider/AISEARCH/ISou.py +2 -23
  10. webscout/Provider/AISEARCH/felo_search.py +6 -6
  11. webscout/Provider/AISEARCH/genspark_search.py +1 -1
  12. webscout/Provider/Aitopia.py +292 -0
  13. webscout/Provider/AllenAI.py +5 -22
  14. webscout/Provider/Andi.py +3 -3
  15. webscout/Provider/C4ai.py +1 -1
  16. webscout/Provider/ChatGPTClone.py +226 -0
  17. webscout/Provider/ChatGPTES.py +3 -5
  18. webscout/Provider/ChatGPTGratis.py +4 -4
  19. webscout/Provider/Chatify.py +2 -2
  20. webscout/Provider/Cloudflare.py +3 -2
  21. webscout/Provider/DARKAI.py +3 -2
  22. webscout/Provider/DeepSeek.py +2 -2
  23. webscout/Provider/Deepinfra.py +1 -1
  24. webscout/Provider/EDITEE.py +1 -1
  25. webscout/Provider/ElectronHub.py +178 -96
  26. webscout/Provider/ExaChat.py +310 -0
  27. webscout/Provider/Free2GPT.py +2 -2
  28. webscout/Provider/Gemini.py +5 -19
  29. webscout/Provider/GithubChat.py +1 -1
  30. webscout/Provider/Glider.py +12 -8
  31. webscout/Provider/Groq.py +3 -3
  32. webscout/Provider/HF_space/qwen_qwen2.py +1 -1
  33. webscout/Provider/HeckAI.py +1 -1
  34. webscout/Provider/HuggingFaceChat.py +1 -1
  35. webscout/Provider/Hunyuan.py +272 -0
  36. webscout/Provider/Jadve.py +3 -3
  37. webscout/Provider/Koboldai.py +3 -3
  38. webscout/Provider/LambdaChat.py +391 -0
  39. webscout/Provider/Llama.py +3 -5
  40. webscout/Provider/Llama3.py +4 -12
  41. webscout/Provider/Marcus.py +3 -3
  42. webscout/Provider/OLLAMA.py +260 -36
  43. webscout/Provider/Openai.py +7 -3
  44. webscout/Provider/PI.py +1 -1
  45. webscout/Provider/Perplexitylabs.py +1 -1
  46. webscout/Provider/Phind.py +1 -1
  47. webscout/Provider/PizzaGPT.py +1 -1
  48. webscout/Provider/QwenLM.py +4 -7
  49. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +21 -46
  50. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +37 -49
  51. webscout/Provider/TTI/ImgSys/__init__.py +23 -0
  52. webscout/Provider/TTI/ImgSys/async_imgsys.py +202 -0
  53. webscout/Provider/TTI/ImgSys/sync_imgsys.py +195 -0
  54. webscout/Provider/TTI/__init__.py +3 -1
  55. webscout/Provider/TTI/artbit/async_artbit.py +4 -33
  56. webscout/Provider/TTI/artbit/sync_artbit.py +4 -32
  57. webscout/Provider/TTI/fastflux/async_fastflux.py +6 -2
  58. webscout/Provider/TTI/fastflux/sync_fastflux.py +7 -2
  59. webscout/Provider/TTI/huggingface/async_huggingface.py +1 -1
  60. webscout/Provider/TTI/huggingface/sync_huggingface.py +1 -1
  61. webscout/Provider/TTI/pixelmuse/__init__.py +4 -0
  62. webscout/Provider/TTI/pixelmuse/async_pixelmuse.py +249 -0
  63. webscout/Provider/TTI/pixelmuse/sync_pixelmuse.py +182 -0
  64. webscout/Provider/TTI/talkai/sync_talkai.py +1 -1
  65. webscout/Provider/TTS/utils.py +1 -1
  66. webscout/Provider/TeachAnything.py +1 -1
  67. webscout/Provider/TextPollinationsAI.py +4 -4
  68. webscout/Provider/TwoAI.py +1 -2
  69. webscout/Provider/Venice.py +4 -2
  70. webscout/Provider/VercelAI.py +234 -0
  71. webscout/Provider/WebSim.py +228 -0
  72. webscout/Provider/WiseCat.py +10 -12
  73. webscout/Provider/Youchat.py +1 -1
  74. webscout/Provider/__init__.py +22 -1
  75. webscout/Provider/ai4chat.py +1 -1
  76. webscout/Provider/aimathgpt.py +2 -6
  77. webscout/Provider/akashgpt.py +1 -1
  78. webscout/Provider/askmyai.py +4 -4
  79. webscout/Provider/asksteve.py +203 -0
  80. webscout/Provider/bagoodex.py +2 -2
  81. webscout/Provider/cerebras.py +1 -1
  82. webscout/Provider/chatglm.py +4 -4
  83. webscout/Provider/cleeai.py +1 -0
  84. webscout/Provider/copilot.py +427 -415
  85. webscout/Provider/elmo.py +1 -1
  86. webscout/Provider/flowith.py +14 -3
  87. webscout/Provider/freeaichat.py +57 -31
  88. webscout/Provider/gaurish.py +3 -5
  89. webscout/Provider/geminiprorealtime.py +1 -1
  90. webscout/Provider/granite.py +4 -4
  91. webscout/Provider/hermes.py +5 -5
  92. webscout/Provider/julius.py +1 -1
  93. webscout/Provider/koala.py +1 -1
  94. webscout/Provider/labyrinth.py +239 -0
  95. webscout/Provider/learnfastai.py +28 -15
  96. webscout/Provider/lepton.py +1 -1
  97. webscout/Provider/llama3mitril.py +4 -4
  98. webscout/Provider/llamatutor.py +1 -1
  99. webscout/Provider/llmchat.py +3 -3
  100. webscout/Provider/meta.py +1 -1
  101. webscout/Provider/multichat.py +10 -10
  102. webscout/Provider/promptrefine.py +1 -1
  103. webscout/Provider/searchchat.py +293 -0
  104. webscout/Provider/sonus.py +208 -0
  105. webscout/Provider/talkai.py +2 -2
  106. webscout/Provider/turboseek.py +1 -1
  107. webscout/Provider/tutorai.py +1 -1
  108. webscout/Provider/typegpt.py +6 -43
  109. webscout/Provider/uncovr.py +299 -0
  110. webscout/Provider/x0gpt.py +1 -1
  111. webscout/__init__.py +36 -36
  112. webscout/cli.py +293 -283
  113. webscout/litagent/agent.py +14 -9
  114. webscout/tempid.py +11 -11
  115. webscout/utils.py +2 -2
  116. webscout/version.py +1 -1
  117. webscout/webscout_search.py +1282 -1223
  118. webscout/webscout_search_async.py +813 -692
  119. {webscout-7.6.dist-info → webscout-7.8.dist-info}/METADATA +76 -44
  120. {webscout-7.6.dist-info → webscout-7.8.dist-info}/RECORD +124 -106
  121. {webscout-7.6.dist-info → webscout-7.8.dist-info}/LICENSE.md +0 -0
  122. {webscout-7.6.dist-info → webscout-7.8.dist-info}/WHEEL +0 -0
  123. {webscout-7.6.dist-info → webscout-7.8.dist-info}/entry_points.txt +0 -0
  124. {webscout-7.6.dist-info → webscout-7.8.dist-info}/top_level.txt +0 -0
webscout/Extra/gguf.py CHANGED
@@ -1,652 +1,682 @@
1
- """
2
- Convert Hugging Face models to GGUF format with advanced features.
3
-
4
- >>> python -m webscout.Extra.gguf convert -m "OEvortex/HelpingAI-Lite-1.5T" -q "q4_k_m,q5_k_m"
5
- >>> # With upload options:
6
- >>> python -m webscout.Extra.gguf convert -m "your-model" -u "username" -t "token" -q "q4_k_m"
7
- >>> # With imatrix quantization:
8
- >>> python -m webscout.Extra.gguf convert -m "your-model" -i -q "iq4_nl" -t "train_data.txt"
9
- >>> # With model splitting:
10
- >>> python -m webscout.Extra.gguf convert -m "your-model" -s --split-max-tensors 256
11
- """
12
-
13
- import subprocess
14
- import os
15
- import sys
16
- import signal
17
- import tempfile
18
- import platform
19
- from pathlib import Path
20
- from typing import Optional, Dict, List
21
-
22
- from huggingface_hub import HfApi
23
- from webscout.zeroart import figlet_format
24
- from rich.console import Console
25
- from rich.panel import Panel
26
- from rich.table import Table
27
- from ..swiftcli import CLI, option
28
-
29
- console = Console()
30
-
31
- class ConversionError(Exception):
32
- """Custom exception for when things don't go as planned! ⚠️"""
33
- pass
34
-
35
- class ModelConverter:
36
- """Handles the conversion of Hugging Face models to GGUF format."""
37
-
38
- VALID_METHODS = {
39
- "q2_k": "2-bit quantization (smallest size, lowest accuracy)",
40
- "q3_k_l": "3-bit quantization (large) - balanced for size/accuracy",
41
- "q3_k_m": "3-bit quantization (medium) - good balance for most use cases",
42
- "q3_k_s": "3-bit quantization (small) - optimized for speed",
43
- "q4_0": "4-bit quantization (version 0) - standard 4-bit compression",
44
- "q4_1": "4-bit quantization (version 1) - improved accuracy over q4_0",
45
- "q4_k_m": "4-bit quantization (medium) - balanced for most models",
46
- "q4_k_s": "4-bit quantization (small) - optimized for speed",
47
- "q5_0": "5-bit quantization (version 0) - high accuracy, larger size",
48
- "q5_1": "5-bit quantization (version 1) - improved accuracy over q5_0",
49
- "q5_k_m": "5-bit quantization (medium) - best balance for quality/size",
50
- "q5_k_s": "5-bit quantization (small) - optimized for speed",
51
- "q6_k": "6-bit quantization - highest accuracy, largest size",
52
- "q8_0": "8-bit quantization - maximum accuracy, largest size"
53
- }
54
-
55
- VALID_IMATRIX_METHODS = {
56
- "iq3_m": "3-bit imatrix quantization (medium) - balanced importance-based",
57
- "iq3_xxs": "3-bit imatrix quantization (extra extra small) - maximum compression",
58
- "q4_k_m": "4-bit imatrix quantization (medium) - balanced importance-based",
59
- "q4_k_s": "4-bit imatrix quantization (small) - optimized for speed",
60
- "iq4_nl": "4-bit imatrix quantization (non-linear) - best accuracy for 4-bit",
61
- "iq4_xs": "4-bit imatrix quantization (extra small) - maximum compression",
62
- "q5_k_m": "5-bit imatrix quantization (medium) - balanced importance-based",
63
- "q5_k_s": "5-bit imatrix quantization (small) - optimized for speed"
64
- }
65
-
66
- def __init__(self, model_id: str, username: Optional[str] = None,
67
- token: Optional[str] = None, quantization_methods: str = "q4_k_m",
68
- use_imatrix: bool = False, train_data_file: Optional[str] = None,
69
- split_model: bool = False, split_max_tensors: int = 256,
70
- split_max_size: Optional[str] = None):
71
- self.model_id = model_id
72
- self.username = username
73
- self.token = token
74
- self.quantization_methods = quantization_methods.split(',')
75
- self.model_name = model_id.split('/')[-1]
76
- self.workspace = Path(os.getcwd())
77
- self.use_imatrix = use_imatrix
78
- self.train_data_file = train_data_file
79
- self.split_model = split_model
80
- self.split_max_tensors = split_max_tensors
81
- self.split_max_size = split_max_size
82
-
83
- def validate_inputs(self) -> None:
84
- """Validates all input parameters."""
85
- if not '/' in self.model_id:
86
- raise ValueError("Invalid model ID format. Expected format: 'organization/model-name'")
87
-
88
- if self.use_imatrix:
89
- invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_IMATRIX_METHODS]
90
- if invalid_methods:
91
- raise ValueError(
92
- f"Invalid imatrix quantization methods: {', '.join(invalid_methods)}.\n"
93
- f"Valid methods are: {', '.join(self.VALID_IMATRIX_METHODS.keys())}"
94
- )
95
- if not self.train_data_file and not os.path.exists("llama.cpp/groups_merged.txt"):
96
- raise ValueError("Training data file is required for imatrix quantization")
97
- else:
98
- invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_METHODS]
99
- if invalid_methods:
100
- raise ValueError(
101
- f"Invalid quantization methods: {', '.join(invalid_methods)}.\n"
102
- f"Valid methods are: {', '.join(self.VALID_METHODS.keys())}"
103
- )
104
-
105
- if bool(self.username) != bool(self.token):
106
- raise ValueError("Both username and token must be provided for upload, or neither.")
107
-
108
- if self.split_model and self.split_max_size:
109
- try:
110
- size = int(self.split_max_size[:-1])
111
- unit = self.split_max_size[-1].upper()
112
- if unit not in ['M', 'G']:
113
- raise ValueError("Split max size must end with M or G")
114
- except ValueError:
115
- raise ValueError("Invalid split max size format. Use format like '256M' or '5G'")
116
-
117
- @staticmethod
118
- def check_dependencies() -> Dict[str, bool]:
119
- """Check if all required dependencies are installed."""
120
- dependencies = {
121
- 'git': 'Git version control',
122
- 'pip3': 'Python package installer',
123
- 'huggingface-cli': 'Hugging Face CLI',
124
- 'cmake': 'CMake build system',
125
- 'ninja': 'Ninja build system (optional)'
126
- }
127
-
128
- status = {}
129
- for cmd, desc in dependencies.items():
130
- status[cmd] = subprocess.run(['which', cmd], capture_output=True, text=True).returncode == 0
131
-
132
- return status
133
-
134
- def detect_hardware(self) -> Dict[str, bool]:
135
- """Detect available hardware acceleration."""
136
- hardware = {
137
- 'cuda': False,
138
- 'metal': False,
139
- 'opencl': False,
140
- 'vulkan': False,
141
- 'rocm': False
142
- }
143
-
144
- # Check CUDA
145
- try:
146
- if subprocess.run(['nvcc', '--version'], capture_output=True).returncode == 0:
147
- hardware['cuda'] = True
148
- except FileNotFoundError:
149
- pass
150
-
151
- # Check Metal (macOS)
152
- if platform.system() == 'Darwin':
153
- try:
154
- if subprocess.run(['xcrun', '--show-sdk-path'], capture_output=True).returncode == 0:
155
- hardware['metal'] = True
156
- except FileNotFoundError:
157
- pass
158
-
159
- # Check OpenCL
160
- try:
161
- if subprocess.run(['clinfo'], capture_output=True).returncode == 0:
162
- hardware['opencl'] = True
163
- except FileNotFoundError:
164
- pass
165
-
166
- # Check Vulkan
167
- try:
168
- if subprocess.run(['vulkaninfo'], capture_output=True).returncode == 0:
169
- hardware['vulkan'] = True
170
- except FileNotFoundError:
171
- pass
172
-
173
- # Check ROCm
174
- try:
175
- if subprocess.run(['rocm-smi'], capture_output=True).returncode == 0:
176
- hardware['rocm'] = True
177
- except FileNotFoundError:
178
- pass
179
-
180
- return hardware
181
-
182
- def setup_llama_cpp(self) -> None:
183
- """Sets up and builds llama.cpp repository."""
184
- llama_path = self.workspace / "llama.cpp"
185
-
186
- with console.status("[bold green]Setting up llama.cpp...") as status:
187
- # Clone llama.cpp if not exists
188
- if not llama_path.exists():
189
- subprocess.run(['git', 'clone', 'https://github.com/ggerganov/llama.cpp'], check=True)
190
-
191
- os.chdir(llama_path)
192
-
193
- # Check if we're in a Nix environment
194
- is_nix = platform.system() == "Linux" and os.path.exists("/nix/store")
195
-
196
- if is_nix:
197
- console.print("[yellow]Detected Nix environment. Using system Python packages...")
198
- # In Nix, we need to use the system Python packages
199
- try:
200
- # Try to import required packages to check if they're available
201
- import torch # type: ignore
202
- import numpy # type: ignore
203
- import sentencepiece # type: ignore
204
- import transformers # type: ignore
205
- console.print("[green]Required Python packages are already installed.")
206
- except ImportError as e:
207
- console.print("[red]Missing required Python packages in Nix environment.")
208
- console.print("[yellow]Please install them using:")
209
- console.print("nix-shell -p python3Packages.torch python3Packages.numpy python3Packages.sentencepiece python3Packages.transformers")
210
- raise ConversionError("Missing required Python packages in Nix environment")
211
- else:
212
- # In non-Nix environments, install requirements
213
- try:
214
- subprocess.run(['pip3', 'install', '-r', 'requirements.txt'], check=True)
215
- except subprocess.CalledProcessError as e:
216
- if "externally-managed-environment" in str(e):
217
- console.print("[yellow]Detected externally managed Python environment.")
218
- console.print("[yellow]Please install the required packages manually:")
219
- console.print("pip install torch numpy sentencepiece transformers")
220
- raise ConversionError("Failed to install requirements in externally managed environment")
221
- raise
222
-
223
- # Detect available hardware
224
- hardware = self.detect_hardware()
225
- console.print("[bold green]Detected hardware acceleration:")
226
- for hw, available in hardware.items():
227
- console.print(f" {'' if available else ''} {hw.upper()}")
228
-
229
- # Configure CMake build
230
- cmake_args = ['cmake', '-B', 'build']
231
-
232
- # Add hardware acceleration options
233
- if hardware['cuda']:
234
- cmake_args.extend(['-DLLAMA_CUBLAS=ON'])
235
- if hardware['metal']:
236
- cmake_args.extend(['-DLLAMA_METAL=ON'])
237
- if hardware['opencl']:
238
- cmake_args.extend(['-DLLAMA_CLBLAST=ON'])
239
- if hardware['vulkan']:
240
- cmake_args.extend(['-DLLAMA_VULKAN=ON'])
241
- if hardware['rocm']:
242
- cmake_args.extend(['-DLLAMA_HIPBLAS=ON'])
243
-
244
- # Use Ninja if available
245
- if subprocess.run(['which', 'ninja'], capture_output=True).returncode == 0:
246
- cmake_args.extend(['-G', 'Ninja'])
247
-
248
- # Configure the build
249
- subprocess.run(cmake_args, check=True)
250
-
251
- # Build the project
252
- if any(hardware.values()):
253
- status.update("[bold green]Building with hardware acceleration...")
254
- else:
255
- status.update("[bold yellow]Building for CPU only...")
256
-
257
- subprocess.run(['cmake', '--build', 'build', '-j', str(os.cpu_count() or 1)], check=True)
258
-
259
- os.chdir(self.workspace)
260
-
261
- def display_config(self) -> None:
262
- """Displays the current configuration in a formatted table."""
263
- table = Table(title="Configuration", show_header=True, header_style="bold magenta")
264
- table.add_column("Setting", style="cyan")
265
- table.add_column("Value", style="green")
266
-
267
- table.add_row("Model ID", self.model_id)
268
- table.add_row("Model Name", self.model_name)
269
- table.add_row("Username", self.username or "Not provided")
270
- table.add_row("Token", "****" if self.token else "Not provided")
271
- table.add_row("Quantization Methods", "\n".join(
272
- f"{method} ({self.VALID_METHODS[method]})"
273
- for method in self.quantization_methods
274
- ))
275
-
276
- console.print(Panel(table))
277
-
278
- def generate_importance_matrix(self, model_path: str, train_data_path: str, output_path: str) -> None:
279
- """Generates importance matrix for quantization."""
280
- imatrix_command = [
281
- "./llama.cpp/build/bin/llama-imatrix",
282
- "-m", model_path,
283
- "-f", train_data_path,
284
- "-ngl", "99",
285
- "--output-frequency", "10",
286
- "-o", output_path,
287
- ]
288
-
289
- if not os.path.isfile(model_path):
290
- raise ConversionError(f"Model file not found: {model_path}")
291
-
292
- console.print("[bold green]Generating importance matrix...")
293
- process = subprocess.Popen(imatrix_command, shell=False)
294
-
295
- try:
296
- process.wait(timeout=60)
297
- except subprocess.TimeoutExpired:
298
- console.print("[yellow]Imatrix computation timed out. Sending SIGINT...")
299
- process.send_signal(signal.SIGINT)
300
- try:
301
- process.wait(timeout=5)
302
- except subprocess.TimeoutExpired:
303
- console.print("[red]Imatrix process still running. Force terminating...")
304
- process.kill()
305
-
306
- if process.returncode != 0:
307
- raise ConversionError("Failed to generate importance matrix")
308
-
309
- console.print("[green]Importance matrix generation completed.")
310
-
311
- def split_model(self, model_path: str, outdir: str) -> List[str]:
312
- """Splits the model into smaller chunks."""
313
- split_cmd = [
314
- "./llama.cpp/build/bin/llama-gguf-split",
315
- "--split",
316
- ]
317
-
318
- if self.split_max_size:
319
- split_cmd.extend(["--split-max-size", self.split_max_size])
320
- else:
321
- split_cmd.extend(["--split-max-tensors", str(self.split_max_tensors)])
322
-
323
- model_path_prefix = '.'.join(model_path.split('.')[:-1])
324
- split_cmd.extend([model_path, model_path_prefix])
325
-
326
- console.print(f"[bold green]Splitting model with command: {' '.join(split_cmd)}")
327
-
328
- result = subprocess.run(split_cmd, shell=False, capture_output=True, text=True)
329
-
330
- if result.returncode != 0:
331
- raise ConversionError(f"Error splitting model: {result.stderr}")
332
-
333
- console.print("[green]Model split successfully!")
334
-
335
- # Get list of split files
336
- model_file_prefix = model_path_prefix.split('/')[-1]
337
- split_files = [f for f in os.listdir(outdir)
338
- if f.startswith(model_file_prefix) and f.endswith(".gguf")]
339
-
340
- if not split_files:
341
- raise ConversionError("No split files found")
342
-
343
- return split_files
344
-
345
- def upload_split_files(self, split_files: List[str], outdir: str, repo_id: str) -> None:
346
- """Uploads split model files to Hugging Face."""
347
- api = HfApi(token=self.token)
348
-
349
- for file in split_files:
350
- file_path = os.path.join(outdir, file)
351
- console.print(f"[bold green]Uploading file: {file}")
352
- try:
353
- api.upload_file(
354
- path_or_fileobj=file_path,
355
- path_in_repo=file,
356
- repo_id=repo_id,
357
- )
358
- except Exception as e:
359
- raise ConversionError(f"Error uploading file {file}: {e}")
360
-
361
- def generate_readme(self, quantized_files: List[str]) -> str:
362
- """Generate a README.md file for the Hugging Face Hub."""
363
- readme = f"""# {self.model_name} GGUF
364
-
365
- This repository contains GGUF quantized versions of [{self.model_id}](https://huggingface.co/{self.model_id}).
366
-
367
- ## About
368
-
369
- This model was converted using [Webscout](https://github.com/Webscout/webscout).
370
-
371
- ## Quantization Methods
372
-
373
- The following quantization methods were used:
374
-
375
- """
376
- # Add quantization method descriptions
377
- for method in self.quantization_methods:
378
- if self.use_imatrix:
379
- readme += f"- `{method}`: {self.VALID_IMATRIX_METHODS[method]}\n"
380
- else:
381
- readme += f"- `{method}`: {self.VALID_METHODS[method]}\n"
382
-
383
- readme += """
384
- ## Available Files
385
-
386
- The following quantized files are available:
387
-
388
- """
389
- # Add file information
390
- for file in quantized_files:
391
- readme += f"- `{file}`\n"
392
-
393
- if self.use_imatrix:
394
- readme += """
395
- ## Importance Matrix
396
-
397
- This model was quantized using importance matrix quantization. The `imatrix.dat` file contains the importance matrix used for quantization.
398
-
399
- """
400
-
401
- readme += """
402
- ## Usage
403
-
404
- These GGUF files can be used with [llama.cpp](https://github.com/ggerganov/llama.cpp) and compatible tools.
405
-
406
- Example usage:
407
- ```bash
408
- ./main -m model.gguf -n 1024 --repeat_penalty 1.0 --color -i -r "User:" -f prompts/chat-with-bob.txt
409
- ```
410
-
411
- ## Conversion Process
412
-
413
- This model was converted using the following command:
414
- ```bash
415
- python -m webscout.Extra.gguf convert \\
416
- -m "{self.model_id}" \\
417
- -q "{','.join(self.quantization_methods)}" \\
418
- {f'-i' if self.use_imatrix else ''} \\
419
- {f'--train-data "{self.train_data_file}"' if self.train_data_file else ''} \\
420
- {f'-s' if self.split_model else ''} \\
421
- {f'--split-max-tensors {self.split_max_tensors}' if self.split_model else ''} \\
422
- {f'--split-max-size {self.split_max_size}' if self.split_max_size else ''}
423
- ```
424
-
425
- ## License
426
-
427
- This repository is licensed under the same terms as the original model.
428
- """
429
- return readme
430
-
431
- def upload_readme(self, readme_content: str, repo_id: str) -> None:
432
- """Upload README.md to Hugging Face Hub."""
433
- api = HfApi(token=self.token)
434
- try:
435
- api.upload_file(
436
- path_or_fileobj=readme_content.encode(),
437
- path_in_repo="README.md",
438
- repo_id=repo_id,
439
- )
440
- console.print("[green]README.md uploaded successfully!")
441
- except Exception as e:
442
- console.print(f"[yellow]Warning: Failed to upload README.md: {e}")
443
-
444
- def convert(self) -> None:
445
- """Performs the model conversion process."""
446
- try:
447
- # Display banner and configuration
448
- console.print(f"[bold green]{figlet_format('GGUF Converter')}")
449
- self.display_config()
450
-
451
- # Validate inputs
452
- self.validate_inputs()
453
-
454
- # Check dependencies
455
- deps = self.check_dependencies()
456
- missing = [name for name, installed in deps.items() if not installed and name != 'ninja']
457
- if missing:
458
- raise ConversionError(f"Missing required dependencies: {', '.join(missing)}")
459
-
460
- # Setup llama.cpp
461
- self.setup_llama_cpp()
462
-
463
- # Determine if we need temporary directories (only for uploads)
464
- needs_temp = bool(self.username and self.token)
465
-
466
- if needs_temp:
467
- # Use temporary directories for upload case
468
- with tempfile.TemporaryDirectory() as outdir:
469
- with tempfile.TemporaryDirectory() as tmpdir:
470
- self._convert_with_dirs(tmpdir, outdir)
471
- else:
472
- # Use current directory for local output
473
- outdir = os.getcwd()
474
- tmpdir = os.path.join(outdir, "temp_download")
475
- os.makedirs(tmpdir, exist_ok=True)
476
- try:
477
- self._convert_with_dirs(tmpdir, outdir)
478
- finally:
479
- # Clean up temporary download directory
480
- import shutil
481
- shutil.rmtree(tmpdir, ignore_errors=True)
482
-
483
- # Display success message
484
- console.print(Panel.fit(
485
- "[bold green]✓[/] Conversion completed successfully!\n\n"
486
- f"[cyan]Output files can be found in: {self.workspace / self.model_name}[/]",
487
- title="Success",
488
- border_style="green"
489
- ))
490
-
491
- except Exception as e:
492
- console.print(Panel.fit(
493
- f"[bold red]✗[/] {str(e)}",
494
- title="Error",
495
- border_style="red"
496
- ))
497
- raise
498
-
499
- def _convert_with_dirs(self, tmpdir: str, outdir: str) -> None:
500
- """Helper method to perform conversion with given directories."""
501
- fp16 = str(Path(outdir)/f"{self.model_name}.fp16.gguf")
502
-
503
- # Download model
504
- local_dir = Path(tmpdir)/self.model_name
505
- console.print("[bold green]Downloading model...")
506
- api = HfApi(token=self.token)
507
- api.snapshot_download(
508
- repo_id=self.model_id,
509
- local_dir=local_dir,
510
- local_dir_use_symlinks=False
511
- )
512
-
513
- # Convert to fp16
514
- console.print("[bold green]Converting to fp16...")
515
- result = subprocess.run([
516
- "python", "llama.cpp/convert_hf_to_gguf.py",
517
- str(local_dir),
518
- "--outtype", "f16",
519
- "--outfile", fp16
520
- ], capture_output=True, text=True)
521
-
522
- if result.returncode != 0:
523
- raise ConversionError(f"Error converting to fp16: {result.stderr}")
524
-
525
- # Generate importance matrix if needed
526
- imatrix_path = None
527
- if self.use_imatrix:
528
- train_data_path = self.train_data_file if self.train_data_file else "llama.cpp/groups_merged.txt"
529
- imatrix_path = str(Path(outdir)/"imatrix.dat")
530
- self.generate_importance_matrix(fp16, train_data_path, imatrix_path)
531
-
532
- # Quantize model
533
- console.print("[bold green]Quantizing model...")
534
- quantized_files = []
535
- for method in self.quantization_methods:
536
- quantized_name = f"{self.model_name.lower()}-{method.lower()}"
537
- if self.use_imatrix:
538
- quantized_name += "-imat"
539
- quantized_path = str(Path(outdir)/f"{quantized_name}.gguf")
540
-
541
- if self.use_imatrix:
542
- quantize_cmd = [
543
- "./llama.cpp/build/bin/llama-quantize",
544
- "--imatrix", imatrix_path,
545
- fp16, quantized_path, method
546
- ]
547
- else:
548
- quantize_cmd = [
549
- "./llama.cpp/build/bin/llama-quantize",
550
- fp16, quantized_path, method
551
- ]
552
-
553
- result = subprocess.run(quantize_cmd, capture_output=True, text=True)
554
- if result.returncode != 0:
555
- raise ConversionError(f"Error quantizing with {method}: {result.stderr}")
556
-
557
- quantized_files.append(f"{quantized_name}.gguf")
558
-
559
- # Split model if requested
560
- if self.split_model:
561
- split_files = self.split_model(quantized_path, outdir)
562
- if self.username and self.token:
563
- self.upload_split_files(split_files, outdir, f"{self.username}/{self.model_name}-GGUF")
564
- else:
565
- # Upload single file if credentials provided
566
- if self.username and self.token:
567
- api.upload_file(
568
- path_or_fileobj=quantized_path,
569
- path_in_repo=f"{self.model_name.lower()}-{self.quantization_methods[0].lower()}.gguf",
570
- repo_id=f"{self.username}/{self.model_name}-GGUF"
571
- )
572
-
573
- # Upload imatrix if generated and credentials provided
574
- if imatrix_path and self.username and self.token:
575
- api.upload_file(
576
- path_or_fileobj=imatrix_path,
577
- path_in_repo="imatrix.dat",
578
- repo_id=f"{self.username}/{self.model_name}-GGUF"
579
- )
580
-
581
- # Generate and upload README if credentials provided
582
- if self.username and self.token:
583
- readme_content = self.generate_readme(quantized_files)
584
- self.upload_readme(readme_content, f"{self.username}/{self.model_name}-GGUF")
585
-
586
- # Initialize CLI with HAI vibes
587
- app = CLI(
588
- name="gguf",
589
- help="Convert HuggingFace models to GGUF format with style! 🔥",
590
- version="1.0.0"
591
- )
592
-
593
- @app.command(name="convert")
594
- @option("-m", "--model-id", help="The HuggingFace model ID (e.g., 'OEvortex/HelpingAI-Lite-1.5T')", required=True)
595
- @option("-u", "--username", help="Your HuggingFace username for uploads", default=None)
596
- @option("-t", "--token", help="Your HuggingFace API token for uploads", default=None)
597
- @option("-q", "--quantization", help="Comma-separated quantization methods", default="q4_k_m")
598
- @option("-i", "--use-imatrix", help="Use importance matrix for quantization", is_flag=True)
599
- @option("--train-data", help="Training data file for imatrix quantization", default=None)
600
- @option("-s", "--split-model", help="Split the model into smaller chunks", is_flag=True)
601
- @option("--split-max-tensors", help="Maximum number of tensors per file when splitting", default=256)
602
- @option("--split-max-size", help="Maximum file size when splitting (e.g., '256M', '5G')", default=None)
603
- def convert_command(model_id: str, username: Optional[str] = None,
604
- token: Optional[str] = None, quantization: str = "q4_k_m",
605
- use_imatrix: bool = False, train_data: Optional[str] = None,
606
- split_model: bool = False, split_max_tensors: int = 256,
607
- split_max_size: Optional[str] = None):
608
- """
609
- Convert and quantize HuggingFace models to GGUF format! 🚀
610
-
611
- Args:
612
- model_id (str): Your model's HF ID (like 'OEvortex/HelpingAI-Lite-1.5T') 🎯
613
- username (str, optional): Your HF username for uploads 👤
614
- token (str, optional): Your HF API token 🔑
615
- quantization (str): Quantization methods (default: q4_k_m,q5_k_m) 🎮
616
- use_imatrix (bool): Use importance matrix for quantization 🔍
617
- train_data (str, optional): Training data file for imatrix quantization 📚
618
- split_model (bool): Split the model into smaller chunks 🔪
619
- split_max_tensors (int): Max tensors per file when splitting (default: 256) 📊
620
- split_max_size (str, optional): Max file size when splitting (e.g., '256M', '5G') 📏
621
-
622
- Example:
623
- >>> python -m webscout.Extra.gguf convert \\
624
- ... -m "OEvortex/HelpingAI-Lite-1.5T" \\
625
- ... -q "q4_k_m,q5_k_m"
626
- """
627
- try:
628
- converter = ModelConverter(
629
- model_id=model_id,
630
- username=username,
631
- token=token,
632
- quantization_methods=quantization,
633
- use_imatrix=use_imatrix,
634
- train_data_file=train_data,
635
- split_model=split_model,
636
- split_max_tensors=split_max_tensors,
637
- split_max_size=split_max_size
638
- )
639
- converter.convert()
640
- except (ConversionError, ValueError) as e:
641
- console.print(f"[red]Error: {str(e)}")
642
- sys.exit(1)
643
- except Exception as e:
644
- console.print(f"[red]Unexpected error: {str(e)}")
645
- sys.exit(1)
646
-
647
- def main():
648
- """Fire up the GGUF converter! 🚀"""
649
- app.run()
650
-
651
- if __name__ == "__main__":
652
- main()
1
+ """
2
+ Convert Hugging Face models to GGUF format with advanced features.
3
+
4
+ >>> python -m webscout.Extra.gguf convert -m "OEvortex/HelpingAI-Lite-1.5T" -q "q4_k_m,q5_k_m"
5
+ >>> # With upload options:
6
+ >>> python -m webscout.Extra.gguf convert -m "your-model" -u "username" -t "token" -q "q4_k_m"
7
+ >>> # With imatrix quantization:
8
+ >>> python -m webscout.Extra.gguf convert -m "your-model" -i -q "iq4_nl" -t "train_data.txt"
9
+ >>> # With model splitting:
10
+ >>> python -m webscout.Extra.gguf convert -m "your-model" -s --split-max-tensors 256
11
+ """
12
+
13
+ import subprocess
14
+ import os
15
+ import sys
16
+ import signal
17
+ import tempfile
18
+ import platform
19
+ from pathlib import Path
20
+ from typing import Optional, Dict, List, Any, Union, Literal, TypedDict, Set
21
+
22
+ from huggingface_hub import HfApi
23
+ from webscout.zeroart import figlet_format
24
+ from rich.console import Console
25
+ from rich.panel import Panel
26
+ from rich.table import Table
27
+ from ..swiftcli import CLI, option
28
+
29
+ console = Console()
30
+
31
+ class ConversionError(Exception):
32
+ """Custom exception for when things don't go as planned! ⚠️"""
33
+ pass
34
+
35
+ class QuantizationMethod(TypedDict):
36
+ """Type definition for quantization method descriptions."""
37
+ description: str
38
+
39
+ class ModelConverter:
40
+ """Handles the conversion of Hugging Face models to GGUF format."""
41
+
42
+ VALID_METHODS: Dict[str, str] = {
43
+ "fp16": "16-bit floating point - maximum accuracy, largest size",
44
+ "q2_k": "2-bit quantization (smallest size, lowest accuracy)",
45
+ "q3_k_l": "3-bit quantization (large) - balanced for size/accuracy",
46
+ "q3_k_m": "3-bit quantization (medium) - good balance for most use cases",
47
+ "q3_k_s": "3-bit quantization (small) - optimized for speed",
48
+ "q4_0": "4-bit quantization (version 0) - standard 4-bit compression",
49
+ "q4_1": "4-bit quantization (version 1) - improved accuracy over q4_0",
50
+ "q4_k_m": "4-bit quantization (medium) - balanced for most models",
51
+ "q4_k_s": "4-bit quantization (small) - optimized for speed",
52
+ "q5_0": "5-bit quantization (version 0) - high accuracy, larger size",
53
+ "q5_1": "5-bit quantization (version 1) - improved accuracy over q5_0",
54
+ "q5_k_m": "5-bit quantization (medium) - best balance for quality/size",
55
+ "q5_k_s": "5-bit quantization (small) - optimized for speed",
56
+ "q6_k": "6-bit quantization - highest accuracy, largest size",
57
+ "q8_0": "8-bit quantization - maximum accuracy, largest size"
58
+ }
59
+
60
+ VALID_IMATRIX_METHODS: Dict[str, str] = {
61
+ "iq3_m": "3-bit imatrix quantization (medium) - balanced importance-based",
62
+ "iq3_xxs": "3-bit imatrix quantization (extra extra small) - maximum compression",
63
+ "q4_k_m": "4-bit imatrix quantization (medium) - balanced importance-based",
64
+ "q4_k_s": "4-bit imatrix quantization (small) - optimized for speed",
65
+ "iq4_nl": "4-bit imatrix quantization (non-linear) - best accuracy for 4-bit",
66
+ "iq4_xs": "4-bit imatrix quantization (extra small) - maximum compression",
67
+ "q5_k_m": "5-bit imatrix quantization (medium) - balanced importance-based",
68
+ "q5_k_s": "5-bit imatrix quantization (small) - optimized for speed"
69
+ }
70
+
71
+ def __init__(
72
+ self,
73
+ model_id: str,
74
+ username: Optional[str] = None,
75
+ token: Optional[str] = None,
76
+ quantization_methods: str = "q4_k_m",
77
+ use_imatrix: bool = False,
78
+ train_data_file: Optional[str] = None,
79
+ split_model: bool = False,
80
+ split_max_tensors: int = 256,
81
+ split_max_size: Optional[str] = None
82
+ ) -> None:
83
+ self.model_id = model_id
84
+ self.username = username
85
+ self.token = token
86
+ self.quantization_methods = quantization_methods.split(',')
87
+ self.model_name = model_id.split('/')[-1]
88
+ self.workspace = Path(os.getcwd())
89
+ self.use_imatrix = use_imatrix
90
+ self.train_data_file = train_data_file
91
+ self.split_model = split_model
92
+ self.split_max_tensors = split_max_tensors
93
+ self.split_max_size = split_max_size
94
+ self.fp16_only = "fp16" in self.quantization_methods and len(self.quantization_methods) == 1
95
+
96
+ def validate_inputs(self) -> None:
97
+ """Validates all input parameters."""
98
+ if not '/' in self.model_id:
99
+ raise ValueError("Invalid model ID format. Expected format: 'organization/model-name'")
100
+
101
+ if self.use_imatrix:
102
+ invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_IMATRIX_METHODS]
103
+ if invalid_methods:
104
+ raise ValueError(
105
+ f"Invalid imatrix quantization methods: {', '.join(invalid_methods)}.\n"
106
+ f"Valid methods are: {', '.join(self.VALID_IMATRIX_METHODS.keys())}"
107
+ )
108
+ if not self.train_data_file and not os.path.exists("llama.cpp/groups_merged.txt"):
109
+ raise ValueError("Training data file is required for imatrix quantization")
110
+ else:
111
+ invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_METHODS]
112
+ if invalid_methods:
113
+ raise ValueError(
114
+ f"Invalid quantization methods: {', '.join(invalid_methods)}.\n"
115
+ f"Valid methods are: {', '.join(self.VALID_METHODS.keys())}"
116
+ )
117
+
118
+ if bool(self.username) != bool(self.token):
119
+ raise ValueError("Both username and token must be provided for upload, or neither.")
120
+
121
+ if self.split_model and self.split_max_size:
122
+ try:
123
+ size = int(self.split_max_size[:-1])
124
+ unit = self.split_max_size[-1].upper()
125
+ if unit not in ['M', 'G']:
126
+ raise ValueError("Split max size must end with M or G")
127
+ except ValueError:
128
+ raise ValueError("Invalid split max size format. Use format like '256M' or '5G'")
129
+
130
+ @staticmethod
131
+ def check_dependencies() -> Dict[str, bool]:
132
+ """Check if all required dependencies are installed."""
133
+ dependencies: Dict[str, str] = {
134
+ 'git': 'Git version control',
135
+ 'pip3': 'Python package installer',
136
+ 'huggingface-cli': 'Hugging Face CLI',
137
+ 'cmake': 'CMake build system',
138
+ 'ninja': 'Ninja build system (optional)'
139
+ }
140
+
141
+ status: Dict[str, bool] = {}
142
+ for cmd, desc in dependencies.items():
143
+ status[cmd] = subprocess.run(['which', cmd], capture_output=True, text=True).returncode == 0
144
+
145
+ return status
146
+
147
+ def detect_hardware(self) -> Dict[str, bool]:
148
+ """Detect available hardware acceleration."""
149
+ hardware: Dict[str, bool] = {
150
+ 'cuda': False,
151
+ 'metal': False,
152
+ 'opencl': False,
153
+ 'vulkan': False,
154
+ 'rocm': False
155
+ }
156
+
157
+ # Check CUDA
158
+ try:
159
+ if subprocess.run(['nvcc', '--version'], capture_output=True).returncode == 0:
160
+ hardware['cuda'] = True
161
+ except FileNotFoundError:
162
+ pass
163
+
164
+ # Check Metal (macOS)
165
+ if platform.system() == 'Darwin':
166
+ try:
167
+ if subprocess.run(['xcrun', '--show-sdk-path'], capture_output=True).returncode == 0:
168
+ hardware['metal'] = True
169
+ except FileNotFoundError:
170
+ pass
171
+
172
+ # Check OpenCL
173
+ try:
174
+ if subprocess.run(['clinfo'], capture_output=True).returncode == 0:
175
+ hardware['opencl'] = True
176
+ except FileNotFoundError:
177
+ pass
178
+
179
+ # Check Vulkan
180
+ try:
181
+ if subprocess.run(['vulkaninfo'], capture_output=True).returncode == 0:
182
+ hardware['vulkan'] = True
183
+ except FileNotFoundError:
184
+ pass
185
+
186
+ # Check ROCm
187
+ try:
188
+ if subprocess.run(['rocm-smi'], capture_output=True).returncode == 0:
189
+ hardware['rocm'] = True
190
+ except FileNotFoundError:
191
+ pass
192
+
193
+ return hardware
194
+
195
+ def setup_llama_cpp(self) -> None:
196
+ """Sets up and builds llama.cpp repository."""
197
+ llama_path = self.workspace / "llama.cpp"
198
+
199
+ with console.status("[bold green]Setting up llama.cpp...") as status:
200
+ # Clone llama.cpp if not exists
201
+ if not llama_path.exists():
202
+ subprocess.run(['git', 'clone', 'https://github.com/ggerganov/llama.cpp'], check=True)
203
+
204
+ os.chdir(llama_path)
205
+
206
+ # Check if we're in a Nix environment
207
+ is_nix = platform.system() == "Linux" and os.path.exists("/nix/store")
208
+
209
+ if is_nix:
210
+ console.print("[yellow]Detected Nix environment. Using system Python packages...")
211
+ # In Nix, we need to use the system Python packages
212
+ try:
213
+ # Try to import required packages to check if they're available
214
+ import torch # type: ignore
215
+ import numpy # type: ignore
216
+ import sentencepiece # type: ignore
217
+ import transformers # type: ignore
218
+ console.print("[green]Required Python packages are already installed.")
219
+ except ImportError as e:
220
+ console.print("[red]Missing required Python packages in Nix environment.")
221
+ console.print("[yellow]Please install them using:")
222
+ console.print("nix-shell -p python3Packages.torch python3Packages.numpy python3Packages.sentencepiece python3Packages.transformers")
223
+ raise ConversionError("Missing required Python packages in Nix environment")
224
+ else:
225
+ # In non-Nix environments, install requirements
226
+ try:
227
+ subprocess.run(['pip3', 'install', '-r', 'requirements.txt'], check=True)
228
+ except subprocess.CalledProcessError as e:
229
+ if "externally-managed-environment" in str(e):
230
+ console.print("[yellow]Detected externally managed Python environment.")
231
+ console.print("[yellow]Please install the required packages manually:")
232
+ console.print("pip install torch numpy sentencepiece transformers")
233
+ raise ConversionError("Failed to install requirements in externally managed environment")
234
+ raise
235
+
236
+ # Detect available hardware
237
+ hardware = self.detect_hardware()
238
+ console.print("[bold green]Detected hardware acceleration:")
239
+ for hw, available in hardware.items():
240
+ console.print(f" {'' if available else '✗'} {hw.upper()}")
241
+
242
+ # Configure CMake build
243
+ cmake_args: List[str] = ['cmake', '-B', 'build']
244
+
245
+ # Add hardware acceleration options
246
+ if hardware['cuda']:
247
+ cmake_args.extend(['-DLLAMA_CUBLAS=ON'])
248
+ if hardware['metal']:
249
+ cmake_args.extend(['-DLLAMA_METAL=ON'])
250
+ if hardware['opencl']:
251
+ cmake_args.extend(['-DLLAMA_CLBLAST=ON'])
252
+ if hardware['vulkan']:
253
+ cmake_args.extend(['-DLLAMA_VULKAN=ON'])
254
+ if hardware['rocm']:
255
+ cmake_args.extend(['-DLLAMA_HIPBLAS=ON'])
256
+
257
+ # Use Ninja if available
258
+ if subprocess.run(['which', 'ninja'], capture_output=True).returncode == 0:
259
+ cmake_args.extend(['-G', 'Ninja'])
260
+
261
+ # Configure the build
262
+ subprocess.run(cmake_args, check=True)
263
+
264
+ # Build the project
265
+ if any(hardware.values()):
266
+ status.update("[bold green]Building with hardware acceleration...")
267
+ else:
268
+ status.update("[bold yellow]Building for CPU only...")
269
+
270
+ subprocess.run(['cmake', '--build', 'build', '-j', str(os.cpu_count() or 1)], check=True)
271
+
272
+ os.chdir(self.workspace)
273
+
274
+ def display_config(self) -> None:
275
+ """Displays the current configuration in a formatted table."""
276
+ table = Table(title="Configuration", show_header=True, header_style="bold magenta")
277
+ table.add_column("Setting", style="cyan")
278
+ table.add_column("Value", style="green")
279
+
280
+ table.add_row("Model ID", self.model_id)
281
+ table.add_row("Model Name", self.model_name)
282
+ table.add_row("Username", self.username or "Not provided")
283
+ table.add_row("Token", "****" if self.token else "Not provided")
284
+ table.add_row("Quantization Methods", "\n".join(
285
+ f"{method} ({self.VALID_METHODS[method]})"
286
+ for method in self.quantization_methods
287
+ ))
288
+
289
+ console.print(Panel(table))
290
+
291
+ def generate_importance_matrix(self, model_path: str, train_data_path: str, output_path: str) -> None:
292
+ """Generates importance matrix for quantization."""
293
+ imatrix_command: List[str] = [
294
+ "./llama.cpp/build/bin/llama-imatrix",
295
+ "-m", model_path,
296
+ "-f", train_data_path,
297
+ "-ngl", "99",
298
+ "--output-frequency", "10",
299
+ "-o", output_path,
300
+ ]
301
+
302
+ if not os.path.isfile(model_path):
303
+ raise ConversionError(f"Model file not found: {model_path}")
304
+
305
+ console.print("[bold green]Generating importance matrix...")
306
+ process = subprocess.Popen(imatrix_command, shell=False)
307
+
308
+ try:
309
+ process.wait(timeout=60)
310
+ except subprocess.TimeoutExpired:
311
+ console.print("[yellow]Imatrix computation timed out. Sending SIGINT...")
312
+ process.send_signal(signal.SIGINT)
313
+ try:
314
+ process.wait(timeout=5)
315
+ except subprocess.TimeoutExpired:
316
+ console.print("[red]Imatrix process still running. Force terminating...")
317
+ process.kill()
318
+
319
+ if process.returncode != 0:
320
+ raise ConversionError("Failed to generate importance matrix")
321
+
322
+ console.print("[green]Importance matrix generation completed.")
323
+
324
+ def split_model(self, model_path: str, outdir: str) -> List[str]:
325
+ """Splits the model into smaller chunks."""
326
+ split_cmd: List[str] = [
327
+ "./llama.cpp/build/bin/llama-gguf-split",
328
+ "--split",
329
+ ]
330
+
331
+ if self.split_max_size:
332
+ split_cmd.extend(["--split-max-size", self.split_max_size])
333
+ else:
334
+ split_cmd.extend(["--split-max-tensors", str(self.split_max_tensors)])
335
+
336
+ model_path_prefix = '.'.join(model_path.split('.')[:-1])
337
+ split_cmd.extend([model_path, model_path_prefix])
338
+
339
+ console.print(f"[bold green]Splitting model with command: {' '.join(split_cmd)}")
340
+
341
+ result = subprocess.run(split_cmd, shell=False, capture_output=True, text=True)
342
+
343
+ if result.returncode != 0:
344
+ raise ConversionError(f"Error splitting model: {result.stderr}")
345
+
346
+ console.print("[green]Model split successfully!")
347
+
348
+ # Get list of split files
349
+ model_file_prefix = model_path_prefix.split('/')[-1]
350
+ split_files = [f for f in os.listdir(outdir)
351
+ if f.startswith(model_file_prefix) and f.endswith(".gguf")]
352
+
353
+ if not split_files:
354
+ raise ConversionError("No split files found")
355
+
356
+ return split_files
357
+
358
+ def upload_split_files(self, split_files: List[str], outdir: str, repo_id: str) -> None:
359
+ """Uploads split model files to Hugging Face."""
360
+ api = HfApi(token=self.token)
361
+
362
+ for file in split_files:
363
+ file_path = os.path.join(outdir, file)
364
+ console.print(f"[bold green]Uploading file: {file}")
365
+ try:
366
+ api.upload_file(
367
+ path_or_fileobj=file_path,
368
+ path_in_repo=file,
369
+ repo_id=repo_id,
370
+ )
371
+ except Exception as e:
372
+ raise ConversionError(f"Error uploading file {file}: {e}")
373
+
374
+ def generate_readme(self, quantized_files: List[str]) -> str:
375
+ """Generate a README.md file for the Hugging Face Hub."""
376
+ readme = f"""# {self.model_name} GGUF
377
+
378
+ This repository contains GGUF quantized versions of [{self.model_id}](https://huggingface.co/{self.model_id}).
379
+
380
+ ## About
381
+
382
+ This model was converted using [Webscout](https://github.com/Webscout/webscout).
383
+
384
+ ## Quantization Methods
385
+
386
+ The following quantization methods were used:
387
+
388
+ """
389
+ # Add quantization method descriptions
390
+ for method in self.quantization_methods:
391
+ if self.use_imatrix:
392
+ readme += f"- `{method}`: {self.VALID_IMATRIX_METHODS[method]}\n"
393
+ else:
394
+ readme += f"- `{method}`: {self.VALID_METHODS[method]}\n"
395
+
396
+ readme += """
397
+ ## Available Files
398
+
399
+ The following quantized files are available:
400
+
401
+ """
402
+ # Add file information
403
+ for file in quantized_files:
404
+ readme += f"- `{file}`\n"
405
+
406
+ if self.use_imatrix:
407
+ readme += """
408
+ ## Importance Matrix
409
+
410
+ This model was quantized using importance matrix quantization. The `imatrix.dat` file contains the importance matrix used for quantization.
411
+
412
+ """
413
+
414
+ readme += """
415
+ ## Usage
416
+
417
+ These GGUF files can be used with [llama.cpp](https://github.com/ggerganov/llama.cpp) and compatible tools.
418
+
419
+ Example usage:
420
+ ```bash
421
+ ./main -m model.gguf -n 1024 --repeat_penalty 1.0 --color -i -r "User:" -f prompts/chat-with-bob.txt
422
+ ```
423
+
424
+ ## Conversion Process
425
+
426
+ This model was converted using the following command:
427
+ ```bash
428
+ python -m webscout.Extra.gguf convert \\
429
+ -m "{self.model_id}" \\
430
+ -q "{','.join(self.quantization_methods)}" \\
431
+ {f'-i' if self.use_imatrix else ''} \\
432
+ {f'--train-data "{self.train_data_file}"' if self.train_data_file else ''} \\
433
+ {f'-s' if self.split_model else ''} \\
434
+ {f'--split-max-tensors {self.split_max_tensors}' if self.split_model else ''} \\
435
+ {f'--split-max-size {self.split_max_size}' if self.split_max_size else ''}
436
+ ```
437
+
438
+ ## License
439
+
440
+ This repository is licensed under the same terms as the original model.
441
+ """
442
+ return readme
443
+
444
+ def upload_readme(self, readme_content: str, repo_id: str) -> None:
445
+ """Upload README.md to Hugging Face Hub."""
446
+ api = HfApi(token=self.token)
447
+ try:
448
+ api.upload_file(
449
+ path_or_fileobj=readme_content.encode(),
450
+ path_in_repo="README.md",
451
+ repo_id=repo_id,
452
+ )
453
+ console.print("[green]README.md uploaded successfully!")
454
+ except Exception as e:
455
+ console.print(f"[yellow]Warning: Failed to upload README.md: {e}")
456
+
457
+ def convert(self) -> None:
458
+ """Performs the model conversion process."""
459
+ try:
460
+ # Display banner and configuration
461
+ console.print(f"[bold green]{figlet_format('GGUF Converter')}")
462
+ self.display_config()
463
+
464
+ # Validate inputs
465
+ self.validate_inputs()
466
+
467
+ # Check dependencies
468
+ deps = self.check_dependencies()
469
+ missing = [name for name, installed in deps.items() if not installed and name != 'ninja']
470
+ if missing:
471
+ raise ConversionError(f"Missing required dependencies: {', '.join(missing)}")
472
+
473
+ # Setup llama.cpp
474
+ self.setup_llama_cpp()
475
+
476
+ # Determine if we need temporary directories (only for uploads)
477
+ needs_temp = bool(self.username and self.token)
478
+
479
+ if needs_temp:
480
+ # Use temporary directories for upload case
481
+ with tempfile.TemporaryDirectory() as outdir:
482
+ with tempfile.TemporaryDirectory() as tmpdir:
483
+ self._convert_with_dirs(tmpdir, outdir)
484
+ else:
485
+ # Use current directory for local output
486
+ outdir = os.getcwd()
487
+ tmpdir = os.path.join(outdir, "temp_download")
488
+ os.makedirs(tmpdir, exist_ok=True)
489
+ try:
490
+ self._convert_with_dirs(tmpdir, outdir)
491
+ finally:
492
+ # Clean up temporary download directory
493
+ import shutil
494
+ shutil.rmtree(tmpdir, ignore_errors=True)
495
+
496
+ # Display success message
497
+ console.print(Panel.fit(
498
+ "[bold green]✓[/] Conversion completed successfully!\n\n"
499
+ f"[cyan]Output files can be found in: {self.workspace / self.model_name}[/]",
500
+ title="Success",
501
+ border_style="green"
502
+ ))
503
+
504
+ except Exception as e:
505
+ console.print(Panel.fit(
506
+ f"[bold red]✗[/] {str(e)}",
507
+ title="Error",
508
+ border_style="red"
509
+ ))
510
+ raise
511
+
512
+ def _convert_with_dirs(self, tmpdir: str, outdir: str) -> None:
513
+ """Helper method to perform conversion with given directories."""
514
+ fp16 = str(Path(outdir)/f"{self.model_name}.fp16.gguf")
515
+
516
+ # Download model
517
+ local_dir = Path(tmpdir)/self.model_name
518
+ console.print("[bold green]Downloading model...")
519
+ api = HfApi(token=self.token)
520
+ api.snapshot_download(
521
+ repo_id=self.model_id,
522
+ local_dir=local_dir,
523
+ local_dir_use_symlinks=False
524
+ )
525
+
526
+ # Convert to fp16
527
+ console.print("[bold green]Converting to fp16...")
528
+ result = subprocess.run([
529
+ "python", "llama.cpp/convert_hf_to_gguf.py",
530
+ str(local_dir),
531
+ "--outtype", "f16",
532
+ "--outfile", fp16
533
+ ], capture_output=True, text=True)
534
+
535
+ if result.returncode != 0:
536
+ raise ConversionError(f"Error converting to fp16: {result.stderr}")
537
+
538
+ # If fp16_only is True, we're done after fp16 conversion
539
+ if self.fp16_only:
540
+ quantized_files = [f"{self.model_name}.fp16.gguf"]
541
+ if self.username and self.token:
542
+ api.upload_file(
543
+ path_or_fileobj=fp16,
544
+ path_in_repo=f"{self.model_name}.fp16.gguf",
545
+ repo_id=f"{self.username}/{self.model_name}-GGUF"
546
+ )
547
+ return
548
+
549
+ # Generate importance matrix if needed
550
+ imatrix_path: Optional[str] = None
551
+ if self.use_imatrix:
552
+ train_data_path = self.train_data_file if self.train_data_file else "llama.cpp/groups_merged.txt"
553
+ imatrix_path = str(Path(outdir)/"imatrix.dat")
554
+ self.generate_importance_matrix(fp16, train_data_path, imatrix_path)
555
+
556
+ # Quantize model
557
+ console.print("[bold green]Quantizing model...")
558
+ quantized_files: List[str] = []
559
+ for method in self.quantization_methods:
560
+ quantized_name = f"{self.model_name.lower()}-{method.lower()}"
561
+ if self.use_imatrix:
562
+ quantized_name += "-imat"
563
+ quantized_path = str(Path(outdir)/f"{quantized_name}.gguf")
564
+
565
+ if self.use_imatrix:
566
+ quantize_cmd: List[str] = [
567
+ "./llama.cpp/build/bin/llama-quantize",
568
+ "--imatrix", imatrix_path,
569
+ fp16, quantized_path, method
570
+ ]
571
+ else:
572
+ quantize_cmd = [
573
+ "./llama.cpp/build/bin/llama-quantize",
574
+ fp16, quantized_path, method
575
+ ]
576
+
577
+ result = subprocess.run(quantize_cmd, capture_output=True, text=True)
578
+ if result.returncode != 0:
579
+ raise ConversionError(f"Error quantizing with {method}: {result.stderr}")
580
+
581
+ quantized_files.append(f"{quantized_name}.gguf")
582
+
583
+ # Split model if requested
584
+ if self.split_model:
585
+ split_files = self.split_model(quantized_path, outdir)
586
+ if self.username and self.token:
587
+ self.upload_split_files(split_files, outdir, f"{self.username}/{self.model_name}-GGUF")
588
+ else:
589
+ # Upload single file if credentials provided
590
+ if self.username and self.token:
591
+ api.upload_file(
592
+ path_or_fileobj=quantized_path,
593
+ path_in_repo=f"{self.model_name.lower()}-{self.quantization_methods[0].lower()}.gguf",
594
+ repo_id=f"{self.username}/{self.model_name}-GGUF"
595
+ )
596
+
597
+ # Upload imatrix if generated and credentials provided
598
+ if imatrix_path and self.username and self.token:
599
+ api.upload_file(
600
+ path_or_fileobj=imatrix_path,
601
+ path_in_repo="imatrix.dat",
602
+ repo_id=f"{self.username}/{self.model_name}-GGUF"
603
+ )
604
+
605
+ # Generate and upload README if credentials provided
606
+ if self.username and self.token:
607
+ readme_content = self.generate_readme(quantized_files)
608
+ self.upload_readme(readme_content, f"{self.username}/{self.model_name}-GGUF")
609
+
610
+ # Initialize CLI with HAI vibes
611
+ app = CLI(
612
+ name="gguf",
613
+ help="Convert HuggingFace models to GGUF format with style! 🔥",
614
+ version="1.0.0"
615
+ )
616
+
617
+ @app.command(name="convert")
618
+ @option("-m", "--model-id", help="The HuggingFace model ID (e.g., 'OEvortex/HelpingAI-Lite-1.5T')", required=True)
619
+ @option("-u", "--username", help="Your HuggingFace username for uploads", default=None)
620
+ @option("-t", "--token", help="Your HuggingFace API token for uploads", default=None)
621
+ @option("-q", "--quantization", help="Comma-separated quantization methods", default="q4_k_m")
622
+ @option("-i", "--use-imatrix", help="Use importance matrix for quantization", is_flag=True)
623
+ @option("--train-data", help="Training data file for imatrix quantization", default=None)
624
+ @option("-s", "--split-model", help="Split the model into smaller chunks", is_flag=True)
625
+ @option("--split-max-tensors", help="Maximum number of tensors per file when splitting", default=256)
626
+ @option("--split-max-size", help="Maximum file size when splitting (e.g., '256M', '5G')", default=None)
627
+ def convert_command(
628
+ model_id: str,
629
+ username: Optional[str] = None,
630
+ token: Optional[str] = None,
631
+ quantization: str = "q4_k_m",
632
+ use_imatrix: bool = False,
633
+ train_data: Optional[str] = None,
634
+ split_model: bool = False,
635
+ split_max_tensors: int = 256,
636
+ split_max_size: Optional[str] = None
637
+ ) -> None:
638
+ """
639
+ Convert and quantize HuggingFace models to GGUF format! 🚀
640
+
641
+ Args:
642
+ model_id (str): Your model's HF ID (like 'OEvortex/HelpingAI-Lite-1.5T') 🎯
643
+ username (str, optional): Your HF username for uploads 👤
644
+ token (str, optional): Your HF API token 🔑
645
+ quantization (str): Quantization methods (default: q4_k_m,q5_k_m) 🎮
646
+ use_imatrix (bool): Use importance matrix for quantization 🔍
647
+ train_data (str, optional): Training data file for imatrix quantization 📚
648
+ split_model (bool): Split the model into smaller chunks 🔪
649
+ split_max_tensors (int): Max tensors per file when splitting (default: 256) 📊
650
+ split_max_size (str, optional): Max file size when splitting (e.g., '256M', '5G') 📏
651
+
652
+ Example:
653
+ >>> python -m webscout.Extra.gguf convert \\
654
+ ... -m "OEvortex/HelpingAI-Lite-1.5T" \\
655
+ ... -q "q4_k_m,q5_k_m"
656
+ """
657
+ try:
658
+ converter = ModelConverter(
659
+ model_id=model_id,
660
+ username=username,
661
+ token=token,
662
+ quantization_methods=quantization,
663
+ use_imatrix=use_imatrix,
664
+ train_data_file=train_data,
665
+ split_model=split_model,
666
+ split_max_tensors=split_max_tensors,
667
+ split_max_size=split_max_size
668
+ )
669
+ converter.convert()
670
+ except (ConversionError, ValueError) as e:
671
+ console.print(f"[red]Error: {str(e)}")
672
+ sys.exit(1)
673
+ except Exception as e:
674
+ console.print(f"[red]Unexpected error: {str(e)}")
675
+ sys.exit(1)
676
+
677
+ def main() -> None:
678
+ """Fire up the GGUF converter! 🚀"""
679
+ app.run()
680
+
681
+ if __name__ == "__main__":
682
+ main()