ExportCivitAIMetadata

导出 civitai.com 的 safetensors 模型元数据 / Export .safetensor file's metadata from civitAI

当前为 2023-06-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name ExportCivitAIMetadata
  3. // @namespace https://github.com/magicFeirl/ExportCivitAIMetadata.git
  4. // @description 导出 civitai.com 的 safetensors 模型元数据 / Export .safetensor file's metadata from civitAI
  5. // @author ctrn43062
  6. // @match https://civitai.com/*
  7. // @icon https://www.google.com/s2/favicons?sz=64&domain=civitai.com
  8. // @version 0.2
  9. // @note 0.2 修复某些情况下复制按钮没有出现的bug
  10. // @note 0.1 init
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. /**
  15. * Usage:
  16. * SafetensorsHeaderReader.readFromURL(url, [offset])
  17. **/
  18. class SafetensorsHeaderReader {
  19. static async getHeaderLengthFromURL(url, offset = 0) {
  20. const resp = await fetch(url, { headers: { range: 'bytes=0-7' } })
  21.  
  22. try {
  23. const buffer = new BigUint64Array(await resp.arrayBuffer()).buffer
  24. return new DataView(buffer).getBigUint64(0, true) + offset
  25. } catch (error) {
  26. // backend error?
  27. console.log('Failed to get header length from backend:', error)
  28. return -1
  29. }
  30.  
  31. }
  32.  
  33. static async readFromURL(url, offset = 0) {
  34. if (!url) {
  35. return console.error('No model url')
  36. }
  37.  
  38. const headerLength = await this.getHeaderLengthFromURL(url, BigInt(offset))
  39.  
  40. if (headerLength <= 0) {
  41. return {
  42. error: 'Failed to get header length from civitai'
  43. }
  44. }
  45.  
  46. const resp = await fetch(url, { headers: { range: `bytes=8-${headerLength}` } })
  47. const data = await resp.json()
  48. return data
  49. }
  50. // TODO: readHeader from file
  51. }
  52.  
  53. function createCopyHeaderButton() {
  54. const icon = `<?xml version="1.0" ?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
  55. <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 8V7C10 6.05719 10 5.58579 10.2929 5.29289C10.5858 5 11.0572 5 12 5H17C17.9428 5 18.4142 5 18.7071 5.29289C19 5.58579 19 6.05719 19 7V12C19 12.9428 19 13.4142 18.7071 13.7071C18.4142 14 17.9428 14 17 14H16M7 19H12C12.9428 19 13.4142 19 13.7071 18.7071C14 18.4142 14 17.9428 14 17V12C14 11.0572 14 10.5858 13.7071 10.2929C13.4142 10 12.9428 10 12 10H7C6.05719 10 5.58579 10 5.29289 10.2929C5 10.5858 5 11.0572 5 12V17C5 17.9428 5 18.4142 5.29289 18.7071C5.58579 19 6.05719 19 7 19Z" stroke="#fff" stroke-linecap="round" stroke-linejoin="round"/></svg>`
  56.  
  57. const downloadBtn = document.querySelector('.mantine-Group-root .mantine-Stack-root a[download]')
  58.  
  59. if (!downloadBtn) {
  60. // waiting for DOM loaded
  61. console.error('can\'t find download button')
  62. return {}
  63. }
  64.  
  65. const buttonWrapper = downloadBtn.parentElement.parentElement
  66.  
  67. const btnCopy = buttonWrapper.lastChild.cloneNode(true)
  68.  
  69. btnCopy.setAttribute('id', 'CVI-copy-btn')
  70. btnCopy.setAttribute('title', 'Export model\'s metadata')
  71.  
  72. const svg = btnCopy.querySelector('span.mantine-Button-label')
  73. svg.innerHTML = icon
  74.  
  75. buttonWrapper.appendChild(btnCopy)
  76.  
  77. return { header: buttonWrapper.parentElement, btn: btnCopy.firstChild }
  78. }
  79.  
  80. function download(url, name) {
  81. const link = document.createElement('a');
  82. link.href = url;
  83. link.download = name;
  84. document.body.appendChild(link);
  85. link.click();
  86. setTimeout(() => link.remove(), 0)
  87. }
  88.  
  89. function downloadText(text, name) {
  90. const blob = new Blob([text])
  91. const url = URL.createObjectURL(blob)
  92. download(url, name)
  93. URL.revokeObjectURL(url)
  94. }
  95.  
  96. function init() {
  97. // we have init the copy button
  98. if (document.querySelector('#CVI-copy-btn')) {
  99. return;
  100. }
  101.  
  102. const { header = undefined, btn = undefined } = createCopyHeaderButton()
  103.  
  104. if (!header || !btn) {
  105. return;
  106. }
  107.  
  108. btn.onclick = () => {
  109. const isSafetensor = [...header.querySelectorAll('.mantine-Text-root')].map(el => el.textContent).some(text => text.toLowerCase() === 'safetensor')
  110.  
  111. function stringifyObject(obj) {
  112. return JSON.stringify(obj, (_, v) => {
  113. if (typeof v === 'string') {
  114. try {
  115. return JSON.parse(v, null, 2)
  116. } catch {
  117. return v
  118. }
  119. }
  120.  
  121. return v
  122. }, 2)
  123. }
  124.  
  125. if (!isSafetensor) {
  126. alert('Not a .safetensors model')
  127. return;
  128. }
  129.  
  130. const modelURL = header.querySelector('a[download]').href
  131. const RANGE_OFFSET = 7
  132.  
  133. const { pathname } = location
  134. // model title + model url id = filename
  135. const title = document.querySelector('#freezeBlock h1').textContent
  136. const path = pathname.substring(pathname.lastIndexOf('/') + 1)
  137. const filename = title + '_' + path + '_metadata.json'
  138.  
  139. btn.setAttribute('disabled', true)
  140. SafetensorsHeaderReader.readFromURL(modelURL, RANGE_OFFSET).then((json) => {
  141. if (json['error']) {
  142. alert('error: ' + json['error'] + ', please try later.')
  143. return;
  144. }
  145.  
  146. return json
  147. }).catch((error) => {
  148. alert('error: Network error:', error)
  149. console.error(error)
  150. }).then(json => {
  151. if (!json) {
  152. return
  153. }
  154.  
  155. // 避免 undefined 或 null
  156. json.__metadata__ = json.__metadata__ || {}
  157.  
  158. if (!Object.keys(json.__metadata__).length) {
  159. alert('This model has no metadata')
  160. return
  161. }
  162. // export __metadata__ to .txt file
  163. downloadText(stringifyObject(json.__metadata__), filename)
  164. }).finally(() => {
  165. btn.removeAttribute('disabled')
  166. })
  167. }
  168. }
  169.  
  170. function initPageChangeObserver(callback, window) {
  171. const ob = new window.MutationObserver((mutationList) => {
  172. if (mutationList.some(record => record.type === 'childList')) {
  173. // model detail page
  174. if (/civitai\.com\/models\/\d+/.test(location.href)) {
  175. callback && callback()
  176. }
  177. }
  178. })
  179.  
  180. ob.observe(window.document.querySelector('title'), { childList: true, subtree: true })
  181.  
  182. return ob
  183. }
  184.  
  185. function findCopyButton(callback) {
  186. setTimeout(() => {
  187. if (!document.querySelector('#CVI-copy-btn')) {
  188. findCopyButton(callback)
  189. callback()
  190. }
  191. }, 50)
  192. }
  193.  
  194. (function () {
  195. findCopyButton(init)
  196.  
  197. // For SPA
  198. initPageChangeObserver(init, unsafeWindow || window)
  199. })();