Skip to content

Commit

Permalink
refactor: use replaceAll() instead of eval()
Browse files Browse the repository at this point in the history
`eval()` is slower than the alternatives, and it is also unsafe.
Using template string instead to avoid `eval()` calls.
  • Loading branch information
yin1999 committed Aug 21, 2023
1 parent 50096a4 commit 3eac8f2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion addon/prefs.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pref("__prefsPrefix__.gptModel", "gpt-3.5-turbo");
pref("__prefsPrefix__.gptTemperature", "1.0");
pref(
"__prefsPrefix__.gptPrompt",
"As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation translation from ${data.langfrom} to ${data.langto} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows: 🔤 ${data.raw} 🔤 Please provide the translated result without any additional explanation and remove 🔤.",
"As an academic expert with specialized knowledge in various fields, please provide a proficient and precise translation translation from ${langFrom} to ${langTo} of the academic text enclosed in 🔤. It is crucial to maintaining the original phrase or sentence and ensure accuracy while utilizing the appropriate language. The text is as follows: 🔤 ${sourceText} 🔤 Please provide the translated result without any additional explanation and remove 🔤.",
);
pref(
"__prefsPrefix__.cnkiRegex",
Expand Down
10 changes: 9 additions & 1 deletion src/modules/services/gpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ export const gptTranslate = <TranslateTaskProcessor>async function (data) {
const model = getPref("gptModel");
const temperature = parseFloat(getPref("gptTemperature") as string);
const apiUrl = getPref("gptUrl");

function transformContent(langFrom: string, langTo: string, sourceText: string) {
return (getPref("gptPrompt") as string)
.replaceAll("${langFrom}", langFrom)
.replaceAll("${langTo}", langTo)
.replaceAll("${sourceText}", sourceText);
}

const xhr = await Zotero.HTTP.request("POST", apiUrl, {
headers: {
"Content-Type": "application/json",
Expand All @@ -16,7 +24,7 @@ export const gptTranslate = <TranslateTaskProcessor>async function (data) {
messages: [
{
role: "user",
content: eval((("`" + getPref("gptPrompt")) as string) + "`"),
content: transformContent(data.langfrom, data.langto, data.raw),
},
],
temperature: temperature,
Expand Down

0 comments on commit 3eac8f2

Please sign in to comment.