| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- /**
- * AI服务工具函数
- * 用于调用腾讯云AI接口生成文章
- */
- // 引入通用工具函数
- const util = require('./util.js');
- /**
- * 调用腾讯云AI接口生成文章
- * @param {Array} words - 选中的单词列表
- * @param {String} difficulty - 难度级别 (primary/middle/high)
- * @return {Promise} - 返回Promise对象,包含生成的文章和译文
- */
- function generateArticle(words, difficulty) {
- return new Promise((resolve, reject) => {
- // 获取访问凭证
- const accessToken = wx.getStorageSync('accessToken');
- if (!accessToken) {
- reject(new Error('未获取到访问凭证'));
- return;
- }
- // 构建请求参数
- const params = {
- words: words,
- difficulty: difficulty,
- // 可以根据需要添加其他参数
- };
- // 调用腾讯云AI接口
- wx.request({
- url: 'https://api.cloud.tencent.com/article/generate', // 替换为实际的API地址
- method: 'POST',
- header: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${accessToken}`
- },
- data: params,
- success: (res) => {
- if (res.statusCode === 200 && res.data) {
- // 处理API返回的数据
- resolve({
- article: processArticleWithUnderline(res.data.article, words),
- translation: res.data.translation || ''
- });
- } else {
- reject(new Error(`API调用失败: ${res.statusCode}`));
- }
- },
- fail: (err) => {
- reject(new Error(`请求失败: ${err.errMsg}`));
- }
- });
- });
- }
- /**
- * 处理文章,为选中的单词添加下划线
- * @param {String} article - 原始文章
- * @param {Array} words - 需要添加下划线的单词列表
- * @return {String} - 处理后的文章
- */
- function processArticleWithUnderline(article, words) {
- if (!article || !words || words.length === 0) {
- return article;
- }
- // 创建一个正则表达式,匹配所有选中的单词(考虑单词边界)
- const wordPattern = new RegExp(`\\b(${words.join('|')})\\b`, 'gi');
-
- // 替换匹配到的单词,添加下划线标记
- return article.replace(wordPattern, '<u>$1</u>');
- }
- module.exports = {
- generateArticle
- };
|