| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274 |
- import common from '../../utils/util';
- import main from '../../utils/main';
- Page({
- data: {
- cameraActive: true,
- imageUrl: '',
- recognizedTexts: [],
- showCanvas: false,
- Count:0,
- },
- onLoad: function(options) {
- let that=this;
- that.setData({
- englishWords: null, // 存储提取的英语单词
- });
- },
- // 提取英语单词的函数 - 增强版
- extractEnglishWords(texts) {
- console.group('英语单词提取');
- const words = new Set();
-
- texts.forEach(item => {
- const text = item.text;
- console.log('处理文本:', text);
-
- // 改进的正则表达式,能更好处理中英文混合文本
- const wordRegex = /(?:^|\s|[\u4e00-\u9fa5])([A-Za-z]{2,}(?:['’-][A-Za-z]+)*)(?=$|\s|[\u4e00-\u9fa5])/g;
-
- let match;
- while ((match = wordRegex.exec(text)) !== null) {
- const word = match[1];
- console.log('匹配到单词:', word);
-
- // 验证单词有效性
- if (/^[A-Za-z'’-]+$/.test(word)) {
- const lowerWord = word.toLowerCase();
- words.add(lowerWord);
- console.log('添加单词:', lowerWord);
- }
- }
- });
-
- //const result = Array.from(words).sort();
- const result=Array.from(words);
- console.log('提取结果:', result);
- console.groupEnd();
- return result;
- },
- // 拍照识别
- takePhoto() {
- const ctx = wx.createCameraContext()
- ctx.takePhoto({
- quality: 'high',
- success: (res) => {
- this.setData({
- imageUrl: res.tempImagePath,
- cameraActive: false,
- showCanvas: true
- })
- this.performOCR(res.tempImagePath)
- },
- fail: (err) => {
- console.error('拍照失败:', err)
- wx.showToast({
- title: '拍照失败,请重试',
- icon: 'none'
- })
- }
- })
- },
- // 从相册选择
- chooseImage() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- sourceType: ['album'],
- success: (res) => {
- const tempFilePath = res.tempFiles[0].tempFilePath
- this.setData({
- imageUrl: tempFilePath,
- cameraActive: false,
- showCanvas: true
- })
- this.performOCR(tempFilePath)
- },
- fail: (err) => {
- console.error('选择图片失败:', err)
- wx.showToast({
- title: '选择图片失败',
- icon: 'none'
- })
- }
- })
- },
- // 加强版的OCR识别方法
- async performOCR(imagePath) {
- if (!imagePath) {
- console.error('图片路径无效')
- }
- wx.showLoading({ title: '识别中...', mask: true })
- try {
- // 1. 压缩图片
- const compressed = await new Promise((resolve, reject) => {
- wx.compressImage({
- src: imagePath,
- quality: 70,
- success: resolve,
- fail: () => resolve({ tempFilePath: imagePath })
- })
- })
- //console.log("1");
- // 2. 转换为base64
- const fileRes = await new Promise((resolve, reject) => {
- wx.getFileSystemManager().readFile({
- filePath: compressed.tempFilePath,
- encoding: 'base64',
- success: resolve,
- fail: reject
- })
- })
- //console.log("2");
- // 3. 调用云函数(添加超时处理)
- let postData={ ImageBase64: `data:image/jpeg;base64,${fileRes.data}` };
-
- let url = common.Encrypt("OCRImageData");
- url="https://www.kylx365.com/apiData/"+url;
- //url="http://localhost:3020/api/OCRImageData";
- //console.log("url:"+url);
- const cloudRes = await new Promise((resolve, reject) => {
- wx.request({
- url: url,
- method: "POST",
- data: postData,
- success: resolve,
- fail: reject,
- })
- });
- //console.log("3");
- // 4. 验证返回结果
- if (!cloudRes || !cloudRes.data.result) {
- throw new Error('无效的响应格式')
- }
- //console.log("4");
- if (!cloudRes.data.result) {
- throw new Error(cloudRes.data.result.message || '识别服务返回空数据')
- }
- // 5. 处理识别结果
- const texts = cloudRes.data.result.TextDetections.map(item => ({
- text: item.DetectedText || '未识别到文字',
- pos: this.convertPosition(item.ItemPolygon || { Points: [] })
- })).filter(item => item.DetectedText !== '未识别到文字')
- //console.log("5");
- if (texts.length === 0) {
- throw new Error('未识别到有效文字')
- }
- // 6.提取英文单词
- const engTexts=this.extractEnglishWords(texts);
- let arr=[];
- for(var i=0;i<engTexts.length;i++){
- let obj={};
- obj.Word=engTexts[i];
- obj.Selected=0;
- arr.push(obj);
- }
- this.setData({
- recognizedTexts: texts,
- englishWords:arr,
- })
- } catch (err) {
- console.error('OCR处理失败:', err)
- wx.showToast({
- title: err.message || '识别失败',
- icon: 'none',
- duration: 3000
- })
- } finally {
- wx.hideLoading()
- }
- },
- // 加强坐标转换
- convertPosition(polygon) {
- try {
- const points = polygon.Points || []
- if (points.length === 0) {
- return { x: 50, y: 50, width: 200, height: 30 }
- }
- const xs = points.map(p => p.X || 0)
- const ys = points.map(p => p.Y || 0)
- return {
- x: Math.min(...xs),
- y: Math.min(...ys),
- width: Math.max(...xs) - Math.min(...xs),
- height: Math.max(...ys) - Math.min(...ys)
- }
- } catch (e) {
- return { x: 50, y: 50, width: 200, height: 30 }
- }
- },
-
- // 重新拍照
- retake() {
- this.setData({
- cameraActive: true,
- imageUrl: '',
- recognizedTexts: [],
- showCanvas: false
- })
- },
- // 选择单词
- selectWord(e) {
- let that=this;
- let list=that.data.englishWords;
- const text = e.currentTarget.dataset.text
- if (!text) return;
- for(let i=0;i<list.length;i++){
- if (text.Word==list[i].Word){
- list[i].Selected=list[i].Selected==1?0:1;
- }
- }
- that.setData({
- englishWords:that.data.englishWords,
- });
- let count=0;
- for(let i=0;i<list.length;i++){
- if (list[i].Selected==1){
- count++;
- }
- }
- if (count>10){
- wx.showToast({
- title: '最多10个单词',
- })
- }
- that.setData({
- Count:count,
- });
- },
- // 跳转到文章生成页面
- goToArticleGenerator() {
- let that=this;
- let words=[];
- let list=that.data.englishWords;
- for(let i=0;i<list.length;i++){
- if (list[i].Selected==1){
- words.push(list[i].Word);
- }
- }
- wx.redirectTo({
- url: '/pages/index/index?words=' + words.join(","),
- });
- }
- })
|