ai_service.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * AI服务工具函数
  3. * 用于调用腾讯云AI接口生成文章
  4. */
  5. // 引入通用工具函数
  6. const util = require('./util.js');
  7. /**
  8. * 调用腾讯云AI接口生成文章
  9. * @param {Array} words - 选中的单词列表
  10. * @param {String} difficulty - 难度级别 (primary/middle/high)
  11. * @return {Promise} - 返回Promise对象,包含生成的文章和译文
  12. */
  13. function generateArticle(words, difficulty) {
  14. return new Promise((resolve, reject) => {
  15. // 获取访问凭证
  16. const accessToken = wx.getStorageSync('accessToken');
  17. if (!accessToken) {
  18. reject(new Error('未获取到访问凭证'));
  19. return;
  20. }
  21. // 构建请求参数
  22. const params = {
  23. words: words,
  24. difficulty: difficulty,
  25. // 可以根据需要添加其他参数
  26. };
  27. // 调用腾讯云AI接口
  28. wx.request({
  29. url: 'https://api.cloud.tencent.com/article/generate', // 替换为实际的API地址
  30. method: 'POST',
  31. header: {
  32. 'Content-Type': 'application/json',
  33. 'Authorization': `Bearer ${accessToken}`
  34. },
  35. data: params,
  36. success: (res) => {
  37. if (res.statusCode === 200 && res.data) {
  38. // 处理API返回的数据
  39. resolve({
  40. article: processArticleWithUnderline(res.data.article, words),
  41. translation: res.data.translation || ''
  42. });
  43. } else {
  44. reject(new Error(`API调用失败: ${res.statusCode}`));
  45. }
  46. },
  47. fail: (err) => {
  48. reject(new Error(`请求失败: ${err.errMsg}`));
  49. }
  50. });
  51. });
  52. }
  53. /**
  54. * 处理文章,为选中的单词添加下划线
  55. * @param {String} article - 原始文章
  56. * @param {Array} words - 需要添加下划线的单词列表
  57. * @return {String} - 处理后的文章
  58. */
  59. function processArticleWithUnderline(article, words) {
  60. if (!article || !words || words.length === 0) {
  61. return article;
  62. }
  63. // 创建一个正则表达式,匹配所有选中的单词(考虑单词边界)
  64. const wordPattern = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');
  65. // 替换匹配到的单词,添加下划线标记
  66. return article.replace(wordPattern, '<u>$1</u>');
  67. }
  68. module.exports = {
  69. generateArticle
  70. };