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