ExportCivitAIMetadata

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

当前为 2023-07-01 提交的版本,查看 最新版本

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