鸿蒙 自然语言处理(聊天机器人/文档摘要)

举报
鱼弦 发表于 2025/11/03 11:26:51 2025/11/03
【摘要】 一、引言在人工智能技术飞速发展的今天,​​自然语言处理(NLP)​​ 已成为人机交互的核心技术。据统计,2023年全球NLP市场规模达到​​254亿美元​​,预计到2028年将增长至​​1,273亿美元​​,年复合增长率​**​38%。鸿蒙(HarmonyOS)作为分布式操作系统,其NLP能力具有重要战略意义:​​智能交互​​:实现自然、流畅的人机对话​​效率提升​​:文档自动摘要节省90%...


一、引言

在人工智能技术飞速发展的今天,​​自然语言处理(NLP)​​ 已成为人机交互的核心技术。据统计,2023年全球NLP市场规模达到​​254亿美元​​,预计到2028年将增长至​​1,273亿美元​​,年复合增长率​**​38%。鸿蒙(HarmonyOS)作为分布式操作系统,其NLP能力具有重要战略意义:
  • ​智能交互​​:实现自然、流畅的人机对话
  • ​效率提升​​:文档自动摘要节省90%阅读时间
  • ​知识管理​​:智能信息提取和知识图谱构建
  • ​无障碍支持​​:语音交互助力视障用户
鸿蒙NLP通过​​端云协同架构​​,在保护用户隐私的同时,提供强大的语言理解和生成能力。

二、技术背景

1. NLP技术演进历程

timeline
    title 自然语言处理技术发展
    section 规则方法
        1950s: 基于规则的系统<br>有限领域对话
        1960s: ELIZA 聊天机器人<br>模式匹配技术
        1970s: 概念依存理论<br>语义表示尝试
    section 统计方法
        1990s: 统计机器翻译<br>隐马尔可夫模型
        2000s: 条件随机场<br>支持向量机分类
        2010: Word2Vec<br>词向量表示
    section 神经网络
        2013: Word Embeddings<br>分布式表示
        2014: Seq2Seq<br>序列到序列学习
        2017: Transformer<br>自注意力机制
    section 预训练时代
        2018: BERT<br>双向编码表示
        2019: GPT-2<br>生成式预训练
        2020: T5<br>文本到文本统一框架
    section 鸿蒙特色
        2021: 端侧轻量化模型<br>隐私保护推理
        2022: 多模态融合<br>文本+语音+视觉
        2023: 联邦学习<br>分布式模型优化

2. 鸿蒙NLP架构优势

// 鸿蒙NLP技术栈
public class HarmonyNLPArchitecture {
    // 1. 分布式计算框架
    private DistributedComputingFramework computingFramework;
    
    // 2. 端侧推理引擎
    private OnDeviceInferenceEngine inferenceEngine;
    
    // 3. 云侧模型服务
    private CloudModelService cloudModelService;
    
    // 4. 多语言支持
    private MultilingualSupport multilingualSupport;
    
    // 5. 隐私计算
    private PrivacyPreservingComputation privacyComputation;
    
    // 6. 实时学习
    private RealTimeLearning realTimeLearning;
}

三、应用使用场景

1. 智能聊天机器人

​场景特征​​:
  • 多轮对话管理
  • 上下文理解
  • 个性化响应
  • 情感分析
​技术需求​​:
public class SmartChatbot {
    // 对话状态管理
    @DialogStateManagement
    public DialogState manageConversationFlow(UserInput input) {
        return stateMachine.process(input);
    }
    
    // 上下文感知
    @ContextAware
    public Response generateContextualResponse(DialogContext context) {
        return contextAwareNLG.generate(context);
    }
    
    // 情感分析
    @SentimentAnalysis
    public EmotionalResponse adaptToUserEmotion(Sentiment sentiment) {
        return emotionEngine.adaptResponse(sentiment);
    }
    
    // 个性化学习
    @PersonalizedLearning
    public void learnFromInteraction(UserProfile profile, DialogHistory history) {
        personalizationEngine.update(profile, history);
    }
}

2. 智能文档摘要

​场景特征​​:
  • 长文档处理
  • 关键信息提取
  • 多粒度摘要
  • 领域适配
​技术需求​​:
public class DocumentSummarization {
    // 多粒度摘要
    @MultiGranularity
    public Summary generateAdaptiveSummary(Document doc, SummaryType type) {
        return multiScaleSummarizer.summarize(doc, type);
    }
    
    // 关键信息提取
    @KeyInformationExtraction
    public List<KeyPoint> extractKeyPoints(Document doc) {
        return keyPointExtractor.extract(doc);
    }
    
    // 领域适配
    @DomainAdaptation
    public void adaptToDomain(Domain domain) {
        domainAdapter.adapt(domain);
    }
    
    // 质量评估
    @QualityAssessment
    public SummaryQuality evaluateSummary(Summary summary, Document doc) {
        return qualityEvaluator.evaluate(summary, doc);
    }
}

3. 智能客服系统

​场景特征​​:
  • 业务知识库
  • 意图识别
  • 工单生成
  • 满意度分析
​技术需求​​:
public class CustomerServiceBot {
    // 意图识别
    @IntentRecognition
    public UserIntent recognizeIntent(String query) {
        return intentClassifier.classify(query);
    }
    
    // 知识检索
    @KnowledgeRetrieval
    public Answer retrieveSolution(UserIntent intent) {
        return knowledgeGraph.retrieve(intent);
    }
    
    // 工单自动生成
    @TicketGeneration
    public SupportTicket generateTicket(ProblemDescription problem) {
        return ticketGenerator.generate(problem);
    }
    
    // 满意度预测
    @SatisfactionPrediction
    public SatisfactionLevel predictSatisfaction(Interaction interaction) {
        return satisfactionPredictor.predict(interaction);
    }
}

四、不同场景下详细代码实现

环境准备

// package.json
{
  "name": "harmonyos-nlp-app",
  "version": "1.0.0",
  "dependencies": {
    "@ohos/nlp": "1.0.0",
    "@ohos/ai": "1.0.0",
    "@ohos/network": "1.0.0",
    "@ohos/data": "1.0.0"
  },
  "devDependencies": {
    "@ohos/hypium": "1.0.0"
  }
}
// config.json
{
  "module": {
    "name": "entry",
    "type": "entry",
    "deviceTypes": ["phone", "tablet", "smartSpeaker"],
    "abilities": [
      {
        "name": "MainAbility",
        "srcEntrance": "./src/main/ets/MainAbility/MainAbility.ts",
        "description": "NLP应用主入口",
        "permissions": [
          "ohos.permission.INTERNET",
          "ohos.permission.GET_NETWORK_STATE",
          "ohos.permission.READ_USER_STORAGE"
        ]
      }
    ]
  }
}

场景1:智能聊天机器人实现

1.1 聊天机器人核心服务

// src/main/ets/services/ChatbotService.ts
import { BusinessError } from '@ohos.base';

/**
 * 智能聊天机器人服务
 * 支持多轮对话和上下文理解
 */
export class ChatbotService {
  private nlpEngine: NLPEngine;
  private dialogManager: DialogManager;
  private knowledgeBase: KnowledgeBase;
  private userProfileManager: UserProfileManager;
  
  private conversationContext: ConversationContext;
  private isInitialized: boolean = false;

  constructor() {
    this.nlpEngine = new NLPEngine();
    this.dialogManager = new DialogManager();
    this.knowledgeBase = new KnowledgeBase();
    this.userProfileManager = new UserProfileManager();
    this.conversationContext = new ConversationContext();
  }

  /**
   * 初始化服务
   */
  async initialize(): Promise<void> {
    if (this.isInitialized) {
      return;
    }

    try {
      // 并行初始化各个组件
      await Promise.all([
        this.nlpEngine.initialize(),
        this.dialogManager.initialize(),
        this.knowledgeBase.initialize(),
        this.userProfileManager.initialize()
      ]);

      this.isInitialized = true;
      console.info('ChatbotService: 初始化成功');
    } catch (error) {
      console.error('ChatbotService: 初始化失败', error);
      throw error;
    }
  }

  /**
   * 处理用户消息
   */
  async processMessage(userInput: UserInput): Promise<ChatResponse> {
    if (!this.isInitialized) {
      throw new Error('服务未初始化');
    }

    const startTime = Date.now();

    try {
      // 1. 自然语言理解
      const understandingResult = await this.nlpEngine.understand(userInput.text, this.conversationContext);
      
      // 2. 对话状态更新
      const dialogState = await this.dialogManager.updateState(understandingResult, this.conversationContext);
      
      // 3. 知识检索
      const knowledge = await this.knowledgeBase.retrieveRelevantKnowledge(understandingResult);
      
      // 4. 响应生成
      const response = await this.generateResponse(understandingResult, dialogState, knowledge);
      
      // 5. 上下文更新
      this.updateConversationContext(userInput, understandingResult, response);
      
      // 6. 用户画像更新
      await this.updateUserProfile(userInput, understandingResult);

      const processingTime = Date.now() - startTime;
      console.info(`消息处理完成,耗时: ${processingTime}ms`);

      return {
        ...response,
        processingTime,
        confidence: understandingResult.confidence
      };

    } catch (error) {
      console.error('处理消息失败:', error);
      throw new Error(`消息处理失败: ${error.message}`);
    }
  }

  /**
   * 自然语言理解
   */
  private async naturalLanguageUnderstanding(text: string, context: ConversationContext): Promise<NLUResult> {
    const nluResult = await this.nlpEngine.understand(text, context);
    
    // 意图识别置信度检查
    if (nluResult.confidence < 0.3) {
      nluResult.intent = 'clarification_required';
      nluResult.confidence = 1.0;
    }
    
    return nluResult;
  }

  /**
   * 生成响应
   */
  private async generateResponse(
    understanding: NLUResult, 
    dialogState: DialogState, 
    knowledge: Knowledge
  ): Promise<ChatResponse> {
    
    // 根据意图类型选择生成策略
    switch (understanding.intent) {
      case 'greeting':
        return this.generateGreetingResponse(understanding, dialogState);
      
      case 'question':
        return this.generateAnswerResponse(understanding, knowledge);
      
      case 'chitchat':
        return this.generateChitchatResponse(understanding, dialogState);
      
      case 'clarification_required':
        return this.generateClarificationResponse(understanding);
      
      default:
        return this.generateFallbackResponse(understanding);
    }
  }

  /**
   * 生成问候响应
   */
  private generateGreetingResponse(understanding: NLUResult, dialogState: DialogState): ChatResponse {
    const greetings = [
      '你好!我是鸿蒙智能助手,有什么可以帮您的吗?',
      '您好!很高兴为您服务。',
      '嗨!我是小鸿,随时为您提供帮助。'
    ];
    
    const personalization = this.getPersonalization(dialogState.userId);
    const greeting = personalization ? `${personalization} ${greetings[0]}` : greetings[Math.floor(Math.random() * greetings.length)];
    
    return {
      text: greeting,
      type: 'text',
      suggestions: ['介绍功能', '常见问题', '使用帮助'],
      emotionalTone: 'friendly'
    };
  }

  /**
   * 生成答案响应
   */
  private async generateAnswerResponse(understanding: NLUResult, knowledge: Knowledge): Promise<ChatResponse> {
    if (knowledge.hasAnswer) {
      return {
        text: knowledge.answer,
        type: 'text',
        sources: knowledge.sources,
        confidence: knowledge.confidence
      };
    } else {
      return {
        text: '抱歉,我暂时无法回答这个问题。您可以尝试重新表述问题或询问其他内容。',
        type: 'text',
        suggestions: ['重新表述', '换一个问题', '联系人工客服'],
        emotionalTone: 'apologetic'
      };
    }
  }

  /**
   * 生成闲聊响应
   */
  private generateChitchatResponse(understanding: NLUResult, dialogState: DialogState): ChatResponse {
    const chitchatResponses = {
      'weather': ['今天天气不错呢!', '天气变化快,注意保暖哦。'],
      'joke': ['为什么程序员总是分不清万圣节和圣诞节?因为 Oct 31 == Dec 25!'],
      'compliment': ['您真会聊天!', '谢谢夸奖,您也很棒!']
    };
    
    const topic = understanding.entities.topic || 'general';
    const responses = chitchatResponses[topic] || ['哈哈,这个话题很有趣!'];
    const response = responses[Math.floor(Math.random() * responses.length)];
    
    return {
      text: response,
      type: 'text',
      emotionalTone: 'playful'
    };
  }

  /**
   * 生成澄清请求
   */
  private generateClarificationResponse(understanding: NLUResult): ChatResponse {
    const clarificationQuestions = [
      '您能再详细描述一下吗?',
      '我不太明白您的意思,可以换种说法吗?',
      '您是想问关于哪方面的问题呢?'
    ];
    
    return {
      text: clarificationQuestions[Math.floor(Math.random() * clarificationQuestions.length)],
      type: 'text',
      needsClarification: true,
      clarificationType: understanding.ambiguityType
    };
  }

  /**
   * 生成回退响应
   */
  private generateFallbackResponse(understanding: NLUResult): ChatResponse {
    return {
      text: '我还在学习中,暂时无法处理这个请求。您可以尝试其他问题或联系客服。',
      type: 'text',
      suggestions: ['帮助文档', '常见问题', '人工服务'],
      emotionalTone: 'helpful'
    };
  }

  /**
   * 更新对话上下文
   */
  private updateConversationContext(userInput: UserInput, understanding: NLUResult, response: ChatResponse): void {
    this.conversationContext.addTurn({
      userInput,
      understanding,
      botResponse: response,
      timestamp: Date.now()
    });
    
    // 保持合理的上下文长度
    if (this.conversationContext.getTurns().length > 10) {
      this.conversationContext.compress();
    }
  }

  /**
   * 更新用户画像
   */
  private async updateUserProfile(userInput: UserInput, understanding: NLUResult): Promise<void> {
    await this.userProfileManager.recordInteraction({
      userId: userInput.userId,
      intent: understanding.intent,
      entities: understanding.entities,
      timestamp: Date.now()
    });
  }

  /**
   * 获取个性化信息
   */
  private getPersonalization(userId: string): string {
    const profile = this.userProfileManager.getProfile(userId);
    if (profile && profile.preferredName) {
      return `${profile.preferredName},`;
    }
    return '';
  }

  /**
   * 重置对话
   */
  resetConversation(): void {
    this.conversationContext.clear();
    console.info('对话已重置');
  }

  /**
   * 获取对话历史
   */
  getConversationHistory(): ConversationTurn[] {
    return this.conversationContext.getTurns();
  }

  /**
   * 导出对话数据
   */
  exportConversationData(): ExportedConversation {
    return {
      turns: this.conversationContext.getTurns(),
      summary: this.conversationContext.getSummary(),
      metadata: {
        exportTime: Date.now(),
        version: '1.0'
      }
    };
  }

  /**
   * 释放资源
   */
  async release(): Promise<void> {
    await Promise.allSettled([
      this.nlpEngine.release(),
      this.dialogManager.release(),
      this.knowledgeBase.release(),
      this.userProfileManager.release()
    ]);
    
    this.isInitialized = false;
    console.info('ChatbotService: 资源已释放');
  }
}

// 类型定义
interface UserInput {
  text: string;
  userId: string;
  timestamp: number;
  metadata?: any;
}

interface ChatResponse {
  text: string;
  type: 'text' | 'rich' | 'interactive';
  suggestions?: string[];
  emotionalTone?: string;
  processingTime?: number;
  confidence?: number;
  needsClarification?: boolean;
  clarificationType?: string;
  sources?: string[];
}

interface NLUResult {
  intent: string;
  confidence: number;
  entities: Record<string, any>;
  sentiment: Sentiment;
  ambiguityType?: string;
}

interface DialogState {
  currentIntent: string;
  dialogAct: string;
  slots: Record<string, any>;
  context: any;
}

interface Knowledge {
  hasAnswer: boolean;
  answer?: string;
  confidence: number;
  sources?: string[];
}

interface ConversationTurn {
  userInput: UserInput;
  understanding: NLUResult;
  botResponse: ChatResponse;
  timestamp: number;
}

interface ExportedConversation {
  turns: ConversationTurn[];
  summary: string;
  metadata: any;
}

type Sentiment = 'positive' | 'negative' | 'neutral';

// 核心组件实现
class NLPEngine {
  private isInitialized: boolean = false;

  async initialize(): Promise<void> {
    // 初始化NLP模型
    await this.loadModels();
    this.isInitialized = true;
  }

  async understand(text: string, context: ConversationContext): Promise<NLUResult> {
    if (!this.isInitialized) {
      throw new Error('NLP引擎未初始化');
    }

    // 模拟NLP处理流程
    const intent = await this.classifyIntent(text, context);
    const entities = await this.extractEntities(text, intent);
    const sentiment = await this.analyzeSentiment(text);
    
    return {
      intent,
      confidence: await this.calculateConfidence(text, intent),
      entities,
      sentiment
    };
  }

  private async classifyIntent(text: string, context: ConversationContext): Promise<string> {
    // 模拟意图分类
    const intents = ['greeting', 'question', 'chitchat', 'complaint', 'thanks'];
    const contextualIntents = this.applyContextualBiasing(text, context, intents);
    return contextualIntents[0]; // 返回最可能的意图
  }

  private async extractEntities(text: string, intent: string): Promise<Record<string, any>> {
    // 模拟实体提取
    const entities: Record<string, any> = {};
    
    // 简单规则提取
    if (text.includes('天气')) {
      entities.topic = 'weather';
    }
    if (text.includes('时间')) {
      entities.topic = 'time';
    }
    
    return entities;
  }

  private async analyzeSentiment(text: string): Promise<Sentiment> {
    // 简单情感分析
    const positiveWords = ['好', '棒', '优秀', '感谢', '喜欢'];
    const negativeWords = ['差', '坏', '糟糕', '讨厌', '问题'];
    
    const positiveCount = positiveWords.filter(word => text.includes(word)).length;
    const negativeCount = negativeWords.filter(word => text.includes(word)).length;
    
    if (positiveCount > negativeCount) return 'positive';
    if (negativeCount > positiveCount) return 'negative';
    return 'neutral';
  }

  private async calculateConfidence(text: string, intent: string): Promise<number> {
    // 简单置信度计算
    const baseConfidence = 0.7;
    const lengthFactor = Math.min(text.length / 20, 1); // 文本长度影响
    return baseConfidence * lengthFactor;
  }

  private applyContextualBiasing(text: string, context: ConversationContext, intents: string[]): string[] {
    // 基于上下文调整意图优先级
    const lastIntent = context.getLastIntent();
    if (lastIntent === 'greeting') {
      // 问候后更可能是问题
      return ['question', 'chitchat', ...intents.filter(i => i !== 'question')];
    }
    return intents;
  }

  async release(): Promise<void> {
    this.isInitialized = false;
  }

  private async loadModels(): Promise<void> {
    // 模拟模型加载
    await new Promise(resolve => setTimeout(resolve, 100));
  }
}

class DialogManager {
  private stateMachine: DialogStateMachine;

  async initialize(): Promise<void> {
    this.stateMachine = new DialogStateMachine();
    await this.stateMachine.initialize();
  }

  async updateState(understanding: NLUResult, context: ConversationContext): Promise<DialogState> {
    return await this.stateMachine.process(understanding, context);
  }

  async release(): Promise<void> {
    // 清理资源
  }
}

class KnowledgeBase {
  private knowledgeGraph: Map<string, any> = new Map();

  async initialize(): Promise<void> {
    // 初始化知识图谱
    this.loadBaseKnowledge();
  }

  async retrieveRelevantKnowledge(understanding: NLUResult): Promise<Knowledge> {
    const query = this.buildQuery(understanding);
    const result = this.knowledgeGraph.get(query) || this.fallbackRetrieval(understanding);
    
    return {
      hasAnswer: !!result,
      answer: result?.answer,
      confidence: result?.confidence || 0,
      sources: result?.sources
    };
  }

  private buildQuery(understanding: NLUResult): string {
    return `${understanding.intent}_${Object.values(understanding.entities).join('_')}`;
  }

  private fallbackRetrieval(understanding: NLUResult): any {
    // 回退检索逻辑
    return null;
  }

  private loadBaseKnowledge(): void {
    // 加载基础知识
    this.knowledgeGraph.set('greeting_weather', {
      answer: '今天天气晴朗,温度适宜,适合外出活动。',
      confidence: 0.9,
      sources: ['气象局']
    });
    
    this.knowledgeGraph.set('question_time', {
      answer: `现在是${new Date().toLocaleTimeString('zh-CN')}。`,
      confidence: 1.0,
      sources: ['系统时间']
    });
  }

  async release(): Promise<void> {
    this.knowledgeGraph.clear();
  }
}

class UserProfileManager {
  private profiles: Map<string, UserProfile> = new Map();

  async initialize(): Promise<void> {
    // 加载用户画像数据
  }

  async recordInteraction(interaction: UserInteraction): Promise<void> {
    const profile = this.getOrCreateProfile(interaction.userId);
    profile.interactionHistory.push(interaction);
    profile.lastActive = Date.now();
    
    // 更新用户偏好
    this.updatePreferences(profile, interaction);
  }

  getProfile(userId: string): UserProfile | undefined {
    return this.profiles.get(userId);
  }

  private getOrCreateProfile(userId: string): UserProfile {
    if (!this.profiles.has(userId)) {
      this.profiles.set(userId, {
        userId,
        interactionHistory: [],
        preferences: {},
        createdAt: Date.now(),
        lastActive: Date.now()
      });
    }
    return this.profiles.get(userId)!;
  }

  private updatePreferences(profile: UserProfile, interaction: UserInteraction): void {
    // 基于交互更新用户偏好
    if (!profile.preferences.preferredIntents) {
      profile.preferences.preferredIntents = {};
    }
    
    const currentCount = profile.preferences.preferredIntents[interaction.intent] || 0;
    profile.preferences.preferredIntents[interaction.intent] = currentCount + 1;
  }

  async release(): Promise<void> {
    this.profiles.clear();
  }
}

class ConversationContext {
  private turns: ConversationTurn[] = [];
  private maxTurns: number = 10;

  addTurn(turn: ConversationTurn): void {
    this.turns.push(turn);
    if (this.turns.length > this.maxTurns) {
      this.turns = this.turns.slice(-this.maxTurns);
    }
  }

  getTurns(): ConversationTurn[] {
    return [...this.turns];
  }

  getLastIntent(): string | null {
    if (this.turns.length === 0) return null;
    return this.turns[this.turns.length - 1].understanding.intent;
  }

  clear(): void {
    this.turns = [];
  }

  compress(): void {
    // 对话上下文压缩逻辑
    if (this.turns.length > 5) {
      this.turns = [this.turns[0], ...this.turns.slice(-4)];
    }
  }

  getSummary(): string {
    if (this.turns.length === 0) return '无对话历史';
    
    const intents = this.turns.map(t => t.understanding.intent);
    return `共${this.turns.length}轮对话,主要意图: ${[...new Set(intents)].join(', ')}`;
  }
}

// 辅助类型
interface UserProfile {
  userId: string;
  interactionHistory: UserInteraction[];
  preferences: UserPreferences;
  createdAt: number;
  lastActive: number;
}

interface UserInteraction {
  userId: string;
  intent: string;
  entities: Record<string, any>;
  timestamp: number;
}

interface UserPreferences {
  preferredName?: string;
  preferredIntents?: Record<string, number>;
  communicationStyle?: string;
}

class DialogStateMachine {
  private currentState: DialogState = {
    currentIntent: 'idle',
    dialogAct: 'init',
    slots: {},
    context: {}
  };

  async initialize(): Promise<void> {
    // 初始化状态机
  }

  async process(understanding: NLUResult, context: ConversationContext): Promise<DialogState> {
    // 状态转移逻辑
    this.currentState.currentIntent = understanding.intent;
    this.currentState.dialogAct = this.determineDialogAct(understanding, context);
    this.currentState.slots = this.updateSlots(understanding, this.currentState.slots);
    
    return this.currentState;
  }

  private determineDialogAct(understanding: NLUResult, context: ConversationContext): string {
    // 确定对话行为
    switch (understanding.intent) {
      case 'greeting': return 'greet';
      case 'question': return 'answer';
      case 'chitchat': return 'socialize';
      default: return 'inform';
    }
  }

  private updateSlots(understanding: NLUResult, currentSlots: Record<string, any>): Record<string, any> {
    // 更新对话槽位
    return { ...currentSlots, ...understanding.entities };
  }
}

1.2 聊天界面组件

// src/main/ets/components/ChatInterface.ts
import { ChatbotService, ChatResponse, UserInput } from '../services/ChatbotService';

@Entry
@Component
struct ChatInterface {
  private chatbotService: ChatbotService = new ChatbotService();
  @State messages: ChatMessage[] = [];
  @State inputText: string = '';
  @State isProcessing: boolean = false;
  @State errorMessage: string = '';
  @State connectionStatus: 'connected' | 'disconnected' | 'error' = 'disconnected';

  aboutToAppear() {
    this.initializeChatbot();
  }

  async initializeChatbot() {
    try {
      await this.chatbotService.initialize();
      this.connectionStatus = 'connected';
      
      // 添加欢迎消息
      this.addSystemMessage('您好!我是鸿蒙智能助手,请问有什么可以帮您?');
      
    } catch (error) {
      this.connectionStatus = 'error';
      this.errorMessage = `初始化失败: ${error.message}`;
    }
  }

  async sendMessage() {
    if (!this.inputText.trim() || this.isProcessing) return;

    const userMessage = this.inputText.trim();
    this.inputText = '';
    
    // 添加用户消息
    this.addUserMessage(userMessage);
    
    this.isProcessing = true;
    this.errorMessage = '';

    try {
      const userInput: UserInput = {
        text: userMessage,
        userId: 'current_user', // 实际应该从用户系统获取
        timestamp: Date.now()
      };

      const response = await this.chatbotService.processMessage(userInput);
      this.addBotMessage(response);
      
    } catch (error) {
      this.errorMessage = `发送失败: ${error.message}`;
      this.addSystemMessage('抱歉,我遇到了一些问题,请稍后再试。');
    } finally {
      this.isProcessing = false;
    }
  }

  addUserMessage(text: string) {
    this.messages = [...this.messages, {
      id: this.generateMessageId(),
      type: 'user',
      text: text,
      timestamp: Date.now(),
      status: 'delivered'
    }];
  }

  addBotMessage(response: ChatResponse) {
    this.messages = [...this.messages, {
      id: this.generateMessageId(),
      type: 'bot',
      text: response.text,
      timestamp: Date.now(),
      status: 'delivered',
      suggestions: response.suggestions,
      processingTime: response.processingTime,
      confidence: response.confidence
    }];
  }

  addSystemMessage(text: string) {
    this.messages = [...this.messages, {
      id: this.generateMessageId(),
      type: 'system',
      text: text,
      timestamp: Date.now(),
      status: 'delivered'
    }];
  }

  generateMessageId(): string {
    return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  clearChat() {
    this.messages = [];
    this.chatbotService.resetConversation();
    this.addSystemMessage('对话已清空,开始新的对话吧!');
  }

  build() {
    Column() {
      // 顶部状态栏
      this.buildStatusBar()
      
      // 消息列表
      this.buildMessageList()
      
      // 输入区域
      this.buildInputArea()
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#f5f5f5')
  }

  @Builder
  buildStatusBar() {
    Row() {
      Text('鸿蒙智能助手')
        .fontSize(18)
        .fontWeight(FontWeight.Bold)
        .fontColor('#333333')
      
      Blank()
      
      // 连接状态指示器
      Circle({ width: 8, height: 8 })
        .fill(this.getStatusColor())
      
      Text(this.getStatusText())
        .fontSize(12)
        .fontColor('#666666')
      
      Button('清空')
        .fontSize(12)
        .padding(4)
        .backgroundColor('transparent')
        .onClick(() => this.clearChat())
    }
    .width('100%')
    .padding(10)
    .backgroundColor('#ffffff')
    .shadow({ radius: 2, color: '#00000010' })
  }

  @Builder
  buildMessageList() {
    Scroll() {
      Column() {
        ForEach(this.messages, (message: ChatMessage) => {
          this.buildMessageBubble(message)
        })
      }
      .width('100%')
      .padding(10)
    }
    .scrollBar(BarState.Off)
    .layoutWeight(1)
  }

  @Builder
  buildMessageBubble(message: ChatMessage) {
    const isUser = message.type === 'user';
    
    Row() {
      if (!isUser) {
        // 机器人头像
        Circle({ width: 32, height: 32 })
          .fill('#4cd964')
          .margin({ right: 8 })
      }
      
      Column({ space: 4 }) {
        // 消息内容
        Text(message.text)
          .fontSize(14)
          .fontColor(isUser ? '#ffffff' : '#333333')
          .textAlign(isUser ? TextAlign.End : TextAlign.Start)
          .padding(12)
          .backgroundColor(isUser ? '#4cd964' : '#ffffff')
          .borderRadius(12)
          .maxLines(10)
          .minFontSize(12)
          .maxFontSize(16)
        
        // 消息元信息
        Row() {
          if (message.processingTime) {
            Text(`${message.processingTime}ms`)
              .fontSize(10)
              .fontColor('#999999')
          }
          
          if (message.confidence) {
            Text(`${Math.round(message.confidence * 100)}%`)
              .fontSize(10)
              .fontColor(message.confidence > 0.7 ? '#4cd964' : '#ff9500')
          }
          
          Text(this.formatTime(message.timestamp))
            .fontSize(10)
            .fontColor('#999999')
        }
        .justifyContent(isUser ? FlexAlign.End : FlexAlign.Start)
        .width('100%')
        
        // 建议按钮
        if (message.type === 'bot' && message.suggestions) {
          Wrap() {
            ForEach(message.suggestions, (suggestion: string) => {
              Button(suggestion)
                .fontSize(12)
                .padding(6)
                .backgroundColor('#e9ecef')
                .borderColor('transparent')
                .onClick(() => this.inputText = suggestion)
            })
          }
          .margin({ top: 8 })
        }
      }
      .alignItems(isUser ? HorizontalAlign.End : HorizontalAlign.Start)
      
      if (isUser) {
        // 用户头像
        Circle({ width: 32, height: 32 })
          .fill('#007aff')
          .margin({ left: 8 })
      }
    }
    .justifyContent(isUser ? FlexAlign.End : FlexAlign.Start)
    .width('100%')
    .margin({ bottom: 16 })
  }

  @Builder
  buildInputArea() {
    Column() {
      // 错误信息
      if (this.errorMessage) {
        Text(this.errorMessage)
          .fontSize(12)
          .fontColor('#ff3b30')
          .padding(8)
          .backgroundColor('#ffcccc')
          .borderRadius(4)
          .width('100%')
      }
      
      Row() {
        TextInput({ placeholder: '输入您的问题...', text: this.inputText })
          .onChange((value: string) => this.inputText = value)
          .onSubmit(() => this.sendMessage())
          .layoutWeight(1)
          .padding(12)
          .backgroundColor('#ffffff')
          .borderRadius(20)
          .border({ width: 1, color: '#dddddd' })
        
        Button('发送')
          .padding(12)
          .backgroundColor(this.inputText.trim() ? '#4cd964' : '#cccccc')
          .borderRadius(20)
          .margin({ left: 8 })
          .enabled(!!this.inputText.trim() && !this.isProcessing)
          .onClick(() => this.sendMessage())
      }
    }
    .padding(10)
    .backgroundColor('#ffffff')
    .shadow({ radius: 2, color: '#00000010' })
  }

  private getStatusColor(): string {
    switch (this.connectionStatus) {
      case 'connected': return '#4cd964';
      case 'disconnected': return '#ff3b30';
      case 'error': return '#ff9500';
      default: return '#cccccc';
    }
  }

  private getStatusText(): string {
    switch (this.connectionStatus) {
      case 'connected': return '已连接';
      case 'disconnected': return '未连接';
      case 'error': return '连接错误';
      default: return '未知状态';
    }
  }

  private formatTime(timestamp: number): string {
    return new Date(timestamp).toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }

  aboutToDisappear() {
    this.chatbotService.release().catch(console.error);
  }
}

interface ChatMessage {
  id: string;
  type: 'user' | 'bot' | 'system';
  text: string;
  timestamp: number;
  status: 'sending' | 'delivered' | 'failed';
  suggestions?: string[];
  processingTime?: number;
  confidence?: number;
}

场景2:智能文档摘要系统

2.1 文档摘要核心服务

// src/main/ets/services/DocumentSummarizationService.ts
import { BusinessError } from '@ohos.base';

/**
 * 智能文档摘要服务
 * 支持多粒度摘要和关键信息提取
 */
export class DocumentSummarizationService {
  private textProcessor: TextProcessor;
  private summarizationEngine: SummarizationEngine;
  private keyPointExtractor: KeyPointExtractor;
  private qualityEvaluator: QualityEvaluator;
  
  private isInitialized: boolean = false;

  constructor() {
    this.textProcessor = new TextProcessor();
    this.summarizationEngine = new SummarizationEngine();
    this.keyPointExtractor = new KeyPointExtractor();
    this.qualityEvaluator = new QualityEvaluator();
  }

  /**
   * 初始化服务
   */
  async initialize(): Promise<void> {
    if (this.isInitialized) {
      return;
    }

    try {
      await Promise.all([
        this.textProcessor.initialize(),
        this.summarizationEngine.initialize(),
        this.keyPointExtractor.initialize(),
        this.qualityEvaluator.initialize()
      ]);

      this.isInitialized = true;
      console.info('DocumentSummarizationService: 初始化成功');
    } catch (error) {
      console.error('DocumentSummarizationService: 初始化失败', error);
      throw error;
    }
  }

  /**
   * 生成文档摘要
   */
  async summarizeDocument(document: Document, options: SummarizationOptions = {}): Promise<SummaryResult> {
    if (!this.isInitialized) {
      throw new Error('服务未初始化');
    }

    const startTime = Date.now();

    try {
      // 1. 文档预处理
      const processedDoc = await this.textProcessor.preprocess(document);
      
      // 2. 关键信息提取
      const keyPoints = await this.keyPointExtractor.extract(processedDoc, options);
      
      // 3. 摘要生成
      const summary = await this.summarizationEngine.generateSummary(processedDoc, keyPoints, options);
      
      // 4. 质量评估
      const quality = await this.qualityEvaluator.evaluate(summary, processedDoc);
      
      const processingTime = Date.now() - startTime;
      
      return {
        summary,
        keyPoints,
        quality,
        processingTime,
        originalLength: document.content.length,
        summaryLength: summary.length,
        compressionRatio: summary.length / document.content.length
      };

    } catch (error) {
      console.error('文档摘要失败:', error);
      throw new Error(`文档摘要失败: ${error.message}`);
    }
  }

  /**
   * 批量文档摘要
   */
  async summarizeBatch(documents: Document[], options: SummarizationOptions = {}): Promise<BatchSummaryResult> {
    const results: SummaryResult[] = [];
    const errors: SummarizationError[] = [];
    
    for (let i = 0; i < documents.length; i++) {
      try {
        const result = await this.summarizeDocument(documents[i], options);
        results.push(result);
      } catch (error) {
        errors.push({
          documentIndex: i,
          documentTitle: documents[i].title,
          error: error.message
        });
      }
    }
    
    return {
      results,
      errors,
      totalProcessed: documents.length,
      successRate: results.length / documents.length,
      averageProcessingTime: results.reduce((sum, r) => sum + r.processingTime, 0) / results.length
    };
  }

  /**
   * 多粒度摘要生成
   */
  async generateMultiGranularitySummary(document: Document): Promise<MultiGranularitySummary> {
    const granularities: SummaryGranularity[] = ['extreme', 'normal', 'detailed'];
    const summaries: Map<SummaryGranularity, string> = new Map();
    
    for (const granularity of granularities) {
      const options: SummarizationOptions = {
        granularity,
        maxLength: this.getMaxLengthForGranularity(granularity)
      };
      
      try {
        const result = await this.summarizeDocument(document, options);
        summaries.set(granularity, result.summary);
      } catch (error) {
        console.warn(`生成${granularity}粒度摘要失败:`, error);
      }
    }
    
    return {
      extreme: summaries.get('extreme') || '',
      normal: summaries.get('normal') || '',
      detailed: summaries.get('detailed') || '',
      generatedAt: Date.now()
    };
  }

  private getMaxLengthForGranularity(granularity: SummaryGranularity): number {
    const ratios = {
      'extreme': 0.1,   // 10%
      'normal': 0.3,    // 30%
      'detailed': 0.5   // 50%
    };
    return Math.floor(1000 * ratios[granularity]); // 假设文档长度1000字
  }

  /**
   * 摘要质量比较
   */
  async compareSummaries(document: Document, summaries: string[]): Promise<SummaryComparison> {
    const qualities = await Promise.all(
      summaries.map(summary => this.qualityEvaluator.evaluate(summary, document))
    );
    
    return {
      summaries: summaries.map((summary, index) => ({
        content: summary,
        quality: qualities[index],
        rank: 0 // 将在下面计算
      })),
      bestSummaryIndex: this.findBestSummaryIndex(qualities)
    };
  }

  private findBestSummaryIndex(qualities: SummaryQuality[]): number {
    let bestIndex = 0;
    let bestScore = 0;
    
    qualities.forEach((quality, index) => {
      const score = quality.coherence * 0.3 + quality.relevance * 0.4 + quality.conciseness * 0.3;
      if (score > bestScore) {
        bestScore = score;
        bestIndex = index;
      }
    });
    
    return bestIndex;
  }

  /**
   * 释放资源
   */
  async release(): Promise<void> {
    await Promise.allSettled([
      this.textProcessor.release(),
      this.summarizationEngine.release(),
      this.keyPointExtractor.release(),
      this.qualityEvaluator.release()
    ]);
    
    this.isInitialized = false;
    console.info('DocumentSummarizationService: 资源已释放');
  }
}

// 类型定义
interface Document {
  title: string;
  content: string;
  language?: string;
  domain?: string;
  metadata?: any;
}

interface SummarizationOptions {
  granularity?: SummaryGranularity;
  maxLength?: number;
  focusPoints?: string[];
  style?: SummaryStyle;
}

type SummaryGranularity = 'extreme' | 'normal' | 'detailed';
type SummaryStyle = 'academic' | 'business' | 'general';

interface SummaryResult {
  summary: string;
  keyPoints: KeyPoint[];
  quality: SummaryQuality;
  processingTime: number;
  originalLength: number;
  summaryLength: number;
  compressionRatio: number;
}

interface KeyPoint {
  text: string;
  importance: number;
  position: number;
  category?: string;
}

interface SummaryQuality {
  coherence: number;      // 连贯性
  relevance: number;      // 相关性
  conciseness: number;    // 简洁性
  readability: number;    // 可读性
  overall: number;        // 综合评分
}

interface BatchSummaryResult {
  results: SummaryResult[];
  errors: SummarizationError[];
  totalProcessed: number;
  successRate: number;
  averageProcessingTime: number;
}

interface SummarizationError {
  documentIndex: number;
  documentTitle: string;
  error: string;
}

interface MultiGranularitySummary {
  extreme: string;    // 极简摘要
  normal: string;    // 常规摘要
  detailed: string;  // 详细摘要
  generatedAt: number;
}

interface SummaryComparison {
  summaries: ComparedSummary[];
  bestSummaryIndex: number;
}

interface ComparedSummary {
  content: string;
  quality: SummaryQuality;
  rank: number;
}

// 核心组件实现
class TextProcessor {
  async initialize(): Promise<void> {
    // 初始化文本处理组件
  }

  async preprocess(document: Document): Promise<ProcessedDocument> {
    // 1. 文本清洗
    const cleanedContent = this.cleanText(document.content);
    
    // 2. 分句分段
    const sentences = this.splitIntoSentences(cleanedContent);
    const paragraphs = this.groupIntoParagraphs(sentences);
    
    // 3. 语言检测
    const language = await this.detectLanguage(cleanedContent);
    
    // 4. 关键词提取
    const keywords = this.extractKeywords(cleanedContent);
    
    return {
      original: document,
      cleanedContent,
      sentences,
      paragraphs,
      language,
      keywords,
      wordCount: cleanedContent.length
    };
  }

  private cleanText(content: string): string {
    // 移除多余空格、特殊字符等
    return content
      .replace(/\s+/g, ' ')
      .replace(/[^\u4e00-\u9fa5a-zA-Z0-9\s.,!?;:]/g, '')
      .trim();
  }

  private splitIntoSentences(content: string): string[] {
    // 简单分句逻辑
    return content.split(/[.!?。!?]/).filter(s => s.trim().length > 0);
  }

  private groupIntoParagraphs(sentences: string[]): string[][] {
    // 简单分段逻辑(每5句一段)
    const paragraphs: string[][] = [];
    for (let i = 0; i < sentences.length; i += 5) {
      paragraphs.push(sentences.slice(i, i + 5));
    }
    return paragraphs;
  }

  private async detectLanguage(content: string): Promise<string> {
    // 简单语言检测
    const chineseChars = content.match(/[\u4e00-\u9fa5]/g) || [];
    const englishWords = content.match(/\b[a-zA-Z]+\b/g) || [];
    
    if (chineseChars.length > englishWords.length) return 'zh';
    return 'en';
  }

  private extractKeywords(content: string): string[] {
    // 简单关键词提取
    const words = content.split(/\s+/);
    const frequency: Map<string, number> = new Map();
    
    words.forEach(word => {
      if (word.length > 1) { // 过滤单字
        frequency.set(word, (frequency.get(word) || 0) + 1);
      }
    });
    
    return Array.from(frequency.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10)
      .map(([word]) => word);
  }

  async release(): Promise<void> {
    // 清理资源
  }
}

class SummarizationEngine {
  private summarizationModel: any;

  async initialize(): Promise<void> {
    // 加载摘要模型
    await this.loadModel();
  }

  async generateSummary(processedDoc: ProcessedDocument, keyPoints: KeyPoint[], options: SummarizationOptions): Promise<string> {
    // 根据选项选择摘要策略
    switch (options.granularity) {
      case 'extreme':
        return this.generateExtremeSummary(processedDoc, keyPoints);
      case 'detailed':
        return this.generateDetailedSummary(processedDoc, keyPoints);
      default:
        return this.generateNormalSummary(processedDoc, keyPoints);
    }
  }

  private generateExtremeSummary(processedDoc: ProcessedDocument, keyPoints: KeyPoint[]): string {
    // 生成极简摘要(1-2句话)
    const mostImportant = keyPoints
      .sort((a, b) => b.importance - a.importance)
      .slice(0, 1);
    
    return mostImportant.map(kp => kp.text).join('。') + '。';
  }

  private generateNormalSummary(processedDoc: ProcessedDocument, keyPoints: KeyPoint[]): string {
    // 生成常规摘要
    const importantPoints = keyPoints
      .sort((a, b) => b.importance - a.importance)
      .slice(0, 3);
    
    return importantPoints.map(kp => kp.text).join('。') + '。';
  }

  private generateDetailedSummary(processedDoc: ProcessedDocument, keyPoints: KeyPoint[]): string {
    // 生成详细摘要
    return keyPoints
      .sort((a, b) => a.position - b.position) // 按原文顺序
      .slice(0, 5)
      .map(kp => kp.text)
      .join('。') + '。';
  }

  private async loadModel(): Promise<void> {
    // 模拟模型加载
    await new Promise(resolve => setTimeout(resolve, 200));
  }

  async release(): Promise<void> {
    // 清理模型资源
  }
}

class KeyPointExtractor {
  async initialize(): Promise<void> {
    // 初始化关键点提取组件
  }

  async extract(processedDoc: ProcessedDocument, options: SummarizationOptions): Promise<KeyPoint[]> {
    const keyPoints: KeyPoint[] = [];
    
    // 提取每个句子的关键点
    processedDoc.sentences.forEach((sentence, index) => {
      const importance = this.calculateSentenceImportance(sentence, processedDoc, index);
      
      if (importance > 0.1) { // 重要性阈值
        keyPoints.push({
          text: sentence,
          importance,
          position: index,
          category: this.categorizeSentence(sentence)
        });
      }
    });
    
    return keyPoints.sort((a, b) => b.importance - a.importance);
  }

  private calculateSentenceImportance(sentence: string, doc: ProcessedDocument, position: number): number {
    let importance = 0;
    
    // 1. 位置权重(开头和结尾更重要)
    if (position === 0) importance += 0.3; // 开头
    if (position === doc.sentences.length - 1) importance += 0.2; // 结尾
    
    // 2. 关键词匹配
    const keywordMatches = doc.keywords.filter(keyword => 
      sentence.toLowerCase().includes(keyword.toLowerCase())
    ).length;
    importance += keywordMatches * 0.1;
    
    // 3. 句子长度权重(适中的长度更重要)
    const length = sentence.length;
    if (length > 20 && length < 100) importance += 0.2;
    
    return Math.min(importance, 1.0);
  }

  private categorizeSentence(sentence: string): string {
    if (sentence.includes('总结') || sentence.includes('结论')) return 'conclusion';
    if (sentence.includes('因为') || sentence.includes('原因')) return 'reason';
    if (sentence.includes('但是') || sentence.includes('然而')) return 'contrast';
    return 'general';
  }

  async release(): Promise<void> {
    // 清理资源
  }
}

class QualityEvaluator {
  async initialize(): Promise<void> {
    // 初始化质量评估组件
  }

  async evaluate(summary: string, document: ProcessedDocument): Promise<SummaryQuality> {
    const coherence = this.evaluateCoherence(summary);
    const relevance = this.evaluateRelevance(summary, document);
    const conciseness = this.evaluateConciseness(summary, document.original.content);
    const readability = this.evaluateReadability(summary);
    
    const overall = coherence * 0.25 + relevance * 0.35 + conciseness * 0.2 + readability * 0.2;
    
    return {
      coherence,
      relevance,
      conciseness,
      readability,
      overall
    };
  }

  private evaluateCoherence(summary: string): number {
    // 评估连贯性(句子间的逻辑连接)
    const sentences = summary.split(/[.!?。!?]/).filter(s => s.trim().length > 0);
    if (sentences.length <= 1) return 1.0;
    
    // 简单连贯性评估
    const transitionWords = ['首先', '然后', '另外', '但是', '因此', '总之'];
    const transitions = transitionWords.filter(word => summary.includes(word)).length;
    
    return Math.min(transitions / sentences.length * 2, 1.0);
  }

  private evaluateRelevance(summary: string, document: ProcessedDocument): number {
    // 评估相关性(摘要与原文的相关程度)
    const summaryKeywords = this.extractKeywords(summary);
    const docKeywords = document.keywords;
    
    const matches = summaryKeywords.filter(keyword => 
      docKeywords.includes(keyword)
    ).length;
    
    return Math.min(matches / docKeywords.length * 2, 1.0);
  }

  private evaluateConciseness(summary: string, original: string): number {
    // 评估简洁性
    const summaryLength = summary.length;
    const originalLength = original.length;
    
    if (originalLength === 0) return 1.0;
    
    const ratio = summaryLength / originalLength;
    
    // 理想压缩比在10%-30%之间
    if (ratio >= 0.1 && ratio <= 0.3) return 1.0;
    if (ratio < 0.1) return 0.5 + ratio * 5; // 过短
    return 1.0 - (ratio - 0.3) * 2; // 过长
  }

  private evaluateReadability(summary: string): number {
    // 评估可读性
    const sentences = summary.split(/[.!?。!?]/).filter(s => s.trim().length > 0);
    if (sentences.length === 0) return 0;
    
    const avgSentenceLength = summary.length / sentences.length;
    
    // 理想句子长度在15-25字之间
    if (avgSentenceLength >= 15 && avgSentenceLength <= 25) return 1.0;
    if (avgSentenceLength < 15) return avgSentenceLength / 15;
    return 25 / avgSentenceLength;
  }

  private extractKeywords(text: string): string[] {
    // 简单关键词提取
    const words = text.split(/\s+/).filter(word => word.length > 1);
    const frequency: Map<string, number> = new Map();
    
    words.forEach(word => {
      frequency.set(word, (frequency.get(word) || 0) + 1);
    });
    
    return Array.from(frequency.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5)
      .map(([word]) => word);
  }

  async release(): Promise<void> {
    // 清理资源
  }
}

// 辅助类型
interface ProcessedDocument {
  original: Document;
  cleanedContent: string;
  sentences: string[];
  paragraphs: string[][];
  language: string;
  keywords: string[];
  wordCount: number;
}

2.2 文档摘要界面组件

// src/main/ets/components/DocumentSummarizationInterface.ts
import { DocumentSummarizationService, SummaryResult, Document } from '../services/DocumentSummarizationService';

@Entry
@Component
struct DocumentSummarizationInterface {
  private summarizationService: DocumentSummarizationService = new DocumentSummarizationService();
  @State inputText: string = '';
  @State currentResult: SummaryResult | null = null;
  @State isProcessing: boolean = false;
  @State errorMessage: string = '';
  @State summaryGranularity: SummaryGranularity = 'normal';
  @State history: SummaryResult[] = [];

  aboutToAppear() {
    this.initializeService();
  }

  async initializeService() {
    try {
      await this.summarizationService.initialize();
    } catch (error) {
      this.errorMessage = `服务初始化失败: ${error.message}`;
    }
  }

  async generateSummary() {
    if (!this.inputText.trim() || this.isProcessing) return;

    this.isProcessing = true;
    this.errorMessage = '';

    const document: Document = {
      title: '用户输入文档',
      content: this.inputText,
      language: 'zh'
    };

    try {
      const result = await this.summarizationService.summarizeDocument(document, {
        granularity: this.summaryGranularity
      });
      
      this.currentResult = result;
      this.history = [result, ...this.history].slice(0, 10); // 保持最近10条
      
    } catch (error) {
      this.errorMessage = `摘要生成失败: ${error.message}`;
    } finally {
      this.isProcessing = false;
    }
  }

  build() {
    Column() {
      // 标题和控件
      this.buildHeader()
      
      // 输入区域
      this.buildInputArea()
      
      // 结果展示
      this.buildResultArea()
      
      // 历史记录
      this.buildHistoryArea()
    }
    .width('100%')
    .height('100%')
    .padding(20)
    .backgroundColor('#f8f9fa')
  }

  @Builder
  buildHeader() {
    Column({ space: 15 }) {
      Text('智能文档摘要')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .fontColor('#333333')
      
      // 粒度选择
      Row() {
        Text('摘要粒度:')
          .fontSize(14)
          .fontColor('#666666')
        
        RadioGroup({ radioGroup: 'granularity' }) {
          Radio({ value: 'extreme' }).value('extreme')
          Text('极简').fontSize(12)
          
          Radio({ value: 'normal' }).value('normal')
          Text('常规').fontSize(12)
          
          Radio({ value: 'detailed' }).value('detailed')
          Text('详细').fontSize(12)
        }
        .onChange((value: string) => this.summaryGranularity = value as SummaryGranularity)
        .selected(this.summaryGranularity)
      }
      .justifyContent(FlexAlign.Center)
    }
    .width('100%')
    .margin({ bottom: 20 })
  }

  @Builder
  buildInputArea() {
    Column({ space: 10 }) {
      Text('输入文档内容:')
        .fontSize(16)
        .fontColor('#333333')
        .alignSelf(ItemAlign.Start)
      
      TextArea({ placeholder: '请输入要摘要的文档内容...', text: this.inputText })
        .onChange((value: string) => this.inputText = value)
        .height(200)
        .width('100%')
        .padding(12)
        .backgroundColor(Color.White)
        .borderRadius(8)
        .border({ width: 1, color: '#dddddd' })
      
      Button('生成摘要')
        .width('100%')
        .height(40)
        .backgroundColor(this.inputText.trim() ? '#4cd964' : '#cccccc')
        .enabled(!!this.inputText.trim() && !this.isProcessing)
        .onClick(() => this.generateSummary())
    }
    .width('100%')
    .margin({ bottom: 20 })
  }

  @Builder
  buildResultArea() {
    if (this.isProcessing) {
      this.buildLoadingIndicator()
    } else if (this.currentResult) {
      this.buildSummaryResult(this.currentResult)
    } else if (this.errorMessage) {
      this.buildErrorMessage()
    }
  }

  @Builder
  buildLoadingIndicator() {
    Column() {
      Progress({ value: 0, total: 100 })
        .width('100%')
        .color('#4cd964')
      
      Text('AI正在分析文档...')
        .fontSize(14)
        .fontColor('#666666')
        .margin({ top: 10 })
    }
    .width('100%')
    .padding(20)
    .backgroundColor(Color.White)
    .borderRadius(8)
    .margin({ bottom: 20 })
  }

  @Builder
  buildSummaryResult(result: SummaryResult) {
    Column({ space: 15 }) {
      // 摘要标题和质量指示器
      Row() {
        Text('生成摘要')
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .fontColor('#333333')
        
        Blank()
        
        // 质量评分
        Row() {
          Text('质量:')
            .fontSize(12)
            .fontColor('#666666')
          
          Text(`${Math.round(result.quality.overall * 100)}%`)
            .fontSize(12)
            .fontColor(this.getQualityColor(result.quality.overall))
        }
      }
      
      // 摘要内容
      Text(result.summary)
        .fontSize(14)
        .fontColor('#333333')
        .lineHeight(20)
        .padding(15)
        .backgroundColor('#f8f9fa')
        .borderRadius(8)
        .width('100%')
      
      // 统计信息
      this.buildStatistics(result)
      
      // 关键点
      this.buildKeyPoints(result.keyPoints)
    }
    .width('100%')
    .padding(20)
    .backgroundColor(Color.White)
    .borderRadius(8)
    .margin({ bottom: 20 })
  }

  @Builder
  buildStatistics(result: SummaryResult) {
    Row() {
      StatItem('原文长度', `${result.originalLength}字`)
      StatItem('摘要长度', `${result.summaryLength}字`)
      StatItem('压缩比例', `${Math.round(result.compressionRatio * 100)}%`)
      StatItem('处理时间', `${result.processingTime}ms`)
    }
    .justifyContent(FlexAlign.SpaceAround)
    .width('100%')
  }

  @Builder
  buildKeyPoints(keyPoints: KeyPoint[]) {
    Column({ space: 10 }) {
      Text('关键信息点:')
        .fontSize(14)
        .fontWeight(FontWeight.Medium)
        .fontColor('#333333')
        .alignSelf(ItemAlign.Start)
      
      ForEach(keyPoints.slice(0, 5), (point: KeyPoint, index: number) => {
        Row() {
          Text(`${index + 1}. ${point.text}`)
            .fontSize(12)
            .fontColor('#666666')
            .flexGrow(1)
          
          // 重要性指示器
          Progress({ value: point.importance * 100, total: 100 })
            .width(60)
            .height(6)
            .color(this.getImportanceColor(point.importance))
        }
        .width('100%')
        .padding(8)
        .backgroundColor(index % 2 === 0 ? '#f8f9fa' : 'transparent')
        .borderRadius(4)
      })
    }
    .width('100%')
  }

  @Builder
  buildErrorMessage() {
    Text(this.errorMessage)
      .fontSize(14)
      .fontColor('#ff3b30')
      .padding(15)
      .backgroundColor('#ffcccc')
      .borderRadius(8)
      .width('100%')
      .margin({ bottom: 20 })
  }

  @Builder
  buildHistoryArea() {
    if (this.history.length > 0) {
      Column({ space: 10 }) {
        Text('摘要历史')
          .fontSize(16)
          .fontWeight(FontWeight.Bold)
          .fontColor('#333333')
          .alignSelf(ItemAlign.Start)
        
        ForEach(this.history.slice(0, 5), (item: SummaryResult, index: number) => {
          ListItem() {
            Column({ space: 8 }) {
              Text(item.summary.substring(0, 50) + '...')
                .fontSize(12)
                .fontColor('#666666')
              
              Row() {
                Text(`质量: ${Math.round(item.quality.overall * 100)}%`)
                  .fontSize(10)
                  .fontColor('#999999')
                
                Text(`长度: ${item.summaryLength}字`)
                  .fontSize(10)
                  .fontColor('#999999')
                
                Text(new Date().toLocaleTimeString())
                  .fontSize(10)
                  .fontColor('#999999')
              }
            }
            .width('100%')
            .padding(10)
            .backgroundColor(Color.White)
            .borderRadius(6)
            .onClick(() => this.currentResult = item)
          }
        })
      }
      .width('100%')
    }
  }

  private getQualityColor(score: number): string {
    if (score > 0.8) return '#4cd964';
    if (score > 0.6) return '#ff9500';
    return '#ff3b30';
  }

  private getImportanceColor(importance: number): string {
    if (importance > 0.7) return '#4cd964';
    if (importance > 0.4) return '#ff9500';
    return '#ff3b30';
  }

  aboutToDisappear() {
    this.summarizationService.release().catch(console.error);
  }
}

@Builder
function StatItem(label: string, value: string) {
  Column() {
    Text(value)
      .fontSize(14)
      .fontWeight(FontWeight.Bold)
      .fontColor('#333333')
    
    Text(label)
      .fontSize(10)
      .fontColor('#999999')
  }
}

五、原理解释

1. NLP技术原理架构

graph TB
    A[输入文本] --> B[文本预处理]
    B --> C[词法分析]
    C --> D[句法分析]
    D --> E[语义理解]
    E --> F[知识推理]
    F --> G[响应生成]
    
    B --> B1[分词]
    B --> B2[词性标注]
    B --> B3[命名实体识别]
    
    C --> C1[依存分析]
    C --> C2[成分分析]
    
    E --> E1[意图识别]
    E --> E2[情感分析]
    E --> E3[关系抽取]
    
    F --> F1[知识图谱]
    F --> F2[逻辑推理]
    
    G --> G1[文本生成]
    G --> G2[风格转换]

2. 聊天机器人工作原理

public class ChatbotArchitecture {
    // 1. 自然语言理解
    public NLUResult understand(String text) {
        return new NLUProcessor()
            .tokenize(text)
            .parseSyntax()
            .extractEntities()
            .classifyIntent();
    }
    
    // 2. 对话管理
    public DialogState manageDialog(NLUResult understanding) {
        return new DialogManager()
            .updateState(understanding)
            .maintainContext()
            .determineStrategy();
    }
    
    // 3. 响应生成
    public Response generateResponse(DialogState state) {
        return new ResponseGenerator()
            .retrieveKnowledge(state)
            .planResponse()
            .generateText();
    }
}

六、核心特性

1. 多轮对话管理

// 对话状态管理
class DialogManager {
    private context: DialogContext;
    
    async processTurn(userInput: UserInput): Promise<DialogState> {
        // 1. 上下文理解
        const context = await this.understandContext(userInput);
        
        // 2. 状态更新
        const newState = this.updateState(context);
        
        // 3. 策略选择
        const strategy = this.selectStrategy(newState);
        
        return {
            state: newState,
            strategy,
            needsClarification: this.requiresClarification(newState)
        };
    }
    
    private requiresClarification(state: DialogState): boolean {
        // 检查是否需要澄清
        return state.confidence < 0.3 || state.ambiguity > 0.7;
    }
}

2. 智能摘要生成

// 多策略摘要生成
class MultiStrategySummarizer {
    async generateSummary(document: Document, strategy: SummaryStrategy): Promise<string> {
        switch (strategy) {
            case 'extractive':
                return this.extractiveSummarization(document);
            case 'abstractive':
                return this.abstractiveSummarization(document);
            case 'hybrid':
                return this.hybridSummarization(document);
            default:
                return this.defaultSummarization(document);
        }
    }
    
    private extractiveSummarization(document: Document): string {
        // 抽取式摘要:选择重要句子
        return this.selectImportantSentences(document);
    }
    
    private abstractiveSummarization(document: Document): string {
        // 生成式摘要:理解后重新表达
        return this.generateNewSummary(document);
    }
}

七、原理流程图

sequenceDiagram
    participant User
    participant NLU
    participant DialogManager
    participant KnowledgeBase
    participant NLG
    participant Response
    
    User->>NLU: 用户输入文本
    NLU->>DialogManager: 理解结果
    DialogManager->>KnowledgeBase: 查询知识
    KnowledgeBase->>NLG: 相关信息
    NLG->>Response: 生成响应文本
    Response->>User: 返回响应
    
    Note over NLU,KnowledgeBase: 自然语言理解
    Note over DialogManager: 对话状态管理
    Note over NLG,Response: 自然语言生成

八、环境准备

1. 开发环境配置

// package.json
{
  "name": "harmonyos-nlp-app",
  "version": "1.0.0",
  "dependencies": {
    "@ohos/nlp": "1.0.0",
    "@ohos/ai": "1.0.0", 
    "@ohos/network": "1.0.0",
    "@ohos/data": "1.0.0"
  },
  "devDependencies": {
    "@ohos/hypium": "1.0.0"
  }
}

2. 模型资源配置

// resources/base/model/nlp_models.json
{
  "intent_classification": {
    "model": "intent_model.om",
    "vocab": "vocab.txt",
    "labels": "intent_labels.json"
  },
  "ner_model": {
    "model": "ner_model.om", 
    "vocab": "vocab.txt",
    "entities": ["person", "location", "organization"]
  },
  "summarization": {
    "model": "summarization_model.om",
    "max_input_length": 1024,
    "max_output_length": 256
  }
}

九、实际详细应用代码示例实现

完整示例:企业智能助手

// src/main/ets/application/EnterpriseAssistantApp.ts
import { ChatbotService } from '../services/ChatbotService';
import { DocumentSummarizationService } from '../services/DocumentSummarizationService';

@Entry  
@Component
struct EnterpriseAssistantApp {
  private chatbotService: ChatbotService = new ChatbotService();
  private summarizationService: DocumentSummarizationService = new DocumentSummarizationService();
  
  @State currentTab: string = 'chat';
  @State isServicesReady: boolean = false;
  @State initializationError: string = '';

  aboutToAppear() {
    this.initializeServices();
  }

  async initializeServices() {
    try {
      await Promise.all([
        this.chatbotService.initialize(),
        this.summarizationService.initialize()
      ]);
      
      this.isServicesReady = true;
    } catch (error) {
      this.initializationError = `服务初始化失败: ${error.message}`;
    }
  }

  build() {
    Column() {
      if (this.initializationError) {
        this.buildErrorState()
      } else if (!this.isServicesReady) {
        this.buildLoadingState()
      } else {
        this.buildMainInterface()
      }
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#f5f5f5')
  }

  @Builder
  buildErrorState() {
    Column() {
      Image($r('app.media.error'))
        .width(100)
        .height(100)
        .margin({ bottom: 20 })
      
      Text('初始化失败')
        .fontSize(18)
        .fontColor('#ff3b30')
        .margin({ bottom: 10 })
      
      Text(this.initializationError)
        .fontSize(14)
        .fontColor('#666666')
        .textAlign(TextAlign.Center)
        .margin({ bottom: 20 })
      
      Button('重试')
        .onClick(() => this.initializeServices())
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
  }

  @Builder
  buildLoadingState() {
    Column() {
      Progress({ value: 0, total: 100 })
        .width(200)
        .color('#4cd964')
      
      Text('AI服务初始化中...')
        .fontSize(16)
        .fontColor('#666666')
        .margin({ top: 20 })
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
  }

  @Builder
  buildMainInterface() {
    Column() {
      // 导航标签
      this.buildNavigationTabs()
      
      // 内容区域
      if (this.currentTab === 'chat') {
        ChatInterface({ chatbotService: this.chatbotService })
          .layoutWeight(
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。