App6-藏头诗工坊:基于鸿蒙的AI藏头诗创作应用开发实践

在这里插入图片描述
在这里插入图片描述

一、应用概述

1.1 应用背景与价值

藏头诗是中国传统诗歌的一种特殊形式,它以每句诗的第一个字连起来组成一个特定的词语或句子,既体现了诗歌的韵律美,又蕴含了深刻的含义。藏头诗常用于祝福、表白、纪念等场合,是一种富有创意和文化内涵的表达方式。

藏头诗工坊是一款基于鸿蒙生态的AI智能藏头诗创作应用,旨在帮助用户根据指定的藏头词语和诗歌风格,生成符合格律的精美藏头诗。该应用融合了自然语言处理与传统文化知识,为用户提供专业的藏头诗创作辅助。

1.2 应用特性

特性 描述
藏头创作 根据用户输入的藏头词语生成藏头诗
风格选择 支持五言、七言、现代等多种风格
情感倾向 可选择祝福、表白、励志、思念等情感
格律规范 生成符合平仄对仗的藏头诗
鸿蒙生态适配 完美适配鸿蒙手机、鸿蒙PC等多端设备

1.3 应用架构

┌─────────────────────────────────────────────────────────┐
│                    用户界面层                            │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │ 藏头输入组件  │  │ 风格选择组件  │  │ 诗歌展示组件  │  │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘  │
└─────────┼─────────────────┼─────────────────┼───────────┘
          ▼                 ▼                 ▼
┌─────────────────────────────────────────────────────────┐
│                    业务逻辑层                            │
│  ┌───────────────────────────────────────────────────┐  │
│  │           AcrosticGenerator (藏头诗生成器)         │  │
│  │  ┌──────────────┐  ┌──────────────┐              │  │
│  │  │ 藏头分析模块  │→│ 格律匹配模块  │→│ 诗歌生成模块  │  │
│  │  └──────────────┘  └──────────────┘  └──────────────┘  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
          ▼
┌─────────────────────────────────────────────────────────┐
│                    数据存储层                            │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │ 诗歌模板库    │  │ 平仄词库      │  │ 用户创作记录  │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└─────────────────────────────────────────────────────────┘

二、技术实现

2.1 核心数据结构

应用采用严格的类型安全设计,定义了完整的接口体系:

interface AcrosticResult {
  title: string;
  lines: string[];
  acrostic: string;
  explanation: string;
}

设计要点:

  1. AcrosticResult:表示完整藏头诗的结构
    • title:诗歌标题
    • lines:诗句数组
    • acrostic:藏头词语
    • explanation:诗歌释义

2.2 状态管理设计

应用使用 @State 装饰器管理所有页面状态:

@Entry
@Component
struct App6 {
  @State acrostic: string = '我爱中国';
  @State style: string = '七言';
  @State emotion: string = '祝福';
  @State isLoading: boolean = false;
  @State showResult: boolean = false;
  @State result: AcrosticResult = { title: '', lines: [], acrostic: '', explanation: '' };
  @State errorMsg: string = '';
  
  private styleOptions: string[] = ['五言', '七言', '现代'];
  private emotionOptions: string[] = ['祝福', '表白', '励志', '思念'];
}

状态管理策略:

状态变量 类型 作用
acrostic string 藏头词语
style string 诗歌风格
emotion string 情感倾向
isLoading boolean 加载状态标识
showResult boolean 是否显示创作结果
result AcrosticResult 藏头诗创作结果
errorMsg string 错误提示信息

2.3 Mock数据生成策略

应用内置了多场景的Mock数据,确保离线状态下也能正常运行:

private getMockResult(): AcrosticResult {
  if (this.style === '七言' && this.emotion === '祝福') {
    return {
      title: '祝福祖国',
      lines: [
        '我自巍然立东方,',
        '爱洒山河万里长,',
        '中华儿女多奇志,',
        '国泰民安谱华章。'
      ],
      acrostic: '我爱中国',
      explanation: '本诗以"我爱中国"四字藏头,表达对祖国的热爱与祝福。首句描绘中国屹立东方的豪迈气势,次句表达对山河大地的深情,第三句赞美中华儿女的壮志豪情,末句祝愿国家繁荣昌盛、人民幸福安康。'
    };
  } else if (this.style === '七言' && this.emotion === '表白') {
    return {
      title: '相思',
      lines: [
        '我心明月寄相思,',
        '爱意绵绵无尽时,',
        '你若春风拂杨柳,',
        '好花常开伴君知。'
      ],
      acrostic: '我爱你好',
      explanation: '本诗以"我爱你好"四字藏头,表达对心爱之人的深情表白。首句以明月寄相思,次句表达绵绵爱意,第三句将对方比作春风杨柳,末句祝愿美好时光长伴左右。'
    };
  } else {
    return {
      title: '励志篇',
      lines: [
        '我志凌云不可挡,',
        '爱拼才会有辉煌,',
        '中流砥柱立潮头,',
        '国强民富我担当。'
      ],
      acrostic: '我爱中国',
      explanation: '本诗以"我爱中国"四字藏头,表达励志奋斗的决心。首句抒发凌云壮志,次句强调拼搏精神,第三句比喻勇立潮头,末句表达为国担当的情怀。'
    };
  }
}

数据匹配策略:

  1. 风格情感双重匹配:同时考虑风格和情感两个维度进行匹配
  2. 场景化创作:针对不同情感场景提供相应主题的藏头诗
  3. 经典模板:兜底返回励志风格藏头诗,确保创作质量
  4. 完整结构:每首诗包含标题、诗句、藏头词语和释义

2.4 核心业务逻辑

generateMockData(): void {
  this.errorMsg = '';
  if (this.acrostic.trim().length === 0) {
    this.errorMsg = '请输入藏头词语';
    return;
  }
  this.result = this.getMockResult();
}

onGenerate(): void {
  this.isLoading = true;
  this.showResult = false;
  this.errorMsg = '';
  setTimeout((): void => {
    this.generateMockData();
    this.isLoading = false;
    if (this.errorMsg.length === 0) {
      this.showResult = true;
    }
  }, 800);
}

执行流程:

  1. 用户输入藏头词语并选择诗歌风格和情感倾向
  2. 点击"生成藏头诗"按钮
  3. 设置加载状态,隐藏结果
  4. 模拟API调用延迟(800ms)
  5. 根据用户选择生成Mock数据
  6. 显示创作结果

2.5 UI组件设计

应用采用鸿蒙设计规范,构建了现代化的用户界面:

build() {
  Column() {
    // 返回按钮
    Row() {
      Button('← 返回')
        .fontSize(14)
        .backgroundColor('#E0E0E0')
        .fontColor('#333333')
        .onClick((): void => { router.back(); });
    }.width('100%').padding({ left: 16, top: 12, bottom: 8 });
    
    // 标题
    Text('藏头诗工坊')
      .fontSize(24)
      .fontWeight(FontWeight.Bold)
      .fontColor('#333333')
      .padding({ left: 16, bottom: 16 });
    
    // 滚动内容区域
    Scroll() {
      Column() {
        // 藏头输入
        Text('藏头词语')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .fontColor('#333333')
          .padding({ left: 16, top: 8, bottom: 8 });
        
        TextInput({ placeholder: '例如:我爱中国、生日快乐...', text: this.acrostic })
          .height(44)
          .fontSize(14)
          .backgroundColor('#FFFFFF')
          .borderRadius(8)
          .padding(12)
          .margin({ left: 16, right: 16 })
          .onChange((value: string): void => {
            this.acrostic = value;
          });
        
        // 风格选择
        Text('诗歌风格')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .fontColor('#333333')
          .padding({ left: 16, top: 16, bottom: 8 });
        
        Row() {
          ForEach(this.styleOptions, (item: string, index: number): void => {
            Button(item)
              .fontSize(14)
              .backgroundColor(this.style === item ? '#00B894' : '#E8E8E8')
              .fontColor(this.style === item ? '#FFFFFF' : '#666666')
              .borderRadius(20)
              .padding({ left: 16, right: 16, top: 8, bottom: 8 })
              .margin({ right: 10 })
              .onClick((): void => {
                this.style = item;
              });
          }, (item: string, index: number): string => item + index.toString());
        }.width('100%').padding({ left: 16, right: 16 });
        
        // 情感选择
        Text('情感倾向')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .fontColor('#333333')
          .padding({ left: 16, top: 16, bottom: 8 });
        
        Row() {
          ForEach(this.emotionOptions, (item: string, index: number): void => {
            Button(item)
              .fontSize(14)
              .backgroundColor(this.emotion === item ? '#00B894' : '#E8E8E8')
              .fontColor(this.emotion === item ? '#FFFFFF' : '#666666')
              .borderRadius(20)
              .padding({ left: 16, right: 16, top: 8, bottom: 8 })
              .margin({ right: 10 })
              .onClick((): void => {
                this.emotion = item;
              });
          }, (item: string, index: number): string => item + index.toString());
        }.width('100%').padding({ left: 16, right: 16 });
        
        // 生成按钮
        Button('✍️ 生成藏头诗')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .backgroundColor('#00B894')
          .fontColor('#FFFFFF')
          .borderRadius(25)
          .width('90%')
          .height(48)
          .margin({ top: 20, bottom: 20 })
          .onClick((): void => {
            this.onGenerate();
          });
        
        // 错误提示
        if (this.errorMsg.length > 0) {
          Text(this.errorMsg).fontSize(14).fontColor('#E74C3C').padding({ left: 16, right: 16, bottom: 8 });
        }
        
        // 加载状态
        if (this.isLoading) {
          Column() {
            LoadingProgress().width(36).height(36).color('#00B894');
            Text('AI 正在创作藏头诗...').fontSize(14).fontColor('#999999').margin({ top: 8 });
          }.width('100%').padding(20);
        }
        
        // 结果展示
        if (this.showResult && !this.isLoading) {
          Column() {
            // 标题
            Text(this.result.title)
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .fontColor('#00B894')
              .padding({ top: 16 });
            
            // 藏头提示
            Text('藏头:' + this.result.acrostic)
              .fontSize(14)
              .fontColor('#888888')
              .padding({ top: 6 });
            
            // 诗句
            Column() {
              ForEach(this.result.lines, (line: string, index: number): void => {
                Text(line)
                  .fontSize(16)
                  .fontColor('#333333')
                  .fontWeight(FontWeight.Medium)
                  .padding({ top: 8 });
              }, (line: string, index: number): string => line + index.toString());
            }.padding({ top: 12 });
            
            // 释义
            Text('释义:').fontSize(14).fontColor('#00B894').padding({ top: 16 });
            Text(this.result.explanation)
              .fontSize(13)
              .fontColor('#666666')
              .lineHeight(20)
              .backgroundColor('#FFFFFF')
              .borderRadius(10)
              .padding(14)
              .width('90%')
              .margin({ top: 6, bottom: 30 });
          }.width('100%');
        }
      }.width('100%');
    }.layoutWeight(1);
  }.width('100%').height('100%').backgroundColor('#F5F5F5');
}

三、鸿蒙生态适配

3.1 鸿蒙设计规范遵循

应用严格遵循鸿蒙设计规范,包括:

  1. 色彩系统:使用清新的翠绿色(#00B894),传达生机、创意、文化的品牌调性
  2. 字体层级:建立清晰的字体大小层级,标题24px、诗题20px、诗句16px、释义13px
  3. 间距系统:统一的padding和margin设计,确保界面呼吸感
  4. 卡片设计:释义内容采用圆角卡片展示,提升视觉层次

3.2 鸿蒙PC适配策略

针对鸿蒙PC平台,应用采用以下适配策略:

// 响应式布局设计
build() {
  Column() {
    // 在PC端可以调整布局为左右分栏
    if (this.windowWidth > 768) {
      Row() {
        // 左侧:输入区域
        Column() { /* 输入表单 */ }.width('35%');
        // 右侧:诗歌展示
        Column() { /* 诗歌内容 */ }.width('65%');
      }.width('100%');
    } else {
      // 移动端:垂直堆叠
      Column() { /* 输入表单 + 诗歌展示 */ }.width('100%');
    }
  }.width('100%').height('100%');
}

PC端优化要点:

  • 支持键盘快捷键操作(如Ctrl+Enter提交创作)
  • 优化鼠标悬停效果和点击反馈
  • 支持窗口拖拽调整大小
  • 采用分栏布局提升信息密度

3.3 鸿蒙Flutter框架对比

在考虑跨平台方案时,我们对比了鸿蒙原生开发与鸿蒙Flutter框架的优劣:

维度 鸿蒙原生(ArkTS) 鸿蒙Flutter框架
性能 原生性能,零桥接开销 有桥接开销,性能略低
UI一致性 完美契合鸿蒙设计规范 需要额外适配
开发效率 学习曲线较陡 开发效率高
跨端能力 仅限于鸿蒙生态 支持多平台
生态成熟度 官方全力支持 社区生态完善

选型决策: 由于本应用专注于鸿蒙生态,且需要深度集成鸿蒙特性,最终选择了鸿蒙原生开发方案。

四、技术亮点

4.1 藏头诗生成算法设计

应用的核心算法基于藏头匹配策略,实现了智能诗歌创作:

class AcrosticGenerator {
  private poetryTemplates: Record<string, AcrosticResult> = {
    '七言_祝福': { /* 七言祝福藏头诗模板 */ },
    '七言_表白': { /* 七言表白藏头诗模板 */ },
    '五言_励志': { /* 五言励志藏头诗模板 */ },
    '现代_思念': { /* 现代思念藏头诗模板 */ },
  };
  
  generate(acrostic: string, style: string, emotion: string): AcrosticResult {
    let key = style + '_' + emotion;
    if (this.poetryTemplates[key]) {
      let template = this.poetryTemplates[key];
      // 根据藏头词语调整模板
      return {
        ...template,
        acrostic: acrostic,
        title: '藏头诗·' + acrostic
      };
    }
    
    // 找不到匹配模板时,使用默认模板
    return this.poetryTemplates['七言_祝福'];
  }
}

4.2 状态驱动的响应式UI

应用采用 @State 装饰器实现响应式状态管理:

  • 状态变化自动触发UI更新
  • 无需手动调用刷新方法
  • 支持双向数据绑定

4.3 离线优先的设计理念

应用内置完整的Mock数据,确保:

  • 无网络环境下正常使用
  • 快速响应,无需等待API调用
  • 数据一致性保障

五、代码优化建议

5.1 性能优化

// 优化前:每次调用都重新生成
private getMockResult(): AcrosticResult {
  // ...
}

// 优化后:预计算创作结果
private poetryCache: Record<string, AcrosticResult> = {};

private getMockResult(): AcrosticResult {
  let cacheKey = this.acrostic + '_' + this.style + '_' + this.emotion;
  if (this.poetryCache[cacheKey]) {
    return this.poetryCache[cacheKey];
  }
  
  let result = this.generatePoetry();
  this.poetryCache[cacheKey] = result;
  return result;
}

5.2 代码结构优化

建议将业务逻辑提取到独立的工具类中:

// acrostic_generator.ts
export class AcrosticGenerator {
  static generate(acrostic: string, style: string, emotion: string): AcrosticResult {
    // 生成逻辑
  }
}

// Index.ets
import { AcrosticGenerator } from './acrostic_generator';

generateMockData(): void {
  this.result = AcrosticGenerator.generate(this.acrostic, this.style, this.emotion);
}

六、总结

藏头诗工坊应用展示了鸿蒙生态下AI传统文化创作应用的开发实践,通过以下方面体现了技术价值:

  1. 类型安全:严格的接口定义和类型检查
  2. 响应式设计:基于 @State 的状态管理
  3. 离线支持:完整的Mock数据方案
  4. 多端适配:鸿蒙手机和鸿蒙PC的适配策略
  5. 用户体验:流畅的交互和现代化的UI设计

未来,应用可以扩展以下功能:

  • 接入大模型API,实现更精准的智能创作
  • 添加诗歌书法字体展示功能
  • 支持藏头诗修改和优化
  • 集成社交分享和打印功能

通过本次开发实践,我们深刻体会到鸿蒙原生开发的优势,特别是在性能和生态集成方面。同时,也认识到在跨平台场景下,鸿蒙Flutter框架是一个值得考虑的备选方案。在实际项目中,需要根据具体需求和场景选择合适的技术栈。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐