? 大家好,我是潘Sir,持續分享IT技術,幫你少走彎路。《鴻蒙應用開發從入門到項目實戰》系列文章持續更新中,歡迎關注!
隨著鴻蒙(HarmonyOS)生態發展,越來越多的APP需要進行鴻蒙適配。本文以快遞APP寄件中的收貨地址識別功能為例,探討HarmonyOS鴻蒙版本的開發和適配。
一、需求分析
1、應用場景
隨著互聯網的發展,網購已成為大家日常生活中不可或缺的一部分。網購涉及到發貨和收貨操作,為了簡化操作、提升APP的使用效率,各大APP都融入了AI能力。在AI賦能下,從傳統的文字輸入交互方式,逐步拓展到人臉識別、指紋識別、圖片識別、語言識別等方式,降低了APP使用門檻的同時極大提高了交互效率。
本文研究以支付寶APP里邊的“菜鳥裹裹”寄件場景為例,通過粘貼文字或者圖片識別進行收貨地址自動識別填充。在鴻蒙操作系統(HarmonyOS)上借助HarmonyOS SDK 提供的AI能力,開發鴻蒙原生應用APP功能,完成上述功能。
ps:相信大家都寄過快遞,如果沒操作過可以先了解一下。
2、實現效果
主頁 | 拍照 | 識別 | 保存 |
---|---|---|---|
![]() | ![]() | ![]() | ![]() |
ps:由于編寫的提取規則中,名字為2-4個中文,因此上邊的名字“潘Sir”包含了1個英文,故未識別正確。如果改為2-4個漢字則可以正確識別。這就是傳統的用規則來匹配的弊端,更好的方法是使用AI大模型或NLP工具來提取地址信息。
讀者可以直接運行提供的代碼查看效果。由于使用了視覺服務,需要真機運行。
使用說明:
- 點擊
圖片識別
按鈕,拉起選擇圖片獲取方式
的彈窗,選擇拍照
方式,通過對要識別的文字進行拍照獲得要識別的圖片。也可以選擇相冊
方式,在圖庫中直接選擇需要識別的圖片。 - 識別出圖片包含的文本信息后,會自動將文本內容填充到文本輸入框。
- 點擊`地址解析按鈕,會將文本框中的信息提取為結構化數據,顯示到按鈕下方的列表中。
- 點擊
保存地址
按鈕,提示保存成功,文本框舊的內容會自動清空。
3、技術分析
基于HarmonyOS SDK提供的基礎視覺服務(CoreVisionKit),使用@kit.CoreVisionKit
提供的通用文字識別能力,通過拍照(CameraPicker)或者相冊(PhotoViewPicker)方式,將印刷品文字(如:收貨信息)轉化為圖像信息,再利用文字識別技術將圖像信息轉化為設備可以使用的文本字符,最后可以根據實際業務規則提取結構化數據。
二、界面制作
1、布局分析
主界面布局分析:
彈窗界面布局分析:
2、界面制作
開發環境說明:DevEco Studio5.0.4 Release、 HarmonyOS5.0.4(API 16)
通過DevEco Studio創建項目,項目名稱為:ExtractAddress,刪除Index.ets文件中默認的代碼。
2.1 制作主界面
為了便于代碼復用和程序擴展,將收貨人信息的界面上的每一行顯示的數據,抽取為一個對象,該對象類型為ConsigneeInfo類。在ets目錄下新建viewmodel目錄,新建DataModel.ets文件,內容如下:
// 收貨人信息界面視圖模型
@ObservedV2
export class ConsigneeInfo {label: ResourceStr; //標簽名稱placeholder: ResourceStr; //提示語@Trace value: string; //輸入值constructor(label: ResourceStr, placeholder: ResourceStr, value: string) {this.label = label;this.placeholder = placeholder;this.value = value;}
}
有了此類,在主界面上就只需要實例化3個對象,通過列表進行循環渲染即可,避免了重復臃腫的代碼。接下來制作主界面,Index.ets文件內容如下:
import { ConsigneeInfo} from '../viewmodel/DataModel';@Entry
@Component
struct Index {@State consigneeInfos: ConsigneeInfo[] = []; //收貨人信息界面視圖@State saveAvailable: boolean = false; //保存按鈕是否可用aboutToAppear(): void {this.consigneeInfos = [new ConsigneeInfo('收貨人', '收貨人姓名', ''),new ConsigneeInfo('電話', '收貨人電話', ''),new ConsigneeInfo('地址', '地址', ''),];}build() {RelativeContainer() {// 界面主體內容Column() {Text('新增收貨地址').id('title').width('100%').font({ size: 26, weight: 700 }).fontColor('#000000').opacity(0.9).height(64).align(Alignment.TopStart)Text('地址信息').width('100%').padding({ left: 12, right: 12 }).font({ size: 14, weight: 400 }).fontColor('#000000').opacity(0.6).lineHeight(19).margin({ bottom: 8 })// 識別或填寫區域Column() {TextArea({placeholder: '圖片識別的文本自動顯示到此處(也可手動復制文本到此處),將自動識別收貨信息。例:大美麗,182*******,四川省成都市天府新區某小區',}).height(100).margin({ bottom: 12 }).backgroundColor('#FFFFFF')Row({ space: 12 }) {Button() {Row({ space: 8 }) {Text() {SymbolSpan($r('sys.symbol.camera')).fontSize(26).fontColor(['#0A59F2'])}Text('圖片識別').fontSize(16).fontColor('#0A59F2')}}.height(40).layoutWeight(1).backgroundColor('#F1F3F5')Button('地址解析').height(40).layoutWeight(1)}.width('100%').padding({left: 16,right: 16,})}.backgroundColor('#FFFFFF').borderRadius(16).padding({top: 16,bottom: 16})// 收貨人信息Column() {List() {//列表渲染,避免重復代碼ForEach(this.consigneeInfos, (item: ConsigneeInfo) => {ListItem() {Row() {Text(item.label).fontSize(16).fontWeight(400).lineHeight(19).textAlign(TextAlign.Start).fontColor('#000000').opacity(0.9).layoutWeight(1)TextArea({ placeholder: item.placeholder, text: item.value }).type(item.label === '收貨人' ? TextAreaType.PHONE_NUMBER : TextAreaType.NORMAL).fontSize(16).fontWeight(500).lineHeight(21).padding(0).borderRadius(0).textAlign(TextAlign.End).fontColor('#000000').opacity(0.9).backgroundColor('#FFFFFF').heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST).layoutWeight(2).onChange((value: string) => {item.value = value;//判斷保存按鈕是否可用(均填寫即可保存)if (this.consigneeInfos[0].value && this.consigneeInfos[1].value && this.consigneeInfos[2].value) {this.saveAvailable = true;} else {this.saveAvailable = false;}})}.width('100%').constraintSize({ minHeight: 48 }).justifyContent(FlexAlign.SpaceBetween)}}, (item: ConsigneeInfo, index: number) => JSON.stringify(item) + index)}.width('100%').height(LayoutPolicy.matchParent).scrollBar(BarState.Off).divider({ strokeWidth: 0.5, color: '#33000000' }).padding({left: 12,right: 12,top: 4,bottom: 4}).borderRadius(16).backgroundColor('#FFFFFF')}.borderRadius(16).margin({ top: 12 }).constraintSize({ minHeight: 150, maxHeight: '50%' }).backgroundColor('#FFFFFF')}// 保存按鈕if (this.saveAvailable) {// 可用狀態Button("保存地址", { stateEffect: true }).width('100%').alignRules({bottom: { anchor: '__container__', align: VerticalAlign.Bottom }})} else {// 不可用狀態Button("保存地址", { stateEffect: false }).width('100%').alignRules({bottom: { anchor: '__container__', align: VerticalAlign.Bottom }}).opacity(0.4).backgroundColor('#317AFF')}}.height('100%').width('100%').padding({left: 16,right: 16,top: 24,bottom: 24}).backgroundColor('#F1F3F5').alignRules({left: { anchor: '__container__', align: HorizontalAlign.Start }}).expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])}
}
該界面中通過RelativeContainer進行相對布局,保存按鈕通過相對布局定位到界面底部,主要內容區域使用Column布局。在aboutToAppear周期函數中,初始化收貨人列表數據,界面中通過List列表渲染完成顯示。至此,主界面的靜態效果就實現了。
但主界面代碼依然較多,可以考慮將List列表渲染部分抽取為單獨的組件,提取到單獨文件中。在ets目錄下新建components目錄,在該目錄下新建ConsigneeInfoItem.ets文件,將主界面列表渲染部分的內容拷貝進去并進改造。
ConsigneeInfoItem.ets文件內容:
import { ConsigneeInfo } from '../viewmodel/DataModel';@Builder
export function ConsigneeInfoItem(item: ConsigneeInfo, checkAvailable?: () => void) {Row() {Text(item.label).fontSize(16).fontWeight(400).lineHeight(19).textAlign(TextAlign.Start).fontColor('#000000').opacity(0.9).layoutWeight(1)TextArea({ placeholder: item.placeholder, text: item.value }).type(item.label === '收貨人' ? TextAreaType.PHONE_NUMBER : TextAreaType.NORMAL).fontSize(16).fontWeight(500).lineHeight(21).padding(0).borderRadius(0).textAlign(TextAlign.End).fontColor('#000000').opacity(0.9).backgroundColor('#FFFFFF').heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST).layoutWeight(2).onChange((value: string) => {item.value = value;//判斷保存按鈕是否可用(均填寫即可保存)checkAvailable?.();})}.width('100%').constraintSize({ minHeight: 48 }).justifyContent(FlexAlign.SpaceBetween)}
Index.ets改造
import {ConsigneeInfoItem} from '../components/ConsigneeInfoItem'
...
ListItem() {//抽取為組件ConsigneeInfoItem(item,() => {if (this.consigneeInfos[0].value && this.consigneeInfos[1].value && this.consigneeInfos[2].value) {this.saveAvailable = true;} else {this.saveAvailable = false;}})}
...
主界面效果實現完成
2.2 圖片識別彈窗
點擊“圖片識別”按鈕,彈出獲取圖片方式選擇框。接下來完成該界面制作。
為了彈出框管理更加方面,封裝彈窗口管理工具類PromptActionManager,在ets目錄新建utils目錄,新建PromptActionManager.ets文件,內容如下:
import { promptAction } from '@kit.ArkUI';/*** Dialog管理類*/
export class PromptActionManager {static ctx: UIContext;static contentNode: ComponentContent<Object>;static options: promptAction.BaseDialogOptions;static setCtx(ctx: UIContext) {PromptActionManager.ctx = ctx;}static setContentNode(contentNode: ComponentContent<Object>) {PromptActionManager.contentNode = contentNode;}static setOptions(options: promptAction.BaseDialogOptions) {PromptActionManager.options = options;}static openCustomDialog() {if (!PromptActionManager.contentNode) {return;}try {PromptActionManager.ctx.getPromptAction().openCustomDialog(PromptActionManager.contentNode,PromptActionManager.options)} catch (error) {}}static closeCustomDialog() {if (!PromptActionManager.contentNode) {return;}try {PromptActionManager.ctx.getPromptAction().closeCustomDialog(PromptActionManager.contentNode)} catch (error) {}}
}
不同的彈出界面可能需要不同的樣式控制,因此為彈出框的控制定義參數類型Params。在DataModel.ets文件中新加類Params,代碼如下:
...
export class Params {uiContext: UIContext;textAreaController: TextAreaController; //識別信息的TextArealoadingController: CustomDialogController; //識別過程中的加載提示框constructor(uiContext: UIContext, textAreaController: TextAreaController, loadingController: CustomDialogController) {this.uiContext = uiContext;this.textAreaController = textAreaController;this.loadingController = loadingController;}
}
接下來制作彈出框組件界面,在components目錄新建dialogBuilder.ets文件
import { Params } from '../viewmodel/DataModel'
import { PromptActionManager } from '../common/utils/PromptActionManager'@Builder
export function dialogBuilder(params: Params): void {Column() {Text('圖片識別').font({ size: 20, weight: 700 }).lineHeight(27).margin({ bottom: 16 })Text('選擇獲取圖片的方式').font({ size: 16, weight: 50 }).lineHeight(21).margin({ bottom: 8 })Column({ space: 8 }) {Button('拍照').width('100%').height(40)Button('相冊').width('100%').height(40).fontColor('#0A59F2').backgroundColor('#FFFFFF')Button('取消').width('100%').height(40).fontColor('#0A59F2').backgroundColor('#FFFFFF').onClick(() => {PromptActionManager.closeCustomDialog();})}}.size({ width: 'calc(100% - 32vp)', height: 235 }).borderRadius(32).backgroundColor('#FFFFFF').padding(16)
}
修改Index.ets文件,為“圖片識別”按鈕綁定事件,點擊時彈出自定義對話框。
...
import { PromptActionManager } from '../common/utils/PromptActionManager';
import { ComponentContent, LoadingDialog } from '@kit.ArkUI';
import { ConsigneeInfo,Params} from '../viewmodel/DataModel';
import { dialogBuilder } from '../components/dialogBuilder';...
private uiContext: UIContext = this.getUIContext();
private resultController: TextAreaController = new TextAreaController();
private loadingController: CustomDialogController = new CustomDialogController({builder: LoadingDialog({content: '圖片識別中'}),autoCancel: false});
private contentNode: ComponentContent<Object> =new ComponentContent(this.uiContext, wrapBuilder(dialogBuilder),new Params(this.uiContext, this.resultController, this.loadingController));
...//圖片識別按鈕
.onClick(() => {PromptActionManager.openCustomDialog();})
靜態界面制作完成。
三、功能實現
1、通用功能封裝
創建OCR識別管理類OCRManager,需要用到HarmonyOS SDK中的AI和媒體兩類Kit。在utils目錄下新建OCRManager.ets,封裝相關方法。
import { textRecognition } from '@kit.CoreVisionKit';
import { camera, cameraPicker } from '@kit.CameraKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';export class OCRManager {static async recognizeByCamera(ctx: Context, loadingController: CustomDialogController): Promise<string> {// The configuration information of cameraPickerlet pickProfile: cameraPicker.PickerProfile = {cameraPosition: camera.CameraPosition.CAMERA_POSITION_UNSPECIFIED};try {let result: cameraPicker.PickerResult =await cameraPicker.pick(ctx, [cameraPicker.PickerMediaType.PHOTO], pickProfile);if (!result || !result.resultUri) {return '';}loadingController.open();return OCRManager.recognizeText(result.resultUri);} catch (error) {loadingController.close();return '';}}static async recognizeByAlbum(loadingController: CustomDialogController): Promise<string> {try {let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();let photoResult: photoAccessHelper.PhotoSelectResult =await photoPicker.select({MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,maxSelectNumber: 1,isPhotoTakingSupported: false});if (!photoResult || photoResult.photoUris.length === 0) {return '';}loadingController.open();return OCRManager.recognizeText(photoResult.photoUris[0]);} catch (error) {loadingController.close();return '';}}static async recognizeText(uri: string): Promise<string> {// Visual information to be recognized.// Currently, only the visual information of the PixelMap type in color data format RGBA_8888 is supported.let visionInfo: textRecognition.VisionInfo = { pixelMap: await OCRManager.getPixelMap(uri) };let result: textRecognition.TextRecognitionResult = await textRecognition.recognizeText(visionInfo);visionInfo.pixelMap.release();return result.value;}static async getPixelMap(uri: string): Promise<image.PixelMap> {// Convert image resources to PixelMaplet fileSource = await fs.open(uri, fs.OpenMode.READ_ONLY);let imgSource: image.ImageSource = image.createImageSource(fileSource.fd);let pixelMap: image.PixelMap = await imgSource.createPixelMap();fs.close(fileSource);imgSource.release();return pixelMap;}
}
2、拍照識別
彈出框界面,為“拍照”按鈕綁定事件
import { common } from '@kit.AbilityKit'
import { OCRManager } from '../common/utils/OCRManager'//拍照按鈕
.onClick(async () => {PromptActionManager.closeCustomDialog();let text: string =await OCRManager.recognizeByCamera(params.uiContext.getHostContext() as common.UIAbilityContext,params.loadingController);params.loadingController.close();if (text) {params.textAreaController.deleteText();params.textAreaController.addText(text);}})
主界面,修改TextArea,傳入controller并雙向綁定識別結果。
...
@State ocrResult: string = '';
...//TextArea
controller: this.resultController,
text: $$this.ocrResult
拍照識別功能實現。
3、相冊識別
彈出框界面,為“相冊”按鈕綁定事件
//相冊按鈕
.onClick(async () => {PromptActionManager.closeCustomDialog();let text: string =await OCRManager.recognizeByAlbum(params.loadingController);params.loadingController.close();if (text) {params.textAreaController.deleteText();params.textAreaController.addText(text);}})
相冊識別功能實現。
4、地址解析
主界面的“地址解析”按鈕,將通過圖片識別或手工輸入的地址信息,解析顯示到對應的輸入框中。
封裝地址解析類AddressParse,本案例使用正則表達式進行匹配。后續可以使用大模型或NLP工具進行解析。
在utils目錄下新建AddressParse.ets文件
import { ConsigneeInfo } from '../../viewmodel/DataModel';export class AddressParse {static nameBeforeRegex = /([\w\u4e00-\u9fa5]+[\s\,\,\。]+|[\s\,\,\。]*)([\u4e00-\u9fa5]{2,4})[\s\,\,\。]+/;static nameAfterRegex = /[\s\,\,\。]+([\u4e00-\u9fa5]{2,4})[\s\,\,\。]*/;static nameTagRegex = /(?:收貨人|收件人|姓名|聯系人)[::\s]*([\u4e00-\u9fa5]{2,4})/i;static namePlainRegex = /[\u4e00-\u9fa5]{2,4}/;static phoneRegex =/(1[3-9]\d[\s-]?\d{4}[\s-]?\d{4})|(\d{3,4}[\s-]?\d{7,8})|(\(\d{2,4}\)[\s-]?\d{4,8})|(\+\d{1,4}[\s-]?\d{5,15})/g;static phoneHyphenRegex = /[\(\)\s-]/g;static addressKeywords =['收貨地址', '收件地址', '配送地址', '所在地區', '位置','地址', '寄至', '寄往', '送至', '詳細地址'];static addressNoiseWords = ['收貨人', '收件人', '姓名', '聯系人', '電話', '手機', '聯系方式', ':', ':', ',', ','];static extractInfo(text: string, info: ConsigneeInfo[]): ConsigneeInfo[] {const baseText: string = text.replace(/\s+/g, ' ')const phoneResult: string = AddressParse.extractPhone(baseText);const nameResult: string = AddressParse.extractName(baseText, phoneResult);const addressResult: string = AddressParse.extractAddress(baseText, phoneResult, nameResult);info[0].value = nameResult;info[1].value = phoneResult.replace(AddressParse.phoneHyphenRegex, '');info[2].value = addressResult;return info;}static extractPhone(text: string): string {const phoneMatch: RegExpMatchArray | null = text.match(AddressParse.phoneRegex);return phoneMatch ? phoneMatch[0] : '';}static extractName(text: string, phone: string): string {let name = '';// Try to extract from the labelconst nameFromTag = text.match(AddressParse.nameTagRegex);if (nameFromTag) {name = nameFromTag[1];}// Try to extract before or after the phoneif (!name && phone) {const phoneIndex = text.indexOf(phone);const beforePhone = text.substring(0, phoneIndex);const nameBefore = beforePhone.match(AddressParse.nameBeforeRegex);if (nameBefore) {name = nameBefore[2];}if (!name) {const afterPhone = text.substring(phoneIndex + phone.length);const nameAfter = afterPhone.match(AddressParse.nameAfterRegex);if (nameAfter) {name = nameAfter[1];}}}// Try to extract 2-4 Chinese characters directlyif (!name) {const nameMatch = text.match(AddressParse.namePlainRegex);if (nameMatch) {name = nameMatch[0];}}return name;}static extractAddress(text: string, phone: string, name: string): string {for (const keyword of AddressParse.addressKeywords) {const keywordIndex = text.indexOf(keyword);if (keywordIndex !== -1) {const possibleAddress = text.substring(keywordIndex + keyword.length).trim();// Clean up the beginning punctuationconst cleanedAddress = possibleAddress.replace(/^[::,,。、\s]+/, '');if (cleanedAddress.length > 5) {return cleanedAddress;}}}// Try to remove name and phone numberlet cleanedText = text;if (name) {cleanedText = cleanedText.replace(name, '');}if (phone) {cleanedText = cleanedText.replace(phone, '');}// Remove common distracting wordsAddressParse.addressNoiseWords.forEach(word => {cleanedText = cleanedText.replace(word, '');});// Extract the longest text segment that may contain an addressconst segments = cleanedText.split(/[\s,,。;;]+/).filter(seg => seg.length > 4);if (segments.length > 0) {// The segment containing the address key is preferredconst addressSegments = segments.filter(seg =>seg.includes('省') || seg.includes('市') || seg.includes('區') ||seg.includes('縣') || seg.includes('路') || seg.includes('街') ||seg.includes('號') || seg.includes('棟') || seg.includes('單元'));if (addressSegments.length > 0) {return addressSegments.join(' ');}// Otherwise select the longest segmentreturn segments.reduce((longest, current) =>current.length > longest.length ? current : longest, '');}// Finally, return the entire textreturn cleanedText;}
}
在主文件中調用地址解析方法,修改Index.ets文件
import { AddressParse } from '../common/utils/AddressParse';...
//地址解析按鈕
.onClick(() => {if (!this.ocrResult || !this.ocrResult.trim()) {this.uiContext.getPromptAction().showToast({ message: $r('app.string.empty_toast') });return;}this.consigneeInfos = AddressParse.extractInfo(this.ocrResult, this.consigneeInfos);})
5、保存地址
為保存按鈕綁定事件,清空界面數據并提示保存結果。
修改Index.ets文件,封裝clearConsigneeInfos模擬保存操作后清空數據。
...// 保存地址,清空內容clearConsigneeInfos() {for (const item of this.consigneeInfos) {item.value = '';}this.ocrResult = '';}...
//保存地址按鈕
.onClick(() => {if (this.consigneeInfos[0].value && this.consigneeInfos[1].value && this.consigneeInfos[2].value) {this.uiContext.getPromptAction().showToast({ message: '保存成功' });this.clearConsigneeInfos();}})
至此,功能完成。
《鴻蒙應用開發從入門到項目實戰》系列文章持續更新中,歡迎關注!