diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d2ff20141ceed86d87c0ea5d99481973005bab2b --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +/.appanalyzer \ No newline at end of file diff --git a/AppScope/app.json5 b/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c25242ca247f07e5dbed51e9759e7c80c9462e4f --- /dev/null +++ b/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.corevisionkitocr", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:layered_image", + "label": "$string:app_name" + } +} diff --git a/AppScope/resources/base/element/string.json b/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..ebbaf9ef352ffde2fd465795500f743abc0cdcb4 --- /dev/null +++ b/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "CoreVisionKitOCR" + } + ] +} diff --git a/AppScope/resources/base/media/background.png b/AppScope/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..923f2b3f27e915d6871871deea0420eb45ce102f Binary files /dev/null and b/AppScope/resources/base/media/background.png differ diff --git a/AppScope/resources/base/media/foreground.png b/AppScope/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9427585b36d14b12477435b6419d1f07b3e0bb Binary files /dev/null and b/AppScope/resources/base/media/foreground.png differ diff --git a/AppScope/resources/base/media/layered_image.json b/AppScope/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/AppScope/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..18795a48d6b12fcdc1aa7bac9a9cb99f83815267 --- /dev/null +++ b/LICENSE @@ -0,0 +1,78 @@ + Copyright (c) 2025 Huawei Device Co., Ltd. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Apache License, Version 2.0 +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +1.You must give any other recipients of the Work or Derivative Works a copy of this License; and +2.You must cause any modified files to carry prominent notices stating that You changed the files; and +3.You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +4.If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.en.md b/README.en.md deleted file mode 100644 index d4f4c7d3cec9d1e7cd065e41093e083f165ef4ef..0000000000000000000000000000000000000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# CoreVisionKitOCR - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md index 06c459d54dfd006d8c792c7a679ae5fb75a88a89..4479cc8f0759a2dea4412d64b7d9091f65312927 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,75 @@ -# CoreVisionKitOCR +# 基于拍照识别能力实现文字自动填充 -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} +## 介绍 -#### 软件架构 -软件架构说明 +本示例基于基础视觉服务,使用`@kit.CoreVisionKit`提供的通用文字识别能力,通过拍照(CameraPicker)或者相册(PhotoViewPicker)方式,将印刷品文字(如:收货信息)转化为图像信息,再利用文字识别技术将图像信息转化为设备可以使用的文本字符,最后可以根据实际业务规则提取结构化数据。 +## 效果预览 -#### 安装教程 +| 主页 | 拍照 | 识别 | 保存 | +|----------------------------------------|----------------------------------------|---------------------------------------------|-----------------------------------------| +| ![主页](screenshots/device/1.png "主页") | ![拍照](screenshots/device/2.png "拍照") | ![识别](screenshots/device/3.png "识别") | ![保存](screenshots/device/4.png "保存") | -1. xxxx -2. xxxx -3. xxxx +使用说明: +1. 点击`图片识别`按钮,拉起`选择图片获取方式`的弹窗,选择`拍照`方式,通过对要识别的文字进行拍照获得要识别的图片。也可以选择`相册`方式,在图库中直接选择需要识别的图片。 +2. 识别出图片包含的文本信息后,会自动将文本内容填充到文本输入框。 +3. 点击`识别`按钮,会将文本框中的信息提取为结构化数据,显示到按钮下方的列表中。 +4. 点击`保存地址`按钮,提示保存成功,文本框旧的内容会自动清空。 -#### 使用说明 +## 工程目录 -1. xxxx -2. xxxx -3. xxxx +``` +entry/src/main/ +├──ets +| ├──common +| | ├──constants +| | | └──CommonConstants.ets // 公共常量类 +| | └──utils +| | ├──AddressParse.ets // 收货信息解析类 +| | ├──OCRManager.ets // 视觉识别类 +| | ├──PromptActionManager.ets // 弹窗管理类 +| | └──Logger.ets // 日志类 +| ├──entryability +| | └──EntryAbility.ets // 入口Ability +| ├──viewmodel +| | └──DataModel.ets // UI模型类 +| ├──views +| | ├──ConsigneeInfoItem.ets // 列表项UI +| | └──DialogBuilder.ets // 弹窗UI +| └──pages +| └──Index.ets // 首页 +└──resources // 资源目录 +``` -#### 参与贡献 +## 具体实现 -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request +通用文字识别能力,是调用`@kit.CoreVisionKit`的textRecognition.recognizeText()方法实现 +* 拍照:通过调用`@kit.CameraKit`的CameraPicker.pick()拍摄照片。交互界面由系统提供,无需申请相机权限。 +* 相册:通过调用`@kit.MediaLibraryKit`的photoAccessHelper.PhotoViewPicker对象的select()方法拉起图库,选择图片。 +* 视觉文字识别:通过调用`@kit.CoreVisionKit`的textRecognition.recognizeText()方法对图像信息进行识别。 +* 结构化数据提取:通过正则处理和提取格式化数据。示例中只是对常见的收货信息进行简单提取。如需覆盖全面复杂的场景,做到精确提取,可以考虑使用专业的云服务或NLP工具。 -#### 特技 +## 相关权限 -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) +无 + +## 约束与限制 + +1. 本示例仅支持标准系统上运行,支持设备:华为手机。 +2. Core Vision Kit仅支持中国境内(不包含中国香港、中国澳门、中国台湾)提供服务。 +3. HarmonyOS系统:HarmonyOS 5.1.1 Release及以上。 +4. DevEco Studio版本:DevEco Studio 5.1.1 Release及以上。 +5. HarmonyOS SDK版本:HarmonyOS 5.1.1 Release SDK及以上。 +6. 支持的图片格式:JPEG、JPG、PNG。 +7. 支持的语言:简体中文、英文、日文、韩文、繁体中文。 +8. 文本长度:不超过10000字符。 +9. 支持文档印刷体识别,在识别手写字体方面能力有所欠缺。 +10. 输入图像具有合适成像的质量(建议720p以上),100px<高度<15210px,100px<宽度<10000px,高宽比例建议10:1以下(高度小于宽度的10倍),接近手机屏幕高宽比例为宜。 +11. 拍摄角度与文本所在平面垂直方向的夹角应小于30度。 +12. 推荐使用以下常规的收货信息进行拍照识别: + + 1. 收货人:赵六 联系方式:13800000000 收货地址:广州市天河区体育西路18999号城建大厦66层 + 2. 张先生 (138-0000-0000) 收货地址: 北京市朝阳区建国路888号院5号楼3203室 + 3. 收件人:王工,联系电话:010-88881234,地址:海淀区中关村南大街55号院33号楼44单元302室 + 4. 广东省珠海市香洲区盘山路2688号幸运茶馆,陈先生,13500000000 \ No newline at end of file diff --git a/build-profile.json5 b/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..807c91e155fe6ca1b5ca44febf15cb793fad91f9 --- /dev/null +++ b/build-profile.json5 @@ -0,0 +1,43 @@ +{ + "app": { + "signingConfigs": [ + ], + "products": [ + { + "name": "default", + "signingConfig": "default", + "targetSdkVersion": "5.1.1(19)", + "compatibleSdkVersion": "5.1.1(19)", + "runtimeOS": "HarmonyOS", + "buildOption": { + "strictMode": { + "caseSensitiveCheck": true, + "useNormalizedOHMUrl": true + } + } + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/code-linter.json5 b/code-linter.json5 new file mode 100644 index 0000000000000000000000000000000000000000..073990fa45394e1f8e85d85418ee60a8953f9b99 --- /dev/null +++ b/code-linter.json5 @@ -0,0 +1,32 @@ +{ + "files": [ + "**/*.ets" + ], + "ignore": [ + "**/src/ohosTest/**/*", + "**/src/test/**/*", + "**/src/mock/**/*", + "**/node_modules/**/*", + "**/oh_modules/**/*", + "**/build/**/*", + "**/.preview/**/*" + ], + "ruleSet": [ + "plugin:@performance/recommended", + "plugin:@typescript-eslint/recommended" + ], + "rules": { + "@security/no-unsafe-aes": "error", + "@security/no-unsafe-hash": "error", + "@security/no-unsafe-mac": "warn", + "@security/no-unsafe-dh": "error", + "@security/no-unsafe-dsa": "error", + "@security/no-unsafe-ecdsa": "error", + "@security/no-unsafe-rsa-encrypt": "error", + "@security/no-unsafe-rsa-sign": "error", + "@security/no-unsafe-rsa-key": "error", + "@security/no-unsafe-dsa-key": "error", + "@security/no-unsafe-dh-key": "error", + "@security/no-unsafe-3des": "error" + } +} \ No newline at end of file diff --git a/entry/.gitignore b/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9247cc0d79c2f396ee169d4781b737e3305e97af --- /dev/null +++ b/entry/.gitignore @@ -0,0 +1,13 @@ +/node_modules +/oh_modules +/.preview +/.idea +/local.properties +**/build +**/.test +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +/.appanalyzer \ No newline at end of file diff --git a/entry/build-profile.json5 b/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..4d611879c7913fb0610c686e2399258ab3a6dad1 --- /dev/null +++ b/entry/build-profile.json5 @@ -0,0 +1,28 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + } + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/entry/hvigorfile.ts b/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0e3a1ab98a91bc918d6404b2413111a5011f14a --- /dev/null +++ b/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/entry/obfuscation-rules.txt b/entry/obfuscation-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..272efb6ca3f240859091bbbfc7c5802d52793b0b --- /dev/null +++ b/entry/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/entry/oh-package.json5 b/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..248c3b7541a589682a250f86a6d3ecf7414d2d6a --- /dev/null +++ b/entry/oh-package.json5 @@ -0,0 +1,10 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} + diff --git a/entry/src/main/ets/common/constants/CommonConstants.ets b/entry/src/main/ets/common/constants/CommonConstants.ets new file mode 100644 index 0000000000000000000000000000000000000000..29fb1c13065002eb55edd612f3e5a0c429c73e32 --- /dev/null +++ b/entry/src/main/ets/common/constants/CommonConstants.ets @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default class CommonConstants { + static NAME_LABEL: ResourceStr = $r('app.string.list_name_label'); + static PHONE_LABEL: ResourceStr = $r('app.string.list_phone_label'); + static ADDRESS_LABEL: ResourceStr = $r('app.string.list_address_label'); + static NAME_PLACEHOLDER: ResourceStr = $r('app.string.list_name_placeholder'); + static PHONE_PLACEHOLDER: ResourceStr = $r('app.string.list_phone_placeholder'); + static ADDRESS_PLACEHOLDER: ResourceStr = $r('app.string.list_address_placeholder'); +} + diff --git a/entry/src/main/ets/common/utils/AddressParse.ets b/entry/src/main/ets/common/utils/AddressParse.ets new file mode 100644 index 0000000000000000000000000000000000000000..d8ec0ce901a42231b93973e53b377e7ff40f9c14 --- /dev/null +++ b/entry/src/main/ets/common/utils/AddressParse.ets @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConsigneeInfo } from '../../viewmodel/DataModel'; + + +/** + * This example uses regular expression processing to extract formatted data, + * and simply extracts common recipient information. + * To cover comprehensive and complex scenarios and achieve accurate extraction, + * consider using professional cloud services or NLP tools. + */ +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 label + const nameFromTag = text.match(AddressParse.nameTagRegex); + if (nameFromTag) { + name = nameFromTag[1]; + } + + // Try to extract before or after the phone + if (!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 directly + if (!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 punctuation + const cleanedAddress = possibleAddress.replace(/^[::,,。、\s]+/, ''); + + if (cleanedAddress.length > 5) { + return cleanedAddress; + } + } + } + + // Try to remove name and phone number + let cleanedText = text; + if (name) { + cleanedText = cleanedText.replace(name, ''); + } + if (phone) { + cleanedText = cleanedText.replace(phone, ''); + } + + // Remove common distracting words + AddressParse.addressNoiseWords.forEach(word => { + cleanedText = cleanedText.replace(word, ''); + }); + + // Extract the longest text segment that may contain an address + const segments = cleanedText.split(/[\s,,。;;]+/).filter(seg => seg.length > 4); + if (segments.length > 0) { + + // The segment containing the address key is preferred + const 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 segment + return segments.reduce((longest, current) => + current.length > longest.length ? current : longest, ''); + } + + // Finally, return the entire text + return cleanedText; + } +} \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/Logger.ets b/entry/src/main/ets/common/utils/Logger.ets new file mode 100644 index 0000000000000000000000000000000000000000..ffece6fa4d298d993c6d0ac000e40e16cf98a9e0 --- /dev/null +++ b/entry/src/main/ets/common/utils/Logger.ets @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; + +export class Logger { + private static readonly DOMAIN: number = 0xFF00; + private static readonly TAG: string = 'com.example.corevisionkitocr'; + private static readonly PREFIX: string = '[ocr]'; + + public static debug(logTag: string, messageFormat: string, ...args: Object[]): void { + hilog.debug(Logger.DOMAIN, Logger.TAG, `${Logger.PREFIX} ${logTag}: ${messageFormat}`, args); + } + + public static info(logTag: string, messageFormat: string, ...args: Object[]): void { + hilog.info(Logger.DOMAIN, Logger.TAG, `${Logger.PREFIX} ${logTag}: ${messageFormat}`, args); + } + + public static warn(logTag: string, messageFormat: string, ...args: Object[]): void { + hilog.warn(Logger.DOMAIN, Logger.TAG, `${Logger.PREFIX} ${logTag}: ${messageFormat}`, args); + } + + public static error(logTag: string, messageFormat: string, ...args: Object[]): void { + hilog.error(Logger.DOMAIN, Logger.TAG, `${Logger.PREFIX} ${logTag}: ${messageFormat}`, args); + } + + public static fatal(logTag: string, messageFormat: string, ...args: Object[]): void { + hilog.fatal(Logger.DOMAIN, Logger.TAG, `${Logger.PREFIX} ${logTag}: ${messageFormat}`, args); + } + + private constructor() { + } +} diff --git a/entry/src/main/ets/common/utils/OCRManager.ets b/entry/src/main/ets/common/utils/OCRManager.ets new file mode 100644 index 0000000000000000000000000000000000000000..4252e3be3ab2069e4eaa5fc38e01dcdc97393709 --- /dev/null +++ b/entry/src/main/ets/common/utils/OCRManager.ets @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { textRecognition } from '@kit.CoreVisionKit'; +import { camera, cameraPicker } from '@kit.CameraKit'; +import { Logger } from './Logger'; +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 { + // The configuration information of cameraPicker + let 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) { + Logger.error('cameraPicker', 'camera picker result is empty'); + return ''; + } + loadingController.open(); + return OCRManager.recognizeText(result.resultUri); + } catch (error) { + loadingController.close(); + Logger.error('OCRManager', `recognizeByCamera failed, code is ${error.code}, message is ${error.message}`); + return ''; + } + } + + static async recognizeByAlbum(loadingController: CustomDialogController): Promise { + 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) { + Logger.error('photoViewPicker', 'photo view picker result is empty'); + return ''; + } + loadingController.open(); + return OCRManager.recognizeText(photoResult.photoUris[0]); + } catch (error) { + loadingController.close(); + Logger.error('OCRManager', `recognizeByAlbum failed, code is ${error.code}, message is ${error.message}`); + return ''; + } + } + + static async recognizeText(uri: string): Promise { + // 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 { + // Convert image resources to PixelMap + let 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; + } +} \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/PromptActionManager.ets b/entry/src/main/ets/common/utils/PromptActionManager.ets new file mode 100644 index 0000000000000000000000000000000000000000..5ac36b754484cf8f31678251810464caea8b287f --- /dev/null +++ b/entry/src/main/ets/common/utils/PromptActionManager.ets @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { promptAction } from '@kit.ArkUI'; +import { Logger } from './Logger'; + +/** + * Dialog management class + */ +export class PromptActionManager { + static ctx: UIContext; + static contentNode: ComponentContent; + static options: promptAction.BaseDialogOptions; + + static setCtx(ctx: UIContext) { + PromptActionManager.ctx = ctx; + } + + static setContentNode(contentNode: ComponentContent) { + 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) { + Logger.error('openCustomDialog', `openCustomDialog failed, code is ${error.code}, message is ${error.message}`); + } + } + + static closeCustomDialog() { + if (!PromptActionManager.contentNode) { + return; + } + try { + PromptActionManager.ctx.getPromptAction().closeCustomDialog( + PromptActionManager.contentNode + ) + } catch (error) { + Logger.error('openCustomDialog', `openCustomDialog failed, code is ${error.code}, message is ${error.message}`); + } + } +} \ No newline at end of file diff --git a/entry/src/main/ets/entryability/EntryAbility.ets b/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..bc9af5ce98616f1df4074a8cf49199f4398310cb --- /dev/null +++ b/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +const DOMAIN = 0x0000; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT); + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err) => { + if (err.code) { + hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); + return; + } + hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); + } +} \ No newline at end of file diff --git a/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..0a97e21bd7a15599af76a806695860ff1eb0ebfe --- /dev/null +++ b/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; + +const DOMAIN = 0x0000; + +export default class EntryBackupAbility extends BackupExtensionAbility { + async onBackup() { + hilog.info(DOMAIN, 'testTag', 'onBackup ok'); + await Promise.resolve(); + } + + async onRestore(bundleVersion: BundleVersion) { + hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion)); + await Promise.resolve(); + } +} \ No newline at end of file diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..2424aad964f5ab3beddc1e1fe59b81126248bac3 --- /dev/null +++ b/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ComponentContent, LoadingDialog } from '@kit.ArkUI'; +import { PromptActionManager } from '../common/utils/PromptActionManager'; +import { ConsigneeInfo, Params } from '../viewmodel/DataModel'; +import { AddressParse } from '../common/utils/AddressParse'; +import CommonConstants from '../common/constants/CommonConstants'; +import { ConsigneeInfoItem } from '../views/ConsigneeInfoItem'; +import { dialogBuilder } from '../views/DialogBuilder'; + + +@Entry +@Component +struct Index { + private uiContext: UIContext = this.getUIContext(); + @State consigneeInfos: ConsigneeInfo[] = []; + @State saveAvailable: boolean = false; + @State ocrResult: string = ''; + private resultController: TextAreaController = new TextAreaController(); + private loadingController: CustomDialogController = new CustomDialogController({ + builder: LoadingDialog({ + content: $r('app.string.loading_content') + }), + autoCancel: false + }); + private contentNode: ComponentContent = + new ComponentContent(this.uiContext, wrapBuilder(dialogBuilder), + new Params(this.uiContext, this.resultController, this.loadingController)); + + aboutToAppear(): void { + this.consigneeInfos = [ + new ConsigneeInfo(CommonConstants.NAME_LABEL, CommonConstants.NAME_PLACEHOLDER, ''), + new ConsigneeInfo(CommonConstants.PHONE_LABEL, CommonConstants.PHONE_PLACEHOLDER, ''), + new ConsigneeInfo(CommonConstants.ADDRESS_LABEL, CommonConstants.ADDRESS_LABEL, ''), + ]; + PromptActionManager.setCtx(this.uiContext); + PromptActionManager.setContentNode(this.contentNode); + PromptActionManager.setOptions({ + alignment: DialogAlignment.Center, + }); + } + + build() { + RelativeContainer() { + Column() { + Text($r('app.string.page_title')) + .id('title') + .width('100%') + .font({ size: 26, weight: 700 }) + .fontColor($r('app.color.title_color')) + .opacity(0.9) + .height(64) + .align(Alignment.TopStart) + Text($r('app.string.page_subtitle')) + .width('100%') + .padding({ left: 12, right: 12 }) + .font({ size: 14, weight: 400 }) + .fontColor($r('app.color.title_color')) + .opacity(0.6) + .lineHeight(19) + .margin({ bottom: 8 }) + Column() { + TextArea({ + placeholder: $r('app.string.input_placeholder'), + controller: this.resultController, + text: $$this.ocrResult + }) + .height(73) + .margin({ bottom: 12 }) + .backgroundColor($r('app.color.light_background')) + Row({ space: 12 }) { + Button() { + Row({ space: 8 }) { + Text() { + SymbolSpan($r('sys.symbol.camera')) + .fontSize(26) + .fontColor([$r('app.color.btn_font_color')]) + } + + Text($r('app.string.open_dialog_btn')) + .fontSize(16) + .fontColor($r('app.color.btn_font_color')) + } + } + .height(40) + .layoutWeight(1) + .backgroundColor($r('app.color.app_background')) + .onClick(() => { + PromptActionManager.openCustomDialog(); + }) + + Button($r('app.string.parse_btn')) + .height(40) + .layoutWeight(1) + .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); + }) + } + .width('100%') + .padding({ + left: 16, + right: 16, + }) + } + .backgroundColor($r('app.color.light_background')) + .borderRadius(16) + .padding({ + top: 16, + bottom: 16 + }) + + Column() { + List() { + ForEach(this.consigneeInfos, (item: ConsigneeInfo) => { + ListItem() { + ConsigneeInfoItem( + item, () => { + if (this.consigneeInfos[0].value && this.consigneeInfos[1].value && this.consigneeInfos[2].value) { + this.saveAvailable = true; + } else { + this.saveAvailable = false; + } + }) + } + }, (item: ConsigneeInfo, index: number) => JSON.stringify(item) + index) + } + .width('100%') + .height(LayoutPolicy.matchParent) + .scrollBar(BarState.Off) + .divider({ strokeWidth: 0.5, color: $r('app.color.divider_color') }) + .padding({ + left: 12, + right: 12, + top: 4, + bottom: 4 + }) + .borderRadius(16) + .backgroundColor($r('app.color.light_background')) + } + .borderRadius(16) + .margin({ top: 12 }) + .constraintSize({ minHeight: 150, maxHeight: '50%' }) + .backgroundColor($r('app.color.light_background')) + } + + if (this.saveAvailable) { + Button($r('app.string.save_btn'), { stateEffect: true }) + .width('100%') + .alignRules({ + bottom: { anchor: '__container__', align: VerticalAlign.Bottom } + }) + .onClick(() => { + if (this.consigneeInfos[0].value && this.consigneeInfos[1].value && this.consigneeInfos[2].value) { + this.uiContext.getPromptAction().showToast({ message: $r('app.string.save_success_toast') }); + this.clearConsigneeInfos(); + } + }) + } else { + Button($r('app.string.save_btn'), { stateEffect: false }) + .width('100%') + .opacity(0.4) + .backgroundColor($r('app.color.save_btn_disabled')) + .alignRules({ + bottom: { anchor: '__container__', align: VerticalAlign.Bottom } + }) + } + } + .height('100%') + .width('100%') + .alignRules({ + left: { anchor: '__container__', align: HorizontalAlign.Start } + }) + .padding({ + left: 16, + right: 16, + top: 24, + bottom: 24 + }) + .backgroundColor($r('app.color.app_background')) + .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) + } + + clearConsigneeInfos() { + for (const item of this.consigneeInfos) { + item.value = ''; + } + this.ocrResult = ''; + } +} + + + diff --git a/entry/src/main/ets/viewmodel/DataModel.ets b/entry/src/main/ets/viewmodel/DataModel.ets new file mode 100644 index 0000000000000000000000000000000000000000..f68dfa95d4105556bf505b413743f9905fa35e04 --- /dev/null +++ b/entry/src/main/ets/viewmodel/DataModel.ets @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@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; + } +} + +export class Params { + uiContext: UIContext; + textAreaController: TextAreaController; + loadingController: CustomDialogController; + + constructor(uiContext: UIContext, textAreaController: TextAreaController, loadingController: CustomDialogController) { + this.uiContext = uiContext; + this.textAreaController = textAreaController; + this.loadingController = loadingController; + } +} \ No newline at end of file diff --git a/entry/src/main/ets/views/ConsigneeInfoItem.ets b/entry/src/main/ets/views/ConsigneeInfoItem.ets new file mode 100644 index 0000000000000000000000000000000000000000..6df973356b80b218250157bee42ab6bb88b49801 --- /dev/null +++ b/entry/src/main/ets/views/ConsigneeInfoItem.ets @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import CommonConstants from '../common/constants/CommonConstants'; +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($r('app.color.item_label_color')) + .opacity(0.9) + .layoutWeight(1) + + TextArea({ placeholder: item.placeholder, text: item.value }) + .type(item.label === CommonConstants.PHONE_LABEL ? TextAreaType.PHONE_NUMBER : TextAreaType.NORMAL) + .fontSize(16) + .fontWeight(500) + .lineHeight(21) + .padding(0) + .borderRadius(0) + .textAlign(TextAlign.End) + .fontColor($r('app.color.item_label_color')) + .opacity(0.9) + .backgroundColor($r('app.color.light_background')) + .heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST) + .layoutWeight(2) + .onChange((value: string) => { + item.value = value; + checkAvailable?.(); + }) + } + .width('100%') + .constraintSize({ minHeight: 48 }) + .justifyContent(FlexAlign.SpaceBetween) +} \ No newline at end of file diff --git a/entry/src/main/ets/views/DialogBuilder.ets b/entry/src/main/ets/views/DialogBuilder.ets new file mode 100644 index 0000000000000000000000000000000000000000..9a15ceb32c681164fa27a7f9f3e80ca6f222b043 --- /dev/null +++ b/entry/src/main/ets/views/DialogBuilder.ets @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Params } from '../viewmodel/DataModel' +import { common } from '@kit.AbilityKit' +import { PromptActionManager } from '../common/utils/PromptActionManager' +import { OCRManager } from '../common/utils/OCRManager' + +@Builder +export function dialogBuilder(params: Params): void { + Column() { + Text($r('app.string.dialog_title')) + .font({ size: 20, weight: 700 }) + .lineHeight(27) + .margin({ bottom: 16 }) + Text($r('app.string.dialog_subtitle')) + .font({ size: 16, weight: 50 }) + .lineHeight(21) + .margin({ bottom: 8 }) + Column({ space: 8 }) { + Button($r('app.string.dialog_camera_btn')) + .width('100%') + .height(40) + .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); + } + }) + Button($r('app.string.dialog_photo_btn')) + .width('100%') + .height(40) + .fontColor($r('app.color.btn_font_color')) + .backgroundColor($r('app.color.light_background')) + .onClick(async () => { + PromptActionManager.closeCustomDialog(); + let text: string = + await OCRManager.recognizeByAlbum(params.loadingController); + params.loadingController.close(); + if (text) { + params.textAreaController.deleteText(); + params.textAreaController.addText(text); + } + }) + Button($r('app.string.dialog_cancel_btn')) + .width('100%') + .height(40) + .fontColor($r('app.color.btn_font_color')) + .backgroundColor($r('app.color.light_background')) + .onClick(() => { + PromptActionManager.closeCustomDialog(); + }) + } + } + .size({ width: 'calc(100% - 32vp)', height: 235 }) + .borderRadius(32) + .backgroundColor($r('app.color.light_background')) + .padding(16) +} \ No newline at end of file diff --git a/entry/src/main/module.json5 b/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..53024e8f020cc0824592631ba6924108c8028f0f --- /dev/null +++ b/entry/src/main/module.json5 @@ -0,0 +1,50 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "ohos.want.action.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "name": "EntryBackupAbility", + "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", + "type": "backup", + "exported": false, + "metadata": [ + { + "name": "ohos.extension.backup", + "resource": "$profile:backup_config" + } + ], + } + ] + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/color.json b/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..71181142d5159ed939cf48e6932fec6a74268371 --- /dev/null +++ b/entry/src/main/resources/base/element/color.json @@ -0,0 +1,36 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + }, + { + "name": "app_background", + "value": "#F1F3F5" + }, + { + "name": "save_btn_disabled", + "value": "#317AFF" + }, + { + "name": "btn_font_color", + "value": "#0A59F2" + }, + { + "name": "light_background", + "value": "#FFFFFF" + }, + { + "name": "item_label_color", + "value": "#000000" + }, + { + "name": "title_color", + "value": "#000000" + }, + { + "name": "divider_color", + "value": "#33000000" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/element/float.json b/entry/src/main/resources/base/element/float.json new file mode 100644 index 0000000000000000000000000000000000000000..33ea22304f9b1485b5f22d811023701b5d4e35b6 --- /dev/null +++ b/entry/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/entry/src/main/resources/base/element/string.json b/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..9c19e2f2a4a19a5db69e3f865908800f234b657e --- /dev/null +++ b/entry/src/main/resources/base/element/string.json @@ -0,0 +1,96 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "CoreVisionKitOCR" + }, + { + "name": "page_title", + "value": "Picture recognition" + }, + { + "name": "page_subtitle", + "value": "New address" + }, + { + "name": "dialog_title", + "value": "Picture recognition" + }, + { + "name": "dialog_subtitle", + "value": "Image capture options" + }, + { + "name": "dialog_camera_btn", + "value": "Photograph" + }, + { + "name": "dialog_photo_btn", + "value": "Album" + }, + { + "name": "dialog_cancel_btn", + "value": "cancel" + }, + { + "name": "loading_content", + "value": "Recognition..." + }, + { + "name": "input_placeholder", + "value": "Text recognized from images will appear here, automatically identifying shipping information.Example: Lili, 139******* " + }, + { + "name": "open_dialog_btn", + "value": "Recognition" + }, + { + "name": "parse_btn", + "value": "Parse" + }, + { + "name": "empty_toast", + "value": "Please enter the text to be parsed" + }, + { + "name": "save_btn", + "value": "Saving address" + }, + { + "name": "save_success_toast", + "value": "Saving successfully" + }, + { + "name": "list_name_label", + "value": "Name" + }, + { + "name": "list_phone_label", + "value": "Phone" + }, + { + "name": "list_address_label", + "value": "Address" + }, + { + "name": "list_name_placeholder", + "value": "Consignee's name" + }, + { + "name": "list_phone_placeholder", + "value": "Consignee's phone number" + }, + { + "name": "list_address_placeholder", + "value": "Full address and house number" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/background.png b/entry/src/main/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..923f2b3f27e915d6871871deea0420eb45ce102f Binary files /dev/null and b/entry/src/main/resources/base/media/background.png differ diff --git a/entry/src/main/resources/base/media/foreground.png b/entry/src/main/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..97014d3e10e5ff511409c378cd4255713aecd85f Binary files /dev/null and b/entry/src/main/resources/base/media/foreground.png differ diff --git a/entry/src/main/resources/base/media/layered_image.json b/entry/src/main/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/entry/src/main/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/startIcon.png b/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b Binary files /dev/null and b/entry/src/main/resources/base/media/startIcon.png differ diff --git a/entry/src/main/resources/base/profile/backup_config.json b/entry/src/main/resources/base/profile/backup_config.json new file mode 100644 index 0000000000000000000000000000000000000000..78f40ae7c494d71e2482278f359ec790ca73471a --- /dev/null +++ b/entry/src/main/resources/base/profile/backup_config.json @@ -0,0 +1,3 @@ +{ + "allowToBackupRestore": true +} \ No newline at end of file diff --git a/entry/src/main/resources/base/profile/main_pages.json b/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/entry/src/main/resources/dark/element/color.json b/entry/src/main/resources/dark/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..dde4ce9345199008bca13f986e9e67c5bba16f82 --- /dev/null +++ b/entry/src/main/resources/dark/element/color.json @@ -0,0 +1,36 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#000000" + }, + { + "name": "app_background", + "value": "#F1F3F5" + }, + { + "name": "save_btn_disabled", + "value": "#317AFF" + }, + { + "name": "btn_font_color", + "value": "#0A59F2" + }, + { + "name": "light_background", + "value": "#FFFFFF" + }, + { + "name": "item_label_color", + "value": "#000000" + }, + { + "name": "title_color", + "value": "#000000" + }, + { + "name": "divider_color", + "value": "#33000000" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/en_US/element/string.json b/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..9c19e2f2a4a19a5db69e3f865908800f234b657e --- /dev/null +++ b/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,96 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "CoreVisionKitOCR" + }, + { + "name": "page_title", + "value": "Picture recognition" + }, + { + "name": "page_subtitle", + "value": "New address" + }, + { + "name": "dialog_title", + "value": "Picture recognition" + }, + { + "name": "dialog_subtitle", + "value": "Image capture options" + }, + { + "name": "dialog_camera_btn", + "value": "Photograph" + }, + { + "name": "dialog_photo_btn", + "value": "Album" + }, + { + "name": "dialog_cancel_btn", + "value": "cancel" + }, + { + "name": "loading_content", + "value": "Recognition..." + }, + { + "name": "input_placeholder", + "value": "Text recognized from images will appear here, automatically identifying shipping information.Example: Lili, 139******* " + }, + { + "name": "open_dialog_btn", + "value": "Recognition" + }, + { + "name": "parse_btn", + "value": "Parse" + }, + { + "name": "empty_toast", + "value": "Please enter the text to be parsed" + }, + { + "name": "save_btn", + "value": "Saving address" + }, + { + "name": "save_success_toast", + "value": "Saving successfully" + }, + { + "name": "list_name_label", + "value": "Name" + }, + { + "name": "list_phone_label", + "value": "Phone" + }, + { + "name": "list_address_label", + "value": "Address" + }, + { + "name": "list_name_placeholder", + "value": "Consignee's name" + }, + { + "name": "list_phone_placeholder", + "value": "Consignee's phone number" + }, + { + "name": "list_address_placeholder", + "value": "Full address and house number" + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/zh_CN/element/string.json b/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..a6e833412b4c74c5e137ee368e9c382c6fbedc87 --- /dev/null +++ b/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,96 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "CoreVisionKitOCR" + }, + { + "name": "page_title", + "value": "图片识别" + }, + { + "name": "page_subtitle", + "value": "新增地址" + }, + { + "name": "dialog_title", + "value": "图片识别" + }, + { + "name": "dialog_subtitle", + "value": "选择获取图片的方式" + }, + { + "name": "dialog_camera_btn", + "value": "拍照" + }, + { + "name": "dialog_photo_btn", + "value": "相册" + }, + { + "name": "dialog_cancel_btn", + "value": "取消" + }, + { + "name": "loading_content", + "value": "图片识别中" + }, + { + "name": "input_placeholder", + "value": "图片识别的文本到此处,将自动识别收货信息 例:丽丽,139*******,广东省深圳市宝安区某小区" + }, + { + "name": "open_dialog_btn", + "value": "图片识别" + }, + { + "name": "parse_btn", + "value": "识别" + }, + { + "name": "empty_toast", + "value": "请输入要识别的文本" + }, + { + "name": "save_btn", + "value": "保存地址" + }, + { + "name": "save_success_toast", + "value": "保存成功" + }, + { + "name": "list_name_label", + "value": "收货人" + }, + { + "name": "list_phone_label", + "value": "电话" + }, + { + "name": "list_address_label", + "value": "地址" + }, + { + "name": "list_name_placeholder", + "value": "收货人姓名" + }, + { + "name": "list_phone_placeholder", + "value": "收货人电话" + }, + { + "name": "list_address_placeholder", + "value": "详细地址与门牌号" + } + ] +} \ No newline at end of file diff --git a/hvigor/hvigor-config.json5 b/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..6f008c99c91ca502036e67232e4c089e0421aefc --- /dev/null +++ b/hvigor/hvigor-config.json5 @@ -0,0 +1,22 @@ +{ + "modelVersion": "5.1.1", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} diff --git a/hvigorfile.ts b/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..47113e2e36ecefde41c136272a0bd6ff745cffe4 --- /dev/null +++ b/hvigorfile.ts @@ -0,0 +1,6 @@ +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/oh-package-lock.json5 b/oh-package-lock.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c2f6d1bc9cb330eeb990573aa7e74cbccfb64b61 --- /dev/null +++ b/oh-package-lock.json5 @@ -0,0 +1,28 @@ +{ + "meta": { + "stableOrder": true, + "enableUnifiedLockfile": false + }, + "lockfileVersion": 3, + "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", + "specifiers": { + "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0", + "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21" + }, + "packages": { + "@ohos/hamock@1.0.0": { + "name": "@ohos/hamock", + "version": "1.0.0", + "integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hamock/-/hamock-1.0.0.har", + "registryType": "ohpm" + }, + "@ohos/hypium@1.0.21": { + "name": "@ohos/hypium", + "version": "1.0.21", + "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.21.har", + "registryType": "ohpm" + } + } +} \ No newline at end of file diff --git a/oh-package.json5 b/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..052cc24d6e7b3f754ab5557652fd9db52c4c2549 --- /dev/null +++ b/oh-package.json5 @@ -0,0 +1,10 @@ +{ + "modelVersion": "5.1.1", + "description": "Please describe the basic information.", + "dependencies": { + }, + "devDependencies": { + "@ohos/hypium": "1.0.21", + "@ohos/hamock": "1.0.0" + } +} diff --git a/screenshots/device/1.png b/screenshots/device/1.png new file mode 100644 index 0000000000000000000000000000000000000000..78d0db42f20f51584346a6b993efd7792c6efaae Binary files /dev/null and b/screenshots/device/1.png differ diff --git a/screenshots/device/2.png b/screenshots/device/2.png new file mode 100644 index 0000000000000000000000000000000000000000..10488d38b06c6bafc053801a840c1108602866c3 Binary files /dev/null and b/screenshots/device/2.png differ diff --git a/screenshots/device/3.png b/screenshots/device/3.png new file mode 100644 index 0000000000000000000000000000000000000000..6bad473176bad235af2d919679d179b3de6bddd0 Binary files /dev/null and b/screenshots/device/3.png differ diff --git a/screenshots/device/4.png b/screenshots/device/4.png new file mode 100644 index 0000000000000000000000000000000000000000..5d2afc54a71372e8e234ae0b60ebb17e4b468983 Binary files /dev/null and b/screenshots/device/4.png differ