webscout 7.4__py3-none-any.whl → 7.6__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 (137) 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/autocoder_utiles.py +0 -4
  9. webscout/Extra/autocoder/rawdog.py +13 -41
  10. webscout/Extra/gguf.py +652 -428
  11. webscout/Extra/weather.py +178 -156
  12. webscout/Extra/weather_ascii.py +70 -17
  13. webscout/Litlogger/core/logger.py +1 -2
  14. webscout/Litlogger/handlers/file.py +1 -1
  15. webscout/Litlogger/styles/formats.py +0 -2
  16. webscout/Litlogger/utils/detectors.py +0 -1
  17. webscout/Provider/AISEARCH/DeepFind.py +0 -1
  18. webscout/Provider/AISEARCH/ISou.py +1 -1
  19. webscout/Provider/AISEARCH/felo_search.py +0 -1
  20. webscout/Provider/AllenAI.py +24 -9
  21. webscout/Provider/C4ai.py +432 -0
  22. webscout/Provider/ChatGPTGratis.py +24 -56
  23. webscout/Provider/Cloudflare.py +18 -21
  24. webscout/Provider/DeepSeek.py +27 -48
  25. webscout/Provider/Deepinfra.py +129 -53
  26. webscout/Provider/Gemini.py +1 -1
  27. webscout/Provider/GithubChat.py +362 -0
  28. webscout/Provider/Glider.py +25 -8
  29. webscout/Provider/HF_space/qwen_qwen2.py +2 -2
  30. webscout/Provider/HeckAI.py +38 -5
  31. webscout/Provider/HuggingFaceChat.py +462 -0
  32. webscout/Provider/Jadve.py +20 -5
  33. webscout/Provider/Marcus.py +7 -50
  34. webscout/Provider/Netwrck.py +43 -67
  35. webscout/Provider/PI.py +4 -2
  36. webscout/Provider/Perplexitylabs.py +26 -6
  37. webscout/Provider/Phind.py +29 -3
  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 +206 -206
  43. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +192 -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/__init__.py +2 -0
  51. webscout/Provider/TTI/aiarta/async_aiarta.py +482 -0
  52. webscout/Provider/TTI/aiarta/sync_aiarta.py +440 -0
  53. webscout/Provider/TTI/fastflux/__init__.py +22 -0
  54. webscout/Provider/TTI/fastflux/async_fastflux.py +257 -0
  55. webscout/Provider/TTI/fastflux/sync_fastflux.py +247 -0
  56. webscout/Provider/TTS/__init__.py +2 -2
  57. webscout/Provider/TTS/deepgram.py +12 -39
  58. webscout/Provider/TTS/elevenlabs.py +14 -40
  59. webscout/Provider/TTS/gesserit.py +11 -35
  60. webscout/Provider/TTS/murfai.py +13 -39
  61. webscout/Provider/TTS/parler.py +17 -40
  62. webscout/Provider/TTS/speechma.py +180 -0
  63. webscout/Provider/TTS/streamElements.py +17 -44
  64. webscout/Provider/TextPollinationsAI.py +39 -59
  65. webscout/Provider/Venice.py +217 -200
  66. webscout/Provider/WiseCat.py +27 -5
  67. webscout/Provider/Youchat.py +63 -36
  68. webscout/Provider/__init__.py +13 -8
  69. webscout/Provider/akashgpt.py +28 -10
  70. webscout/Provider/copilot.py +416 -0
  71. webscout/Provider/flowith.py +196 -0
  72. webscout/Provider/freeaichat.py +32 -45
  73. webscout/Provider/granite.py +17 -53
  74. webscout/Provider/koala.py +20 -5
  75. webscout/Provider/llamatutor.py +7 -47
  76. webscout/Provider/llmchat.py +36 -53
  77. webscout/Provider/multichat.py +92 -98
  78. webscout/Provider/talkai.py +1 -0
  79. webscout/Provider/turboseek.py +3 -0
  80. webscout/Provider/tutorai.py +2 -0
  81. webscout/Provider/typegpt.py +154 -64
  82. webscout/Provider/x0gpt.py +3 -1
  83. webscout/Provider/yep.py +102 -20
  84. webscout/__init__.py +3 -0
  85. webscout/cli.py +4 -40
  86. webscout/conversation.py +1 -10
  87. webscout/exceptions.py +19 -9
  88. webscout/litagent/__init__.py +2 -2
  89. webscout/litagent/agent.py +351 -20
  90. webscout/litagent/constants.py +34 -5
  91. webscout/litprinter/__init__.py +0 -3
  92. webscout/models.py +181 -0
  93. webscout/optimizers.py +1 -1
  94. webscout/prompt_manager.py +2 -8
  95. webscout/scout/core/scout.py +1 -4
  96. webscout/scout/core/search_result.py +1 -1
  97. webscout/scout/core/text_utils.py +1 -1
  98. webscout/scout/core.py +2 -5
  99. webscout/scout/element.py +1 -1
  100. webscout/scout/parsers/html_parser.py +1 -1
  101. webscout/scout/utils.py +0 -1
  102. webscout/swiftcli/__init__.py +1 -3
  103. webscout/tempid.py +1 -1
  104. webscout/update_checker.py +55 -95
  105. webscout/version.py +1 -1
  106. webscout/webscout_search_async.py +1 -2
  107. webscout/yep_search.py +297 -297
  108. webscout-7.6.dist-info/LICENSE.md +146 -0
  109. {webscout-7.4.dist-info → webscout-7.6.dist-info}/METADATA +104 -514
  110. {webscout-7.4.dist-info → webscout-7.6.dist-info}/RECORD +113 -120
  111. webscout/Extra/autollama.py +0 -231
  112. webscout/Local/__init__.py +0 -10
  113. webscout/Local/_version.py +0 -3
  114. webscout/Local/formats.py +0 -747
  115. webscout/Local/model.py +0 -1368
  116. webscout/Local/samplers.py +0 -125
  117. webscout/Local/thread.py +0 -539
  118. webscout/Local/ui.py +0 -401
  119. webscout/Local/utils.py +0 -388
  120. webscout/Provider/Amigo.py +0 -274
  121. webscout/Provider/Bing.py +0 -243
  122. webscout/Provider/DiscordRocks.py +0 -253
  123. webscout/Provider/TTI/blackbox/__init__.py +0 -4
  124. webscout/Provider/TTI/blackbox/async_blackbox.py +0 -212
  125. webscout/Provider/TTI/blackbox/sync_blackbox.py +0 -199
  126. webscout/Provider/TTI/deepinfra/__init__.py +0 -4
  127. webscout/Provider/TTI/deepinfra/async_deepinfra.py +0 -227
  128. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +0 -199
  129. webscout/Provider/TTI/imgninza/__init__.py +0 -4
  130. webscout/Provider/TTI/imgninza/async_ninza.py +0 -214
  131. webscout/Provider/TTI/imgninza/sync_ninza.py +0 -209
  132. webscout/Provider/TTS/voicepod.py +0 -117
  133. webscout/Provider/dgaf.py +0 -214
  134. webscout-7.4.dist-info/LICENSE.md +0 -211
  135. {webscout-7.4.dist-info → webscout-7.6.dist-info}/WHEEL +0 -0
  136. {webscout-7.4.dist-info → webscout-7.6.dist-info}/entry_points.txt +0 -0
  137. {webscout-7.4.dist-info → webscout-7.6.dist-info}/top_level.txt +0 -0
webscout/Extra/gguf.py CHANGED
@@ -1,428 +1,652 @@
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
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()