webscout 8.2.9__py3-none-any.whl → 2026.1.19__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.
Files changed (413) hide show
  1. webscout/AIauto.py +524 -251
  2. webscout/AIbase.py +247 -319
  3. webscout/AIutel.py +68 -703
  4. webscout/Bard.py +1072 -1026
  5. webscout/Extra/GitToolkit/__init__.py +10 -10
  6. webscout/Extra/GitToolkit/gitapi/__init__.py +20 -12
  7. webscout/Extra/GitToolkit/gitapi/gist.py +142 -0
  8. webscout/Extra/GitToolkit/gitapi/organization.py +91 -0
  9. webscout/Extra/GitToolkit/gitapi/repository.py +308 -195
  10. webscout/Extra/GitToolkit/gitapi/search.py +162 -0
  11. webscout/Extra/GitToolkit/gitapi/trending.py +236 -0
  12. webscout/Extra/GitToolkit/gitapi/user.py +128 -96
  13. webscout/Extra/GitToolkit/gitapi/utils.py +82 -62
  14. webscout/Extra/YTToolkit/README.md +443 -375
  15. webscout/Extra/YTToolkit/YTdownloader.py +953 -957
  16. webscout/Extra/YTToolkit/__init__.py +3 -3
  17. webscout/Extra/YTToolkit/transcriber.py +595 -476
  18. webscout/Extra/YTToolkit/ytapi/README.md +230 -44
  19. webscout/Extra/YTToolkit/ytapi/__init__.py +22 -6
  20. webscout/Extra/YTToolkit/ytapi/captions.py +190 -0
  21. webscout/Extra/YTToolkit/ytapi/channel.py +302 -307
  22. webscout/Extra/YTToolkit/ytapi/errors.py +13 -13
  23. webscout/Extra/YTToolkit/ytapi/extras.py +178 -118
  24. webscout/Extra/YTToolkit/ytapi/hashtag.py +120 -0
  25. webscout/Extra/YTToolkit/ytapi/https.py +89 -88
  26. webscout/Extra/YTToolkit/ytapi/patterns.py +61 -61
  27. webscout/Extra/YTToolkit/ytapi/playlist.py +59 -59
  28. webscout/Extra/YTToolkit/ytapi/pool.py +8 -8
  29. webscout/Extra/YTToolkit/ytapi/query.py +143 -40
  30. webscout/Extra/YTToolkit/ytapi/shorts.py +122 -0
  31. webscout/Extra/YTToolkit/ytapi/stream.py +68 -63
  32. webscout/Extra/YTToolkit/ytapi/suggestions.py +97 -0
  33. webscout/Extra/YTToolkit/ytapi/utils.py +66 -62
  34. webscout/Extra/YTToolkit/ytapi/video.py +403 -232
  35. webscout/Extra/__init__.py +2 -3
  36. webscout/Extra/gguf.py +1298 -684
  37. webscout/Extra/tempmail/README.md +487 -487
  38. webscout/Extra/tempmail/__init__.py +28 -28
  39. webscout/Extra/tempmail/async_utils.py +143 -141
  40. webscout/Extra/tempmail/base.py +172 -161
  41. webscout/Extra/tempmail/cli.py +191 -187
  42. webscout/Extra/tempmail/emailnator.py +88 -84
  43. webscout/Extra/tempmail/mail_tm.py +378 -361
  44. webscout/Extra/tempmail/temp_mail_io.py +304 -292
  45. webscout/Extra/weather.py +196 -194
  46. webscout/Extra/weather_ascii.py +17 -15
  47. webscout/Provider/AISEARCH/PERPLEXED_search.py +175 -0
  48. webscout/Provider/AISEARCH/Perplexity.py +292 -333
  49. webscout/Provider/AISEARCH/README.md +106 -279
  50. webscout/Provider/AISEARCH/__init__.py +16 -9
  51. webscout/Provider/AISEARCH/brave_search.py +298 -0
  52. webscout/Provider/AISEARCH/iask_search.py +357 -410
  53. webscout/Provider/AISEARCH/monica_search.py +200 -220
  54. webscout/Provider/AISEARCH/webpilotai_search.py +242 -255
  55. webscout/Provider/Algion.py +413 -0
  56. webscout/Provider/Andi.py +74 -69
  57. webscout/Provider/Apriel.py +313 -0
  58. webscout/Provider/Ayle.py +323 -0
  59. webscout/Provider/ChatSandbox.py +329 -342
  60. webscout/Provider/ClaudeOnline.py +365 -0
  61. webscout/Provider/Cohere.py +232 -208
  62. webscout/Provider/DeepAI.py +367 -0
  63. webscout/Provider/Deepinfra.py +467 -340
  64. webscout/Provider/EssentialAI.py +217 -0
  65. webscout/Provider/ExaAI.py +274 -261
  66. webscout/Provider/Gemini.py +175 -169
  67. webscout/Provider/GithubChat.py +385 -369
  68. webscout/Provider/Gradient.py +286 -0
  69. webscout/Provider/Groq.py +556 -801
  70. webscout/Provider/HadadXYZ.py +323 -0
  71. webscout/Provider/HeckAI.py +392 -375
  72. webscout/Provider/HuggingFace.py +387 -0
  73. webscout/Provider/IBM.py +340 -0
  74. webscout/Provider/Jadve.py +317 -291
  75. webscout/Provider/K2Think.py +306 -0
  76. webscout/Provider/Koboldai.py +221 -384
  77. webscout/Provider/Netwrck.py +273 -270
  78. webscout/Provider/Nvidia.py +310 -0
  79. webscout/Provider/OPENAI/DeepAI.py +489 -0
  80. webscout/Provider/OPENAI/K2Think.py +423 -0
  81. webscout/Provider/OPENAI/PI.py +463 -0
  82. webscout/Provider/OPENAI/README.md +890 -952
  83. webscout/Provider/OPENAI/TogetherAI.py +405 -0
  84. webscout/Provider/OPENAI/TwoAI.py +255 -357
  85. webscout/Provider/OPENAI/__init__.py +148 -40
  86. webscout/Provider/OPENAI/ai4chat.py +348 -293
  87. webscout/Provider/OPENAI/akashgpt.py +436 -0
  88. webscout/Provider/OPENAI/algion.py +303 -0
  89. webscout/Provider/OPENAI/{exachat.py → ayle.py} +365 -444
  90. webscout/Provider/OPENAI/base.py +253 -249
  91. webscout/Provider/OPENAI/cerebras.py +296 -0
  92. webscout/Provider/OPENAI/chatgpt.py +870 -556
  93. webscout/Provider/OPENAI/chatsandbox.py +233 -173
  94. webscout/Provider/OPENAI/deepinfra.py +403 -322
  95. webscout/Provider/OPENAI/e2b.py +2370 -1414
  96. webscout/Provider/OPENAI/elmo.py +278 -0
  97. webscout/Provider/OPENAI/exaai.py +452 -417
  98. webscout/Provider/OPENAI/freeassist.py +446 -0
  99. webscout/Provider/OPENAI/gradient.py +448 -0
  100. webscout/Provider/OPENAI/groq.py +380 -364
  101. webscout/Provider/OPENAI/hadadxyz.py +292 -0
  102. webscout/Provider/OPENAI/heckai.py +333 -308
  103. webscout/Provider/OPENAI/huggingface.py +321 -0
  104. webscout/Provider/OPENAI/ibm.py +425 -0
  105. webscout/Provider/OPENAI/llmchat.py +253 -0
  106. webscout/Provider/OPENAI/llmchatco.py +378 -335
  107. webscout/Provider/OPENAI/meta.py +541 -0
  108. webscout/Provider/OPENAI/netwrck.py +374 -357
  109. webscout/Provider/OPENAI/nvidia.py +317 -0
  110. webscout/Provider/OPENAI/oivscode.py +348 -287
  111. webscout/Provider/OPENAI/openrouter.py +328 -0
  112. webscout/Provider/OPENAI/pydantic_imports.py +1 -172
  113. webscout/Provider/OPENAI/sambanova.py +397 -0
  114. webscout/Provider/OPENAI/sonus.py +305 -304
  115. webscout/Provider/OPENAI/textpollinations.py +370 -339
  116. webscout/Provider/OPENAI/toolbaz.py +375 -413
  117. webscout/Provider/OPENAI/typefully.py +419 -355
  118. webscout/Provider/OPENAI/typliai.py +279 -0
  119. webscout/Provider/OPENAI/utils.py +314 -318
  120. webscout/Provider/OPENAI/wisecat.py +359 -387
  121. webscout/Provider/OPENAI/writecream.py +185 -163
  122. webscout/Provider/OPENAI/x0gpt.py +462 -365
  123. webscout/Provider/OPENAI/zenmux.py +380 -0
  124. webscout/Provider/OpenRouter.py +386 -0
  125. webscout/Provider/Openai.py +337 -496
  126. webscout/Provider/PI.py +443 -429
  127. webscout/Provider/QwenLM.py +346 -254
  128. webscout/Provider/STT/__init__.py +28 -0
  129. webscout/Provider/STT/base.py +303 -0
  130. webscout/Provider/STT/elevenlabs.py +264 -0
  131. webscout/Provider/Sambanova.py +317 -0
  132. webscout/Provider/TTI/README.md +69 -82
  133. webscout/Provider/TTI/__init__.py +37 -7
  134. webscout/Provider/TTI/base.py +147 -64
  135. webscout/Provider/TTI/claudeonline.py +393 -0
  136. webscout/Provider/TTI/magicstudio.py +292 -201
  137. webscout/Provider/TTI/miragic.py +180 -0
  138. webscout/Provider/TTI/pollinations.py +331 -221
  139. webscout/Provider/TTI/together.py +334 -0
  140. webscout/Provider/TTI/utils.py +14 -11
  141. webscout/Provider/TTS/README.md +186 -192
  142. webscout/Provider/TTS/__init__.py +43 -10
  143. webscout/Provider/TTS/base.py +523 -159
  144. webscout/Provider/TTS/deepgram.py +286 -156
  145. webscout/Provider/TTS/elevenlabs.py +189 -111
  146. webscout/Provider/TTS/freetts.py +218 -0
  147. webscout/Provider/TTS/murfai.py +288 -113
  148. webscout/Provider/TTS/openai_fm.py +364 -129
  149. webscout/Provider/TTS/parler.py +203 -111
  150. webscout/Provider/TTS/qwen.py +334 -0
  151. webscout/Provider/TTS/sherpa.py +286 -0
  152. webscout/Provider/TTS/speechma.py +693 -580
  153. webscout/Provider/TTS/streamElements.py +275 -333
  154. webscout/Provider/TTS/utils.py +280 -280
  155. webscout/Provider/TextPollinationsAI.py +331 -308
  156. webscout/Provider/TogetherAI.py +450 -0
  157. webscout/Provider/TwoAI.py +309 -475
  158. webscout/Provider/TypliAI.py +311 -305
  159. webscout/Provider/UNFINISHED/ChatHub.py +219 -209
  160. webscout/Provider/{OPENAI/glider.py → UNFINISHED/ChutesAI.py} +331 -326
  161. webscout/Provider/{GizAI.py → UNFINISHED/GizAI.py} +300 -295
  162. webscout/Provider/{Marcus.py → UNFINISHED/Marcus.py} +218 -198
  163. webscout/Provider/UNFINISHED/Qodo.py +481 -0
  164. webscout/Provider/{MCPCore.py → UNFINISHED/XenAI.py} +330 -315
  165. webscout/Provider/UNFINISHED/Youchat.py +347 -330
  166. webscout/Provider/UNFINISHED/aihumanizer.py +41 -0
  167. webscout/Provider/UNFINISHED/grammerchecker.py +37 -0
  168. webscout/Provider/UNFINISHED/liner.py +342 -0
  169. webscout/Provider/UNFINISHED/liner_api_request.py +246 -263
  170. webscout/Provider/{samurai.py → UNFINISHED/samurai.py} +231 -224
  171. webscout/Provider/WiseCat.py +256 -233
  172. webscout/Provider/WrDoChat.py +390 -370
  173. webscout/Provider/__init__.py +115 -174
  174. webscout/Provider/ai4chat.py +181 -174
  175. webscout/Provider/akashgpt.py +330 -335
  176. webscout/Provider/cerebras.py +397 -290
  177. webscout/Provider/cleeai.py +236 -213
  178. webscout/Provider/elmo.py +291 -283
  179. webscout/Provider/geminiapi.py +343 -208
  180. webscout/Provider/julius.py +245 -223
  181. webscout/Provider/learnfastai.py +333 -325
  182. webscout/Provider/llama3mitril.py +230 -215
  183. webscout/Provider/llmchat.py +308 -258
  184. webscout/Provider/llmchatco.py +321 -306
  185. webscout/Provider/meta.py +996 -801
  186. webscout/Provider/oivscode.py +332 -309
  187. webscout/Provider/searchchat.py +316 -292
  188. webscout/Provider/sonus.py +264 -258
  189. webscout/Provider/toolbaz.py +359 -353
  190. webscout/Provider/turboseek.py +332 -266
  191. webscout/Provider/typefully.py +262 -202
  192. webscout/Provider/x0gpt.py +332 -299
  193. webscout/__init__.py +31 -39
  194. webscout/__main__.py +5 -5
  195. webscout/cli.py +585 -524
  196. webscout/client.py +1497 -70
  197. webscout/conversation.py +140 -436
  198. webscout/exceptions.py +383 -362
  199. webscout/litagent/__init__.py +29 -29
  200. webscout/litagent/agent.py +492 -455
  201. webscout/litagent/constants.py +60 -60
  202. webscout/models.py +505 -181
  203. webscout/optimizers.py +74 -420
  204. webscout/prompt_manager.py +376 -288
  205. webscout/sanitize.py +1514 -0
  206. webscout/scout/README.md +452 -404
  207. webscout/scout/__init__.py +8 -8
  208. webscout/scout/core/__init__.py +7 -7
  209. webscout/scout/core/crawler.py +330 -210
  210. webscout/scout/core/scout.py +800 -607
  211. webscout/scout/core/search_result.py +51 -96
  212. webscout/scout/core/text_analyzer.py +64 -63
  213. webscout/scout/core/text_utils.py +412 -277
  214. webscout/scout/core/web_analyzer.py +54 -52
  215. webscout/scout/element.py +872 -478
  216. webscout/scout/parsers/__init__.py +70 -69
  217. webscout/scout/parsers/html5lib_parser.py +182 -172
  218. webscout/scout/parsers/html_parser.py +238 -236
  219. webscout/scout/parsers/lxml_parser.py +203 -178
  220. webscout/scout/utils.py +38 -37
  221. webscout/search/__init__.py +47 -0
  222. webscout/search/base.py +201 -0
  223. webscout/search/bing_main.py +45 -0
  224. webscout/search/brave_main.py +92 -0
  225. webscout/search/duckduckgo_main.py +57 -0
  226. webscout/search/engines/__init__.py +127 -0
  227. webscout/search/engines/bing/__init__.py +15 -0
  228. webscout/search/engines/bing/base.py +35 -0
  229. webscout/search/engines/bing/images.py +114 -0
  230. webscout/search/engines/bing/news.py +96 -0
  231. webscout/search/engines/bing/suggestions.py +36 -0
  232. webscout/search/engines/bing/text.py +109 -0
  233. webscout/search/engines/brave/__init__.py +19 -0
  234. webscout/search/engines/brave/base.py +47 -0
  235. webscout/search/engines/brave/images.py +213 -0
  236. webscout/search/engines/brave/news.py +353 -0
  237. webscout/search/engines/brave/suggestions.py +318 -0
  238. webscout/search/engines/brave/text.py +167 -0
  239. webscout/search/engines/brave/videos.py +364 -0
  240. webscout/search/engines/duckduckgo/__init__.py +25 -0
  241. webscout/search/engines/duckduckgo/answers.py +80 -0
  242. webscout/search/engines/duckduckgo/base.py +189 -0
  243. webscout/search/engines/duckduckgo/images.py +100 -0
  244. webscout/search/engines/duckduckgo/maps.py +183 -0
  245. webscout/search/engines/duckduckgo/news.py +70 -0
  246. webscout/search/engines/duckduckgo/suggestions.py +22 -0
  247. webscout/search/engines/duckduckgo/text.py +221 -0
  248. webscout/search/engines/duckduckgo/translate.py +48 -0
  249. webscout/search/engines/duckduckgo/videos.py +80 -0
  250. webscout/search/engines/duckduckgo/weather.py +84 -0
  251. webscout/search/engines/mojeek.py +61 -0
  252. webscout/search/engines/wikipedia.py +77 -0
  253. webscout/search/engines/yahoo/__init__.py +41 -0
  254. webscout/search/engines/yahoo/answers.py +19 -0
  255. webscout/search/engines/yahoo/base.py +34 -0
  256. webscout/search/engines/yahoo/images.py +323 -0
  257. webscout/search/engines/yahoo/maps.py +19 -0
  258. webscout/search/engines/yahoo/news.py +258 -0
  259. webscout/search/engines/yahoo/suggestions.py +140 -0
  260. webscout/search/engines/yahoo/text.py +273 -0
  261. webscout/search/engines/yahoo/translate.py +19 -0
  262. webscout/search/engines/yahoo/videos.py +302 -0
  263. webscout/search/engines/yahoo/weather.py +220 -0
  264. webscout/search/engines/yandex.py +67 -0
  265. webscout/search/engines/yep/__init__.py +13 -0
  266. webscout/search/engines/yep/base.py +34 -0
  267. webscout/search/engines/yep/images.py +101 -0
  268. webscout/search/engines/yep/suggestions.py +38 -0
  269. webscout/search/engines/yep/text.py +99 -0
  270. webscout/search/http_client.py +172 -0
  271. webscout/search/results.py +141 -0
  272. webscout/search/yahoo_main.py +57 -0
  273. webscout/search/yep_main.py +48 -0
  274. webscout/server/__init__.py +48 -0
  275. webscout/server/config.py +78 -0
  276. webscout/server/exceptions.py +69 -0
  277. webscout/server/providers.py +286 -0
  278. webscout/server/request_models.py +131 -0
  279. webscout/server/request_processing.py +404 -0
  280. webscout/server/routes.py +642 -0
  281. webscout/server/server.py +351 -0
  282. webscout/server/ui_templates.py +1171 -0
  283. webscout/swiftcli/__init__.py +79 -95
  284. webscout/swiftcli/core/__init__.py +7 -7
  285. webscout/swiftcli/core/cli.py +574 -297
  286. webscout/swiftcli/core/context.py +98 -104
  287. webscout/swiftcli/core/group.py +268 -241
  288. webscout/swiftcli/decorators/__init__.py +28 -28
  289. webscout/swiftcli/decorators/command.py +243 -221
  290. webscout/swiftcli/decorators/options.py +247 -220
  291. webscout/swiftcli/decorators/output.py +392 -252
  292. webscout/swiftcli/exceptions.py +21 -21
  293. webscout/swiftcli/plugins/__init__.py +9 -9
  294. webscout/swiftcli/plugins/base.py +134 -135
  295. webscout/swiftcli/plugins/manager.py +269 -269
  296. webscout/swiftcli/utils/__init__.py +58 -59
  297. webscout/swiftcli/utils/formatting.py +251 -252
  298. webscout/swiftcli/utils/parsing.py +368 -267
  299. webscout/update_checker.py +280 -136
  300. webscout/utils.py +28 -14
  301. webscout/version.py +2 -1
  302. webscout/version.py.bak +3 -0
  303. webscout/zeroart/__init__.py +218 -135
  304. webscout/zeroart/base.py +70 -66
  305. webscout/zeroart/effects.py +155 -101
  306. webscout/zeroart/fonts.py +1799 -1239
  307. webscout-2026.1.19.dist-info/METADATA +638 -0
  308. webscout-2026.1.19.dist-info/RECORD +312 -0
  309. {webscout-8.2.9.dist-info → webscout-2026.1.19.dist-info}/WHEEL +1 -1
  310. {webscout-8.2.9.dist-info → webscout-2026.1.19.dist-info}/entry_points.txt +1 -1
  311. webscout/DWEBS.py +0 -520
  312. webscout/Extra/Act.md +0 -309
  313. webscout/Extra/GitToolkit/gitapi/README.md +0 -110
  314. webscout/Extra/autocoder/__init__.py +0 -9
  315. webscout/Extra/autocoder/autocoder.py +0 -1105
  316. webscout/Extra/autocoder/autocoder_utiles.py +0 -332
  317. webscout/Extra/gguf.md +0 -430
  318. webscout/Extra/weather.md +0 -281
  319. webscout/Litlogger/README.md +0 -10
  320. webscout/Litlogger/__init__.py +0 -15
  321. webscout/Litlogger/formats.py +0 -4
  322. webscout/Litlogger/handlers.py +0 -103
  323. webscout/Litlogger/levels.py +0 -13
  324. webscout/Litlogger/logger.py +0 -92
  325. webscout/Provider/AI21.py +0 -177
  326. webscout/Provider/AISEARCH/DeepFind.py +0 -254
  327. webscout/Provider/AISEARCH/felo_search.py +0 -202
  328. webscout/Provider/AISEARCH/genspark_search.py +0 -324
  329. webscout/Provider/AISEARCH/hika_search.py +0 -186
  330. webscout/Provider/AISEARCH/scira_search.py +0 -298
  331. webscout/Provider/Aitopia.py +0 -316
  332. webscout/Provider/AllenAI.py +0 -440
  333. webscout/Provider/Blackboxai.py +0 -791
  334. webscout/Provider/ChatGPTClone.py +0 -237
  335. webscout/Provider/ChatGPTGratis.py +0 -194
  336. webscout/Provider/Cloudflare.py +0 -324
  337. webscout/Provider/ExaChat.py +0 -358
  338. webscout/Provider/Flowith.py +0 -217
  339. webscout/Provider/FreeGemini.py +0 -250
  340. webscout/Provider/Glider.py +0 -225
  341. webscout/Provider/HF_space/__init__.py +0 -0
  342. webscout/Provider/HF_space/qwen_qwen2.py +0 -206
  343. webscout/Provider/HuggingFaceChat.py +0 -469
  344. webscout/Provider/Hunyuan.py +0 -283
  345. webscout/Provider/LambdaChat.py +0 -411
  346. webscout/Provider/Llama3.py +0 -259
  347. webscout/Provider/Nemotron.py +0 -218
  348. webscout/Provider/OLLAMA.py +0 -396
  349. webscout/Provider/OPENAI/BLACKBOXAI.py +0 -766
  350. webscout/Provider/OPENAI/Cloudflare.py +0 -378
  351. webscout/Provider/OPENAI/FreeGemini.py +0 -283
  352. webscout/Provider/OPENAI/NEMOTRON.py +0 -232
  353. webscout/Provider/OPENAI/Qwen3.py +0 -283
  354. webscout/Provider/OPENAI/api.py +0 -969
  355. webscout/Provider/OPENAI/c4ai.py +0 -373
  356. webscout/Provider/OPENAI/chatgptclone.py +0 -494
  357. webscout/Provider/OPENAI/copilot.py +0 -242
  358. webscout/Provider/OPENAI/flowith.py +0 -162
  359. webscout/Provider/OPENAI/freeaichat.py +0 -359
  360. webscout/Provider/OPENAI/mcpcore.py +0 -389
  361. webscout/Provider/OPENAI/multichat.py +0 -376
  362. webscout/Provider/OPENAI/opkfc.py +0 -496
  363. webscout/Provider/OPENAI/scirachat.py +0 -477
  364. webscout/Provider/OPENAI/standardinput.py +0 -433
  365. webscout/Provider/OPENAI/typegpt.py +0 -364
  366. webscout/Provider/OPENAI/uncovrAI.py +0 -463
  367. webscout/Provider/OPENAI/venice.py +0 -431
  368. webscout/Provider/OPENAI/yep.py +0 -382
  369. webscout/Provider/OpenGPT.py +0 -209
  370. webscout/Provider/Perplexitylabs.py +0 -415
  371. webscout/Provider/Reka.py +0 -214
  372. webscout/Provider/StandardInput.py +0 -290
  373. webscout/Provider/TTI/aiarta.py +0 -365
  374. webscout/Provider/TTI/artbit.py +0 -0
  375. webscout/Provider/TTI/fastflux.py +0 -200
  376. webscout/Provider/TTI/piclumen.py +0 -203
  377. webscout/Provider/TTI/pixelmuse.py +0 -225
  378. webscout/Provider/TTS/gesserit.py +0 -128
  379. webscout/Provider/TTS/sthir.py +0 -94
  380. webscout/Provider/TeachAnything.py +0 -229
  381. webscout/Provider/UNFINISHED/puterjs.py +0 -635
  382. webscout/Provider/UNFINISHED/test_lmarena.py +0 -119
  383. webscout/Provider/Venice.py +0 -258
  384. webscout/Provider/VercelAI.py +0 -253
  385. webscout/Provider/Writecream.py +0 -246
  386. webscout/Provider/WritingMate.py +0 -269
  387. webscout/Provider/asksteve.py +0 -220
  388. webscout/Provider/chatglm.py +0 -215
  389. webscout/Provider/copilot.py +0 -425
  390. webscout/Provider/freeaichat.py +0 -285
  391. webscout/Provider/granite.py +0 -235
  392. webscout/Provider/hermes.py +0 -266
  393. webscout/Provider/koala.py +0 -170
  394. webscout/Provider/lmarena.py +0 -198
  395. webscout/Provider/multichat.py +0 -364
  396. webscout/Provider/scira_chat.py +0 -299
  397. webscout/Provider/scnet.py +0 -243
  398. webscout/Provider/talkai.py +0 -194
  399. webscout/Provider/typegpt.py +0 -289
  400. webscout/Provider/uncovr.py +0 -368
  401. webscout/Provider/yep.py +0 -389
  402. webscout/litagent/Readme.md +0 -276
  403. webscout/litprinter/__init__.py +0 -59
  404. webscout/swiftcli/Readme.md +0 -323
  405. webscout/tempid.py +0 -128
  406. webscout/webscout_search.py +0 -1184
  407. webscout/webscout_search_async.py +0 -654
  408. webscout/yep_search.py +0 -347
  409. webscout/zeroart/README.md +0 -89
  410. webscout-8.2.9.dist-info/METADATA +0 -1033
  411. webscout-8.2.9.dist-info/RECORD +0 -289
  412. {webscout-8.2.9.dist-info → webscout-2026.1.19.dist-info}/licenses/LICENSE.md +0 -0
  413. {webscout-8.2.9.dist-info → webscout-2026.1.19.dist-info}/top_level.txt +0 -0
webscout/Extra/gguf.py CHANGED
@@ -1,684 +1,1298 @@
1
- """
2
- Convert Hugging Face models to GGUF format with advanced features.
3
-
4
- For detailed documentation, see: webscout/Extra/gguf.md
5
-
6
- >>> python -m webscout.Extra.gguf convert -m "OEvortex/HelpingAI-Lite-1.5T" -q "q4_k_m,q5_k_m"
7
- >>> # With upload options:
8
- >>> python -m webscout.Extra.gguf convert -m "your-model" -u "username" -t "token" -q "q4_k_m"
9
- >>> # With imatrix quantization:
10
- >>> python -m webscout.Extra.gguf convert -m "your-model" -i -q "iq4_nl" -t "train_data.txt"
11
- >>> # With model splitting:
12
- >>> python -m webscout.Extra.gguf convert -m "your-model" -s --split-max-tensors 256
13
- """
14
-
15
- import subprocess
16
- import os
17
- import sys
18
- import signal
19
- import tempfile
20
- import platform
21
- from pathlib import Path
22
- from typing import Optional, Dict, List, Any, Union, Literal, TypedDict, Set
23
-
24
- from huggingface_hub import HfApi
25
- from webscout.zeroart import figlet_format
26
- from rich.console import Console
27
- from rich.panel import Panel
28
- from rich.table import Table
29
- from ..swiftcli import CLI, option
30
-
31
- console = Console()
32
-
33
- class ConversionError(Exception):
34
- """Custom exception for when things don't go as planned! ⚠️"""
35
- pass
36
-
37
- class QuantizationMethod(TypedDict):
38
- """Type definition for quantization method descriptions."""
39
- description: str
40
-
41
- class ModelConverter:
42
- """Handles the conversion of Hugging Face models to GGUF format."""
43
-
44
- VALID_METHODS: Dict[str, str] = {
45
- "fp16": "16-bit floating point - maximum accuracy, largest size",
46
- "q2_k": "2-bit quantization (smallest size, lowest accuracy)",
47
- "q3_k_l": "3-bit quantization (large) - balanced for size/accuracy",
48
- "q3_k_m": "3-bit quantization (medium) - good balance for most use cases",
49
- "q3_k_s": "3-bit quantization (small) - optimized for speed",
50
- "q4_0": "4-bit quantization (version 0) - standard 4-bit compression",
51
- "q4_1": "4-bit quantization (version 1) - improved accuracy over q4_0",
52
- "q4_k_m": "4-bit quantization (medium) - balanced for most models",
53
- "q4_k_s": "4-bit quantization (small) - optimized for speed",
54
- "q5_0": "5-bit quantization (version 0) - high accuracy, larger size",
55
- "q5_1": "5-bit quantization (version 1) - improved accuracy over q5_0",
56
- "q5_k_m": "5-bit quantization (medium) - best balance for quality/size",
57
- "q5_k_s": "5-bit quantization (small) - optimized for speed",
58
- "q6_k": "6-bit quantization - highest accuracy, largest size",
59
- "q8_0": "8-bit quantization - maximum accuracy, largest size"
60
- }
61
-
62
- VALID_IMATRIX_METHODS: Dict[str, str] = {
63
- "iq3_m": "3-bit imatrix quantization (medium) - balanced importance-based",
64
- "iq3_xxs": "3-bit imatrix quantization (extra extra small) - maximum compression",
65
- "q4_k_m": "4-bit imatrix quantization (medium) - balanced importance-based",
66
- "q4_k_s": "4-bit imatrix quantization (small) - optimized for speed",
67
- "iq4_nl": "4-bit imatrix quantization (non-linear) - best accuracy for 4-bit",
68
- "iq4_xs": "4-bit imatrix quantization (extra small) - maximum compression",
69
- "q5_k_m": "5-bit imatrix quantization (medium) - balanced importance-based",
70
- "q5_k_s": "5-bit imatrix quantization (small) - optimized for speed"
71
- }
72
-
73
- def __init__(
74
- self,
75
- model_id: str,
76
- username: Optional[str] = None,
77
- token: Optional[str] = None,
78
- quantization_methods: str = "q4_k_m",
79
- use_imatrix: bool = False,
80
- train_data_file: Optional[str] = None,
81
- split_model: bool = False,
82
- split_max_tensors: int = 256,
83
- split_max_size: Optional[str] = None
84
- ) -> None:
85
- self.model_id = model_id
86
- self.username = username
87
- self.token = token
88
- self.quantization_methods = quantization_methods.split(',')
89
- self.model_name = model_id.split('/')[-1]
90
- self.workspace = Path(os.getcwd())
91
- self.use_imatrix = use_imatrix
92
- self.train_data_file = train_data_file
93
- self.split_model = split_model
94
- self.split_max_tensors = split_max_tensors
95
- self.split_max_size = split_max_size
96
- self.fp16_only = "fp16" in self.quantization_methods and len(self.quantization_methods) == 1
97
-
98
- def validate_inputs(self) -> None:
99
- """Validates all input parameters."""
100
- if not '/' in self.model_id:
101
- raise ValueError("Invalid model ID format. Expected format: 'organization/model-name'")
102
-
103
- if self.use_imatrix:
104
- invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_IMATRIX_METHODS]
105
- if invalid_methods:
106
- raise ValueError(
107
- f"Invalid imatrix quantization methods: {', '.join(invalid_methods)}.\n"
108
- f"Valid methods are: {', '.join(self.VALID_IMATRIX_METHODS.keys())}"
109
- )
110
- if not self.train_data_file and not os.path.exists("llama.cpp/groups_merged.txt"):
111
- raise ValueError("Training data file is required for imatrix quantization")
112
- else:
113
- invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_METHODS]
114
- if invalid_methods:
115
- raise ValueError(
116
- f"Invalid quantization methods: {', '.join(invalid_methods)}.\n"
117
- f"Valid methods are: {', '.join(self.VALID_METHODS.keys())}"
118
- )
119
-
120
- if bool(self.username) != bool(self.token):
121
- raise ValueError("Both username and token must be provided for upload, or neither.")
122
-
123
- if self.split_model and self.split_max_size:
124
- try:
125
- size = int(self.split_max_size[:-1])
126
- unit = self.split_max_size[-1].upper()
127
- if unit not in ['M', 'G']:
128
- raise ValueError("Split max size must end with M or G")
129
- except ValueError:
130
- raise ValueError("Invalid split max size format. Use format like '256M' or '5G'")
131
-
132
- @staticmethod
133
- def check_dependencies() -> Dict[str, bool]:
134
- """Check if all required dependencies are installed."""
135
- dependencies: Dict[str, str] = {
136
- 'git': 'Git version control',
137
- 'pip3': 'Python package installer',
138
- 'huggingface-cli': 'Hugging Face CLI',
139
- 'cmake': 'CMake build system',
140
- 'ninja': 'Ninja build system (optional)'
141
- }
142
-
143
- status: Dict[str, bool] = {}
144
- for cmd, desc in dependencies.items():
145
- status[cmd] = subprocess.run(['which', cmd], capture_output=True, text=True).returncode == 0
146
-
147
- return status
148
-
149
- def detect_hardware(self) -> Dict[str, bool]:
150
- """Detect available hardware acceleration."""
151
- hardware: Dict[str, bool] = {
152
- 'cuda': False,
153
- 'metal': False,
154
- 'opencl': False,
155
- 'vulkan': False,
156
- 'rocm': False
157
- }
158
-
159
- # Check CUDA
160
- try:
161
- if subprocess.run(['nvcc', '--version'], capture_output=True).returncode == 0:
162
- hardware['cuda'] = True
163
- except FileNotFoundError:
164
- pass
165
-
166
- # Check Metal (macOS)
167
- if platform.system() == 'Darwin':
168
- try:
169
- if subprocess.run(['xcrun', '--show-sdk-path'], capture_output=True).returncode == 0:
170
- hardware['metal'] = True
171
- except FileNotFoundError:
172
- pass
173
-
174
- # Check OpenCL
175
- try:
176
- if subprocess.run(['clinfo'], capture_output=True).returncode == 0:
177
- hardware['opencl'] = True
178
- except FileNotFoundError:
179
- pass
180
-
181
- # Check Vulkan
182
- try:
183
- if subprocess.run(['vulkaninfo'], capture_output=True).returncode == 0:
184
- hardware['vulkan'] = True
185
- except FileNotFoundError:
186
- pass
187
-
188
- # Check ROCm
189
- try:
190
- if subprocess.run(['rocm-smi'], capture_output=True).returncode == 0:
191
- hardware['rocm'] = True
192
- except FileNotFoundError:
193
- pass
194
-
195
- return hardware
196
-
197
- def setup_llama_cpp(self) -> None:
198
- """Sets up and builds llama.cpp repository."""
199
- llama_path = self.workspace / "llama.cpp"
200
-
201
- with console.status("[bold green]Setting up llama.cpp...") as status:
202
- # Clone llama.cpp if not exists
203
- if not llama_path.exists():
204
- subprocess.run(['git', 'clone', 'https://github.com/ggerganov/llama.cpp'], check=True)
205
-
206
- os.chdir(llama_path)
207
-
208
- # Check if we're in a Nix environment
209
- is_nix = platform.system() == "Linux" and os.path.exists("/nix/store")
210
-
211
- if is_nix:
212
- console.print("[yellow]Detected Nix environment. Using system Python packages...")
213
- # In Nix, we need to use the system Python packages
214
- try:
215
- # Try to import required packages to check if they're available
216
- import torch # type: ignore
217
- import numpy # type: ignore
218
- import sentencepiece # type: ignore
219
- import transformers # type: ignore
220
- console.print("[green]Required Python packages are already installed.")
221
- except ImportError as e:
222
- console.print("[red]Missing required Python packages in Nix environment.")
223
- console.print("[yellow]Please install them using:")
224
- console.print("nix-shell -p python3Packages.torch python3Packages.numpy python3Packages.sentencepiece python3Packages.transformers")
225
- raise ConversionError("Missing required Python packages in Nix environment")
226
- else:
227
- # In non-Nix environments, install requirements
228
- try:
229
- subprocess.run(['pip3', 'install', '-r', 'requirements.txt'], check=True)
230
- except subprocess.CalledProcessError as e:
231
- if "externally-managed-environment" in str(e):
232
- console.print("[yellow]Detected externally managed Python environment.")
233
- console.print("[yellow]Please install the required packages manually:")
234
- console.print("pip install torch numpy sentencepiece transformers")
235
- raise ConversionError("Failed to install requirements in externally managed environment")
236
- raise
237
-
238
- # Detect available hardware
239
- hardware = self.detect_hardware()
240
- console.print("[bold green]Detected hardware acceleration:")
241
- for hw, available in hardware.items():
242
- console.print(f" {'✓' if available else '✗'} {hw.upper()}")
243
-
244
- # Configure CMake build
245
- cmake_args: List[str] = ['cmake', '-B', 'build']
246
-
247
- # Add hardware acceleration options
248
- if hardware['cuda']:
249
- cmake_args.extend(['-DLLAMA_CUBLAS=ON'])
250
- if hardware['metal']:
251
- cmake_args.extend(['-DLLAMA_METAL=ON'])
252
- if hardware['opencl']:
253
- cmake_args.extend(['-DLLAMA_CLBLAST=ON'])
254
- if hardware['vulkan']:
255
- cmake_args.extend(['-DLLAMA_VULKAN=ON'])
256
- if hardware['rocm']:
257
- cmake_args.extend(['-DLLAMA_HIPBLAS=ON'])
258
-
259
- # Use Ninja if available
260
- if subprocess.run(['which', 'ninja'], capture_output=True).returncode == 0:
261
- cmake_args.extend(['-G', 'Ninja'])
262
-
263
- # Configure the build
264
- subprocess.run(cmake_args, check=True)
265
-
266
- # Build the project
267
- if any(hardware.values()):
268
- status.update("[bold green]Building with hardware acceleration...")
269
- else:
270
- status.update("[bold yellow]Building for CPU only...")
271
-
272
- subprocess.run(['cmake', '--build', 'build', '-j', str(os.cpu_count() or 1)], check=True)
273
-
274
- os.chdir(self.workspace)
275
-
276
- def display_config(self) -> None:
277
- """Displays the current configuration in a formatted table."""
278
- table = Table(title="Configuration", show_header=True, header_style="bold magenta")
279
- table.add_column("Setting", style="cyan")
280
- table.add_column("Value", style="green")
281
-
282
- table.add_row("Model ID", self.model_id)
283
- table.add_row("Model Name", self.model_name)
284
- table.add_row("Username", self.username or "Not provided")
285
- table.add_row("Token", "****" if self.token else "Not provided")
286
- table.add_row("Quantization Methods", "\n".join(
287
- f"{method} ({self.VALID_METHODS[method]})"
288
- for method in self.quantization_methods
289
- ))
290
-
291
- console.print(Panel(table))
292
-
293
- def generate_importance_matrix(self, model_path: str, train_data_path: str, output_path: str) -> None:
294
- """Generates importance matrix for quantization."""
295
- imatrix_command: List[str] = [
296
- "./llama.cpp/build/bin/llama-imatrix",
297
- "-m", model_path,
298
- "-f", train_data_path,
299
- "-ngl", "99",
300
- "--output-frequency", "10",
301
- "-o", output_path,
302
- ]
303
-
304
- if not os.path.isfile(model_path):
305
- raise ConversionError(f"Model file not found: {model_path}")
306
-
307
- console.print("[bold green]Generating importance matrix...")
308
- process = subprocess.Popen(imatrix_command, shell=False)
309
-
310
- try:
311
- process.wait(timeout=60)
312
- except subprocess.TimeoutExpired:
313
- console.print("[yellow]Imatrix computation timed out. Sending SIGINT...")
314
- process.send_signal(signal.SIGINT)
315
- try:
316
- process.wait(timeout=5)
317
- except subprocess.TimeoutExpired:
318
- console.print("[red]Imatrix process still running. Force terminating...")
319
- process.kill()
320
-
321
- if process.returncode != 0:
322
- raise ConversionError("Failed to generate importance matrix")
323
-
324
- console.print("[green]Importance matrix generation completed.")
325
-
326
- def split_model(self, model_path: str, outdir: str) -> List[str]:
327
- """Splits the model into smaller chunks."""
328
- split_cmd: List[str] = [
329
- "./llama.cpp/build/bin/llama-gguf-split",
330
- "--split",
331
- ]
332
-
333
- if self.split_max_size:
334
- split_cmd.extend(["--split-max-size", self.split_max_size])
335
- else:
336
- split_cmd.extend(["--split-max-tensors", str(self.split_max_tensors)])
337
-
338
- model_path_prefix = '.'.join(model_path.split('.')[:-1])
339
- split_cmd.extend([model_path, model_path_prefix])
340
-
341
- console.print(f"[bold green]Splitting model with command: {' '.join(split_cmd)}")
342
-
343
- result = subprocess.run(split_cmd, shell=False, capture_output=True, text=True)
344
-
345
- if result.returncode != 0:
346
- raise ConversionError(f"Error splitting model: {result.stderr}")
347
-
348
- console.print("[green]Model split successfully!")
349
-
350
- # Get list of split files
351
- model_file_prefix = model_path_prefix.split('/')[-1]
352
- split_files = [f for f in os.listdir(outdir)
353
- if f.startswith(model_file_prefix) and f.endswith(".gguf")]
354
-
355
- if not split_files:
356
- raise ConversionError("No split files found")
357
-
358
- return split_files
359
-
360
- def upload_split_files(self, split_files: List[str], outdir: str, repo_id: str) -> None:
361
- """Uploads split model files to Hugging Face."""
362
- api = HfApi(token=self.token)
363
-
364
- for file in split_files:
365
- file_path = os.path.join(outdir, file)
366
- console.print(f"[bold green]Uploading file: {file}")
367
- try:
368
- api.upload_file(
369
- path_or_fileobj=file_path,
370
- path_in_repo=file,
371
- repo_id=repo_id,
372
- )
373
- except Exception as e:
374
- raise ConversionError(f"Error uploading file {file}: {e}")
375
-
376
- def generate_readme(self, quantized_files: List[str]) -> str:
377
- """Generate a README.md file for the Hugging Face Hub."""
378
- readme = f"""# {self.model_name} GGUF
379
-
380
- This repository contains GGUF quantized versions of [{self.model_id}](https://huggingface.co/{self.model_id}).
381
-
382
- ## About
383
-
384
- This model was converted using [Webscout](https://github.com/Webscout/webscout).
385
-
386
- ## Quantization Methods
387
-
388
- The following quantization methods were used:
389
-
390
- """
391
- # Add quantization method descriptions
392
- for method in self.quantization_methods:
393
- if self.use_imatrix:
394
- readme += f"- `{method}`: {self.VALID_IMATRIX_METHODS[method]}\n"
395
- else:
396
- readme += f"- `{method}`: {self.VALID_METHODS[method]}\n"
397
-
398
- readme += """
399
- ## Available Files
400
-
401
- The following quantized files are available:
402
-
403
- """
404
- # Add file information
405
- for file in quantized_files:
406
- readme += f"- `{file}`\n"
407
-
408
- if self.use_imatrix:
409
- readme += """
410
- ## Importance Matrix
411
-
412
- This model was quantized using importance matrix quantization. The `imatrix.dat` file contains the importance matrix used for quantization.
413
-
414
- """
415
-
416
- readme += """
417
- ## Usage
418
-
419
- These GGUF files can be used with [llama.cpp](https://github.com/ggerganov/llama.cpp) and compatible tools.
420
-
421
- Example usage:
422
- ```bash
423
- ./main -m model.gguf -n 1024 --repeat_penalty 1.0 --color -i -r "User:" -f prompts/chat-with-bob.txt
424
- ```
425
-
426
- ## Conversion Process
427
-
428
- This model was converted using the following command:
429
- ```bash
430
- python -m webscout.Extra.gguf convert \\
431
- -m "{self.model_id}" \\
432
- -q "{','.join(self.quantization_methods)}" \\
433
- {f'-i' if self.use_imatrix else ''} \\
434
- {f'--train-data "{self.train_data_file}"' if self.train_data_file else ''} \\
435
- {f'-s' if self.split_model else ''} \\
436
- {f'--split-max-tensors {self.split_max_tensors}' if self.split_model else ''} \\
437
- {f'--split-max-size {self.split_max_size}' if self.split_max_size else ''}
438
- ```
439
-
440
- ## License
441
-
442
- This repository is licensed under the same terms as the original model.
443
- """
444
- return readme
445
-
446
- def upload_readme(self, readme_content: str, repo_id: str) -> None:
447
- """Upload README.md to Hugging Face Hub."""
448
- api = HfApi(token=self.token)
449
- try:
450
- api.upload_file(
451
- path_or_fileobj=readme_content.encode(),
452
- path_in_repo="README.md",
453
- repo_id=repo_id,
454
- )
455
- console.print("[green]README.md uploaded successfully!")
456
- except Exception as e:
457
- console.print(f"[yellow]Warning: Failed to upload README.md: {e}")
458
-
459
- def convert(self) -> None:
460
- """Performs the model conversion process."""
461
- try:
462
- # Display banner and configuration
463
- console.print(f"[bold green]{figlet_format('GGUF Converter')}")
464
- self.display_config()
465
-
466
- # Validate inputs
467
- self.validate_inputs()
468
-
469
- # Check dependencies
470
- deps = self.check_dependencies()
471
- missing = [name for name, installed in deps.items() if not installed and name != 'ninja']
472
- if missing:
473
- raise ConversionError(f"Missing required dependencies: {', '.join(missing)}")
474
-
475
- # Setup llama.cpp
476
- self.setup_llama_cpp()
477
-
478
- # Determine if we need temporary directories (only for uploads)
479
- needs_temp = bool(self.username and self.token)
480
-
481
- if needs_temp:
482
- # Use temporary directories for upload case
483
- with tempfile.TemporaryDirectory() as outdir:
484
- with tempfile.TemporaryDirectory() as tmpdir:
485
- self._convert_with_dirs(tmpdir, outdir)
486
- else:
487
- # Use current directory for local output
488
- outdir = os.getcwd()
489
- tmpdir = os.path.join(outdir, "temp_download")
490
- os.makedirs(tmpdir, exist_ok=True)
491
- try:
492
- self._convert_with_dirs(tmpdir, outdir)
493
- finally:
494
- # Clean up temporary download directory
495
- import shutil
496
- shutil.rmtree(tmpdir, ignore_errors=True)
497
-
498
- # Display success message
499
- console.print(Panel.fit(
500
- "[bold green]✓[/] Conversion completed successfully!\n\n"
501
- f"[cyan]Output files can be found in: {self.workspace / self.model_name}[/]",
502
- title="Success",
503
- border_style="green"
504
- ))
505
-
506
- except Exception as e:
507
- console.print(Panel.fit(
508
- f"[bold red]✗[/] {str(e)}",
509
- title="Error",
510
- border_style="red"
511
- ))
512
- raise
513
-
514
- def _convert_with_dirs(self, tmpdir: str, outdir: str) -> None:
515
- """Helper method to perform conversion with given directories."""
516
- fp16 = str(Path(outdir)/f"{self.model_name}.fp16.gguf")
517
-
518
- # Download model
519
- local_dir = Path(tmpdir)/self.model_name
520
- console.print("[bold green]Downloading model...")
521
- api = HfApi(token=self.token)
522
- api.snapshot_download(
523
- repo_id=self.model_id,
524
- local_dir=local_dir,
525
- local_dir_use_symlinks=False
526
- )
527
-
528
- # Convert to fp16
529
- console.print("[bold green]Converting to fp16...")
530
- result = subprocess.run([
531
- "python", "llama.cpp/convert_hf_to_gguf.py",
532
- str(local_dir),
533
- "--outtype", "f16",
534
- "--outfile", fp16
535
- ], capture_output=True, text=True)
536
-
537
- if result.returncode != 0:
538
- raise ConversionError(f"Error converting to fp16: {result.stderr}")
539
-
540
- # If fp16_only is True, we're done after fp16 conversion
541
- if self.fp16_only:
542
- quantized_files = [f"{self.model_name}.fp16.gguf"]
543
- if self.username and self.token:
544
- api.upload_file(
545
- path_or_fileobj=fp16,
546
- path_in_repo=f"{self.model_name}.fp16.gguf",
547
- repo_id=f"{self.username}/{self.model_name}-GGUF"
548
- )
549
- return
550
-
551
- # Generate importance matrix if needed
552
- imatrix_path: Optional[str] = None
553
- if self.use_imatrix:
554
- train_data_path = self.train_data_file if self.train_data_file else "llama.cpp/groups_merged.txt"
555
- imatrix_path = str(Path(outdir)/"imatrix.dat")
556
- self.generate_importance_matrix(fp16, train_data_path, imatrix_path)
557
-
558
- # Quantize model
559
- console.print("[bold green]Quantizing model...")
560
- quantized_files: List[str] = []
561
- for method in self.quantization_methods:
562
- quantized_name = f"{self.model_name.lower()}-{method.lower()}"
563
- if self.use_imatrix:
564
- quantized_name += "-imat"
565
- quantized_path = str(Path(outdir)/f"{quantized_name}.gguf")
566
-
567
- if self.use_imatrix:
568
- quantize_cmd: List[str] = [
569
- "./llama.cpp/build/bin/llama-quantize",
570
- "--imatrix", imatrix_path,
571
- fp16, quantized_path, method
572
- ]
573
- else:
574
- quantize_cmd = [
575
- "./llama.cpp/build/bin/llama-quantize",
576
- fp16, quantized_path, method
577
- ]
578
-
579
- result = subprocess.run(quantize_cmd, capture_output=True, text=True)
580
- if result.returncode != 0:
581
- raise ConversionError(f"Error quantizing with {method}: {result.stderr}")
582
-
583
- quantized_files.append(f"{quantized_name}.gguf")
584
-
585
- # Split model if requested
586
- if self.split_model:
587
- split_files = self.split_model(quantized_path, outdir)
588
- if self.username and self.token:
589
- self.upload_split_files(split_files, outdir, f"{self.username}/{self.model_name}-GGUF")
590
- else:
591
- # Upload single file if credentials provided
592
- if self.username and self.token:
593
- api.upload_file(
594
- path_or_fileobj=quantized_path,
595
- path_in_repo=f"{self.model_name.lower()}-{self.quantization_methods[0].lower()}.gguf",
596
- repo_id=f"{self.username}/{self.model_name}-GGUF"
597
- )
598
-
599
- # Upload imatrix if generated and credentials provided
600
- if imatrix_path and self.username and self.token:
601
- api.upload_file(
602
- path_or_fileobj=imatrix_path,
603
- path_in_repo="imatrix.dat",
604
- repo_id=f"{self.username}/{self.model_name}-GGUF"
605
- )
606
-
607
- # Generate and upload README if credentials provided
608
- if self.username and self.token:
609
- readme_content = self.generate_readme(quantized_files)
610
- self.upload_readme(readme_content, f"{self.username}/{self.model_name}-GGUF")
611
-
612
- # Initialize CLI with HAI vibes
613
- app = CLI(
614
- name="gguf",
615
- help="Convert HuggingFace models to GGUF format with style! 🔥",
616
- version="1.0.0"
617
- )
618
-
619
- @app.command(name="convert")
620
- @option("-m", "--model-id", help="The HuggingFace model ID (e.g., 'OEvortex/HelpingAI-Lite-1.5T')", required=True)
621
- @option("-u", "--username", help="Your HuggingFace username for uploads", default=None)
622
- @option("-t", "--token", help="Your HuggingFace API token for uploads", default=None)
623
- @option("-q", "--quantization", help="Comma-separated quantization methods", default="q4_k_m")
624
- @option("-i", "--use-imatrix", help="Use importance matrix for quantization", is_flag=True)
625
- @option("--train-data", help="Training data file for imatrix quantization", default=None)
626
- @option("-s", "--split-model", help="Split the model into smaller chunks", is_flag=True)
627
- @option("--split-max-tensors", help="Maximum number of tensors per file when splitting", default=256)
628
- @option("--split-max-size", help="Maximum file size when splitting (e.g., '256M', '5G')", default=None)
629
- def convert_command(
630
- model_id: str,
631
- username: Optional[str] = None,
632
- token: Optional[str] = None,
633
- quantization: str = "q4_k_m",
634
- use_imatrix: bool = False,
635
- train_data: Optional[str] = None,
636
- split_model: bool = False,
637
- split_max_tensors: int = 256,
638
- split_max_size: Optional[str] = None
639
- ) -> None:
640
- """
641
- Convert and quantize HuggingFace models to GGUF format! 🚀
642
-
643
- Args:
644
- model_id (str): Your model's HF ID (like 'OEvortex/HelpingAI-Lite-1.5T') 🎯
645
- username (str, optional): Your HF username for uploads 👤
646
- token (str, optional): Your HF API token 🔑
647
- quantization (str): Quantization methods (default: q4_k_m,q5_k_m) 🎮
648
- use_imatrix (bool): Use importance matrix for quantization 🔍
649
- train_data (str, optional): Training data file for imatrix quantization 📚
650
- split_model (bool): Split the model into smaller chunks 🔪
651
- split_max_tensors (int): Max tensors per file when splitting (default: 256) 📊
652
- split_max_size (str, optional): Max file size when splitting (e.g., '256M', '5G') 📏
653
-
654
- Example:
655
- >>> python -m webscout.Extra.gguf convert \\
656
- ... -m "OEvortex/HelpingAI-Lite-1.5T" \\
657
- ... -q "q4_k_m,q5_k_m"
658
- """
659
- try:
660
- converter = ModelConverter(
661
- model_id=model_id,
662
- username=username,
663
- token=token,
664
- quantization_methods=quantization,
665
- use_imatrix=use_imatrix,
666
- train_data_file=train_data,
667
- split_model=split_model,
668
- split_max_tensors=split_max_tensors,
669
- split_max_size=split_max_size
670
- )
671
- converter.convert()
672
- except (ConversionError, ValueError) as e:
673
- console.print(f"[red]Error: {str(e)}")
674
- sys.exit(1)
675
- except Exception as e:
676
- console.print(f"[red]Unexpected error: {str(e)}")
677
- sys.exit(1)
678
-
679
- def main() -> None:
680
- """Fire up the GGUF converter! 🚀"""
681
- app.run()
682
-
683
- if __name__ == "__main__":
684
- main()
1
+ import os
2
+ import platform
3
+ import signal
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Dict, List, Optional, Set, TypedDict
9
+
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.table import Table
13
+
14
+ from webscout.swiftcli import CLI, option
15
+ from webscout.zeroart import figlet_format
16
+
17
+ # Lazy import for huggingface_hub
18
+ HfApi = None
19
+
20
+ def _ensure_huggingface_hub():
21
+ """Ensure huggingface_hub is imported when needed."""
22
+ global HfApi
23
+ if HfApi is None:
24
+ try:
25
+ from huggingface_hub import HfApi as _HfApi
26
+ HfApi = _HfApi
27
+ except ImportError:
28
+ raise ImportError(
29
+ "huggingface_hub is required for GGUF conversion. "
30
+ "Install it with: pip install huggingface_hub"
31
+ )
32
+ return HfApi
33
+
34
+ console = Console()
35
+
36
+ class ConversionError(Exception):
37
+ """Custom exception for when things don't go as planned! ⚠️"""
38
+ pass
39
+
40
+ class QuantizationMethod(TypedDict):
41
+ """Type definition for quantization method descriptions."""
42
+ description: str
43
+
44
+ class ModelConverter:
45
+ """Handles the conversion of Hugging Face models to GGUF format."""
46
+
47
+ VALID_METHODS: Dict[str, str] = {
48
+ # Full precision types
49
+ "f32": "32-bit floating point - full precision, largest size",
50
+ "fp16": "16-bit floating point - maximum accuracy, large size",
51
+ "f16": "16-bit floating point - alias for fp16",
52
+ "bf16": "bfloat16 - good balance for training and some models",
53
+ "auto": "Auto-detect best 16-bit type based on model tensors",
54
+ # K-Quant types (super-block quantization)
55
+ "q2_k": "2-bit K-quant (smallest size, lowest accuracy)",
56
+ "q2_k_s": "2-bit K-quant small - maximum compression",
57
+ "q3_k_l": "3-bit K-quant large - balanced for size/accuracy",
58
+ "q3_k_m": "3-bit K-quant medium - good balance for most use cases",
59
+ "q3_k_s": "3-bit K-quant small - optimized for speed",
60
+ "q4_0": "4-bit quantization (legacy) - standard 4-bit, auto-repacks for ARM",
61
+ "q4_1": "4-bit quantization (legacy) - improved accuracy over q4_0",
62
+ "q4_k_l": "4-bit K-quant large - highest quality 4-bit",
63
+ "q4_k_m": "4-bit K-quant medium - balanced for most models",
64
+ "q4_k_s": "4-bit K-quant small - optimized for speed",
65
+ "q5_0": "5-bit quantization (legacy) - high accuracy",
66
+ "q5_1": "5-bit quantization (legacy) - improved accuracy over q5_0",
67
+ "q5_k_l": "5-bit K-quant large - highest quality 5-bit",
68
+ "q5_k_m": "5-bit K-quant medium - best balance for quality/size",
69
+ "q5_k_s": "5-bit K-quant small - optimized for speed",
70
+ "q6_k": "6-bit K-quant - near-lossless quality",
71
+ "q8_0": "8-bit quantization - near-original quality",
72
+ # Ternary quantization (experimental)
73
+ "tq1_0": "1-bit ternary quantization - experimental, extreme compression",
74
+ "tq2_0": "2-bit ternary quantization - experimental, very small size"
75
+ }
76
+
77
+ VALID_IMATRIX_METHODS: Dict[str, str] = {
78
+ # 1-bit IQ types (extreme compression, requires imatrix)
79
+ "iq1_s": "1-bit IQ small - extreme compression, requires imatrix",
80
+ "iq1_m": "1-bit IQ medium - extreme compression, requires imatrix",
81
+ # 2-bit IQ types
82
+ "iq2_xxs": "2-bit IQ extra extra small - maximum compression",
83
+ "iq2_xs": "2-bit IQ extra small - very high compression",
84
+ "iq2_s": "2-bit IQ small - high compression",
85
+ "iq2_m": "2-bit IQ medium - balanced compression",
86
+ # 3-bit IQ types
87
+ "iq3_xxs": "3-bit IQ extra extra small - maximum compression",
88
+ "iq3_xs": "3-bit IQ extra small - high compression",
89
+ "iq3_s": "3-bit IQ small - balanced compression",
90
+ "iq3_m": "3-bit IQ medium - balanced importance-based",
91
+ # 4-bit IQ types
92
+ "iq4_nl": "4-bit IQ non-linear - best accuracy for 4-bit",
93
+ "iq4_xs": "4-bit IQ extra small - maximum 4-bit compression",
94
+ # K-Quant types that benefit from imatrix
95
+ "q2_k": "2-bit K-quant with imatrix - improved quality",
96
+ "q2_k_s": "2-bit K-quant small with imatrix",
97
+ "q3_k_s": "3-bit K-quant small with imatrix",
98
+ "q3_k_m": "3-bit K-quant medium with imatrix",
99
+ "q3_k_l": "3-bit K-quant large with imatrix",
100
+ "q4_k_s": "4-bit K-quant small with imatrix",
101
+ "q4_k_m": "4-bit K-quant medium with imatrix",
102
+ "q5_k_s": "5-bit K-quant small with imatrix",
103
+ "q5_k_m": "5-bit K-quant medium with imatrix",
104
+ "q6_k": "6-bit K-quant with imatrix"
105
+ }
106
+ # Default output type options (matches llama.cpp)
107
+ VALID_OUTTYPES: Set[str] = {"f32", "f16", "bf16", "q8_0", "tq1_0", "tq2_0", "auto"}
108
+
109
+ def __init__(
110
+ self,
111
+ model_id: str,
112
+ username: Optional[str] = None,
113
+ token: Optional[str] = None,
114
+ quantization_methods: str = "q4_k_m",
115
+ use_imatrix: bool = False,
116
+ train_data_file: Optional[str] = None,
117
+ split_model: bool = False,
118
+ split_max_tensors: int = 256,
119
+ split_max_size: Optional[str] = None,
120
+ # New llama.cpp options
121
+ outtype: str = "f16",
122
+ vocab_only: bool = False,
123
+ remote: bool = False,
124
+ dry_run: bool = False,
125
+ no_lazy: bool = False,
126
+ model_name: Optional[str] = None,
127
+ small_first_shard: bool = False
128
+ ) -> None:
129
+ self.model_id = model_id
130
+ self.username = username
131
+ self.token = token
132
+ self.quantization_methods = quantization_methods.split(',')
133
+ self.model_name = model_name or model_id.split('/')[-1]
134
+ self.workspace = Path(os.getcwd())
135
+ self.use_imatrix = use_imatrix
136
+ self.train_data_file = train_data_file
137
+ self.use_split = split_model
138
+ self.split_max_tensors = split_max_tensors
139
+ self.split_max_size = split_max_size
140
+ # New llama.cpp options
141
+ self.outtype = outtype.lower()
142
+ self.vocab_only = vocab_only
143
+ self.remote = remote
144
+ self.dry_run = dry_run
145
+ self.no_lazy = no_lazy
146
+ self.small_first_shard = small_first_shard
147
+ # Determine if we only need the base conversion (no quantization)
148
+ self.base_only = self.outtype in self.VALID_OUTTYPES and len(self.quantization_methods) == 1 and self.quantization_methods[0] in ["fp16", "f16", "f32", "bf16", "auto"]
149
+
150
+ def validate_inputs(self) -> None:
151
+ """Validates all input parameters."""
152
+ if '/' not in self.model_id:
153
+ raise ValueError("Invalid model ID format. Expected format: 'organization/model-name'")
154
+
155
+ if self.use_imatrix:
156
+ invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_IMATRIX_METHODS]
157
+ if invalid_methods:
158
+ raise ValueError(
159
+ f"Invalid imatrix quantization methods: {', '.join(invalid_methods)}.\n"
160
+ f"Valid methods are: {', '.join(self.VALID_IMATRIX_METHODS.keys())}"
161
+ )
162
+ if not self.train_data_file and not os.path.exists("llama.cpp/groups_merged.txt"):
163
+ raise ValueError("Training data file is required for imatrix quantization")
164
+ else:
165
+ invalid_methods = [m for m in self.quantization_methods if m not in self.VALID_METHODS]
166
+ if invalid_methods:
167
+ raise ValueError(
168
+ f"Invalid quantization methods: {', '.join(invalid_methods)}.\n"
169
+ f"Valid methods are: {', '.join(self.VALID_METHODS.keys())}"
170
+ )
171
+
172
+ if bool(self.username) != bool(self.token):
173
+ raise ValueError("Both username and token must be provided for upload, or neither.")
174
+
175
+ # Validate outtype
176
+ if self.outtype not in self.VALID_OUTTYPES:
177
+ raise ValueError(
178
+ f"Invalid output type: {self.outtype}.\n"
179
+ f"Valid types are: {', '.join(self.VALID_OUTTYPES)}"
180
+ )
181
+
182
+ if self.use_split and self.split_max_size:
183
+ try:
184
+ # Support K, M, G units (like llama.cpp's split_str_to_n_bytes)
185
+ if self.split_max_size[-1].upper() in ['K', 'M', 'G']:
186
+ int(self.split_max_size[:-1])
187
+ unit = self.split_max_size[-1].upper()
188
+ if unit not in ['K', 'M', 'G']:
189
+ raise ValueError("Split max size must end with K, M, or G")
190
+ elif self.split_max_size.isnumeric():
191
+ int(self.split_max_size)
192
+ else:
193
+ raise ValueError("Invalid format")
194
+ except (ValueError, IndexError):
195
+ raise ValueError("Invalid split max size format. Use format like '256M', '5G', or numeric bytes")
196
+
197
+ @staticmethod
198
+ def check_dependencies() -> Dict[str, bool]:
199
+ """Check if all required dependencies are installed with cross-platform support."""
200
+ system = platform.system()
201
+
202
+ dependencies: Dict[str, str] = {
203
+ 'git': 'Git version control',
204
+ 'cmake': 'CMake build system',
205
+ 'ninja': 'Ninja build system (optional)'
206
+ }
207
+
208
+ # Add platform-specific dependencies
209
+ if system != 'Windows':
210
+ dependencies['pip3'] = 'Python package installer'
211
+ else:
212
+ dependencies['pip'] = 'Python package installer'
213
+
214
+ status: Dict[str, bool] = {}
215
+
216
+ for cmd, desc in dependencies.items():
217
+ try:
218
+ if system == 'Windows':
219
+ # Use 'where' command on Windows
220
+ result = subprocess.run(['where', cmd], capture_output=True, text=True)
221
+ status[cmd] = result.returncode == 0
222
+ else:
223
+ # Use 'which' command on Unix-like systems
224
+ result = subprocess.run(['which', cmd], capture_output=True, text=True)
225
+ status[cmd] = result.returncode == 0
226
+ except (FileNotFoundError, subprocess.SubprocessError):
227
+ status[cmd] = False
228
+
229
+ # Special check for Python - try different variants
230
+ python_variants = ['python3', 'python', 'py'] if system != 'Windows' else ['python', 'py', 'python3']
231
+ status['python'] = False
232
+ for variant in python_variants:
233
+ try:
234
+ if system == 'Windows':
235
+ result = subprocess.run(['where', variant], capture_output=True)
236
+ else:
237
+ result = subprocess.run(['which', variant], capture_output=True)
238
+ if result.returncode == 0:
239
+ status['python'] = True
240
+ break
241
+ except Exception:
242
+ continue
243
+
244
+ # Check for C++ compiler
245
+ cpp_compilers = ['cl', 'g++', 'clang++'] if system == 'Windows' else ['g++', 'clang++']
246
+ status['cpp_compiler'] = False
247
+ for compiler in cpp_compilers:
248
+ try:
249
+ if system == 'Windows':
250
+ result = subprocess.run(['where', compiler], capture_output=True)
251
+ else:
252
+ result = subprocess.run(['which', compiler], capture_output=True)
253
+ if result.returncode == 0:
254
+ status['cpp_compiler'] = True
255
+ break
256
+ except Exception:
257
+ continue
258
+
259
+ dependencies['python'] = 'Python interpreter'
260
+ dependencies['cpp_compiler'] = 'C++ compiler (g++, clang++, or MSVC)'
261
+
262
+ return status
263
+
264
+ def detect_hardware(self) -> Dict[str, bool]:
265
+ """Detect available hardware acceleration with improved cross-platform support."""
266
+ hardware: Dict[str, bool] = {
267
+ 'cuda': False,
268
+ 'metal': False,
269
+ 'opencl': False,
270
+ 'vulkan': False,
271
+ 'rocm': False,
272
+ 'blas': False,
273
+ 'accelerate': False
274
+ }
275
+
276
+ system = platform.system()
277
+
278
+ # Check CUDA
279
+ try:
280
+ # Check for nvcc compiler
281
+ if subprocess.run(['nvcc', '--version'], capture_output=True, shell=(system == 'Windows')).returncode == 0:
282
+ hardware['cuda'] = True
283
+ # Also check for nvidia-smi as fallback
284
+ elif subprocess.run(['nvidia-smi'], capture_output=True, shell=(system == 'Windows')).returncode == 0:
285
+ hardware['cuda'] = True
286
+ except (FileNotFoundError, subprocess.SubprocessError):
287
+ # Check for CUDA libraries on Windows
288
+ if system == 'Windows':
289
+ cuda_paths = [
290
+ os.environ.get('CUDA_PATH'),
291
+ 'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA',
292
+ 'C:\\Program Files (x86)\\NVIDIA GPU Computing Toolkit\\CUDA'
293
+ ]
294
+ for cuda_path in cuda_paths:
295
+ if cuda_path and os.path.exists(cuda_path):
296
+ hardware['cuda'] = True
297
+ break
298
+
299
+ # Check Metal (macOS)
300
+ if system == 'Darwin':
301
+ try:
302
+ # Check for Xcode command line tools
303
+ if subprocess.run(['xcrun', '--show-sdk-path'], capture_output=True).returncode == 0:
304
+ hardware['metal'] = True
305
+ # Check for Metal framework
306
+ if os.path.exists('/System/Library/Frameworks/Metal.framework'):
307
+ hardware['metal'] = True
308
+ # macOS also supports Accelerate framework
309
+ if os.path.exists('/System/Library/Frameworks/Accelerate.framework'):
310
+ hardware['accelerate'] = True
311
+ except (FileNotFoundError, subprocess.SubprocessError):
312
+ pass
313
+
314
+ # Check OpenCL
315
+ try:
316
+ if system == 'Windows':
317
+ # Check for OpenCL on Windows
318
+ opencl_paths = [
319
+ 'C:\\Windows\\System32\\OpenCL.dll',
320
+ 'C:\\Windows\\SysWOW64\\OpenCL.dll'
321
+ ]
322
+ if any(os.path.exists(path) for path in opencl_paths):
323
+ hardware['opencl'] = True
324
+ else:
325
+ if subprocess.run(['clinfo'], capture_output=True).returncode == 0:
326
+ hardware['opencl'] = True
327
+ except (FileNotFoundError, subprocess.SubprocessError):
328
+ pass
329
+
330
+ # Check Vulkan
331
+ try:
332
+ if system == 'Windows':
333
+ # Check for Vulkan on Windows
334
+ vulkan_paths = [
335
+ 'C:\\Windows\\System32\\vulkan-1.dll',
336
+ 'C:\\Windows\\SysWOW64\\vulkan-1.dll'
337
+ ]
338
+ if any(os.path.exists(path) for path in vulkan_paths):
339
+ hardware['vulkan'] = True
340
+ else:
341
+ if subprocess.run(['vulkaninfo'], capture_output=True).returncode == 0:
342
+ hardware['vulkan'] = True
343
+ except (FileNotFoundError, subprocess.SubprocessError):
344
+ pass
345
+
346
+ # Check ROCm (AMD)
347
+ try:
348
+ if subprocess.run(['rocm-smi'], capture_output=True, shell=(system == 'Windows')).returncode == 0:
349
+ hardware['rocm'] = True
350
+ elif system == 'Linux':
351
+ # Check for ROCm installation
352
+ rocm_paths = ['/opt/rocm', '/usr/lib/x86_64-linux-gnu/librocm-smi64.so']
353
+ if any(os.path.exists(path) for path in rocm_paths):
354
+ hardware['rocm'] = True
355
+ except (FileNotFoundError, subprocess.SubprocessError):
356
+ pass
357
+
358
+ # Check for BLAS libraries
359
+ try:
360
+ import numpy as np # type: ignore
361
+ # Check if numpy is linked with optimized BLAS
362
+ config = np.__config__.show()
363
+ if any(lib in str(config).lower() for lib in ['openblas', 'mkl', 'atlas', 'blis']):
364
+ hardware['blas'] = True
365
+ except (ImportError, AttributeError):
366
+ # Fallback: check for common BLAS libraries
367
+ if system == 'Linux':
368
+ blas_libs = ['/usr/lib/x86_64-linux-gnu/libopenblas.so', '/usr/lib/x86_64-linux-gnu/libblas.so']
369
+ if any(os.path.exists(lib) for lib in blas_libs):
370
+ hardware['blas'] = True
371
+ elif system == 'Windows':
372
+ # Check for Intel MKL or OpenBLAS on Windows
373
+ mkl_paths = ['C:\\Program Files (x86)\\Intel\\oneAPI\\mkl']
374
+ if any(os.path.exists(path) for path in mkl_paths):
375
+ hardware['blas'] = True
376
+
377
+ return hardware
378
+
379
+ def setup_llama_cpp(self) -> None:
380
+ """Sets up and builds llama.cpp repository with robust error handling."""
381
+ llama_path = self.workspace / "llama.cpp"
382
+ system = platform.system()
383
+
384
+ with console.status("[bold green]Setting up llama.cpp...") as status:
385
+ # Clone llama.cpp if not exists
386
+ if not llama_path.exists():
387
+ try:
388
+ subprocess.run(['git', 'clone', 'https://github.com/ggerganov/llama.cpp'], check=True)
389
+ except subprocess.CalledProcessError as e:
390
+ raise ConversionError(f"Failed to clone llama.cpp repository: {e}")
391
+
392
+ original_cwd = os.getcwd()
393
+ try:
394
+ os.chdir(llama_path)
395
+
396
+ # Update to latest version
397
+ try:
398
+ subprocess.run(['git', 'pull'], capture_output=True, check=False)
399
+ except subprocess.CalledProcessError:
400
+ console.print("[yellow]Warning: Could not update llama.cpp repository")
401
+
402
+ # Clean any existing build directory to avoid cached CMake variables
403
+ build_dir = Path('build')
404
+ if build_dir.exists():
405
+ console.print("[yellow]Cleaning existing build directory to avoid CMake cache conflicts...")
406
+ import shutil
407
+ try:
408
+ shutil.rmtree(build_dir)
409
+ console.print("[green]Build directory cleaned successfully")
410
+ except Exception as e:
411
+ console.print(f"[yellow]Warning: Could not clean build directory: {e}")
412
+
413
+ # Check if we're in a Nix environment
414
+ is_nix = system == "Linux" and os.path.exists("/nix/store")
415
+
416
+ if is_nix:
417
+ console.print("[yellow]Detected Nix environment. Using system Python packages...")
418
+ # In Nix, we need to use the system Python packages
419
+ try:
420
+ # Try to import required packages to check if they're available
421
+ import numpy # type: ignore
422
+ import sentencepiece # type: ignore
423
+ import torch # type: ignore
424
+ import transformers # type: ignore
425
+ console.print("[green]Required Python packages are already installed.")
426
+ except ImportError:
427
+ console.print("[red]Missing required Python packages in Nix environment.")
428
+ console.print("[yellow]Please install them using:")
429
+ console.print("nix-shell -p python3Packages.torch python3Packages.numpy python3Packages.sentencepiece python3Packages.transformers")
430
+ raise ConversionError("Missing required Python packages in Nix environment")
431
+ else:
432
+ # In non-Nix environments, install requirements if they exist
433
+ if os.path.exists('requirements.txt'):
434
+ try:
435
+ pip_cmd = 'pip' if system == 'Windows' else 'pip3'
436
+ subprocess.run([pip_cmd, 'install', '-r', 'requirements.txt'], check=True)
437
+ except subprocess.CalledProcessError as e:
438
+ if "externally-managed-environment" in str(e):
439
+ console.print("[yellow]Detected externally managed Python environment.")
440
+ console.print("[yellow]Please install the required packages manually:")
441
+ console.print("pip install torch numpy sentencepiece transformers")
442
+ raise ConversionError("Failed to install requirements in externally managed environment")
443
+ else:
444
+ console.print(f"[yellow]Warning: Failed to install requirements: {e}")
445
+
446
+ # Detect available hardware
447
+ hardware = self.detect_hardware()
448
+ console.print("[bold green]Detected hardware acceleration:")
449
+ for hw, available in hardware.items():
450
+ console.print(f" {'✓' if available else '✗'} {hw.upper()}")
451
+
452
+ # Clear any environment variables that might cause conflicts
453
+ env_vars_to_clear = [
454
+ 'LLAMA_CUBLAS', 'LLAMA_CLBLAST', 'LLAMA_HIPBLAS',
455
+ 'LLAMA_METAL', 'LLAMA_ACCELERATE', 'LLAMA_OPENBLAS'
456
+ ]
457
+ for var in env_vars_to_clear:
458
+ if var in os.environ:
459
+ console.print(f"[yellow]Clearing conflicting environment variable: {var}")
460
+ del os.environ[var]
461
+
462
+ # Configure CMake build with robust options
463
+ cmake_args: List[str] = ['cmake', '-B', 'build']
464
+
465
+ # Add basic CMake options
466
+ cmake_args.extend([
467
+ '-DCMAKE_BUILD_TYPE=Release',
468
+ '-DLLAMA_BUILD_TESTS=OFF',
469
+ '-DLLAMA_BUILD_EXAMPLES=ON',
470
+ '-DLLAMA_BUILD_SERVER=OFF',
471
+ # Disable optional dependencies that might cause issues
472
+ '-DLLAMA_CURL=OFF', # Disable CURL (not needed for GGUF conversion)
473
+ '-DLLAMA_LLGUIDANCE=OFF' # Disable LLGuidance (optional feature)
474
+ ])
475
+
476
+ # Add hardware acceleration options with latest 2025 llama.cpp GGML flags
477
+ # Use priority order: CUDA > Metal > Vulkan > OpenCL > ROCm > BLAS > Accelerate
478
+ acceleration_enabled = False
479
+
480
+ if hardware['cuda']:
481
+ # Latest 2025 GGML CUDA flags (LLAMA_CUBLAS is deprecated)
482
+ cmake_args.extend(['-DGGML_CUDA=ON'])
483
+ console.print("[green]Enabling CUDA acceleration (GGML_CUDA=ON)")
484
+ acceleration_enabled = True
485
+ elif hardware['metal']:
486
+ # Latest 2025 GGML Metal flags for macOS
487
+ cmake_args.extend(['-DGGML_METAL=ON'])
488
+ console.print("[green]Enabling Metal acceleration (GGML_METAL=ON)")
489
+ acceleration_enabled = True
490
+ elif hardware['vulkan']:
491
+ # Latest 2025 GGML Vulkan flags
492
+ cmake_args.extend(['-DGGML_VULKAN=ON'])
493
+ console.print("[green]Enabling Vulkan acceleration (GGML_VULKAN=ON)")
494
+ acceleration_enabled = True
495
+ elif hardware['opencl']:
496
+ # Latest 2025 GGML OpenCL flags (LLAMA_CLBLAST is deprecated)
497
+ cmake_args.extend(['-DGGML_OPENCL=ON'])
498
+ console.print("[green]Enabling OpenCL acceleration (GGML_OPENCL=ON)")
499
+ acceleration_enabled = True
500
+ elif hardware['rocm']:
501
+ # Latest 2025 GGML ROCm/HIP flags
502
+ cmake_args.extend(['-DGGML_HIPBLAS=ON'])
503
+ console.print("[green]Enabling ROCm acceleration (GGML_HIPBLAS=ON)")
504
+ acceleration_enabled = True
505
+ elif hardware['blas']:
506
+ # Latest 2025 GGML BLAS flags with vendor detection
507
+ cmake_args.extend(['-DGGML_BLAS=ON'])
508
+ # Try to detect BLAS vendor for optimal performance
509
+ if system == 'Darwin':
510
+ cmake_args.extend(['-DGGML_BLAS_VENDOR=Accelerate'])
511
+ elif 'mkl' in str(hardware).lower():
512
+ cmake_args.extend(['-DGGML_BLAS_VENDOR=Intel10_64lp'])
513
+ else:
514
+ cmake_args.extend(['-DGGML_BLAS_VENDOR=OpenBLAS'])
515
+ console.print("[green]Enabling BLAS acceleration (GGML_BLAS=ON)")
516
+ acceleration_enabled = True
517
+ elif hardware['accelerate']:
518
+ # Latest 2025 GGML Accelerate framework flags for macOS
519
+ cmake_args.extend(['-DGGML_ACCELERATE=ON'])
520
+ console.print("[green]Enabling Accelerate framework (GGML_ACCELERATE=ON)")
521
+ acceleration_enabled = True
522
+
523
+ if not acceleration_enabled:
524
+ console.print("[yellow]No hardware acceleration available, using CPU only")
525
+
526
+ # Platform-specific optimizations
527
+ if system == 'Windows':
528
+ # Use Visual Studio generator on Windows if available
529
+ try:
530
+ vs_result = subprocess.run(['where', 'msbuild'], capture_output=True)
531
+ if vs_result.returncode == 0:
532
+ cmake_args.extend(['-G', 'Visual Studio 17 2022'])
533
+ else:
534
+ cmake_args.extend(['-G', 'MinGW Makefiles'])
535
+ except Exception:
536
+ cmake_args.extend(['-G', 'MinGW Makefiles'])
537
+ else:
538
+ # Use Ninja if available on Unix systems
539
+ try:
540
+ ninja_cmd = 'ninja' if system != 'Windows' else 'ninja.exe'
541
+ if subprocess.run(['which', ninja_cmd], capture_output=True).returncode == 0:
542
+ cmake_args.extend(['-G', 'Ninja'])
543
+ except Exception:
544
+ pass # Fall back to default generator
545
+
546
+ # Configure the build with error handling and multiple fallback strategies
547
+ status.update("[bold green]Configuring CMake build...")
548
+ config_success = False
549
+
550
+ # Try main configuration
551
+ try:
552
+ console.print(f"[cyan]CMake command: {' '.join(cmake_args)}")
553
+ result = subprocess.run(cmake_args, capture_output=True, text=True)
554
+ if result.returncode == 0:
555
+ config_success = True
556
+ console.print("[green]CMake configuration successful!")
557
+ else:
558
+ console.print(f"[red]CMake configuration failed: {result.stderr}")
559
+ except subprocess.CalledProcessError as e:
560
+ console.print(f"[red]CMake execution failed: {e}")
561
+
562
+ # Try fallback without hardware acceleration if main config failed
563
+ if not config_success:
564
+ console.print("[yellow]Attempting fallback configuration without hardware acceleration...")
565
+ console.print("[cyan]Using CPU-only build configuration...")
566
+ fallback_args = [
567
+ 'cmake', '-B', 'build',
568
+ '-DCMAKE_BUILD_TYPE=Release',
569
+ '-DLLAMA_BUILD_TESTS=OFF',
570
+ '-DLLAMA_BUILD_EXAMPLES=ON',
571
+ '-DLLAMA_BUILD_SERVER=OFF',
572
+ # Disable optional dependencies that might cause issues
573
+ '-DLLAMA_CURL=OFF', # Disable CURL (not needed for GGUF conversion)
574
+ '-DLLAMA_LLGUIDANCE=OFF', # Disable LLGuidance (optional feature)
575
+ # Enable CPU optimizations
576
+ '-DGGML_NATIVE=OFF', # Disable native optimizations for compatibility
577
+ '-DGGML_AVX=ON', # Enable AVX if available
578
+ '-DGGML_AVX2=ON', # Enable AVX2 if available
579
+ '-DGGML_FMA=ON' # Enable FMA if available
580
+ ]
581
+ try:
582
+ console.print(f"[cyan]Fallback CMake command: {' '.join(fallback_args)}")
583
+ result = subprocess.run(fallback_args, capture_output=True, text=True)
584
+ if result.returncode == 0:
585
+ config_success = True
586
+ console.print("[green]Fallback CMake configuration successful!")
587
+ else:
588
+ console.print(f"[red]Fallback CMake configuration failed: {result.stderr}")
589
+ except subprocess.CalledProcessError as e:
590
+ console.print(f"[red]Fallback CMake execution failed: {e}")
591
+
592
+ # Try minimal configuration as last resort
593
+ if not config_success:
594
+ console.print("[yellow]Attempting minimal configuration...")
595
+ minimal_args = [
596
+ 'cmake', '-B', 'build',
597
+ '-DCMAKE_BUILD_TYPE=Release',
598
+ # Disable optional dependencies that might cause issues
599
+ '-DLLAMA_CURL=OFF', # Disable CURL (not needed for GGUF conversion)
600
+ '-DLLAMA_LLGUIDANCE=OFF', # Disable LLGuidance (optional feature)
601
+ '-DLLAMA_BUILD_SERVER=OFF', # Disable server (not needed for conversion)
602
+ '-DLLAMA_BUILD_TESTS=OFF' # Disable tests (not needed for conversion)
603
+ ]
604
+ try:
605
+ console.print(f"[cyan]Minimal CMake command: {' '.join(minimal_args)}")
606
+ result = subprocess.run(minimal_args, capture_output=True, text=True)
607
+ if result.returncode == 0:
608
+ config_success = True
609
+ console.print("[green]Minimal CMake configuration successful!")
610
+ else:
611
+ console.print(f"[red]Minimal CMake configuration failed: {result.stderr}")
612
+ raise ConversionError(f"All CMake configuration attempts failed. Last error: {result.stderr}")
613
+ except subprocess.CalledProcessError as e:
614
+ raise ConversionError(f"All CMake configuration attempts failed: {e}")
615
+
616
+ if not config_success:
617
+ raise ConversionError("CMake configuration failed with all attempted strategies")
618
+
619
+ # Build the project
620
+ status.update("[bold green]Building llama.cpp...")
621
+ build_cmd = ['cmake', '--build', 'build', '--config', 'Release']
622
+
623
+ # Add parallel build option
624
+ cpu_count = os.cpu_count() or 1
625
+ if system == 'Windows':
626
+ build_cmd.extend(['--parallel', str(cpu_count)])
627
+ else:
628
+ build_cmd.extend(['-j', str(cpu_count)])
629
+
630
+ try:
631
+ result = subprocess.run(build_cmd, capture_output=True, text=True)
632
+ if result.returncode != 0:
633
+ console.print(f"[red]Build failed: {result.stderr}")
634
+ # Try single-threaded build as fallback
635
+ console.print("[yellow]Attempting single-threaded build...")
636
+ fallback_build = ['cmake', '--build', 'build', '--config', 'Release']
637
+ result = subprocess.run(fallback_build, capture_output=True, text=True)
638
+ if result.returncode != 0:
639
+ raise ConversionError(f"Build failed: {result.stderr}")
640
+ except subprocess.CalledProcessError as e:
641
+ raise ConversionError(f"Build failed: {e}")
642
+
643
+ console.print("[green]llama.cpp built successfully!")
644
+
645
+ finally:
646
+ os.chdir(original_cwd)
647
+
648
+ def display_config(self) -> None:
649
+ """Displays the current configuration in a formatted table."""
650
+ table = Table(title="Configuration", show_header=True, header_style="bold magenta")
651
+ table.add_column("Setting", style="cyan")
652
+ table.add_column("Value", style="green")
653
+
654
+ table.add_row("Model ID", self.model_id)
655
+ table.add_row("Model Name", self.model_name)
656
+ table.add_row("Username", self.username or "Not provided")
657
+ table.add_row("Token", "****" if self.token else "Not provided")
658
+ table.add_row("Quantization Methods", "\n".join(
659
+ f"{method} ({self.VALID_METHODS[method]})"
660
+ for method in self.quantization_methods
661
+ ))
662
+
663
+ console.print(Panel(table))
664
+
665
+ def get_binary_path(self, binary_name: str) -> str:
666
+ """Get the correct path to llama.cpp binaries based on platform."""
667
+ system = platform.system()
668
+
669
+ # Possible binary locations
670
+ possible_paths = [
671
+ f"./llama.cpp/build/bin/{binary_name}", # Standard build location
672
+ f"./llama.cpp/build/{binary_name}", # Alternative build location
673
+ f"./llama.cpp/{binary_name}", # Root directory
674
+ f"./llama.cpp/build/Release/{binary_name}", # Windows Release build
675
+ f"./llama.cpp/build/Debug/{binary_name}", # Windows Debug build
676
+ ]
677
+
678
+ # Add .exe extension on Windows
679
+ if system == 'Windows':
680
+ possible_paths = [path + '.exe' for path in possible_paths]
681
+
682
+ # Find the first existing binary
683
+ for path in possible_paths:
684
+ if os.path.isfile(path):
685
+ return path
686
+
687
+ # If not found, return the most likely path and let it fail with a clear error
688
+ default_path = f"./llama.cpp/build/bin/{binary_name}"
689
+ if system == 'Windows':
690
+ default_path += '.exe'
691
+ return default_path
692
+
693
+ def generate_importance_matrix(self, model_path: str, train_data_path: str, output_path: str) -> None:
694
+ """Generates importance matrix for quantization with improved error handling."""
695
+ imatrix_binary = self.get_binary_path("llama-imatrix")
696
+
697
+ imatrix_command: List[str] = [
698
+ imatrix_binary,
699
+ "-m", model_path,
700
+ "-f", train_data_path,
701
+ "-ngl", "99",
702
+ "--output-frequency", "10",
703
+ "-o", output_path,
704
+ ]
705
+
706
+ if not os.path.isfile(model_path):
707
+ raise ConversionError(f"Model file not found: {model_path}")
708
+
709
+ if not os.path.isfile(train_data_path):
710
+ raise ConversionError(f"Training data file not found: {train_data_path}")
711
+
712
+ if not os.path.isfile(imatrix_binary):
713
+ raise ConversionError(f"llama-imatrix binary not found at: {imatrix_binary}")
714
+
715
+ console.print("[bold green]Generating importance matrix...")
716
+ console.print(f"[cyan]Command: {' '.join(imatrix_command)}")
717
+
718
+ try:
719
+ process = subprocess.Popen(
720
+ imatrix_command,
721
+ shell=False,
722
+ stdout=subprocess.PIPE,
723
+ stderr=subprocess.PIPE,
724
+ text=True
725
+ )
726
+
727
+ try:
728
+ stdout, stderr = process.communicate(timeout=300) # 5 minute timeout
729
+ if process.returncode != 0:
730
+ raise ConversionError(f"Failed to generate importance matrix: {stderr}")
731
+ except subprocess.TimeoutExpired:
732
+ console.print("[yellow]Imatrix computation timed out. Sending SIGINT...")
733
+ process.send_signal(signal.SIGINT)
734
+ try:
735
+ stdout, stderr = process.communicate(timeout=10)
736
+ except subprocess.TimeoutExpired:
737
+ console.print("[red]Imatrix process still running. Force terminating...")
738
+ process.kill()
739
+ stdout, stderr = process.communicate()
740
+ raise ConversionError(f"Imatrix generation timed out: {stderr}")
741
+ except FileNotFoundError:
742
+ raise ConversionError(f"Could not execute llama-imatrix binary: {imatrix_binary}")
743
+
744
+ console.print("[green]Importance matrix generation completed.")
745
+
746
+ def split_model(self, model_path: str, outdir: str) -> List[str]:
747
+ """Splits the model into smaller chunks with improved error handling."""
748
+ split_binary = self.get_binary_path("llama-gguf-split")
749
+
750
+ split_cmd: List[str] = [
751
+ split_binary,
752
+ "--split",
753
+ ]
754
+
755
+ if self.split_max_size:
756
+ split_cmd.extend(["--split-max-size", self.split_max_size])
757
+ else:
758
+ split_cmd.extend(["--split-max-tensors", str(self.split_max_tensors)])
759
+
760
+ model_path_prefix = '.'.join(model_path.split('.')[:-1])
761
+ split_cmd.extend([model_path, model_path_prefix])
762
+
763
+ if not os.path.isfile(model_path):
764
+ raise ConversionError(f"Model file not found: {model_path}")
765
+
766
+ if not os.path.isfile(split_binary):
767
+ raise ConversionError(f"llama-gguf-split binary not found at: {split_binary}")
768
+
769
+ console.print(f"[bold green]Splitting model with command: {' '.join(split_cmd)}")
770
+
771
+ try:
772
+ result = subprocess.run(split_cmd, shell=False, capture_output=True, text=True)
773
+
774
+ if result.returncode != 0:
775
+ raise ConversionError(f"Error splitting model: {result.stderr}")
776
+ except FileNotFoundError:
777
+ raise ConversionError(f"Could not execute llama-gguf-split binary: {split_binary}")
778
+
779
+ console.print("[green]Model split successfully!")
780
+
781
+ # Get list of split files
782
+ model_file_prefix = os.path.basename(model_path_prefix)
783
+ try:
784
+ split_files = [f for f in os.listdir(outdir)
785
+ if f.startswith(model_file_prefix) and f.endswith(".gguf")]
786
+ except OSError as e:
787
+ raise ConversionError(f"Error reading output directory: {e}")
788
+
789
+ if not split_files:
790
+ raise ConversionError(f"No split files found in {outdir} with prefix {model_file_prefix}")
791
+
792
+ console.print(f"[green]Found {len(split_files)} split files: {', '.join(split_files)}")
793
+ return split_files
794
+
795
+ def upload_split_files(self, split_files: List[str], outdir: str, repo_id: str) -> None:
796
+ """Uploads split model files to Hugging Face."""
797
+ api = _ensure_huggingface_hub()(token=self.token)
798
+
799
+ for file in split_files:
800
+ file_path = os.path.join(outdir, file)
801
+ console.print(f"[bold green]Uploading file: {file}")
802
+ try:
803
+ api.upload_file(
804
+ path_or_fileobj=file_path,
805
+ path_in_repo=file,
806
+ repo_id=repo_id,
807
+ )
808
+ console.print(f"[green]✓ Successfully uploaded: {file}")
809
+ except Exception as e:
810
+ console.print(f"[red]✗ Failed to upload {file}: {e}")
811
+ raise ConversionError(f"Error uploading file {file}: {e}")
812
+
813
+ def generate_readme(self, quantized_files: List[str]) -> str:
814
+ """Generate a README.md file for the Hugging Face Hub."""
815
+ readme = f"""# {self.model_name} GGUF
816
+
817
+ This repository contains GGUF quantized versions of [{self.model_id}](https://huggingface.co/{self.model_id}).
818
+
819
+ ## About
820
+
821
+ This model was converted using [Webscout](https://github.com/Webscout/webscout).
822
+
823
+ ## Quantization Methods
824
+
825
+ The following quantization methods were used:
826
+
827
+ """
828
+ # Add quantization method descriptions
829
+ for method in self.quantization_methods:
830
+ if self.use_imatrix:
831
+ readme += f"- `{method}`: {self.VALID_IMATRIX_METHODS[method]}\n"
832
+ else:
833
+ readme += f"- `{method}`: {self.VALID_METHODS[method]}\n"
834
+
835
+ readme += """
836
+ ## Available Files
837
+
838
+ The following quantized files are available:
839
+
840
+ """
841
+ # Add file information
842
+ for file in quantized_files:
843
+ readme += f"- `{file}`\n"
844
+
845
+ if self.use_imatrix:
846
+ readme += """
847
+ ## Importance Matrix
848
+
849
+ This model was quantized using importance matrix quantization. The `imatrix.dat` file contains the importance matrix used for quantization.
850
+
851
+ """
852
+
853
+ readme += """
854
+ ## Usage
855
+
856
+ These GGUF files can be used with [llama.cpp](https://github.com/ggerganov/llama.cpp) and compatible tools.
857
+
858
+ Example usage:
859
+ ```bash
860
+ ./main -m model.gguf -n 1024 --repeat_penalty 1.0 --color -i -r "User:" -f prompts/chat-with-bob.txt
861
+ ```
862
+
863
+ ## Conversion Process
864
+
865
+ This model was converted using the following command:
866
+ ```bash
867
+ python -m webscout.Extra.gguf convert \\
868
+ -m "{self.model_id}" \\
869
+ -q "{','.join(self.quantization_methods)}" \\
870
+ {f'-i' if self.use_imatrix else ''} \\
871
+ {f'--train-data "{self.train_data_file}"' if self.train_data_file else ''} \\
872
+ {f'-s' if self.use_split else ''} \\
873
+ {f'--split-max-tensors {self.split_max_tensors}' if self.use_split else ''} \\
874
+ {f'--split-max-size {self.split_max_size}' if self.split_max_size else ''}
875
+ ```
876
+
877
+ ## License
878
+
879
+ This repository is licensed under the same terms as the original model.
880
+ """
881
+ return readme
882
+
883
+ def create_repository(self, repo_id: str) -> None:
884
+ """Create a new repository on Hugging Face Hub if it doesn't exist."""
885
+ api = _ensure_huggingface_hub()(token=self.token)
886
+ try:
887
+ # Check if repository already exists
888
+ try:
889
+ api.repo_info(repo_id=repo_id)
890
+ console.print(f"[green]✓ Repository {repo_id} already exists")
891
+ return
892
+ except Exception:
893
+ # Repository doesn't exist, create it
894
+ pass
895
+
896
+ console.print(f"[bold green]Creating new repository: {repo_id}")
897
+ api.create_repo(
898
+ repo_id=repo_id,
899
+ exist_ok=True,
900
+ private=False,
901
+ repo_type="model"
902
+ )
903
+ console.print(f"[green]✓ Successfully created repository: {repo_id}")
904
+ console.print(f"[cyan]Repository URL: https://huggingface.co/{repo_id}")
905
+ except Exception as e:
906
+ console.print(f"[red]✗ Failed to create repository: {e}")
907
+ raise ConversionError(f"Error creating repository {repo_id}: {e}")
908
+
909
+ def upload_readme(self, readme_content: str, repo_id: str) -> None:
910
+ """Upload README.md to Hugging Face Hub."""
911
+ api = _ensure_huggingface_hub()(token=self.token)
912
+ console.print("[bold green]Uploading README.md with model documentation")
913
+ try:
914
+ api.upload_file(
915
+ path_or_fileobj=readme_content.encode(),
916
+ path_in_repo="README.md",
917
+ repo_id=repo_id,
918
+ )
919
+ console.print("[green]✓ Successfully uploaded: README.md")
920
+ except Exception as e:
921
+ console.print(f"[red]✗ Failed to upload README.md: {e}")
922
+ raise ConversionError(f"Error uploading README.md: {e}")
923
+
924
+ def convert(self) -> None:
925
+ """Performs the model conversion process."""
926
+ try:
927
+ # Display banner and configuration
928
+ console.print(f"[bold green]{figlet_format('GGUF Converter')}")
929
+ self.display_config()
930
+
931
+ # Validate inputs
932
+ self.validate_inputs()
933
+
934
+ # Check dependencies
935
+ deps = self.check_dependencies()
936
+ missing = [name for name, installed in deps.items() if not installed and name != 'ninja']
937
+ if missing:
938
+ raise ConversionError(f"Missing required dependencies: {', '.join(missing)}")
939
+
940
+ # Setup llama.cpp
941
+ self.setup_llama_cpp()
942
+
943
+ # Determine if we need temporary directories (only for uploads)
944
+ needs_temp = bool(self.username and self.token)
945
+
946
+ if needs_temp:
947
+ # Use temporary directories for upload case
948
+ with tempfile.TemporaryDirectory() as outdir:
949
+ with tempfile.TemporaryDirectory() as tmpdir:
950
+ self._convert_with_dirs(tmpdir, outdir)
951
+ else:
952
+ # Use current directory for local output
953
+ outdir = os.getcwd()
954
+ tmpdir = os.path.join(outdir, "temp_download")
955
+ os.makedirs(tmpdir, exist_ok=True)
956
+ try:
957
+ self._convert_with_dirs(tmpdir, outdir)
958
+ finally:
959
+ # Clean up temporary download directory
960
+ import shutil
961
+ shutil.rmtree(tmpdir, ignore_errors=True)
962
+
963
+ # Display success message
964
+ console.print(Panel.fit(
965
+ "[bold green]✓[/] Conversion completed successfully!\n\n"
966
+ f"[cyan]Output files can be found in: {self.workspace / self.model_name}[/]",
967
+ title="Success",
968
+ border_style="green"
969
+ ))
970
+
971
+ except Exception as e:
972
+ console.print(Panel.fit(
973
+ f"[bold red]✗[/] {str(e)}",
974
+ title="Error",
975
+ border_style="red"
976
+ ))
977
+ raise
978
+
979
+ def _convert_with_dirs(self, tmpdir: str, outdir: str) -> None:
980
+ """Helper method to perform conversion with given directories."""
981
+ # Use outtype for base filename (e.g., model.f16.gguf, model.bf16.gguf)
982
+ outtype_suffix = self.outtype if self.outtype != "auto" else "f16"
983
+ base_gguf = str(Path(outdir)/f"{self.model_name}.{outtype_suffix}.gguf")
984
+
985
+ # Download model (or use remote mode)
986
+ local_dir = Path(tmpdir)/self.model_name
987
+ if self.remote:
988
+ console.print("[bold green]Using remote mode - downloading only config and tokenizer...")
989
+ api = _ensure_huggingface_hub()(token=self.token)
990
+ api.snapshot_download(
991
+ repo_id=self.model_id,
992
+ local_dir=local_dir,
993
+ allow_patterns=["LICENSE", "*.json", "*.md", "*.txt", "tokenizer.model"]
994
+ )
995
+ else:
996
+ console.print("[bold green]Downloading model...")
997
+ api = _ensure_huggingface_hub()(token=self.token)
998
+ api.snapshot_download(
999
+ repo_id=self.model_id,
1000
+ local_dir=local_dir,
1001
+ )
1002
+
1003
+ # Convert to GGUF with specified outtype
1004
+ console.print(f"[bold green]Converting to {self.outtype}...")
1005
+
1006
+ # Find the conversion script
1007
+ conversion_scripts = [
1008
+ "llama.cpp/convert_hf_to_gguf.py",
1009
+ "llama.cpp/convert-hf-to-gguf.py",
1010
+ "llama.cpp/convert.py"
1011
+ ]
1012
+
1013
+ conversion_script = None
1014
+ for script in conversion_scripts:
1015
+ if os.path.isfile(script):
1016
+ conversion_script = script
1017
+ break
1018
+
1019
+ if not conversion_script:
1020
+ raise ConversionError("Could not find HuggingFace to GGUF conversion script")
1021
+
1022
+ # Use the appropriate Python executable
1023
+ python_cmd = "python" if platform.system() == "Windows" else "python3"
1024
+
1025
+ # Build conversion command with new llama.cpp options
1026
+ convert_cmd = [
1027
+ python_cmd, conversion_script,
1028
+ str(local_dir),
1029
+ "--outtype", self.outtype,
1030
+ "--outfile", base_gguf
1031
+ ]
1032
+
1033
+ # Add optional flags based on new llama.cpp features
1034
+ if self.vocab_only:
1035
+ convert_cmd.append("--vocab-only")
1036
+ if self.no_lazy:
1037
+ convert_cmd.append("--no-lazy")
1038
+ if self.dry_run:
1039
+ convert_cmd.append("--dry-run")
1040
+ if self.remote:
1041
+ convert_cmd.extend(["--remote"])
1042
+ if self.model_name:
1043
+ convert_cmd.extend(["--model-name", self.model_name])
1044
+ if self.use_split:
1045
+ if self.split_max_tensors > 0:
1046
+ convert_cmd.extend(["--split-max-tensors", str(self.split_max_tensors)])
1047
+ if self.split_max_size:
1048
+ convert_cmd.extend(["--split-max-size", self.split_max_size])
1049
+ if self.small_first_shard:
1050
+ convert_cmd.append("--no-tensor-first-split")
1051
+
1052
+ console.print(f"[cyan]Conversion command: {' '.join(convert_cmd)}")
1053
+
1054
+ try:
1055
+ result = subprocess.run(convert_cmd, capture_output=True, text=True)
1056
+
1057
+ if result.returncode != 0:
1058
+ raise ConversionError(f"Error converting to {self.outtype}: {result.stderr}")
1059
+ except FileNotFoundError as e:
1060
+ raise ConversionError(f"Could not execute conversion script: {e}")
1061
+
1062
+ if not os.path.isfile(base_gguf):
1063
+ raise ConversionError(f"Conversion completed but output file not found: {base_gguf}")
1064
+
1065
+ console.print(f"[green]Model converted to {self.outtype} successfully!")
1066
+
1067
+ # If base_only is True, we're done after base conversion (no quantization needed)
1068
+ if self.base_only:
1069
+ gguf_filename = f"{self.model_name}.{outtype_suffix}.gguf"
1070
+ quantized_files = [gguf_filename]
1071
+ if self.username and self.token:
1072
+ repo_id = f"{self.username}/{self.model_name}-GGUF"
1073
+
1074
+ # Step 1: Create repository
1075
+ self.create_repository(repo_id)
1076
+
1077
+ # Step 2: Upload README first
1078
+ readme_content = self.generate_readme(quantized_files)
1079
+ self.upload_readme(readme_content, repo_id)
1080
+
1081
+ # Step 3: Upload model GGUF file
1082
+ console.print(f"[bold green]Uploading model file: {gguf_filename}")
1083
+ try:
1084
+ api.upload_file(
1085
+ path_or_fileobj=base_gguf,
1086
+ path_in_repo=gguf_filename,
1087
+ repo_id=repo_id
1088
+ )
1089
+ console.print(f"[green]✓ Successfully uploaded: {gguf_filename}")
1090
+ except Exception as e:
1091
+ console.print(f"[red]✗ Failed to upload {gguf_filename}: {e}")
1092
+ raise ConversionError(f"Error uploading model file: {e}")
1093
+ return
1094
+
1095
+ # Generate importance matrix if needed
1096
+ imatrix_path: Optional[str] = None
1097
+ if self.use_imatrix:
1098
+ train_data_path = self.train_data_file if self.train_data_file else "llama.cpp/groups_merged.txt"
1099
+ imatrix_path = str(Path(outdir)/"imatrix.dat")
1100
+ self.generate_importance_matrix(base_gguf, train_data_path, imatrix_path)
1101
+
1102
+ # Quantize model
1103
+ console.print("[bold green]Quantizing model...")
1104
+ quantized_files: List[str] = []
1105
+ quantize_binary = self.get_binary_path("llama-quantize")
1106
+ quantized_path = ""
1107
+
1108
+ if not os.path.isfile(quantize_binary):
1109
+ raise ConversionError(f"llama-quantize binary not found at: {quantize_binary}")
1110
+
1111
+ for method in self.quantization_methods:
1112
+ quantized_name = f"{self.model_name.lower()}-{method.lower()}"
1113
+ if self.use_imatrix:
1114
+ quantized_name += "-imat"
1115
+ quantized_path = str(Path(outdir)/f"{quantized_name}.gguf")
1116
+
1117
+ console.print(f"[cyan]Quantizing with method: {method}")
1118
+
1119
+ if self.use_imatrix and imatrix_path:
1120
+ quantize_cmd: List[str] = [
1121
+ quantize_binary,
1122
+ "--imatrix", str(imatrix_path),
1123
+ base_gguf, quantized_path, method
1124
+ ]
1125
+ else:
1126
+ quantize_cmd = [
1127
+ quantize_binary,
1128
+ base_gguf, quantized_path, method
1129
+ ]
1130
+
1131
+ console.print(f"[cyan]Quantization command: {' '.join(quantize_cmd)}")
1132
+
1133
+ try:
1134
+ result = subprocess.run(quantize_cmd, capture_output=True, text=True)
1135
+ if result.returncode != 0:
1136
+ raise ConversionError(f"Error quantizing with {method}: {result.stderr}")
1137
+ except FileNotFoundError:
1138
+ raise ConversionError(f"Could not execute llama-quantize binary: {quantize_binary}")
1139
+
1140
+ if not os.path.isfile(quantized_path):
1141
+ raise ConversionError(f"Quantization completed but output file not found: {quantized_path}")
1142
+
1143
+ quantized_files.append(f"{quantized_name}.gguf")
1144
+ console.print(f"[green]Successfully quantized with {method}: {quantized_name}.gguf")
1145
+
1146
+ # Upload to Hugging Face if credentials provided
1147
+ if self.username and self.token:
1148
+ repo_id = f"{self.username}/{self.model_name}-GGUF"
1149
+
1150
+ # Step 1: Create repository
1151
+ console.print(f"[bold blue]Step 1: Creating repository {repo_id}")
1152
+ self.create_repository(repo_id)
1153
+
1154
+ # Step 2: Generate and upload README first
1155
+ console.print("[bold blue]Step 2: Uploading README.md")
1156
+ readme_content = self.generate_readme(quantized_files)
1157
+ self.upload_readme(readme_content, repo_id)
1158
+
1159
+ # Step 3: Upload model GGUF files
1160
+ console.print("[bold blue]Step 3: Upload model files")
1161
+ if self.use_split:
1162
+ split_files = self.split_model(quantized_path, outdir)
1163
+ self.upload_split_files(split_files, outdir, repo_id)
1164
+ else:
1165
+ # Upload single quantized file
1166
+ file_name = f"{self.model_name.lower()}-{self.quantization_methods[0].lower()}.gguf"
1167
+ console.print(f"[bold green]Uploading quantized model: {file_name}")
1168
+ try:
1169
+ api.upload_file(
1170
+ path_or_fileobj=quantized_path,
1171
+ path_in_repo=file_name,
1172
+ repo_id=repo_id
1173
+ )
1174
+ console.print(f"[green]✓ Successfully uploaded: {file_name}")
1175
+ except Exception as e:
1176
+ console.print(f"[red]✗ Failed to upload {file_name}: {e}")
1177
+ raise ConversionError(f"Error uploading quantized model: {e}")
1178
+
1179
+ # Step 4: Upload imatrix if generated (optional)
1180
+ if imatrix_path:
1181
+ console.print("[bold blue]Step 4: Uploading importance matrix")
1182
+ console.print("[bold green]Uploading importance matrix: imatrix.dat")
1183
+ try:
1184
+ api.upload_file(
1185
+ path_or_fileobj=imatrix_path,
1186
+ path_in_repo="imatrix.dat",
1187
+ repo_id=repo_id
1188
+ )
1189
+ console.print("[green]✓ Successfully uploaded: imatrix.dat")
1190
+ except Exception as e:
1191
+ console.print(f"[yellow]Warning: Failed to upload imatrix.dat: {e}")
1192
+
1193
+ # Final success message
1194
+ console.print(f"[bold green]🎉 All files uploaded successfully to {repo_id}!")
1195
+ console.print(f"[cyan]Repository URL: https://huggingface.co/{repo_id}")
1196
+
1197
+ # Initialize CLI with HAI vibes
1198
+ app = CLI(
1199
+ name="gguf",
1200
+ help="Convert HuggingFace models to GGUF format with style! 🔥",
1201
+ version="2.0.0"
1202
+ )
1203
+
1204
+ @app.command(name="convert")
1205
+ @option("-m", "--model-id", help="The HuggingFace model ID (e.g., 'OEvortex/HelpingAI-Lite-1.5T')", required=True)
1206
+ @option("-u", "--username", help="Your HuggingFace username for uploads", default=None)
1207
+ @option("-t", "--token", help="Your HuggingFace API token for uploads", default=None)
1208
+ @option("-q", "--quantization", help="Comma-separated quantization methods", default="q4_k_m")
1209
+ @option("-o", "--outtype", help="Output type: f32, f16, bf16, q8_0, tq1_0, tq2_0, auto", default="f16")
1210
+ @option("-i", "--use-imatrix", help="Use importance matrix for quantization", is_flag=True)
1211
+ @option("--train-data", help="Training data file for imatrix quantization", default=None)
1212
+ @option("-s", "--split-model", help="Split the model into smaller chunks", is_flag=True)
1213
+ @option("--split-max-tensors", help="Maximum number of tensors per file when splitting", default=256)
1214
+ @option("--split-max-size", help="Maximum file size when splitting (e.g., '256M', '5G')", default=None)
1215
+ @option("--vocab-only", help="Only extract vocabulary (no model weights)", is_flag=True)
1216
+ @option("--remote", help="(Experimental) Read tensors remotely without full download", is_flag=True)
1217
+ @option("--dry-run", help="Only print split plan without writing files", is_flag=True)
1218
+ @option("--no-lazy", help="Disable lazy evaluation (use more RAM)", is_flag=True)
1219
+ @option("--model-name", help="Custom model name override", default=None)
1220
+ @option("--small-first-shard", help="Do not add tensors to the first split", is_flag=True)
1221
+ def convert_command(
1222
+ model_id: str,
1223
+ username: Optional[str] = None,
1224
+ token: Optional[str] = None,
1225
+ quantization: str = "q4_k_m",
1226
+ outtype: str = "f16",
1227
+ use_imatrix: bool = False,
1228
+ train_data: Optional[str] = None,
1229
+ split_model: bool = False,
1230
+ split_max_tensors: int = 256,
1231
+ split_max_size: Optional[str] = None,
1232
+ vocab_only: bool = False,
1233
+ remote: bool = False,
1234
+ dry_run: bool = False,
1235
+ no_lazy: bool = False,
1236
+ model_name: Optional[str] = None,
1237
+ small_first_shard: bool = False
1238
+ ) -> None:
1239
+ """
1240
+ Convert and quantize HuggingFace models to GGUF format! 🚀
1241
+
1242
+ Args:
1243
+ model_id (str): Your model's HF ID (like 'OEvortex/HelpingAI-Lite-1.5T') 🎯
1244
+ username (str, optional): Your HF username for uploads 👤
1245
+ token (str, optional): Your HF API token 🔑
1246
+ quantization (str): Quantization methods (default: q4_k_m) 🎮
1247
+ outtype (str): Output type: f32, f16, bf16, q8_0, tq1_0, tq2_0, auto 📊
1248
+ use_imatrix (bool): Use importance matrix for quantization 🔍
1249
+ train_data (str, optional): Training data file for imatrix quantization 📚
1250
+ split_model (bool): Split the model into smaller chunks 🔪
1251
+ split_max_tensors (int): Max tensors per file when splitting (default: 256) 📊
1252
+ split_max_size (str, optional): Max file size when splitting (e.g., '256M', '5G') 📏
1253
+ vocab_only (bool): Only extract vocabulary (no model weights) 📖
1254
+ remote (bool): (Experimental) Read tensors remotely without full download 🌐
1255
+ dry_run (bool): Only print split plan without writing files 📝
1256
+ no_lazy (bool): Disable lazy evaluation (use more RAM) 🧠
1257
+ model_name (str, optional): Custom model name override 🏷️
1258
+ small_first_shard (bool): Do not add tensors to the first split 📦
1259
+
1260
+ Example:
1261
+ >>> python -m webscout.Extra.gguf convert \\
1262
+ ... -m "OEvortex/HelpingAI-Lite-1.5T" \\
1263
+ ... -q "q4_k_m,q5_k_m" \\
1264
+ ... -o "f16"
1265
+ """
1266
+ try:
1267
+ converter = ModelConverter(
1268
+ model_id=model_id,
1269
+ username=username,
1270
+ token=token,
1271
+ quantization_methods=quantization,
1272
+ use_imatrix=use_imatrix,
1273
+ train_data_file=train_data,
1274
+ split_model=split_model,
1275
+ split_max_tensors=split_max_tensors,
1276
+ split_max_size=split_max_size,
1277
+ outtype=outtype,
1278
+ vocab_only=vocab_only,
1279
+ remote=remote,
1280
+ dry_run=dry_run,
1281
+ no_lazy=no_lazy,
1282
+ model_name=model_name,
1283
+ small_first_shard=small_first_shard
1284
+ )
1285
+ converter.convert()
1286
+ except (ConversionError, ValueError) as e:
1287
+ console.print(f"[red]Error: {str(e)}")
1288
+ sys.exit(1)
1289
+ except Exception as e:
1290
+ console.print(f"[red]Unexpected error: {str(e)}")
1291
+ sys.exit(1)
1292
+
1293
+ def main() -> None:
1294
+ """Fire up the GGUF converter! 🚀"""
1295
+ app.run()
1296
+
1297
+ if __name__ == "__main__":
1298
+ main()