js/LibGPT.js

  1. /**=====LICENSE STATEMENT START=====
  2. Translator++
  3. CAT (Computer-Assisted Translation) tools and framework to create quality
  4. translations and localizations efficiently.
  5. Copyright (C) 2018 Dreamsavior<dreamsavior@gmail.com>
  6. This program is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. =====LICENSE STATEMENT END=====*/
  17. const LibGPT = {}
  18. LibGPT.templateParameters = {
  19. get LANG_FROM() {
  20. return langTools.getName(trans.getSl());
  21. },
  22. get LANG_TO() {
  23. return langTools.getName(trans.getTl());
  24. },
  25. get LANG_FROM_FULL() {
  26. return langTools.getFullName(trans.getSl());
  27. },
  28. get LANG_TO_FULL() {
  29. return langTools.getFullName(trans.getTl());
  30. },
  31. get ENGINE() {
  32. return trans.project?.gameEngine;
  33. },
  34. get TITLE() {
  35. return trans.project?.gameTitle;
  36. },
  37. REFERENCE : new Proxy({}, {
  38. get: function(target, name) {
  39. let obj = trans.getObjectById(name);
  40. if (!trans.project) return;
  41. if (!obj) return;
  42. if (!obj?.data?.length) return;
  43. const rows = [];
  44. const keyColumn = trans.keyColumn;
  45. for (let i = 0; i < obj.data.length; i++) {
  46. let translation =trans.getTranslationFromRow(obj.data[i]);
  47. if (!translation) continue;
  48. let line = `${JSON.stringify(obj.data[i][keyColumn])} => ${JSON.stringify(translation)}`;
  49. rows.push(line);
  50. }
  51. return rows.join("\n");
  52. }
  53. })
  54. }
  55. LibGPT.algorithmMsg = {
  56. JSTemplateCloaking: "The source text and translation result is in JavaScript format. Do not change variable name!",
  57. htmlCloaking:"Preserve the HTML tags.",
  58. xmlCloaking: "Preserve the XML tags.",
  59. hexPlaceholder: "Preserve hexadecimal formatting.",
  60. HTMLCloakingWrapped:"Preserve HTML tags and line breaks.",
  61. JSONCloaking: `Source texts are in JSON. Complete every element of the array. Reply in JSON format of \`{"translation":[/*translation here*/]}\`. The index of translation must match the index of the original text. For example:\n`+
  62. `Source: \`["こんにちは", "わぁー。\\nきれいだなぁ。"]\`\nTranslation: \`{"translation": ["Hello", "Waa.\\nIt's so beautiful!"]}\` \n`+"${dat[n]} is place holder for the original text. Do not change it.",
  63. }
  64. LibGPT.getEscapeAlgorithmTemplateString = function(algorithm) {
  65. if (LibGPT.algorithmMsg[algorithm]) return LibGPT.algorithmMsg[algorithm]
  66. return "Number of line of the source and result must be the same.";
  67. }
  68. LibGPT.compileTemplate = function(templateString, parameters={}) {
  69. parameters = {...LibGPT.templateParameters, ...parameters};
  70. if (!templateString || typeof templateString !== 'string') {
  71. throw new Error('Invalid template string');
  72. }
  73. if (!parameters || typeof parameters !== 'object') {
  74. throw new Error('Invalid template parameters');
  75. }
  76. // for (let key in parameters) {
  77. // if (typeof parameters[key] !== 'string') {
  78. // console.error('Invalid template parameters for key', key, parameters[key]);
  79. // throw new Error('Invalid template parameters');
  80. // }
  81. // }
  82. // return templateString.replace(/\$\{(\w+)\}/g, function(match, placeholder) {
  83. // if (!parameters?.[placeholder]) return match;
  84. // return parameters[placeholder];
  85. // });
  86. return templateString.replace(/\$\{(\w+)\[*(\w*)\]*\}/g, function(match, placeholder, param1) {
  87. if (!param1) {
  88. if (!parameters?.[placeholder]) return match;
  89. return parameters[placeholder];
  90. } else {
  91. if (!parameters?.[placeholder]?.[param1]) return match;
  92. return parameters[placeholder][param1];
  93. }
  94. });
  95. }
  96. /**
  97. * Render Array of customParameters into object of key-value pair
  98. * to append into the request body of the API
  99. * @param {Array} customParameters
  100. * @returns {Object}
  101. */
  102. LibGPT.renderCustomParameters = function(customParameters=[], existingParameters={}) {
  103. console.log("%c Custom parameters", "color:cyan", customParameters);
  104. let result = existingParameters;
  105. if (!customParameters.length) return result;
  106. try {
  107. for (let i = 0; i < customParameters.length; i++) {
  108. let param = customParameters[i];
  109. if (!param.key || !param.value) continue;
  110. let thisValue = param.value;
  111. // adjust the value
  112. if (param.type == "number") {
  113. thisValue = parseFloat(param.value);
  114. } else if (param.type == "boolean") {
  115. thisValue = param.value == "true";
  116. } else if (param.type == "javascript") {
  117. thisValue = eval(`(${param.value})`);
  118. console.log("%c Evaluated value", "color:cyan", thisValue);
  119. }
  120. result[param.key] = thisValue;
  121. }
  122. } catch (e) {
  123. console.error("Error in customParameters", e);
  124. throw new Error("Error in customParameters", e);
  125. }
  126. console.log("%c Result of custom parameters", "color:cyan", result);
  127. return result;
  128. }
  129. LibGPT.dropParameters = function(parameters, keys) {
  130. if (!keys.length) return parameters;
  131. for (let i = 0; i < keys.length; i++) {
  132. delete parameters[keys[i]];
  133. }
  134. return parameters;
  135. }
  136. module.exports = LibGPT;