fetch-prompts.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import fetch from "node-fetch";
  2. import fs from "fs/promises";
  3. const RAW_FILE_URL = "https://raw.githubusercontent.com/";
  4. const MIRRORF_FILE_URL = "http://raw.fgit.ml/";
  5. const RAW_CN_URL = "PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh.json";
  6. const CN_URL = MIRRORF_FILE_URL + RAW_CN_URL;
  7. const RAW_EN_URL = "f/awesome-chatgpt-prompts/main/prompts.csv";
  8. const EN_URL = MIRRORF_FILE_URL + RAW_EN_URL;
  9. const FILE = "./public/prompts.json";
  10. const ignoreWords = ["涩涩", "魅魔"];
  11. const timeoutPromise = (timeout) => {
  12. return new Promise((resolve, reject) => {
  13. setTimeout(() => {
  14. reject(new Error("Request timeout"));
  15. }, timeout);
  16. });
  17. };
  18. async function fetchCN() {
  19. console.log("[Fetch] fetching cn prompts...");
  20. try {
  21. const response = await Promise.race([fetch(CN_URL), timeoutPromise(5000)]);
  22. const raw = await response.json();
  23. return raw
  24. .map((v) => [v.act, v.prompt])
  25. .filter(
  26. (v) =>
  27. v[0] &&
  28. v[1] &&
  29. ignoreWords.every((w) => !v[0].includes(w) && !v[1].includes(w)),
  30. );
  31. } catch (error) {
  32. console.error("[Fetch] failed to fetch cn prompts", error);
  33. return [];
  34. }
  35. }
  36. async function fetchEN() {
  37. console.log("[Fetch] fetching en prompts...");
  38. try {
  39. // const raw = await (await fetch(EN_URL)).text();
  40. const response = await Promise.race([fetch(EN_URL), timeoutPromise(5000)]);
  41. const raw = await response.text();
  42. return raw
  43. .split("\n")
  44. .slice(1)
  45. .map((v) =>
  46. v
  47. .split('","')
  48. .map((v) => v.replace(/^"|"$/g, "").replaceAll('""', '"'))
  49. .filter((v) => v[0] && v[1]),
  50. );
  51. } catch (error) {
  52. console.error("[Fetch] failed to fetch en prompts", error);
  53. return [];
  54. }
  55. }
  56. async function main() {
  57. Promise.all([fetchCN(), fetchEN()])
  58. .then(([cn, en]) => {
  59. fs.writeFile(FILE, JSON.stringify({ cn, en }));
  60. })
  61. .catch((e) => {
  62. console.error("[Fetch] failed to fetch prompts");
  63. fs.writeFile(FILE, JSON.stringify({ cn: [], en: [] }));
  64. })
  65. .finally(() => {
  66. console.log("[Fetch] saved to " + FILE);
  67. });
  68. }
  69. main();