Ver código fonte

提交代码6

pqy 4 meses atrás
pai
commit
3541645142
3 arquivos alterados com 172 adições e 38 exclusões
  1. 97 17
      src/app/service/api.ts
  2. 1 1
      src/app/tab2/tab2.page.html
  3. 74 20
      src/app/tab3/tab3.page.ts

+ 97 - 17
src/app/service/api.ts

@@ -1,22 +1,28 @@
 import axios from 'axios';
 
 const BASE_URL = 'http://127.0.0.1:5000';
-const BASE_URL_2='http://127.0.0.1:3001';
-const BASE_URL_3='http://127.0.0.1:8080';
-// 调用 Flask 进行图像识别
-export const predict = async (data: any) => {
+// 登录请求方法
+export const login = async (formData: { username: string; password: string }) => {
   try {
-    const response = await axios.post(`${BASE_URL}/predict`, { data });
-    return response.data;
+    const response = await axios.post(`${BASE_URL}/api/login`, formData);
+    // 检查后端返回的响应结果
+    if (response.data.success) {
+      console.log('登录成功');
+      return response.data;
+    } else {
+      console.error('登录失败:', response.data.message);
+      throw new Error(response.data.message || '登录失败,请检查账号和密码!');
+    }
   } catch (error) {
-    console.error('图像预测时发生错误:', error);
+    console.error('登录请求时发生错误:', error);
     throw error;
   }
 };
+
 // 调用 Flask 进行RAG增强回答
 export const queryRAGKnowledge = async (query: string) => {
   try {
-    const response = await axios.post(`${BASE_URL_2}/query`, { query });
+    const response = await axios.post(`${BASE_URL}/query`, { query });
     // 提取结果中的 content 字段
     const contents = response.data.results.map((result: { sentence: any; }) => result.sentence);
     return contents; // 返回内容列表
@@ -26,20 +32,94 @@ export const queryRAGKnowledge = async (query: string) => {
     throw error;
   }
 };
-// 登录请求方法
-export const login = async (formData: { username: string; password: string }) => {
+
+// 保存用户的 AI 问答记录
+export const saveAIChatRecord = async (record: {
+  nickname: string;
+  chat_time: string;
+  chat_title: string;
+  chat_content: string; // Markdown 格式
+}) => {
   try {
-    const response = await axios.post(`${BASE_URL_3}/api/login`, formData);
-    // 检查后端返回的响应结果
-    if (response.data.success) {
-      console.log('登录成功');
+    const response = await axios.post(`${BASE_URL}/save_chat_record`, record);
+    if (response.data.status === 'success') {
+      console.log('AI 问答记录保存成功:', response.data.message);
       return response.data;
     } else {
-      console.error('登录失败:', response.data.message);
-      throw new Error(response.data.message || '登录失败,请检查账号和密码!');
+      console.error('AI 问答记录保存失败:', response.data.message);
+      throw new Error(response.data.message || 'AI 问答记录保存失败!');
     }
   } catch (error) {
-    console.error('登录请求时发生错误:', error);
+    console.error('保存 AI 问答记录时发生错误:', error);
     throw error;
   }
+};
+
+// 获取 AI 问答记录
+export const getAIChatRecords = async () => {
+  try {
+    const response = await axios.get(`${BASE_URL}/get_chat_records`);
+    if (response.data.status === 'success') {
+      console.log('获取 AI 问答记录成功:', response.data.records);
+      return response.data.records;
+    } else {
+      console.error('获取 AI 问答记录失败:', response.data.message);
+      throw new Error(response.data.message || '获取 AI 问答记录失败!');
+    }
+  } catch (error) {
+    console.error('获取 AI 问答记录时发生错误:', error);
+    throw error;
+  }
+};
+
+// 调用 Flask 进行图像识别
+export const predict = async (data: any) => {
+  try {
+    const response = await axios.post(`${BASE_URL}/predict`, { data });
+    return response.data;
+  } catch (error) {
+    console.error('图像预测时发生错误:', error);
+    throw error;
+  }
+};
+
+// 保存用户的陶瓷识别记录
+export const saveCeramicDetectionRecord = async (record: {
+  nickname: string;
+  detection_time: string;
+  result: string;
+  confidence: string;
+}) => {
+  try {
+    const response = await axios.post(`${BASE_URL}/save_detection`, record);
+    if (response.data.status === 'success') {
+      console.log('陶瓷识别记录保存成功:', response.data.message);
+      return response.data;
+    } else {
+      console.error('陶瓷识别记录保存失败:', response.data.message);
+      throw new Error(response.data.message || '陶瓷识别记录保存失败!');
+    }
+  } catch (error) {
+    console.error('保存陶瓷识别记录时发生错误:', error);
+    throw error;
+  }
+};
+
+// 获取陶瓷识别记录
+export const getCeramicDetectionRecords = async (username: string) => {
+  try {
+    const response = await axios.get(`${BASE_URL}/get_detection_records`, {
+      params: { nickname: username }, // 传递用户名参数
+    });
+    if (response.data.status === 'success') {
+      console.log('获取陶瓷识别记录成功:', response.data.records);
+      return response.data.data || []; // 确保返回数组
+    } else {
+      console.error('获取陶瓷识别记录失败:', response.data.message);
+      return []; // 返回空数组
+    }
+  } catch (error) {
+    console.error('获取陶瓷识别记录时发生错误:', error);
+    return []; // 返回空数组以防止前端崩溃
+  }
 };

+ 1 - 1
src/app/tab2/tab2.page.html

@@ -63,7 +63,7 @@
         </div>
         <!-- 用户头像 -->
         <div *ngIf="message.role === 'user'" class="user-avatar">
-          <img src="/assets/images/user.jpg" class="avatar" alt="用户头像">
+          <img [src]="userAvatar" class="avatar" alt="用户头像">
         </div>
       </div>
     </div>

+ 74 - 20
src/app/tab3/tab3.page.ts

@@ -1,5 +1,5 @@
 import { Component, ElementRef, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core';
-import { predict } from 'src/app/service/api'; // 引入 API 服务
+import { predict,saveCeramicDetectionRecord,getCeramicDetectionRecords} from 'src/app/service/api'; // 引入 API 服务
 import { ModalController } from '@ionic/angular';
 import { CeramicDetailsPage } from '../ceramic-details/ceramic-details.page';
 @Component({
@@ -22,6 +22,21 @@ export class Tab3Page implements AfterViewInit{
   constructor(private modalController: ModalController) {
     this.checkCameraAvailability();
   }
+  ngOnInit() {
+    // 页面初始化时加载用户记录
+    const storedUserData = localStorage.getItem('user'); // 从 localStorage 获取登录用户数据
+    if (storedUserData) {
+      const user = JSON.parse(storedUserData);
+      if (user.username) {
+        console.log('当前登录用户:', user.username);
+        this.fetchUserRecords(user.username); // 调用获取当前用户记录的方法
+      } else {
+        console.error('未找到用户名,请检查登录状态!');
+      }
+    } else {
+      console.error('用户未登录或用户数据未找到');
+    }
+  }
   checkCameraAvailability() {
     navigator.mediaDevices
       .getUserMedia({ video: true })
@@ -148,28 +163,67 @@ export class Tab3Page implements AfterViewInit{
       return;
     }
     console.log('开始检测事件触发,调用后端接口');
-    //调用Flask API进行检测
+    // 检查是否为游客登录
+    const guestFlag = localStorage.getItem('guest');
+    const isGuest = guestFlag === 'true'; // 判断是否为游客
+    // 调用 Flask API 进行检测
     try {
-      predict(this.imageSrc)
-        .then(async (response) => {
-          console.log('检测结果:', response);
-          // 假设后端返回的数据格式为 { prediction: string, confidence: string, details: string }
-          const newResult = {
-            result: response.prediction.predicted_label || '未知结果',
-            confidence: response.prediction.confidence
-            ? response.prediction.confidence.toFixed(3) 
-            : '未知置信度',
-          };
-          // 将新结果添加到识别结果数组
-        this.recognitionResults.push(newResult);
-        // 显示陶瓷详情页面
-        await this.openCeramicDetails(newResult.result, newResult.confidence); // 传递两个参数
-      })
-    }
-    catch(error) {
+      const response = await predict(this.imageSrc); // 调用后端预测接口
+      console.log('检测结果:', response);
+      // 假设后端返回的数据格式为 { prediction: { predicted_label: string, confidence: number } }
+      const newResult = {
+        result: response.prediction?.predicted_label || '未知结果',
+        confidence: response.prediction?.confidence
+          ? response.prediction.confidence.toFixed(3) // 保留 3 位小数
+          : '未知置信度',
+      };
+      // 将新结果添加到识别结果数组
+      this.recognitionResults.push(newResult);
+      // 判断是否为游客
+      if (!isGuest) {
+        console.log('用户已登录,准备保存检测记录...');
+        const storedUserData = localStorage.getItem('user');
+        const user = storedUserData ? JSON.parse(storedUserData) : { nickname: '未知用户' };
+        const record = {
+          nickname: user.username || '匿名用户', // 从用户数据中获取昵称
+          detection_time: new Date().toISOString(), // 当前时间,ISO 格式
+          result: newResult.result, // 识别结果
+          confidence: newResult.confidence, // 置信度
+        };
+        // 打印 record 对象
+        console.log('保存的检测记录:', record);
+        try {
+          const saveResponse = await saveCeramicDetectionRecord(record); // 调用保存接口
+          console.log('识别记录保存成功:', saveResponse);
+        } catch (saveError) {
+          console.error('识别记录保存失败:', saveError);
+          alert('识别记录保存失败,请检查网络或后端服务!');
+        }
+      } else {
+        console.log('游客登录,跳过保存检测记录');
+      }
+  
+      // 显示陶瓷详情页面
+      await this.openCeramicDetails(newResult.result, newResult.confidence); // 传递两个参数
+    } catch (error) {
       console.error('检测失败:', error);
       alert('检测失败,请检查网络或后端服务!');
-    };
+    }
+  }
+  // 获取当前登录用户的识别记录 
+  async fetchUserRecords(username: string) {
+    try {
+      const records = await getCeramicDetectionRecords(username); // 调用后端接口获取所有记录
+      console.log('获取到的所有识别记录:', records);
+      // 更新表格数据
+      this.recognitionResults = records.map((record: any) => ({
+        result: record.result,
+        confidence: record.confidence,
+      }));
+    } catch (error) {
+      console.error('获取用户检测记录时发生错误:', error);
+      alert('获取用户检测记录失败,请检查网络或后端服务!');
+    }
   }
   // 显示陶瓷详情模态框
   async openCeramicDetails(ceramicName: string, confidence: string) {