utilitys.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. (function(){
  2. function module_init() {
  3. console.log("[lora-prompt-tool] load utilitys module");
  4. lorahelper.noop_func = ()=>{};
  5. lorahelper.pointInRect = (rect, {x, y}) => (
  6. (x > rect.left && x < rect.right) && (y > rect.top && y < rect.bottom)
  7. );
  8. function load_json_number(input){
  9. let cvt = parseFloat(input)
  10. if(Number.isNaN(cvt)) return 0;
  11. return cvt;
  12. }
  13. function load_boolean_flag(flag){
  14. let flag_str = `${flag}`;
  15. flag_str = flag_str.toLowerCase().trim();
  16. if(['yes','true','是','y','t'].includes(flag_str)){
  17. return 1;
  18. }
  19. const flag_num = parseInt(load_json_number(flag_str))
  20. if (flag_num != 0){
  21. return 1;
  22. }
  23. return "";
  24. }
  25. function debug(...msg) {
  26. if (lorahelper.settings.is_debug()) console.log(`[${lorahelper.lorahelp_extension_name}]`,...msg);
  27. }
  28. function is_nullptr(obj) {
  29. try {
  30. if (typeof(obj) === "undefined") return true;
  31. if (obj == undefined) return true;
  32. if (obj == null) return true;
  33. } catch (error) {
  34. return true;
  35. }
  36. return false;
  37. }
  38. function is_empty(str) {
  39. if (is_nullptr(str)) return true;
  40. if ((''+str).trim() === '') return true;
  41. return false;
  42. }
  43. function convert_file_path_to_url(path){
  44. let prefix = "file=";
  45. let path_to_url = path.replaceAll('\\', '/');
  46. return prefix+path_to_url;
  47. }
  48. function img_node_str(path){
  49. return `<img src='${convert_file_path_to_url(path)}' style="width:24px"/>`;
  50. }
  51. function pass_url(url_name){
  52. return url_name;
  53. }
  54. function build_hyper_cmd(mode, model, weight, param){
  55. let par_str = param.trim();
  56. if(par_str.charAt(0) !== ':' && par_str !== ""){
  57. par_str = ":" + par_str;
  58. }
  59. switch (mode) {
  60. case "ti":
  61. if(Math.abs(parseFloat(weight) - 1) > 1e-8)
  62. return `(${model}:${weight})`;
  63. return model;
  64. case "hyper":
  65. return `<hypernet:${model}:${weight}${par_str}>`;
  66. case "ckp":
  67. return;
  68. case "lora":
  69. case "lyco":
  70. default:
  71. return `<${mode}:${model}:${weight}${par_str}>`;
  72. }
  73. }
  74. function unescape_string(input_string){
  75. let result = '';
  76. const unicode_list = ['u','x'];
  77. for(var i=0; i<input_string.length; ++i){
  78. const current_char = input_string.charAt(i);
  79. if(current_char == '\\'){
  80. ++i;
  81. if (i >= input_string.length) break;
  82. const string_body = input_string.charAt(i);
  83. if(unicode_list.includes(string_body.toLowerCase())){
  84. result += `${current_char}${string_body}`;
  85. } else {
  86. let char_added = false;
  87. try {
  88. const unescaped = JSON.parse(`"${current_char}${string_body}"`);
  89. if (unescaped){
  90. result += unescaped;
  91. char_added = true;
  92. }
  93. } catch (error) {
  94. }
  95. if(!char_added){
  96. result += string_body;
  97. }
  98. }
  99. } else {
  100. result += current_char;
  101. }
  102. }
  103. return JSON.parse(JSON.stringify(result).replace(/\\\\/g,"\\"));
  104. }
  105. const default_top_index = 10001;
  106. var my_index = default_top_index;
  107. function sendontop(ele_id) {
  108. let element = ele_id;
  109. if (typeof(ele_id)===typeof("string")) {
  110. element = document.getElementById(ele_id);
  111. }
  112. element.classList.add("sendontop");
  113. element.style.zIndex = ++my_index;
  114. }
  115. function resetElementLayer() {
  116. const all_top_element = document.querySelectorAll(".sendontop");
  117. my_index = default_top_index;
  118. for(let ele of all_top_element){
  119. ele.style.zIndex = "unset";
  120. }
  121. }
  122. async function google_translate(text, options = {}) {
  123. const defaultTranslateOptions = {
  124. client: 'gtx',
  125. from: 'auto',
  126. to: 'en',
  127. hl: 'en',
  128. tld: 'com',
  129. };
  130. function sM(a) {
  131. let e = [];
  132. let f = 0;
  133. for (let g = 0; g < a.length; g++) {
  134. let l = a.charCodeAt(g)
  135. 128 > l
  136. ? (e[f++] = l)
  137. : (2048 > l
  138. ? (e[f++] = (l >> 6) | 192)
  139. : (55296 == (l & 64512) &&
  140. g + 1 < a.length &&
  141. 56320 == (a.charCodeAt(g + 1) & 64512)
  142. ? ((l = 65536 + ((l & 1023) << 10) + (a.charCodeAt(++g) & 1023)),
  143. (e[f++] = (l >> 18) | 240),
  144. (e[f++] = ((l >> 12) & 63) | 128))
  145. : (e[f++] = (l >> 12) | 224),
  146. (e[f++] = ((l >> 6) & 63) | 128)),
  147. (e[f++] = (l & 63) | 128));
  148. }
  149. let a_ = 0
  150. for (f = 0; f < e.length; f++) {
  151. a_ += e[f];
  152. a_ = xr(a_, "+-a^+6");
  153. }
  154. a_ = xr(a_, "+-3^+b+-f");
  155. a_ ^= 0;
  156. 0 > a_ && (a_ = (a_ & 2147483647) + 2147483648);
  157. a_ %= 1e6;
  158. return a_.toString() + "." + a_.toString();
  159. }
  160. function xr(a, b) {
  161. for (let c = 0; c < b.length - 2; c += 3) {
  162. let d = b.charAt(c + 2);
  163. d = "a" <= d ? d.charCodeAt(0) - 87 : Number(d);
  164. d = "+" == b.charAt(c + 1) ? a >>> d : a << d;
  165. a = "+" == b.charAt(c) ? a + d : a ^ d;
  166. }
  167. return a;
  168. }
  169. function normaliseResponse(body, raw = false) {
  170. const result = {
  171. text: "",
  172. pronunciation: "",
  173. from: {
  174. language: {
  175. didYouMean: false,
  176. iso: ""
  177. },
  178. text: {
  179. autoCorrected: false,
  180. value: "",
  181. didYouMean: false
  182. }
  183. }
  184. };
  185. body[0].forEach(obj => {
  186. if (obj[0]) {
  187. result.text += obj[0];
  188. } else if (obj[2]) {
  189. result.pronunciation += obj[2];
  190. }
  191. })
  192. if (body[2] === body[8][0][0]) {
  193. result.from.language.iso = body[2];
  194. } else {
  195. result.from.language.didYouMean = true;
  196. result.from.language.iso = body[8][0][0];
  197. }
  198. if (body[7] && body[7][0]) {
  199. let str = body[7][0];
  200. str = str.replace(/<b><i>/g, "[");
  201. str = str.replace(/<\/i><\/b>/g, "]");
  202. result.from.text.value = str;
  203. if (body[7][5] === true) {
  204. result.from.text.autoCorrected = true;
  205. } else {
  206. result.from.text.didYouMean = true;
  207. }
  208. }
  209. if (raw) {
  210. result.raw = body;
  211. }
  212. return result;
  213. }
  214. function generateRequestUrl(text, options) {
  215. const translateOptions = { ...defaultTranslateOptions, ...options }
  216. const queryParams = {
  217. client: translateOptions.client,
  218. sl: translateOptions.from,
  219. tl: translateOptions.to,
  220. hl: translateOptions.hl,
  221. ie: "UTF-8",
  222. oe: "UTF-8",
  223. otf: "1",
  224. ssel: "0",
  225. tsel: "0",
  226. kc: "7",
  227. q: text,
  228. tk: sM(text)
  229. }
  230. const searchParams = new URLSearchParams(queryParams);
  231. ["at", "bd", "ex", "ld", "md", "qca", "rw", "rm", "ss", "t"].forEach(l =>
  232. searchParams.append("dt", l)
  233. )
  234. return `https://translate.google.${translateOptions.tld}/translate_a/single?${searchParams}`;
  235. }
  236. const translateUrl = generateRequestUrl(text, options);
  237. const response = await lorahelper.build_cors_request(translateUrl);
  238. const body = await JSON.parse(response);
  239. return normaliseResponse(body, options.raw);
  240. }
  241. function isTouchDevice() {
  242. return (('ontouchstart' in window) ||
  243. (navigator.maxTouchPoints > 0) ||
  244. (navigator.msMaxTouchPoints > 0));
  245. }
  246. lorahelper.gradioApp = function() {
  247. const elems = document.getElementsByTagName('gradio-app');
  248. const elem = elems.length == 0 ? document : elems[0];
  249. if (elem !== document) elem.getElementById = function (id) { return document.getElementById(id); }
  250. return elem.shadowRoot ? elem.shadowRoot : elem;
  251. };
  252. lorahelper.debug = debug;
  253. lorahelper.load_json_number = load_json_number;
  254. lorahelper.load_boolean_flag = load_boolean_flag;
  255. lorahelper.is_nullptr = is_nullptr;
  256. lorahelper.is_empty = is_empty;
  257. lorahelper.convert_file_path_to_url = convert_file_path_to_url;
  258. lorahelper.img_node_str = img_node_str;
  259. lorahelper.pass_url = pass_url;
  260. lorahelper.unescape_string = unescape_string;
  261. lorahelper.google_translate = google_translate;
  262. lorahelper.isTouchDevice = isTouchDevice;
  263. lorahelper.sendontop = sendontop;
  264. lorahelper.resetElementLayer = resetElementLayer;
  265. lorahelper.build_hyper_cmd = build_hyper_cmd;
  266. }
  267. let module_loadded = false;
  268. document.addEventListener("DOMContentLoaded", () => {
  269. if (module_loadded) return;
  270. module_loadded = true;
  271. module_init();
  272. });
  273. document.addEventListener("load", () => {
  274. if (module_loadded) return;
  275. module_loadded = true;
  276. module_init();
  277. });
  278. })();