webscout 7.5__py3-none-any.whl → 7.7__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 (132) hide show
  1. webscout/AIauto.py +5 -53
  2. webscout/AIutel.py +8 -318
  3. webscout/DWEBS.py +460 -489
  4. webscout/Extra/YTToolkit/YTdownloader.py +14 -53
  5. webscout/Extra/YTToolkit/transcriber.py +12 -13
  6. webscout/Extra/YTToolkit/ytapi/video.py +0 -1
  7. webscout/Extra/__init__.py +0 -1
  8. webscout/Extra/autocoder/__init__.py +9 -9
  9. webscout/Extra/autocoder/autocoder_utiles.py +193 -199
  10. webscout/Extra/autocoder/rawdog.py +789 -677
  11. webscout/Extra/gguf.py +682 -428
  12. webscout/Extra/weather.py +178 -156
  13. webscout/Extra/weather_ascii.py +70 -17
  14. webscout/Litlogger/core/logger.py +1 -2
  15. webscout/Litlogger/handlers/file.py +1 -1
  16. webscout/Litlogger/styles/formats.py +0 -2
  17. webscout/Litlogger/utils/detectors.py +0 -1
  18. webscout/Provider/AISEARCH/DeepFind.py +0 -1
  19. webscout/Provider/AISEARCH/ISou.py +1 -22
  20. webscout/Provider/AISEARCH/felo_search.py +0 -1
  21. webscout/Provider/AllenAI.py +28 -30
  22. webscout/Provider/C4ai.py +29 -11
  23. webscout/Provider/ChatGPTClone.py +226 -0
  24. webscout/Provider/ChatGPTGratis.py +24 -56
  25. webscout/Provider/DeepSeek.py +25 -17
  26. webscout/Provider/Deepinfra.py +115 -48
  27. webscout/Provider/Gemini.py +1 -1
  28. webscout/Provider/Glider.py +33 -12
  29. webscout/Provider/HF_space/qwen_qwen2.py +2 -2
  30. webscout/Provider/HeckAI.py +23 -7
  31. webscout/Provider/Hunyuan.py +272 -0
  32. webscout/Provider/Jadve.py +20 -5
  33. webscout/Provider/LambdaChat.py +391 -0
  34. webscout/Provider/Netwrck.py +42 -19
  35. webscout/Provider/OLLAMA.py +256 -32
  36. webscout/Provider/PI.py +4 -2
  37. webscout/Provider/Perplexitylabs.py +26 -6
  38. webscout/Provider/PizzaGPT.py +10 -51
  39. webscout/Provider/TTI/AiForce/async_aiforce.py +4 -37
  40. webscout/Provider/TTI/AiForce/sync_aiforce.py +41 -38
  41. webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -9
  42. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +179 -206
  43. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +180 -192
  44. webscout/Provider/TTI/MagicStudio/__init__.py +2 -0
  45. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +111 -0
  46. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +109 -0
  47. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +5 -24
  48. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +2 -22
  49. webscout/Provider/TTI/__init__.py +2 -3
  50. webscout/Provider/TTI/aiarta/async_aiarta.py +14 -14
  51. webscout/Provider/TTI/aiarta/sync_aiarta.py +52 -21
  52. webscout/Provider/TTI/artbit/async_artbit.py +3 -32
  53. webscout/Provider/TTI/artbit/sync_artbit.py +3 -31
  54. webscout/Provider/TTI/fastflux/__init__.py +22 -0
  55. webscout/Provider/TTI/fastflux/async_fastflux.py +261 -0
  56. webscout/Provider/TTI/fastflux/sync_fastflux.py +252 -0
  57. webscout/Provider/TTI/piclumen/__init__.py +22 -22
  58. webscout/Provider/TTI/piclumen/sync_piclumen.py +232 -232
  59. webscout/Provider/TTS/__init__.py +2 -2
  60. webscout/Provider/TTS/deepgram.py +12 -39
  61. webscout/Provider/TTS/elevenlabs.py +14 -40
  62. webscout/Provider/TTS/gesserit.py +11 -35
  63. webscout/Provider/TTS/murfai.py +13 -39
  64. webscout/Provider/TTS/parler.py +17 -40
  65. webscout/Provider/TTS/speechma.py +180 -0
  66. webscout/Provider/TTS/streamElements.py +17 -44
  67. webscout/Provider/TextPollinationsAI.py +39 -59
  68. webscout/Provider/Venice.py +25 -8
  69. webscout/Provider/WebSim.py +227 -0
  70. webscout/Provider/WiseCat.py +27 -5
  71. webscout/Provider/Youchat.py +64 -37
  72. webscout/Provider/__init__.py +12 -7
  73. webscout/Provider/akashgpt.py +20 -5
  74. webscout/Provider/flowith.py +33 -7
  75. webscout/Provider/freeaichat.py +32 -45
  76. webscout/Provider/koala.py +20 -5
  77. webscout/Provider/labyrinth.py +239 -0
  78. webscout/Provider/learnfastai.py +28 -15
  79. webscout/Provider/llamatutor.py +1 -1
  80. webscout/Provider/llmchat.py +30 -8
  81. webscout/Provider/multichat.py +65 -9
  82. webscout/Provider/sonus.py +208 -0
  83. webscout/Provider/talkai.py +1 -0
  84. webscout/Provider/turboseek.py +3 -0
  85. webscout/Provider/tutorai.py +2 -0
  86. webscout/Provider/typegpt.py +155 -65
  87. webscout/Provider/uncovr.py +297 -0
  88. webscout/Provider/x0gpt.py +3 -1
  89. webscout/Provider/yep.py +102 -20
  90. webscout/__init__.py +3 -0
  91. webscout/cli.py +53 -40
  92. webscout/conversation.py +1 -10
  93. webscout/litagent/__init__.py +2 -2
  94. webscout/litagent/agent.py +356 -20
  95. webscout/litagent/constants.py +34 -5
  96. webscout/litprinter/__init__.py +0 -3
  97. webscout/models.py +181 -0
  98. webscout/optimizers.py +1 -1
  99. webscout/prompt_manager.py +2 -8
  100. webscout/scout/core/scout.py +1 -4
  101. webscout/scout/core/search_result.py +1 -1
  102. webscout/scout/core/text_utils.py +1 -1
  103. webscout/scout/core.py +2 -5
  104. webscout/scout/element.py +1 -1
  105. webscout/scout/parsers/html_parser.py +1 -1
  106. webscout/scout/utils.py +0 -1
  107. webscout/swiftcli/__init__.py +1 -3
  108. webscout/tempid.py +1 -1
  109. webscout/update_checker.py +1 -3
  110. webscout/version.py +1 -1
  111. webscout/webscout_search_async.py +1 -2
  112. webscout/yep_search.py +297 -297
  113. {webscout-7.5.dist-info → webscout-7.7.dist-info}/LICENSE.md +4 -4
  114. {webscout-7.5.dist-info → webscout-7.7.dist-info}/METADATA +127 -405
  115. {webscout-7.5.dist-info → webscout-7.7.dist-info}/RECORD +118 -117
  116. webscout/Extra/autollama.py +0 -231
  117. webscout/Provider/Amigo.py +0 -274
  118. webscout/Provider/Bing.py +0 -243
  119. webscout/Provider/DiscordRocks.py +0 -253
  120. webscout/Provider/TTI/blackbox/__init__.py +0 -4
  121. webscout/Provider/TTI/blackbox/async_blackbox.py +0 -212
  122. webscout/Provider/TTI/blackbox/sync_blackbox.py +0 -199
  123. webscout/Provider/TTI/deepinfra/__init__.py +0 -4
  124. webscout/Provider/TTI/deepinfra/async_deepinfra.py +0 -227
  125. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +0 -199
  126. webscout/Provider/TTI/imgninza/__init__.py +0 -4
  127. webscout/Provider/TTI/imgninza/async_ninza.py +0 -214
  128. webscout/Provider/TTI/imgninza/sync_ninza.py +0 -209
  129. webscout/Provider/TTS/voicepod.py +0 -117
  130. {webscout-7.5.dist-info → webscout-7.7.dist-info}/WHEEL +0 -0
  131. {webscout-7.5.dist-info → webscout-7.7.dist-info}/entry_points.txt +0 -0
  132. {webscout-7.5.dist-info → webscout-7.7.dist-info}/top_level.txt +0 -0
webscout/Extra/gguf.py CHANGED
@@ -1,428 +1,682 @@
1
- """
2
-
3
- >>> python -m webscout.Extra.gguf convert -m "OEvortex/HelpingAI-Lite-1.5T" -q "q4_k_m,q5_k_m"
4
- >>> # With upload options:
5
- >>> python -m webscout.Extra.gguf convert -m "your-model" -u "username" -t "token" -q "q4_k_m"
6
-
7
- """
8
-
9
- import subprocess
10
- import os
11
- import sys
12
- import shutil
13
- from pathlib import Path
14
- from typing import List, Optional, Dict, Any
15
- from webscout.zeroart import figlet_format
16
- from rich.console import Console
17
- from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
18
- from rich.panel import Panel
19
- from rich.table import Table
20
- from ..Litlogger import Logger, LogFormat
21
- from ..swiftcli import CLI, option
22
-
23
- # Initialize LitLogger with ocean vibes
24
- logger = Logger(
25
- name="GGUFConverter",
26
- format=LogFormat.MODERN_EMOJI,
27
-
28
- )
29
-
30
- console = Console()
31
-
32
- class ConversionError(Exception):
33
- """Custom exception for when things don't go as planned! ⚠️"""
34
- pass
35
-
36
- class ModelConverter:
37
- """Handles the conversion of Hugging Face models to GGUF format."""
38
-
39
- VALID_METHODS = {
40
- "q2_k": "2-bit quantization",
41
- "q3_k_l": "3-bit quantization (large)",
42
- "q3_k_m": "3-bit quantization (medium)",
43
- "q3_k_s": "3-bit quantization (small)",
44
- "q4_0": "4-bit quantization (version 0)",
45
- "q4_1": "4-bit quantization (version 1)",
46
- "q4_k_m": "4-bit quantization (medium)",
47
- "q4_k_s": "4-bit quantization (small)",
48
- "q5_0": "5-bit quantization (version 0)",
49
- "q5_1": "5-bit quantization (version 1)",
50
- "q5_k_m": "5-bit quantization (medium)",
51
- "q5_k_s": "5-bit quantization (small)",
52
- "q6_k": "6-bit quantization",
53
- "q8_0": "8-bit quantization"
54
- }
55
-
56
- def __init__(self, model_id: str, username: Optional[str] = None,
57
- token: Optional[str] = None, quantization_methods: str = "q4_k_m,q5_k_m"):
58
- self.model_id = model_id
59
- self.username = username
60
- self.token = token
61
- self.quantization_methods = quantization_methods.split(',')
62
- self.model_name = model_id.split('/')[-1]
63
- self.workspace = Path(os.getcwd())
64
-
65
- def validate_inputs(self) -> None:
66
- """Validates all input parameters."""
67
- if not '/' in self.model_id:
68
- raise ValueError("Invalid model ID format. Expected format: 'organization/model-name'")
69
-
70
- invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_METHODS]
71
- if invalid_methods:
72
- raise ValueError(
73
- f"Invalid quantization methods: {', '.join(invalid_methods)}.\n"
74
- f"Valid methods are: {', '.join(self.VALID_METHODS.keys())}"
75
- )
76
-
77
- if bool(self.username) != bool(self.token):
78
- raise ValueError("Both username and token must be provided for upload, or neither.")
79
-
80
- @staticmethod
81
- def check_dependencies() -> Dict[str, bool]:
82
- """Check if all required dependencies are installed."""
83
- dependencies = {
84
- 'git': 'Git version control',
85
- 'pip3': 'Python package installer',
86
- 'huggingface-cli': 'Hugging Face CLI',
87
- 'nvcc': 'NVIDIA CUDA Compiler (optional)'
88
- }
89
-
90
- status = {}
91
- for cmd, desc in dependencies.items():
92
- status[cmd] = subprocess.run(['which', cmd], capture_output=True, text=True).returncode == 0
93
-
94
- return status
95
-
96
- def setup_llama_cpp(self) -> None:
97
- """Sets up and builds llama.cpp repository."""
98
- llama_path = self.workspace / "llama.cpp"
99
-
100
- with console.status("[bold green]Setting up llama.cpp...") as status:
101
- if not llama_path.exists():
102
- logger.info("Cloning llama.cpp repository...")
103
- subprocess.run(['git', 'clone', 'https://github.com/ggerganov/llama.cpp'], check=True)
104
-
105
- os.chdir(llama_path)
106
- logger.info("Installing requirements...")
107
- subprocess.run(['pip3', 'install', '-r', 'requirements.txt'], check=True)
108
-
109
- has_cuda = subprocess.run(['nvcc', '--version'], capture_output=True).returncode == 0
110
-
111
- logger.info("Building llama.cpp...")
112
- subprocess.run(['make', 'clean'], check=True)
113
- if has_cuda:
114
- status.update("[bold green]Building with CUDA support...")
115
- subprocess.run(['make', 'LLAMA_CUBLAS=1'], check=True)
116
- else:
117
- status.update("[bold yellow]Building without CUDA support...")
118
- subprocess.run(['make'], check=True)
119
-
120
- os.chdir(self.workspace)
121
-
122
- def display_config(self) -> None:
123
- """Displays the current configuration in a formatted table."""
124
- table = Table(title="Configuration", show_header=True, header_style="bold magenta")
125
- table.add_column("Setting", style="cyan")
126
- table.add_column("Value", style="green")
127
-
128
- table.add_row("Model ID", self.model_id)
129
- table.add_row("Model Name", self.model_name)
130
- table.add_row("Username", self.username or "Not provided")
131
- table.add_row("Token", "****" if self.token else "Not provided")
132
- table.add_row("Quantization Methods", "\n".join(
133
- f"{method} ({self.VALID_METHODS[method]})"
134
- for method in self.quantization_methods
135
- ))
136
-
137
- console.print(Panel(table))
138
-
139
- def convert(self) -> None:
140
- """Performs the model conversion process."""
141
- try:
142
- # Display banner and configuration
143
- console.print(f"[bold green]{figlet_format('GGUF Converter')}")
144
- self.display_config()
145
-
146
- # Validate inputs
147
- self.validate_inputs()
148
-
149
- # Check dependencies
150
- deps = self.check_dependencies()
151
- missing = [name for name, installed in deps.items() if not installed and name != 'nvcc']
152
- if missing:
153
- raise ConversionError(f"Missing required dependencies: {', '.join(missing)}")
154
-
155
- # Setup llama.cpp
156
- self.setup_llama_cpp()
157
-
158
- # Create and execute conversion script
159
- script_path = self.workspace / "gguf.sh"
160
- if not script_path.exists():
161
- self._create_conversion_script(script_path)
162
-
163
- # Prepare command
164
- command = ["bash", str(script_path), "-m", self.model_id]
165
- if self.username and self.token:
166
- command.extend(["-u", self.username, "-t", self.token])
167
- command.extend(["-q", ",".join(self.quantization_methods)])
168
-
169
- # Execute conversion with progress tracking
170
- with Progress(
171
- SpinnerColumn(),
172
- TextColumn("[progress.description]{task.description}"),
173
- BarColumn(),
174
- TaskProgressColumn(),
175
- console=console
176
- ) as progress:
177
- task = progress.add_task("Converting model...", total=None)
178
-
179
- process = subprocess.Popen(
180
- command,
181
- stdout=subprocess.PIPE,
182
- stderr=subprocess.PIPE,
183
- text=True,
184
- bufsize=1,
185
- universal_newlines=True
186
- )
187
-
188
- while True:
189
- output = process.stdout.readline()
190
- if output == '' and process.poll() is not None:
191
- break
192
- if output:
193
- progress.update(task, description=output.strip())
194
- logger.info(output.strip())
195
-
196
- stderr = process.stderr.read()
197
- if stderr:
198
- logger.warning(stderr)
199
-
200
- if process.returncode != 0:
201
- raise ConversionError(f"Conversion failed with return code {process.returncode}")
202
-
203
- progress.update(task, completed=True)
204
-
205
- # Display success message
206
- console.print(Panel.fit(
207
- "[bold green]✓[/] Conversion completed successfully!\n\n"
208
- f"[cyan]Output files can be found in: {self.workspace / self.model_name}[/]",
209
- title="Success",
210
- border_style="green"
211
- ))
212
-
213
- except Exception as e:
214
- console.print(Panel.fit(
215
- f"[bold red]✗[/] {str(e)}",
216
- title="Error",
217
- border_style="red"
218
- ))
219
- raise
220
-
221
- def _create_conversion_script(self, script_path: Path) -> None:
222
- """Creates the conversion shell script."""
223
- script_content = """cat << "EOF"
224
- Made with love in India
225
- EOF
226
-
227
- # Default values
228
- MODEL_ID=""
229
- USERNAME=""
230
- TOKEN=""
231
- QUANTIZATION_METHODS="q4_k_m,q5_k_m" # Default to "q4_k_m,q5_k_m" if not provided
232
-
233
- # Display help/usage information
234
- usage() {
235
- echo "Usage: $0 -m MODEL_ID [-u USERNAME] [-t TOKEN] [-q QUANTIZATION_METHODS]"
236
- echo
237
- echo "Options:"
238
- echo " -m MODEL_ID Required: Set the HF model ID"
239
- echo " -u USERNAME Optional: Set the username"
240
- echo " -t TOKEN Optional: Set the token"
241
- echo " -q QUANTIZATION_METHODS Optional: Set the quantization methods (default: q4_k_m,q5_k_m)"
242
- echo " -h Display this help and exit"
243
- echo
244
- }
245
-
246
- # Parse command-line options
247
- while getopts ":m:u:t:q:h" opt; do
248
- case ${opt} in
249
- m )
250
- MODEL_ID=$OPTARG
251
- ;;
252
- u )
253
- USERNAME=$OPTARG
254
- ;;
255
- t )
256
- TOKEN=$OPTARG
257
- ;;
258
- q )
259
- QUANTIZATION_METHODS=$OPTARG
260
- ;;
261
- h )
262
- usage
263
- exit 0
264
- ;;
265
- \? )
266
- echo "Invalid Option: -$OPTARG" 1>&2
267
- usage
268
- exit 1
269
- ;;
270
- : )
271
- echo "Invalid Option: -$OPTARG requires an argument" 1>&2
272
- usage
273
- exit 1
274
- ;;
275
- esac
276
- done
277
- shift $((OPTIND -1))
278
-
279
- # Ensure MODEL_ID is provided
280
- if [ -z "$MODEL_ID" ]; then
281
- echo "Error: MODEL_ID is required."
282
- usage
283
- exit 1
284
- fi
285
-
286
- # # Echoing the arguments for checking
287
- # echo "MODEL_ID: $MODEL_ID"
288
- # echo "USERNAME: ${USERNAME:-'Not provided'}"
289
- # echo "TOKEN: ${TOKEN:-'Not provided'}"
290
- # echo "QUANTIZATION_METHODS: $QUANTIZATION_METHODS"
291
-
292
- # Splitting string into an array for quantization methods, if provided
293
- IFS=',' read -r -a QUANTIZATION_METHOD_ARRAY <<< "$QUANTIZATION_METHODS"
294
- echo "Quantization Methods: ${QUANTIZATION_METHOD_ARRAY[@]}"
295
-
296
- MODEL_NAME=$(echo "$MODEL_ID" | awk -F'/' '{print $NF}')
297
-
298
-
299
- # ----------- llama.cpp setup block-----------
300
- # Check if llama.cpp is already installed and skip the build step if it is
301
- if [ ! -d "llama.cpp" ]; then
302
- echo "llama.cpp not found. Cloning and setting up..."
303
- git clone https://github.com/ggerganov/llama.cpp
304
- cd llama.cpp && git pull
305
- # Install required packages
306
- pip3 install -r requirements.txt
307
- # Build llama.cpp as it's freshly cloned
308
- if ! command -v nvcc &> /dev/null
309
- then
310
- echo "nvcc could not be found, building llama without LLAMA_CUBLAS"
311
- make clean && make
312
- else
313
- make clean && LLAMA_CUBLAS=1 make
314
- fi
315
- cd ..
316
- else
317
- echo "llama.cpp found. Assuming it's already built and up to date."
318
- # Optionally, still update dependencies
319
- # cd llama.cpp && pip3 install -r requirements.txt && cd ..
320
- fi
321
- # ----------- llama.cpp setup block-----------
322
-
323
-
324
-
325
- # Download model
326
- #todo : shall we put condition to check if model has been already downloaded? similar to autogguf?
327
- echo "Downloading the model..."
328
- huggingface-cli download "$MODEL_ID" --local-dir "./${MODEL_NAME}" --local-dir-use-symlinks False --revision main
329
-
330
-
331
- # Convert to fp16
332
- FP16="${MODEL_NAME}/${MODEL_NAME,,}.fp16.bin"
333
- echo "Converting the model to fp16..."
334
- python3 llama.cpp/convert_hf_to_gguf.py "$MODEL_NAME" --outtype f16 --outfile "$FP16"
335
-
336
- # Quantize the model
337
- echo "Quantizing the model..."
338
- for METHOD in "${QUANTIZATION_METHOD_ARRAY[@]}"; do
339
- QTYPE="${MODEL_NAME}/${MODEL_NAME,,}.${METHOD^^}.gguf"
340
- ./llama.cpp/llama-quantize "$FP16" "$QTYPE" "$METHOD"
341
- done
342
-
343
-
344
- # Check if USERNAME and TOKEN are provided
345
- if [[ -n "$USERNAME" && -n "$TOKEN" ]]; then
346
-
347
- # Login to Hugging Face
348
- echo "Logging in to Hugging Face..."
349
- huggingface-cli login --token "$TOKEN"
350
-
351
-
352
- # Uploading .gguf, .md files, and config.json
353
- echo "Uploading .gguf, .md files, and config.json..."
354
-
355
-
356
- # Define a temporary directory
357
- TEMP_DIR="./temp_upload_dir"
358
-
359
- # Create the temporary directory
360
- mkdir -p "${TEMP_DIR}"
361
-
362
- # Copy the specific files to the temporary directory
363
- find "./${MODEL_NAME}" -type f \( -name "*.gguf" -o -name "*.md" -o -name "config.json" \) -exec cp {} "${TEMP_DIR}/" \;
364
-
365
- # Upload the temporary directory to Hugging Face
366
- huggingface-cli upload "${USERNAME}/${MODEL_NAME}-GGUF" "${TEMP_DIR}" --private
367
-
368
- # Remove the temporary directory after upload
369
- rm -rf "${TEMP_DIR}"
370
- echo "Upload completed."
371
- else
372
- echo "USERNAME and TOKEN must be provided for upload."
373
- fi
374
-
375
- echo "Script completed."
376
- """
377
- script_path.write_text(script_content)
378
- script_path.chmod(0o755)
379
-
380
- # Initialize CLI with HAI vibes
381
- app = CLI(
382
- name="gguf",
383
- help="Convert HuggingFace models to GGUF format with style! 🔥",
384
- version="1.0.0"
385
- )
386
-
387
- @app.command(name="convert")
388
- @option("-m", "--model-id", help="The HuggingFace model ID (e.g., 'OEvortex/HelpingAI-Lite-1.5T')", required=True)
389
- @option("-u", "--username", help="Your HuggingFace username for uploads", default=None)
390
- @option("-t", "--token", help="Your HuggingFace API token for uploads", default=None)
391
- @option("-q", "--quantization", help="Comma-separated quantization methods", default="q4_k_m,q5_k_m")
392
- def convert_command(model_id: str, username: Optional[str] = None,
393
- token: Optional[str] = None, quantization: str = "q4_k_m,q5_k_m"):
394
- """
395
- Convert and quantize HuggingFace models to GGUF format! 🚀
396
-
397
- Args:
398
- model_id (str): Your model's HF ID (like 'OEvortex/HelpingAI-Lite-1.5T') 🎯
399
- username (str, optional): Your HF username for uploads 👤
400
- token (str, optional): Your HF API token 🔑
401
- quantization (str): Quantization methods (default: q4_k_m,q5_k_m) 🎮
402
-
403
- Example:
404
- >>> python -m webscout.Extra.gguf convert \\
405
- ... -m "OEvortex/HelpingAI-Lite-1.5T" \\
406
- ... -q "q4_k_m,q5_k_m"
407
- """
408
- try:
409
- converter = ModelConverter(
410
- model_id=model_id,
411
- username=username,
412
- token=token,
413
- quantization_methods=quantization
414
- )
415
- converter.convert()
416
- except (ConversionError, ValueError) as e:
417
- logger.error(f"Conversion failed: {str(e)}")
418
- sys.exit(1)
419
- except Exception as e:
420
- logger.error(f"Unexpected error: {str(e)}")
421
- sys.exit(1)
422
-
423
- def main():
424
- """Fire up the GGUF converter! 🚀"""
425
- app.run()
426
-
427
- if __name__ == "__main__":
428
- 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()