Compare commits

...

137 Commits

Author SHA1 Message Date
)s f7ea93b844
Update README.md 2024-05-11 10:35:43 +08:00
maxmon 94cfa14b60 doc: 添加示例数据 2024-04-30 01:39:03 +08:00
maxmon bf8077f056 doc: flask安装最新版 2024-04-30 01:03:49 +08:00
maxmon 132880715c feat: 放大标注区域 2024-04-24 22:12:16 +08:00
maxmon 3af5ddebc5 feat: 支持外部访问 2024-04-24 22:10:29 +08:00
maxmon a11af98ee5 feat(自动标注): 引入auto_anno_2,支持文本分类、实体抽取接口 2024-01-17 22:15:36 +08:00
maxmon 3e41a34d8a feat: 支持图像分类 2023-09-26 22:53:25 +08:00
maxmon a1ccc5450d doc: 增加后续 CV 方向计划 2023-08-18 01:18:02 +08:00
maxmon 9c13a349ce feat: 点标注接入 auto_anno 自动检测基础目标 2023-08-18 00:57:48 +08:00
maxmon 75fb815d94 fix: 修复没有项目时的报错 2023-04-16 19:46:36 +08:00
maxmon 924e85bea8 document: 完成基础关系标注功能 2023-04-16 19:40:24 +08:00
maxmon 36273071a4 chore: 打包项目 2023-04-16 19:40:05 +08:00
maxmon 00ef3be3df style: 去掉无用的打印 2023-04-16 19:39:55 +08:00
maxmon a594b620f1 feat: 完成关系标注接口联调 2023-04-16 19:35:42 +08:00
maxmon 383534037a refactor: 优化箭头展示,并适配屏幕变化 2023-04-16 19:13:49 +08:00
maxmon 585cd1e65f feat: 完成关系箭头标注,右键删除 2023-04-16 18:53:18 +08:00
maxmon 06d4378c73 feat: 初步接入关系标注 2023-04-16 17:49:02 +08:00
maxmon dec3115831 feat: 支持上传换行分割的.txt文件 2023-04-16 17:45:16 +08:00
maxmon e0beff9fc7 document: 完成基础人类反馈排序功能 2023-04-15 23:25:48 +08:00
maxmon 1c0c2c8d02 chore: 打包项目 2023-04-15 23:25:18 +08:00
maxmon b596ba3278 fix: 修复点击下一页无反应的问题 2023-04-15 23:23:35 +08:00
maxmon 39960affb2 feat: 用类文本框显示文本 2023-04-15 23:21:43 +08:00
maxmon 4d9a0006b6 style: 去掉无关引用 2023-04-15 23:21:25 +08:00
maxmon ca2fb49112 feat: 支持上传jsonl文件,并支持将值按特定标记分割 2023-04-14 00:50:09 +08:00
maxmon 50743b4225 refactor(point): 手机端点击相同类型的关键点,可以删除 2023-04-14 00:01:17 +08:00
maxmon 7f485aa152 refactor(rlhf): 手机去掉hover效果 2023-04-13 23:33:09 +08:00
maxmon be30ca9771 refactor: 适配多行文本 2023-04-13 23:27:57 +08:00
maxmon 25684c211d feat: 支持局域网可访问,用ifconfig/ipconfig获取本机ip 2023-04-13 23:27:38 +08:00
maxmon 9cf736ba33 feat: 增加rlhf排序的基础逻辑 2023-04-13 01:51:14 +08:00
maxmon 9f9b3db46c refactor: 用透明度来代表是否选中 2023-04-13 00:39:54 +08:00
maxmon f1168a9315 feat: 项目按创建顺序,从新到旧排序 2023-04-13 00:20:57 +08:00
maxmon 10331c932f feat: 创建项目时,创建data和anno子目录 2023-04-13 00:08:53 +08:00
maxmon 50d2bd5406 feat: 统一下载地址,并规范下载文件名 2023-04-13 00:02:44 +08:00
maxmon f628c10db0 fix: 修复数据目录迁移导致的目录错误问题 2023-04-12 23:42:59 +08:00
maxmon e40e2678ad refactor: 优化标题和左侧列表展示,防止遮挡贴边 2023-04-12 23:19:36 +08:00
maxmon e6028a8b18 document: 更新开发进度,准备研发RLHF标注 2023-04-12 00:57:04 +08:00
maxmon 41c9bd3ac7 delete: 删除默认项目 2023-04-12 00:51:48 +08:00
maxmon 366cff7d19 refactor: 精简代码,标注以文件为单位存储 2023-04-12 00:42:03 +08:00
maxmon 7fc844b27c feat: 缓存队列 2023-04-11 23:30:36 +08:00
maxmon ebb0dafc82 refactor: 拟加载下一页时不显示下方的第2页 2022-08-10 08:19:30 +08:00
maxmon 9a79eb7cce refactor: 右侧标注太多时出现滚动条 2022-08-10 08:18:54 +08:00
maxmon 45d1da4fd8 fix: 修复单个文件用zip解压后文件名乱码的问题 2022-08-09 21:07:43 +08:00
maxmon c85261dce7 fix: 修复访问过频繁导致标注跑到其他文件的问题 2022-04-22 20:03:36 +08:00
maxmon a7ad14b26d chore: 打包项目 2022-04-16 23:09:32 +08:00
maxmon caf28fba28 fix(瀑布式流): 修复页码持续上升的问题,如果最新的页码没有数据,计数返回上一页 2022-04-16 23:06:46 +08:00
maxmon 600f636819 refactor: 右键在手机上的操作为长按,所以手机上统一长按为删除 2022-04-16 22:57:43 +08:00
maxmon 9a002f1df8 refactor: point改成points,为后续的框、多边形区域做统一 2022-04-16 22:24:36 +08:00
maxmon 1b2cd2deeb feat: 点标注文件下载 2022-04-16 22:16:52 +08:00
maxmon fc9d458495 refactor: 右侧删除功能通用化,适配分类、点标注 2022-04-16 22:16:27 +08:00
maxmon e6efbe5af9 feat: 接入真实类别的颜色 2022-04-16 20:35:51 +08:00
maxmon 9394e61f57 feat: 点标注结果接入后台 2022-04-16 18:29:46 +08:00
maxmon dc1670bb4c feat: 支持左键添加点,右键删除点 2022-04-16 18:03:11 +08:00
maxmon 972028ab9d feat: 支持图片上传并显示 2022-04-16 12:51:25 +08:00
maxmon b5b6febf9e fix: 修复出现空标注的情况 2022-04-07 23:45:25 +08:00
maxmon bc185986f5 chore: 打包项目 2022-04-07 23:20:15 +08:00
maxmon 81f260b13e refactor: 新用户增加删除的使用提示 2022-04-07 23:19:10 +08:00
maxmon e623e3dbc4 feat: 瀑布式列表以及当前文件名显示 2022-04-07 22:59:48 +08:00
maxmon 86d73417b7 refactor(ner): 右侧结果标签鼠标悬浮增加删除按钮 2022-04-07 22:14:14 +08:00
maxmon 30b34ceca5 feat: 手机操作细节优化 2022-04-07 21:03:07 +08:00
maxmon 71435a451a feat: 支持用手机标注ner 2022-04-07 20:58:51 +08:00
maxmon a9e7a08805 feat: 支持用手机标注ner 2022-04-07 20:26:04 +08:00
马琦钧 ac1d2d41e4 chore: 打包项目 2021-08-08 22:30:14 +08:00
马琦钧 14cba39b15 feat: 更换选中样式为黑边框,取消未选中的灰度化 2021-08-08 22:28:27 +08:00
马琦钧 22db97e502 chore: 打包项目 2021-08-08 18:07:58 +08:00
马琦钧 794eb0f1e6 refactor: 未选中的标签默认为灰黑色,用于增强和已选中的区分 2021-08-08 18:07:40 +08:00
马琦钧 8542dfd0d4 chore: 打包项目 2021-08-08 17:50:40 +08:00
马琦钧 560c8f20b5 feat: 加一首诗 2021-08-08 17:49:36 +08:00
马琦钧 bf98572e6c refactor: 文本分类的文本体现出换行 2021-08-08 17:48:38 +08:00
马琦钧 ef5d903ef4 fix: 修复命名实体识别无法选择标签的问题 2021-08-08 17:29:11 +08:00
马琦钧 a929294bc9 refactor: 如果文件未选中,就选中第一个 2021-08-08 17:15:30 +08:00
马琦钧 245acea3ab fix: 修复重试时data被改为字符串的问题 2021-08-08 16:58:38 +08:00
马琦钧 dbd47f5a36 feat: unicode编码转换 2021-08-08 13:27:37 +08:00
马琦钧 93a67b9265 chore: 打包项目 2021-08-08 01:46:33 +08:00
马琦钧 a340136f8c style: 修复lint报错 2021-08-08 01:45:11 +08:00
马琦钧 e48a7653c7 refactor: 通过文件形式下载分类结果 2021-08-08 01:28:57 +08:00
马琦钧 4bb5838795 feat: 增加文本分类功能 2021-08-08 01:10:51 +08:00
xgdyp d9dbf5cbc7 update 2021-08-06 18:09:56 +08:00
xgdyp 3f1390a62c add get_labels 2021-08-06 11:37:54 +08:00
xgdyp 1c79dfb31e add get_labels 2021-08-06 11:36:25 +08:00
xgdyp 0c185cbcfe add get labels api 2021-08-06 01:01:00 +08:00
maxmon d7f546d5dd chore: 打包项目 2021-07-14 23:41:10 +08:00
maxmon ec99bc5b11 feat: 增加删除项目功能 2021-07-14 23:39:53 +08:00
xgdyp e73e573dd5 add delete project api 2021-07-14 20:33:58 +08:00
Sm1les e8c2c06dd6 指定flask版本 2021-07-09 23:11:05 +08:00
maxmon 0b280bc42c Merge branch 'main' of https://github.com/datawhalechina/whale-anno into main 2021-07-09 22:55:51 +08:00
maxmon 278a8baf8f chore: 打包项目 2021-07-09 22:55:47 +08:00
maxmon e8a242f8d1 feat: 优先从10种初始颜色中获取随机颜色 2021-07-09 22:48:54 +08:00
xgdyp 9b00375d93 restrict file type 2021-07-09 22:37:20 +08:00
maxmon ac9817acd3 feat: 本地版支持实体类型修改 2021-07-09 22:27:14 +08:00
maxmon f11f05f5e9 refactor: 只有1页就不展示页码 2021-07-09 22:17:09 +08:00
maxmon 8cffeb1e5c refactor: 去掉右侧标注结果中的标签缩写 2021-07-09 22:03:58 +08:00
maxmon b4ffdbe89e fix: 修复文本过长导致的滚动条出现,影响标注定位 2021-07-09 22:02:19 +08:00
xgdyp 8212a2b32f change to flask 2.0 2021-07-09 21:52:28 +08:00
maxmon eaa98e6210 refactor: 调整压缩包支持范围的文案和限制 2021-07-09 21:50:53 +08:00
xgdyp 223aba983f update gitignore 2021-07-09 18:55:14 +08:00
xgdyp a3684d1737 add test project 2021-07-09 15:53:58 +08:00
xgdyp 47a97f2b0e fix gitignore 2021-07-09 10:52:16 +08:00
xgdyp 3a819d0e2c remove rar 7z type 2021-07-07 20:03:30 +08:00
xgdyp a6c14f75d6 fix result problem in Windows 2021-07-07 00:13:37 +08:00
xgdyp 2d2939cb4d update .gitignore 2021-07-06 22:01:03 +08:00
xgdyp 2721da41c6 gitignore 2021-07-06 21:59:10 +08:00
xgdyp 0111361c72 7.6 support more file type and fix some problems 2021-07-06 21:52:35 +08:00
maxmon 3b0936c6ac feat: 调整压缩文案并打包提交 2021-07-06 20:43:47 +08:00
maxmon 493b575a16 Merge branch 'main' of https://github.com/datawhalechina/whale-anno into main 2021-07-06 20:29:24 +08:00
maxmon d4a704f47a feat: 打包前端代码 2021-07-06 20:27:59 +08:00
maxmon 3b96cad394 feat: 适配支持的压缩以及对应文案 2021-07-06 20:26:33 +08:00
Sm1les 4d529677f0 add 翔宇 2021-07-06 14:32:35 +08:00
maxmon d4150494ab feat: 非单机版直接通过url下载标注记录 2021-07-05 22:06:19 +08:00
maxmon 292e3026df feat: 配置页支持上传zip文本压缩文件 2021-07-05 21:46:39 +08:00
xgdyp 9947df004f 7.1批量添加数据集、导出结果的后端实现 2021-07-02 00:56:47 +08:00
xgdyp 6d93383c12 Merge branch 'main' of https://github.com/datawhalechina/whale-anno into main
merge to push
2021-07-02 00:27:13 +08:00
xgdyp 13091c886f 7.1批量添加数据集、导出结果的后端实现 2021-07-02 00:19:42 +08:00
Sm1les d017913fd4 fix config 2021-06-24 22:47:53 +08:00
Sm1les f8f5a24055 更新doc 2021-06-24 22:33:36 +08:00
Sm1les cac96c7ec1 Merge branch 'main' of github.com:datawhalechina/whale-anno into main 2021-06-24 22:19:10 +08:00
Sm1les 39d7306b8f 简化readme 2021-06-24 22:18:46 +08:00
Sm1les 3ed66f6a5d 更新readme 2021-06-24 22:15:36 +08:00
马琦钧 3b84a4f720 + 增加后端接口测试脚本 2021-06-24 13:36:40 +08:00
马琦钧 11a02909ca + 打包v1.2.10前端代码 2021-06-24 12:40:03 +08:00
Sm1les 36f8eb8929 更新readme 2021-06-22 23:32:48 +08:00
Sm1les 7f9676262e 更新使用教程 2021-06-22 23:32:00 +08:00
Sm1les 0830b1c158 更新说明文档 2021-06-21 21:02:43 +08:00
Sm1les db4225b641 Merge branch 'main' of github.com:datawhalechina/whale-anno into main 2021-06-21 21:01:39 +08:00
Sm1les 645e7718b1 更新说明文档 2021-06-21 20:59:23 +08:00
)s ea111e4eb6
Create LICENSE 2021-06-21 20:51:36 +08:00
Sm1les 95d51a505c 更新说明文档 2021-06-21 20:49:50 +08:00
Sm1les c5c55d1da6 更新说明文档 2021-06-21 20:44:48 +08:00
Sm1les 84f853a670 调整文档 2021-06-21 20:40:49 +08:00
maxmon 506f4755e8
+ 增加快速使用的视频(无声、无字幕版) 2021-06-21 04:36:35 +08:00
maxmon 5c411778be
+ 增加单机版下载说明 2021-06-21 04:34:43 +08:00
maxmon a6e09b03ba
* 微调快速使用文案的细节 2021-06-21 04:30:23 +08:00
maxmon 070235efef
* 优化快速使用文档的展示 2021-06-21 04:08:25 +08:00
maxmon 2bafab2a36 + 初始化纯中文文本的快速使用说明 2021-06-21 04:00:23 +08:00
maxmon c9fb7916aa + 调整标注内容传输结构,取消json转义,去除导出中的isSmall 2021-06-21 03:26:23 +08:00
maxmon 81f191f983 + 清除无关的项目文件夹,并忽略项目文件夹 2021-06-21 01:07:40 +08:00
maxmon 2130df7bb6 Merge branch 'main' of https://github.com/datawhalechina/whale-anno into main 2021-06-19 03:06:30 +08:00
maxmon 0dfd48da68 后端增加文件服务,可直接访问前端已打包的页面,无需再开一个前端端口 2021-06-13 17:58:10 +08:00
74 changed files with 2764 additions and 17878 deletions

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
.idea/
be/.idea
__pycache__
/be/app/projects/*

875
LICENSE
View File

@ -1,201 +1,674 @@
Apache License GNU GENERAL PUBLIC LICENSE
Version 2.0, January 2004 Version 3, 29 June 2007
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
1. Definitions.
Preamble
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document. The GNU General Public License is a free, copyleft license for
software and other kinds of works.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License. The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
"Legal Entity" shall mean the union of the acting entity and all the GNU General Public License is intended to guarantee your freedom to
other entities that control, are controlled by, or are under common share and change all versions of a program--to make sure it remains free
control with that entity. For the purposes of this definition, software for all its users. We, the Free Software Foundation, use the
"control" means (i) the power, direct or indirect, to cause the GNU General Public License for most of our software; it applies also to
direction or management of such entity, whether by contract or any other work released this way by its authors. You can apply it to
otherwise, or (ii) ownership of fifty percent (50%) or more of the your programs, too.
outstanding shares, or (iii) beneficial ownership of such entity.
When we speak of free software, we are referring to freedom, not
"You" (or "Your") shall mean an individual or Legal Entity price. Our General Public Licenses are designed to make sure that you
exercising permissions granted by this License. have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
"Source" form shall mean the preferred form for making modifications, want it, that you can change the software or use pieces of it in new
including but not limited to software source code, documentation free programs, and that you know you can do these things.
source, and configuration files.
To protect your rights, we need to prevent others from denying you
"Object" form shall mean any form resulting from mechanical these rights or asking you to surrender the rights. Therefore, you have
transformation or translation of a Source form, including but certain responsibilities if you distribute copies of the software, or if
not limited to compiled object code, generated documentation, you modify it: responsibilities to respect the freedom of others.
and conversions to other media types.
For example, if you distribute copies of such a program, whether
"Work" shall mean the work of authorship, whether in Source or gratis or for a fee, you must pass on to the recipients the same
Object form, made available under the License, as indicated by a freedoms that you received. You must make sure that they, too, receive
copyright notice that is included in or attached to the work or can get the source code. And you must show them these terms so they
(an example is provided in the Appendix below). know their rights.
"Derivative Works" shall mean any work, whether in Source or Object Developers that use the GNU GPL protect your rights with two steps:
form, that is based on (or derived from) the Work and for which the (1) assert copyright on the software, and (2) offer you this License
editorial revisions, annotations, elaborations, or other modifications giving you legal permission to copy, distribute and/or modify it.
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain For the developers' and authors' protection, the GPL clearly explains
separable from, or merely link (or bind by name) to the interfaces of, that there is no warranty for this free software. For both users' and
the Work and Derivative Works thereof. authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
"Contribution" shall mean any work of authorship, including authors of previous versions.
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally Some devices are designed to deny users access to install or run
submitted to Licensor for inclusion in the Work by the copyright owner modified versions of the software inside them, although the manufacturer
or by an individual or Legal Entity authorized to submit on behalf of can do so. This is fundamentally incompatible with the aim of
the copyright owner. For the purposes of this definition, "submitted" protecting users' freedom to change the software. The systematic
means any form of electronic, verbal, or written communication sent pattern of such abuse occurs in the area of products for individuals to
to the Licensor or its representatives, including but not limited to use, which is precisely where it is most unacceptable. Therefore, we
communication on electronic mailing lists, source code control systems, have designed this version of the GPL to prohibit the practice for those
and issue tracking systems that are managed by, or on behalf of, the products. If such problems arise substantially in other domains, we
Licensor for the purpose of discussing and improving the Work, but stand ready to extend this provision to those domains in future versions
excluding communication that is conspicuously marked or otherwise of the GPL, as needed to protect the freedom of users.
designated in writing by the copyright owner as "Not a Contribution."
Finally, every program is threatened constantly by software patents.
"Contributor" shall mean Licensor and any individual or Legal Entity States should not allow patents to restrict development and use of
on behalf of whom a Contribution has been received by Licensor and software on general-purpose computers, but in those that do, we wish to
subsequently incorporated within the Work. avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
2. Grant of Copyright License. Subject to the terms and conditions of patents cannot be used to render the program non-free.
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable The precise terms and conditions for copying, distribution and
copyright license to reproduce, prepare Derivative Works of, modification follow.
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form. TERMS AND CONDITIONS
3. Grant of Patent License. Subject to the terms and conditions of 0. Definitions.
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable "This License" refers to version 3 of the GNU General Public License.
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work, "Copyright" also means copyright-like laws that apply to other kinds of
where such license applies only to those patent claims licensable works, such as semiconductor masks.
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s) "The Program" refers to any copyrightable work licensed under this
with the Work to which such Contribution(s) was submitted. If You License. Each licensee is addressed as "you". "Licensees" and
institute patent litigation against any entity (including a "recipients" may be individuals or organizations.
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct To "modify" a work means to copy from or adapt all or part of the work
or contributory patent infringement, then any patent licenses in a fashion requiring copyright permission, other than the making of an
granted to You under this License for that Work shall terminate exact copy. The resulting work is called a "modified version" of the
as of the date such litigation is filed. earlier work or a work "based on" the earlier work.
4. Redistribution. You may reproduce and distribute copies of the A "covered work" means either the unmodified Program or a work based
Work or Derivative Works thereof in any medium, with or without on the Program.
modifications, and in Source or Object form, provided that You
meet the following conditions: To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
(a) You must give any other recipients of the Work or infringement under applicable copyright law, except executing it on a
Derivative Works a copy of this License; and computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
(b) You must cause any modified files to carry prominent notices public, and in some countries other activities as well.
stating that You changed the files; and
To "convey" a work means any kind of propagation that enables other
(c) You must retain, in the Source form of any Derivative Works parties to make or receive copies. Mere interaction with a user through
that You distribute, all copyright, patent, trademark, and a computer network, with no transfer of a copy, is not conveying.
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of An interactive user interface displays "Appropriate Legal Notices"
the Derivative Works; and to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
(d) If the Work includes a "NOTICE" text file as part of its tells the user that there is no warranty for the work (except to the
distribution, then any Derivative Works that You distribute must extent that warranties are provided), that licensees may convey the
include a readable copy of the attribution notices contained work under this License, and how to view a copy of this License. If
within such NOTICE file, excluding those notices that do not the interface presents a list of user commands or options, such as a
pertain to any part of the Derivative Works, in at least one menu, a prominent item in the list meets this criterion.
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or 1. Source Code.
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and The "source code" for a work means the preferred form of the work
wherever such third-party notices normally appear. The contents for making modifications to it. "Object code" means any non-source
of the NOTICE file are for informational purposes only and form of a work.
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside A "Standard Interface" means an interface that either is an official
or as an addendum to the NOTICE text from the Work, provided standard defined by a recognized standards body, or, in the case of
that such additional attribution notices cannot be construed interfaces specified for a particular programming language, one that
as modifying the License. is widely used among developers working in that language.
You may add Your own copyright statement to Your modifications and The "System Libraries" of an executable work include anything, other
may provide additional or different license terms and conditions than the work as a whole, that (a) is included in the normal form of
for use, reproduction, or distribution of Your modifications, or packaging a Major Component, but which is not part of that Major
for any such Derivative Works as a whole, provided Your use, Component, and (b) serves only to enable use of the work with that
reproduction, and distribution of the Work otherwise complies with Major Component, or to implement a Standard Interface for which an
the conditions stated in this License. implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
5. Submission of Contributions. Unless You explicitly state otherwise, (kernel, window system, and so on) of the specific operating system
any Contribution intentionally submitted for inclusion in the Work (if any) on which the executable work runs, or a compiler used to
by You to the Licensor shall be under the terms and conditions of produce the work, or an object code interpreter used to run it.
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify The "Corresponding Source" for a work in object code form means all
the terms of any separate license agreement you may have executed the source code needed to generate, install, and (for an executable
with Licensor regarding such Contributions. work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
6. Trademarks. This License does not grant permission to use the trade System Libraries, or general-purpose tools or generally available free
names, trademarks, service marks, or product names of the Licensor, programs which are used unmodified in performing those activities but
except as required for reasonable and customary use in describing the which are not part of the work. For example, Corresponding Source
origin of the Work and reproducing the content of the NOTICE file. includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
7. Disclaimer of Warranty. Unless required by applicable law or linked subprograms that the work is specifically designed to require,
agreed to in writing, Licensor provides the Work (and each such as by intimate data communication or control flow between those
Contributor provides its Contributions) on an "AS IS" BASIS, subprograms and other parts of the work.
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions The Corresponding Source need not include anything that users
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A can regenerate automatically from other parts of the Corresponding
PARTICULAR PURPOSE. You are solely responsible for determining the Source.
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License. The Corresponding Source for a work in source code form is that
same work.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise, 2. Basic Permissions.
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be All rights granted under this License are granted for the term of
liable to You for damages, including any direct, indirect, special, copyright on the Program, and are irrevocable provided the stated
incidental, or consequential damages of any character arising as a conditions are met. This License explicitly affirms your unlimited
result of this License or out of the use or inability to use the permission to run the unmodified Program. The output from running a
Work (including but not limited to damages for loss of goodwill, covered work is covered by this License only if the output, given its
work stoppage, computer failure or malfunction, or any and all content, constitutes a covered work. This License acknowledges your
other commercial damages or losses), even if such Contributor rights of fair use or other equivalent, as provided by copyright law.
has been advised of the possibility of such damages.
You may make, run and propagate covered works that you do not
9. Accepting Warranty or Additional Liability. While redistributing convey, without conditions so long as your license otherwise remains
the Work or Derivative Works thereof, You may choose to offer, in force. You may convey covered works to others for the sole purpose
and charge a fee for, acceptance of support, warranty, indemnity, of having them make modifications exclusively for you, or provide you
or other liability obligations and/or rights consistent with this with facilities for running those works, provided that you comply with
License. However, in accepting such obligations, You may act only the terms of this License in conveying all material for which you do
on Your own behalf and on Your sole responsibility, not on behalf not control copyright. Those thus making or running the covered works
of any other Contributor, and only if You agree to indemnify, for you must do so exclusively on your behalf, under your direction
defend, and hold each Contributor harmless for any liability and control, on terms that prohibit them from making any copies of
incurred by, or claims asserted against, such Contributor by reason your copyrighted material outside their relationship with you.
of your accepting any such warranty or additional liability.
Conveying under any other circumstances is permitted solely under
END OF TERMS AND CONDITIONS the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
APPENDIX: How to apply the Apache License to your work.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]" No covered work shall be deemed part of an effective technological
replaced with your own identifying information. (Don't include measure under any applicable law fulfilling obligations under article
the brackets!) The text should be enclosed in the appropriate 11 of the WIPO copyright treaty adopted on 20 December 1996, or
comment syntax for the file format. We also recommend that a similar laws prohibiting or restricting circumvention of such
file or class name and description of purpose be included on the measures.
same "printed page" as the copyright notice for easier
identification within third-party archives. When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
Copyright [Datawhale] [name of copyright owner] is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
Licensed under the Apache License, Version 2.0 (the "License"); modification of the work as a means of enforcing, against the work's
you may not use this file except in compliance with the License. users, your or third parties' legal rights to forbid circumvention of
You may obtain a copy of the License at technological measures.
http://www.apache.org/licenses/LICENSE-2.0 4. Conveying Verbatim Copies.
Unless required by applicable law or agreed to in writing, software You may convey verbatim copies of the Program's source code as you
distributed under the License is distributed on an "AS IS" BASIS, receive it, in any medium, provided that you conspicuously and
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. appropriately publish on each copy an appropriate copyright notice;
See the License for the specific language governing permissions and keep intact all notices stating that this License and any
limitations under the License. non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,19 +1,78 @@
## whale-anno # whaleAnno
Datawhale自研数据标注工具让标注更简单
<a name="快速体验"></a> Datawhale自研数据标注工具
## 快速体验
- PC端更简单的NER标注工具https://tekii.cn/ner/
- 代码体验:从[快速开始](./doc/doc_ch/quickstart.md)开始
<a name="许可证书"></a> ## 功能开发进度
## 许可证书
本项目的发布受<a href="https://github.com/datawhalechina/whale-anno/blob/main/LICENSE">Apache 2.0 license</a>许可认证。
<a name="贡献代码"></a> - NLP
## 贡献代码 - [X] 命名实体识别
我们非常欢迎你为whale-anno贡献代码也十分感谢你的反馈。 - [X] 文本分类
- [X] 人类反馈强化学习
- [X] 关系标注
- CV
- [X] 关键点
- [X] 图像分类
- [ ] 目标检测
- [ ] 图像分割
- 非常感谢 [谢文睿](https://github.com/Sm1les) 贡献了NER标注工具的概念想法 ## 快速开始
- 非常感谢 [马琦钧](https://github.com/Skypow2012) 贡献了NER标注工具的前端代码并编写了中文文档
- 非常感谢 付文豪 贡献了NER标注工具的后端代码 ### 环境配置
#### Python 3
经测试whaleAnno后端代码可在Python 3.7.9上运行,您也可以测试其他版本,一般建议安装最新版
### 克隆项目
```shell
git clone https://github.com/datawhalechina/whale-anno.git
```
### 安装依赖
```shell
# 下载后端依赖
python3 -m pip install flask -U
```
后端只依赖了flask这个第三方库
### 启动项目
打开终端
```shell
# 进入后端目录
cd ./be
# 启动后端脚本
python3 ./run.py
```
此时项目会被启动在http://localhost:9060/index.html
### 开始使用
打开上述地址,然后点击[这里](https://www.bilibili.com/video/BV1v64y197iA?p=2)查看使用教程。此外我们还提供了一个用于临时标注少量数据的单机版本目前仅支持Windows点击[这里](https://github.com/datawhalechina/whale-anno/releases)去下载,点击[这里](https://www.bilibili.com/video/BV1v64y197iA?p=1)查看单机版使用教程
### 示例数据
图片、文本的示例数据,可以在[这里](https://www.modelscope.cn/datasets/maxmon/whale-anno-example/files)下载
## 开发团队
| 职责 | 名单 |
| :------------: | :-------------------------------------: |
| **PM** | [谢文睿](https://github.com/Sm1les) |
| **前端** | [马琦钧](https://github.com/Skypow2012) |
| **后端** | [张翔宇](https://github.com/xgdyp)、付文豪 |
## 关注我们
<div align=center>
<img src="https://raw.githubusercontent.com/datawhalechina/pumpkin-book/master/res/qrcode.jpeg" width = "250" height = "270" alt="Datawhale是一个专注AI领域的开源组织以“for the learner和学习者一起成长”为愿景构建对学习者最有价值的开源学习社区。关注我们一起学习成长。">
</div>
## LICENSE
<img style="border-width:0" src="https://img.shields.io/badge/license-GPL--3.0-lightgrey" /><br />本作品采用GNU General Public License v3.0进行许可。

9
be/.gitignore vendored
View File

@ -1,2 +1,9 @@
.idea .idea
__pycache__ __pycache__
/app/projects/*
!/app/projects/test/

View File

@ -1,5 +1,5 @@
from flask import Blueprint from flask import Blueprint
from app.api.v1 import index, project, files, anno from ...api.v1 import index, project, files, anno, ai
def create_blueprint_v1(): def create_blueprint_v1():
@ -9,5 +9,6 @@ def create_blueprint_v1():
project.api.register(bp_v1, url_prefix='/project') project.api.register(bp_v1, url_prefix='/project')
anno.api.register(bp_v1, url_prefix='/anno') anno.api.register(bp_v1, url_prefix='/anno')
files.api.register(bp_v1, url_prefix='/files') files.api.register(bp_v1, url_prefix='/files')
ai.api.register(bp_v1, url_prefix='/ai')
return bp_v1 return bp_v1

55
be/app/api/v1/ai.py Normal file
View File

@ -0,0 +1,55 @@
from app.libs.redprint import RedPrint
import time
from flask import request
import json
import os
from ...libs.tools import read_file, write_json, read_json_file, make_dir
import auto_anno_2 as aa
api = RedPrint('ai')
class ReturnInfo:
def __init__(self):
self.errCode = 0
self.errMsg = ''
self.info = []
@api.route('/nlp/cls', methods=['POST'])
def nlp_cls():
ret_info = ReturnInfo()
try:
j = request.get_json()
texts = j['texts']
types = j['types']
annos = []
for text in texts:
anno = aa.cls(text, types)
annos.append(anno)
ret_info.info = annos
except Exception as e:
print(e)
ret_info.errCode = 404
ret_info.errMsg = str(e)
return ret_info.__dict__
@api.route('/nlp/ner', methods=['POST'])
def nlp_ner():
ret_info = ReturnInfo()
try:
j = request.get_json()
texts = j['texts']
types = j['types']
annos = []
for text in texts:
anno = aa.ner(text, types)
annos.append(anno)
ret_info.info = annos
except Exception as e:
print(e)
ret_info.errCode = 404
ret_info.errMsg = str(e)
return ret_info.__dict__

View File

@ -1,45 +1,29 @@
from app.config.setting import PROJECT_NAME, FILE_NAME, PROJECTS, ANNO_OUTPUT_PATH from app.config.setting import PROJECT_NAME, FILE_NAME, PROJECT_PATH, ANNO_OUTPUT_PATH
from app.entities.entities import ReturnInfo, AnnoContents, OutputAnno, QueryAnno from app.entities.entities import ReturnInfo, AnnoContents, OutputAnno, QueryAnno
from app.libs.redprint import RedPrint from app.libs.redprint import RedPrint
import time
from flask import request from flask import request
import json import json
import os import os
import zipfile
from app.libs.tools import read_txt_file, write_json, read_json_file, make_dir from ...libs.tools import read_file, write_json, read_json_file, make_dir
api = RedPrint('anno') api = RedPrint('anno')
waiting_list_dic = {}
@api.route('/create', methods=['POST']) @api.route('/create', methods=['POST'])
def create_anno(): def create_anno():
ret_info = ReturnInfo() ret_info = ReturnInfo()
try: try:
param = request.get_json() j = request.get_json()
project_name = param.get(PROJECT_NAME) anno_output_path = ANNO_OUTPUT_PATH.format(j["projectName"], j["fileName"])
file_name = param.get(FILE_NAME) with open(anno_output_path, 'w', encoding='utf-8') as fh:
anno_details = param.get('annoDetails') fh.write(json.dumps(request.get_json(), ensure_ascii=False))
anno_cont = AnnoContents()
anno_cont.fileName = file_name
anno_cont.annoDetails = anno_details
anno_cont.isAnno = True
anno_output_path = ANNO_OUTPUT_PATH.format(project_name)
# 判断路径是否存在
if not os.path.exists(anno_output_path):
write_json(anno_output_path, [anno_cont])
ret_info.errCode = 0
else:
output_anno = OutputAnno()
output_anno.all_anno = read_json_file(anno_output_path)
output_anno.add_anno(anno_cont)
write_json(anno_output_path, output_anno.all_anno)
ret_info.errCode = 0
except Exception as e: except Exception as e:
print(e)
ret_info.errCode = 404 ret_info.errCode = 404
ret_info.errMsg = str(e) ret_info.errMsg = str(e)
@ -53,16 +37,18 @@ def query_anno():
project_name = request.args.get("projectName").strip() project_name = request.args.get("projectName").strip()
file_name = request.args.get("fileName").strip() file_name = request.args.get("fileName").strip()
file_path = PROJECTS + '/' + project_name + '/' + file_name file_path = PROJECT_PATH.format(project_name) + '/data/' + file_name
file_content = read_txt_file(file_path) file_content = read_file(file_path)
anno_output_path = ANNO_OUTPUT_PATH.format(project_name) anno_output_path = ANNO_OUTPUT_PATH.format(project_name, file_name)
output_anno = OutputAnno() j = {}
output_anno.all_anno = read_json_file(anno_output_path) if os.path.exists(anno_output_path):
j = json.loads(read_file(anno_output_path))
query_anno = QueryAnno() query_anno = QueryAnno()
query_anno.fileContent = file_content query_anno.fileContent = file_content
query_anno.annoDetails = output_anno.get_anno(file_name) query_anno.annoDetails = j.get('annoDetails', [])
query_anno.relDetails = j.get('relDetails', [])
ret_info.info = query_anno ret_info.info = query_anno
ret_info.errCode = 0 ret_info.errCode = 0

View File

@ -1,13 +1,18 @@
from app.config.setting import PROJECT_PATH, ANNO_OUTPUT_PATH from ...config.setting import PROJECT_PATH, ANNO_OUTPUT_PATH, DOWNLOAD_FILE_LOCATION
from app.libs.redprint import RedPrint
from flask import request from ...libs.redprint import RedPrint
from flask import request, send_file, Response, send_from_directory, make_response
import json import json
import os import os
from app.entities.entities import ReturnInfo, FileInfo from ...entities.entities import ReturnInfo, FileInfo
from app.libs.tools import read_json_file from ...libs.tools import read_json_file, read_txt_file, write_json, get_project_file
import threading
import time
from urllib.parse import urlencode
#
api = RedPrint('files') api = RedPrint('files')
@ -19,34 +24,23 @@ def query_file():
page_number = int(request.args.get("pageNumber")) page_number = int(request.args.get("pageNumber"))
page_size = int(request.args.get("pageSize")) page_size = int(request.args.get("pageSize"))
file_names = os.listdir(PROJECT_PATH.format(project_name)) project_path = PROJECT_PATH.format(project_name)
if not os.path.exists(project_path):
os.makedirs(project_path)
os.makedirs(project_path + '/data')
os.makedirs(project_path + '/anno')
file_names = os.listdir(project_path + '/data')
if 'config.json' in file_names: if 'config.json' in file_names:
file_names.remove('config.json') file_names.remove('config.json')
if 'anno.json' in file_names: if 'anno.json' in file_names:
file_names.remove('anno.json') file_names.remove('anno.json')
for file_name in file_names[(page_number - 1) * page_size: (page_number - 1) * page_size + page_size]:
anno_output_path = ANNO_OUTPUT_PATH.format(project_name, file_name)
anno_output_path = ANNO_OUTPUT_PATH.format(project_name) file_info = FileInfo()
file_info.fileName = file_name
# 判断路径是否存在 file_info.isAnno = os.path.exists(anno_output_path)
if not os.path.exists(anno_output_path): ret_info.info.append(file_info)
for file_name in file_names[(page_number - 1) * page_size: (page_number - 1) * page_size + page_size]:
file_info = FileInfo()
file_info.fileName = file_name
file_info.isAnno = False
ret_info.info.append(file_info)
print(2)
else:
for file_name in sorted(file_names)[(page_number - 1) * page_size: (page_number - 1) * page_size + page_size]:
file_info = FileInfo()
file_info.fileName = file_name
for anno_info in read_json_file(anno_output_path):
if anno_info.get('fileName') == file_name:
file_info.isAnno = anno_info.get('isAnno')
ret_info.info.append(file_info.__dict__)
ret_info.errCode = 0 ret_info.errCode = 0
@ -56,3 +50,58 @@ def query_file():
ret_info.errCode = 404 ret_info.errCode = 404
ret_info.errMsg = str(e) ret_info.errMsg = str(e)
return json.dumps(ret_info, default=lambda o: o.__dict__) return json.dumps(ret_info, default=lambda o: o.__dict__)
@api.route('/get_labels', methods=['GET'])
def get_lables():
ret_info = ReturnInfo()
try:
download_json = []
project_name = request.args.get("projectName")
project_path = PROJECT_PATH.format(project_name)
print(project_path)
project_file_list = get_project_file(project_path)
print(project_file_list)
# current_filename = request.args.get("current_filename")
anno_data_set = set()
anno_data = read_json_file(PROJECT_PATH.format(project_name) + '/anno.json')
for item in anno_data:
item_dict = {'file': item['fileName'],
# 'text': read_txt_file(PROJECT_PATH.format(project_name) + '/' + item['fileName']),
'labels': list(set([x['type'] for x in item["annoDetails"]]))}
print(item_dict)
anno_data_set.add(item['fileName'])
download_json.append(item_dict)
#add no label data
for filename in set(project_file_list).difference(anno_data_set):
item_dict = {'file': filename,
'labels': []
}
download_json.append(item_dict)
# print(set(project_file_list).difference(anno_data_set))
except Exception as e:
ret_info.errCode = 404
ret_info.errMsg = str(e)
return json.dumps(download_json, default=lambda o: o.__dict__)
@api.route('/get_anno_json', methods=['GET'])
def get_anno_json():
project_name = request.args.get("projectName")
anno_output_dir = ANNO_OUTPUT_PATH.format(project_name, '').replace('.json', '')
fns = os.listdir(anno_output_dir)
js = []
for fn in fns:
if not fn.endswith('.json'):
continue
js.append(read_txt_file(anno_output_dir + '/' + fn))
anno_json_path = DOWNLOAD_FILE_LOCATION.format(project_name)
open('app/'+anno_json_path, 'w', encoding='utf-8').write('\n'.join(js))
response = make_response(send_from_directory(directory='', path=anno_json_path, as_attachment=True))
filename = project_name + '_' + time.strftime('%Y%m%d_%H%M%S') + '.json'
filename_urlencode = urlencode({'filename': filename})
response.headers["Content-disposition"] = f'attachment; {filename_urlencode}'
return response

View File

@ -10,6 +10,7 @@ api = RedPrint('index')
# 访问首页 http://localhost:9060/v1/index # 访问首页 http://localhost:9060/v1/index
# @api.route('/index') # @api.route('/index')
@api.route('', methods=['GET']) @api.route('', methods=['GET'])
def index(): def index():
@ -17,7 +18,11 @@ def index():
ret_info = ReturnInfo() ret_info = ReturnInfo()
try: try:
project_config_info = [] project_config_info = []
for project_name in os.listdir(PROJECTS): if not os.path.exists(PROJECTS):
os.makedirs(PROJECTS)
project_list = os.listdir(PROJECTS)
project_list.sort(key=lambda x: os.path.getctime(os.path.join(PROJECTS, x)), reverse=True)
for project_name in project_list:
project_config_name = PROJECT_CONFIG_PATH.format(project_name) project_config_name = PROJECT_CONFIG_PATH.format(project_name)
print(project_config_name) print(project_config_name)
if os.path.exists(project_config_name): if os.path.exists(project_config_name):

View File

@ -1,24 +1,152 @@
from app.config.setting import PROJECT_NAME, PROJECT_TYPE, ENTITY_TYPES, PROJECTS, PROJECT_PATH, PROJECT_CONFIG_PATH, \ import shutil
from ...config.setting import PROJECT_NAME, PROJECT_TYPE, ENTITY_TYPES, PROJECTS, PROJECT_PATH, PROJECT_CONFIG_PATH, \
ANNO_OUTPUT_PATH ANNO_OUTPUT_PATH
from app.libs.redprint import RedPrint from ...libs.redprint import RedPrint
from flask import request from flask import request
import json import json
import os import os
from app.libs.tools import make_dir, write_json, read_json_file from ...libs.tools import make_dir, write_json, read_json_file, unzip_file, get_cn_name
from app.entities.entities import Project, ReturnInfo from ...entities.entities import Project, ReturnInfo
from ...config.setting import FILE_NAME
from ...entities.entities import AnnoContents
api = RedPrint('project') api = RedPrint('project')
@api.route('/delete_program', methods=['GET'])
def delete_program():
ret_info = ReturnInfo()
try:
project_name = request.args.get('projectName')
project_path = PROJECT_PATH.format(project_name)
shutil.rmtree(project_path)
print("ok")
except Exception as e:
print(e)
ret_info.errCode = 404
ret_info.errMsg = str(e)
return json.dumps(ret_info, default=lambda o: o.__dict__)
@api.route('/get_zipped_data', methods=['POST'])
def get_zipped_data():
ret_info = ReturnInfo()
try:
project_name = request.form.get('projectName')
upload_file = request.files['file']
file_path = os.path.join(PROJECT_PATH.format(project_name), upload_file.filename)
target_path = PROJECT_PATH.format(project_name) + '/data'
upload_file.save(file_path)
file_type = file_path.split('.')[-1]
# print("zipped data received: .{} form".format(file_type))
unzip_file(file_path, target_path)
os.remove(file_path)
# Put files in the folder directly under the project directory
for item in os.listdir(target_path):
# If item is a folder,copy files in item to project folder,then remove this folder
folder_path = target_path + '/' + item
if os.path.isdir(folder_path):
for file in os.listdir(folder_path):
if file.split('.')[-1] in ['txt', 'jpg', 'png']:
shutil.copy(folder_path + '/' + file, folder_path + '/../')
# Here to deal with chinese encode in module zipfile and rarfile
if file_type == 'zip':
os.replace(folder_path + '/../' + file,
folder_path + '/../' + get_cn_name(file))
shutil.rmtree(folder_path)
except Exception as e:
print(e)
ret_info.errCode = 404
ret_info.errMsg = str(e)
return json.dumps(ret_info, default=lambda o: o.__dict__)
@api.route('/get_jsonl_data', methods=['POST'])
def get_jsonl_data():
ret_info = ReturnInfo()
try:
project_name = request.form.get('projectName')
upload_file = request.files['file']
file_path = os.path.join(PROJECT_PATH.format(project_name), upload_file.filename)
file_name = upload_file.filename.replace('.jsonl', '')
target_path = PROJECT_PATH.format(project_name) + '/data'
upload_file.save(file_path)
with open(file_path, 'r', encoding='utf-8') as fh:
l = fh.readline().strip()
idx = 0
while l:
idx += 1
j = json.loads(l)
txts = []
for key in j:
txts.append(j[key])
_idx = ('000000'+str(idx))[-6:]
if len(str(idx)) > 6:
_idx = str(idx)
open(f'{target_path}/{file_name}_{_idx}', 'w', encoding='utf-8').write('<whale_n>'.join(txts))
l = fh.readline().strip()
os.remove(file_path)
except Exception as e:
print(e)
ret_info.errCode = 404
ret_info.errMsg = str(e)
return json.dumps(ret_info, default=lambda o: o.__dict__)
@api.route('/get_txt_data', methods=['POST'])
def get_txt_data():
ret_info = ReturnInfo()
try:
project_name = request.form.get('projectName')
upload_file = request.files['file']
file_path = os.path.join(PROJECT_PATH.format(project_name), upload_file.filename)
file_name = upload_file.filename.replace('.txt', '')
target_path = PROJECT_PATH.format(project_name) + '/data'
upload_file.save(file_path)
with open(file_path, 'r', encoding='utf-8') as fh:
l = fh.readline().strip()
idx = 0
while l:
idx += 1
_idx = ('000000'+str(idx))[-6:]
if len(str(idx)) > 6:
_idx = str(idx)
open(f'{target_path}/{file_name}_{_idx}', 'w', encoding='utf-8').write(l)
l = fh.readline().strip()
os.remove(file_path)
except Exception as e:
print(e)
ret_info.errCode = 404
ret_info.errMsg = str(e)
return json.dumps(ret_info, default=lambda o: o.__dict__)
@api.route('/create', methods=['POST']) @api.route('/create', methods=['POST'])
def create_project(): def create_project():
ret_info = ReturnInfo() ret_info = ReturnInfo()
try: try:
param = request.get_json()
project_name = param.get(PROJECT_NAME)
make_dir(PROJECT_PATH.format(project_name)) param = request.get_json()
print(param)
project_name = param.get(PROJECT_NAME)
project_path = PROJECT_PATH.format(project_name)
make_dir(project_path)
make_dir(project_path + '/data')
make_dir(project_path + '/anno')
write_json(PROJECT_CONFIG_PATH.format(project_name), param) write_json(PROJECT_CONFIG_PATH.format(project_name), param)
ret_info.errCode = 0 ret_info.errCode = 0
@ -42,8 +170,6 @@ def update_entity_types():
for entity_type in entity_types: for entity_type in entity_types:
new_entity_types.append(entity_type.get('type')) new_entity_types.append(entity_type.get('type'))
anno_output_path = ANNO_OUTPUT_PATH.format(project_name)
if os.path.exists(PROJECT_CONFIG_PATH.format(project_name)): # False if os.path.exists(PROJECT_CONFIG_PATH.format(project_name)): # False
project_config_info = read_json_file(PROJECT_CONFIG_PATH.format(project_name)) project_config_info = read_json_file(PROJECT_CONFIG_PATH.format(project_name))
project = Project() project = Project()
@ -52,16 +178,6 @@ def update_entity_types():
project.entityTypes = entity_types project.entityTypes = entity_types
print(project.entityTypes) print(project.entityTypes)
if os.path.exists(anno_output_path):
anno_details = read_json_file(anno_output_path)
for anno_info in anno_details:
anno_detail = json.loads(anno_info.get('annoDetails'))
for ind, anno in enumerate(anno_detail):
entity_type = anno.get('type')
if entity_type not in new_entity_types:
anno_detail.pop(ind)
write_json(anno_output_path, anno_details)
write_json(PROJECT_CONFIG_PATH.format(project_name), project) write_json(PROJECT_CONFIG_PATH.format(project_name), project)
ret_info.errMsg = 'update ok' ret_info.errMsg = 'update ok'

View File

@ -2,7 +2,7 @@ from flask import Flask
def create_app(): def create_app():
app = Flask(__name__) app = Flask(__name__, static_folder='../../fe/dist/',template_folder='../../fe/dist/', static_url_path='/')
app.config.from_object('app.config.setting') app.config.from_object('app.config.setting')
app.config.from_object('app.config.secure') app.config.from_object('app.config.secure')

View File

@ -13,8 +13,11 @@ FILE_NAME = 'fileName'
PROJECTS = 'app/projects' PROJECTS = 'app/projects'
# 项目路径 # 项目路径
PROJECT_PATH = PROJECTS + '/' + "{}" PROJECT_PATH = PROJECTS + '/{}/'
PROJECT_CONFIG_PATH = PROJECTS + '/' + "{}" + '/config.json' PROJECT_CONFIG_PATH = PROJECTS + '/' + "{}" + '/config.json'
#下载标注结果所在的位置
DOWNLOAD_FILE_LOCATION = 'projects/{}/anno.json'
# 标注信息存储路径 # 标注信息存储路径
ANNO_OUTPUT_PATH = PROJECTS + '/' + '{}' + '/' + 'anno.json' ANNO_OUTPUT_PATH = PROJECTS + '/{}/anno/{}.json'

View File

@ -15,6 +15,7 @@ class ReturnInfo:
class QueryAnno: class QueryAnno:
def __init__(self): def __init__(self):
self.annoDetails = [] self.annoDetails = []
self.relDetails = []
self.fileContent = '' self.fileContent = ''
# self.isAnno = False # self.isAnno = False

View File

@ -1,18 +1,31 @@
import os import os
import json import json
import zipfile
import tarfile
# import rarfile
# import py7zr
from os import rename
from os import listdir
from shutil import move
import base64
def get_cn_name(name):
try:
return name.encode('cp437').decode('GBK')
except:
return name
def make_dir(path): def make_dir(path):
folder = os.path.exists(path) folder = os.path.exists(path)
if not folder: if not folder:
os.mkdir(path) os.makedirs(path)
# 将json数据写入.json文件 # 将json数据写入.json文件
def write_json(json_file_path, data): def write_json(json_file_path, data):
with open(json_file_path, 'w', encoding='utf-8') as f: with open(json_file_path, 'w', encoding='utf-8') as fh:
json.dump(data, f, ensure_ascii=False, default=lambda o: o.__dict__) fh.write(json.dumps(data, ensure_ascii=False))
# 加载json文件中的json数据 # 加载json文件中的json数据
@ -21,9 +34,67 @@ def read_json_file(json_file_name):
data = json.load(f) data = json.load(f)
return data return data
# 自适配读取文件
def read_file(file_path):
ext = file_path.split('.')[-1]
if ext in ['jpg', 'png']:
return read_img_file(file_path)
elif ext in ['txt', 'json']:
return read_txt_file(file_path)
elif '.' not in file_path:
return read_txt_file(file_path)
return ''
# 读取img文件
def read_img_file(file_path):
with open(file_path, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode("ascii")
# 读取txt文件 # 读取txt文件
def read_txt_file(file_path): def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f: with open(file_path, 'r', encoding='utf-8') as f:
data = f.read() data = f.read()
return data return data
def get_project_file(project_path):
file_names = os.listdir(project_path + '/data')
return file_names
def unzip_file(zip_src, dst_dir):
"""
解压数据文件
:param zip_src: 压缩包文件的全路径
:param dst_dir: 要解压到的项目文件夹
:return:
"""
if zipfile.is_zipfile(zip_src):
fz = zipfile.ZipFile(zip_src, "r")
for file in fz.namelist():
fz.extract(file, dst_dir)
# Here to deal with chinese encode in module zipfile and rarfile
os.replace(dst_dir + '/' + file, dst_dir + '/' + get_cn_name(file))
return "unzip .zip file success"
# elif rarfile.is_rarfile(zip_src):
# fr = rarfile.RarFile(zip_src, "r")
# print(fr.namelist())
# for file in fr.namelist():
# fr.extract(file, dst_dir)
# return "unzip .rar file success"
# elif py7zr.is_7zfile(zip_src):
# f7z = py7zr.SevenZipFile(zip_src, "r")
# f7z.extractall(path=dst_dir)
# f7z.close()
elif tarfile.is_tarfile(zip_src):
ft = tarfile.TarFile(zip_src, "r")
print(ft.getnames())
for file in ft.getnames():
ft.extract(file, dst_dir)
else:
return "请上传.zip .tar格式的文件"

View File

@ -1 +0,0 @@
[{"fileName": "文本1 - 副本 - 副本 (3).txt", "annoDetails": "[]"}, {"fileName": "文本1 - 副本 - 副本 (4) - 副本.txt", "annoDetails": "[]"}, {"fileName": null, "annoDetails": "[]"}, {"fileName": "", "annoDetails": "[]"}]

View File

@ -1 +0,0 @@
{"projectName": "123", "projectType": "命名实体识别", "entityTypes": "[{\"type\":\"123\",\"color\":\"#c15892\"}]"}

View File

@ -1 +0,0 @@
[{"fileName": "", "annoDetails": "[]"}]

View File

@ -1 +0,0 @@
{"projectName": "222", "projectType": "命名实体识别", "entityTypes": "[{\"type\":\"23\",\"color\":\"#2ea5f5\"},{\"type\":\"12\",\"color\":\"#f8e817\"}]"}

View File

@ -1 +0,0 @@
{"projectName": "demo1", "projectType": "nlp 标注", "entityTypes": "[{\"type\":\"person1\",\"color\":\"#e61490\"},{\"type\":\"location\",\"color\":\"#0aab8a\"},{\"type\":\"organiztion\",\"color\":\"#2770cd\"},{\"type\":\"123\",\"color\":\"#1c7a82\"}]"}

View File

@ -1 +0,0 @@
{"projectName": "demo4", "projectType": "nlp 标注", "entityTypes": [{"type": "person1", "color": "#e61490"}, {"type": "location", "color": "#0aab8a"}, {"type": "organiztion", "color": "#2770cd"}, {"type": "123", "color": "#1c7a82"}]}

View File

@ -1 +0,0 @@
[{"fileName": "", "annoDetails": "[]", "isAnno": true}, {"fileName": "test2.txt", "annoDetails": "[]", "isAnno": true}, {"fileName": "test4.txt", "annoDetails": "[]", "isAnno": true}, {"fileName": "test1.txt", "annoDetails": "[]", "isAnno": true}, {"fileName": "test10.txt", "annoDetails": "[{\"name\":\"小明\",\"type\":\"person1\",\"start\":0,\"end\":2}]", "isAnno": true}]

View File

@ -1 +0,0 @@
{"projectName": "demo5", "projectType": "NLP标注", "entityTypes": "[{\"type\":\"person1\",\"color\":\"#e61490\"},{\"type\":\"location\",\"color\":\"#0aab8a\"},{\"type\":\"organiztion\",\"color\":\"#2770cd\"},{\"type\":\"123\",\"color\":\"#1c7a82\"}]"}

View File

@ -1 +0,0 @@
hello 你好啊 兄弟们 雄起

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
小明毕业于北京工业大学

View File

@ -1 +0,0 @@
{"projectName": "xixixi", "projectType": "命名实体识别", "entityTypes": "[]"}

View File

@ -1 +0,0 @@
[{"fileName": null, "annoDetails": "[]"}, {"fileName": "", "annoDetails": "[]"}]

View File

@ -1 +0,0 @@
{"projectName": "医疗", "projectType": "命名实体识别", "entityTypes": "[{\"type\":\"pos\",\"color\":\"#e67704\"}]"}

View File

@ -1 +0,0 @@
{"projectName": "项目", "projectType": "nlp 标注", "entityTypes": ""}

2
be/requirements.txt Normal file
View File

@ -0,0 +1,2 @@
flask
auto_anno_2

View File

@ -1,6 +1,6 @@
# 入口程序文件 # 入口程序文件
from app.app import create_app from app.app import create_app
from flask import render_template
app = create_app() app = create_app()
# host='0.0.0.0' # host='0.0.0.0'
@ -13,5 +13,15 @@ app = create_app()
# 9060是端口 # 9060是端口
# v1是版本 # v1是版本
# index是首页 # index是首页
@app.route('/')
def index():
'''
using this route to load index page
'''
return render_template('/index.html')
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=9060, debug=True) app.run(host='0.0.0.0', port=9060, debug=True)

49
be/test.py Normal file
View File

@ -0,0 +1,49 @@
import requests
import json
import threading
import time
import random
headers = {'Content-Type': 'application/json', 'Connection': 'close'}
data = {"projectName": "demo5", "fileName": "test11.txt",
"annoDetails": [{"name": "", "type": "person1", "start": 5, "end": 6, "isSmall": False}]}
test_times = 1000
test_cnt = 0
err_cnt = 0
requests.DEFAULT_RETRIES = 1000
requests.adapters.DEFAULT_RETRIES = 1000
s = requests.session()
s.keep_alive = False
def create_load():
global test_times
global test_cnt
global err_cnt
global s
result = requests.post('http://127.0.0.1:9060/v1/anno/create', data=json.dumps(data), headers=headers, timeout=30)
print(result.text)
if result.json()['errMsg']:
err_cnt += 1
print('Catch Err:', result.json())
test_cnt += 1
if test_cnt == test_times:
if err_cnt == 0:
print('Test success!')
else:
print('Test failed!')
print('Start', test_times, 'test')
for i in range(test_times):
# 单线程测试
# create_load()
# 多线程测试
time.sleep(random.randint(100,200)*0.0001)
t = threading.Thread(target=create_load, args=())
# t.setDaemon(True)
t.start()
time.sleep(1)
print("ERROR COUNT"+str(err_cnt))
# print("OK")

46
doc/README.md Normal file
View File

@ -0,0 +1,46 @@
# 使用说明
## 视频教程
https://www.bilibili.com/video/BV1v64y197iA?p=2
## 创建项目
点击【新建项目】创建一个名称为【demo01】的项目类型选择【命名实体识别】然后点击底部的【提交】完成新建。
## 添加标签
点击项目的【配置】按钮进入配置页。在【新增标签】处输入【人名】,点击右侧的【提交】。在生成标签左侧点击画板可以切换颜色。随后还可以再输入【地名】、【组织】、【日期】等。全部标签录入好以后,点击底部的【提交】更新配置。
## 导入文本文件
将文本文件放置进【be/app/projets/demo01/】中。单机版local分支可直接在release中下载可直接将文件列表拖入标注页左侧的文件列表。
## 标注
点击【开始标注】进入标注页面。默认选中了第一个标签,可以点击标签来切换。在文本处按下鼠标、移动、松开鼠标,可以完成一次标注。右键文本可以取消标注。
## 切换文件
点击左侧的文件名,或者点击底部的【上一个】、【下一个】可以切换需要标注的文件。如果文件过多,左侧列表会分页,点击【上页】、【下页】可以看到更多。
## 设置快捷键
将鼠标移动到标签、底部【上一个】、底部【下一个】按键盘任意按钮设置快捷键按键盘上的【Esc】取消。可在鼠标进入标注区域时使用刚刚设置的快捷键。
## 导出标注
点击左下角的【导出json结果】获取本次的标注内容内容示例如下历史所有标注内容在【be/app/projets/demo01/anno.json】中有记录格式略有不同。
```javascript
[
{
"file": "test10.txt",
"text": "小明毕业于北京工业大学",
"entity": [
{
"name": "小明",
"type": "人名",
"start": 0,
"end": 2
},
{
"name": "北京工业大学",
"type": "组织",
"start": 5,
"end": 11
},
{
"name": "北京",
"type": "地名",
"start": 5,
"end": 7
}
]
}
]
```

7
doc/api.md Normal file
View File

@ -0,0 +1,7 @@
# API文档
| url | methods | params | return |
| -------------------------- | ------- | -------------------------------------------------------- | -------------------------------- |
| v1/project/get_zipped_data | POST | projectName:项目名 file:数据集文件(目前只支持.zip格式 | json errcode表示是否成功导入 |
| v1/files/get_anno_json | GET | projectName:项目名 | file.json格式的数据集标注结果 |
|v1/project/delete_program |GET |projectName:项目名|jsonerrcode表示是否成功|

View File

@ -1,27 +0,0 @@
# 环境配置
## 一、下载所需软件
### 1、Python 3
经测试Whale-anno后端代码可在Python 3.7.9上运行,您也可以测试其他版本,一般建议安装最新版
[Python 3官网下载地址](https://www.python.org/downloads/)
### 2、Node.js
经测试Whale-anno前端代码可在Node.js v12.16.3上运行在Node.js v8.10.0安装本地调试工具失败,您也可以测试其他版本,一般建议安装最新版
[Node.js官网下载地址](https://nodejs.org/zh-cn/download/)
## 二、克隆项目
```shell
git clone https://github.com/datawhalechina/whale-anno.git
```
## 三、下载依赖
### 1、下载后端依赖
```shell
# 下载后端依赖
python3 -m pip install flask
```
*后端只依赖了flask这个第三方库*
### 2、下载前端依赖
```shell
# 进入前端文件夹
cd ./fe
# 下载前端依赖
npm install
```
*npm为Node.js安装以后自带的包管理工具*

View File

@ -1,24 +0,0 @@
# 快速开始
## 一、环境配置
请参考[环境配置](./installation.md)配置whale-anno运行环境。
## 二、启动项目
### 1、启动后端
打开命令行Windows中的打开方式进入项目目录按住键盘上的shift然后右键选择在【在此处打开 PowerShell 窗口(S)】)
```shell
# 进入后端目录
cd ./be
# 启动后端脚本
python3 ./run.py
```
*此时项目的后端会被启动在http://localhost:9060/*
### 2、启动前端
用上述方法,打开一个新的命令行
```shell
# 进入前端
cd ./fe
# 启动前端页面
npm run start
```
*此时项目的前端会被启动在http://localhost:8080/*
## 三、开始使用
打开上述前端页面地址,然后请参考[快速使用](./quickuse.md)。

View File

@ -1,4 +1,4 @@
# dw-tool-ner # whale-anno
> Datawhale's ner tool. > Datawhale's ner tool.

View File

@ -78,15 +78,15 @@ module.exports = new Promise((resolve, reject) => {
process.env.PORT = port process.env.PORT = port
// add port to devServer config // add port to devServer config
devWebpackConfig.devServer.port = port devWebpackConfig.devServer.port = port
let host = devWebpackConfig.devServer.host === '0.0.0.0' ? 'localhost' : devWebpackConfig.devServer.host
// Add FriendlyErrorsPlugin // Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: { compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], messages: [`Your application is running here: http://${host}:${port}`]
}, },
onErrors: config.dev.notifyOnErrors onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback() ? utils.createNotifierCallback()
: undefined : undefined
})) }))
resolve(devWebpackConfig) resolve(devWebpackConfig)

View File

@ -12,12 +12,13 @@ module.exports = {
assetsPublicPath: '/', assetsPublicPath: '/',
proxyTable: { proxyTable: {
'/v1/': { '/v1/': {
target: 'http://localhost:9060/', target: 'http://127.0.0.1:9060/',
// target: 'https://tekii.cn/',
} }
}, },
// Various Dev Server settings // Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false, autoOpenBrowser: false,
errorOverlay: true, errorOverlay: true,
@ -54,7 +55,7 @@ module.exports = {
// Paths // Paths
assetsRoot: path.resolve(__dirname, '../dist'), assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static', assetsSubDirectory: 'static',
assetsPublicPath: '/dw-tool-ner/v1.2.8/', assetsPublicPath: '/',
/** /**
* Source Maps * Source Maps

35
fe/dist/index.html vendored
View File

@ -1,6 +1,37 @@
<!DOCTYPE html><html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>dw-tool-ner</title><link href=/static/css/app.4872490f1327ad4a9444be2c5054e3bd.css rel=stylesheet></head><body><div id=app></div><style>html, body { <!DOCTYPE html><html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"><title>whale-anno</title><link href=/static/css/app.2a080f6c8ff6679135f7ba591f7aff2a.css rel=stylesheet></head><body><div id=app></div><style>html, body {
display: inline-block; display: inline-block;
margin: 0; margin: 0;
width: 100%; width: 100%;
height: 100%; height: 100%;
}</style><script type=text/javascript src=/static/js/manifest.2ae2e69a05c33dfc65f8.js></script><script type=text/javascript src=/static/js/vendor.b6a0dabd8e467dbb8b61.js></script><script type=text/javascript src=/static/js/app.1233f1538d45804c389b.js></script></body></html> }
button, input, span {
-webkit-tap-highlight-color: transparent;
}
*::-webkit-scrollbar { /*滚动条整体样式*/
width: 6px; /*高宽分别对应横竖滚动条的尺寸*/
height: 1px;
}
*::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
/* -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2); */
background: #ffffff;
border-right: 2px solid #054ba8;
}
*::-webkit-scrollbar-track {/*滚动条里面轨道*/
padding: 2px;
background: #cccccc00;
}</style><script>if (!localStorage.isOldUser) {
let isPhone = false
for (let name of ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"]) {
if (navigator.userAgent.indexOf(name) > -1) {
isPhone = true
}
}
console.log(isPhone?'手机用户':'电脑用户')
if (isPhone) {
alert('NER中,双击删除实体\n待标注文本需要txt格式的压缩包')
} else {
alert('NER中,鼠标右键删除实体\n待标注文本需要txt格式的压缩包')
}
localStorage.isOldUser = Date.now()
}</script><script type=text/javascript src=/static/js/manifest.2ae2e69a05c33dfc65f8.js></script><script type=text/javascript src=/static/js/vendor.3da745e97ee6f879329e.js></script><script type=text/javascript src=/static/js/app.e10391caa96d59979aa8.js></script></body></html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"sources":["webpack:///webpack/bootstrap f3383f2c542efd14ff14"],"names":["parentJsonpFunction","window","chunkIds","moreModules","executeModules","moduleId","chunkId","result","i","resolves","length","installedChunks","push","Object","prototype","hasOwnProperty","call","modules","shift","__webpack_require__","s","installedModules","2","exports","module","l","m","c","d","name","getter","o","defineProperty","configurable","enumerable","get","n","__esModule","object","property","p","oe","err","console","error"],"mappings":"aACA,IAAAA,EAAAC,OAAA,aACAA,OAAA,sBAAAC,EAAAC,EAAAC,GAIA,IADA,IAAAC,EAAAC,EAAAC,EAAAC,EAAA,EAAAC,KACQD,EAAAN,EAAAQ,OAAoBF,IAC5BF,EAAAJ,EAAAM,GACAG,EAAAL,IACAG,EAAAG,KAAAD,EAAAL,GAAA,IAEAK,EAAAL,GAAA,EAEA,IAAAD,KAAAF,EACAU,OAAAC,UAAAC,eAAAC,KAAAb,EAAAE,KACAY,EAAAZ,GAAAF,EAAAE,IAIA,IADAL,KAAAE,EAAAC,EAAAC,GACAK,EAAAC,QACAD,EAAAS,OAAAT,GAEA,GAAAL,EACA,IAAAI,EAAA,EAAYA,EAAAJ,EAAAM,OAA2BF,IACvCD,EAAAY,IAAAC,EAAAhB,EAAAI,IAGA,OAAAD,GAIA,IAAAc,KAGAV,GACAW,EAAA,GAIA,SAAAH,EAAAd,GAGA,GAAAgB,EAAAhB,GACA,OAAAgB,EAAAhB,GAAAkB,QAGA,IAAAC,EAAAH,EAAAhB,IACAG,EAAAH,EACAoB,GAAA,EACAF,YAUA,OANAN,EAAAZ,GAAAW,KAAAQ,EAAAD,QAAAC,IAAAD,QAAAJ,GAGAK,EAAAC,GAAA,EAGAD,EAAAD,QAKAJ,EAAAO,EAAAT,EAGAE,EAAAQ,EAAAN,EAGAF,EAAAS,EAAA,SAAAL,EAAAM,EAAAC,GACAX,EAAAY,EAAAR,EAAAM,IACAhB,OAAAmB,eAAAT,EAAAM,GACAI,cAAA,EACAC,YAAA,EACAC,IAAAL,KAMAX,EAAAiB,EAAA,SAAAZ,GACA,IAAAM,EAAAN,KAAAa,WACA,WAA2B,OAAAb,EAAA,SAC3B,WAAiC,OAAAA,GAEjC,OADAL,EAAAS,EAAAE,EAAA,IAAAA,GACAA,GAIAX,EAAAY,EAAA,SAAAO,EAAAC,GAAsD,OAAA1B,OAAAC,UAAAC,eAAAC,KAAAsB,EAAAC,IAGtDpB,EAAAqB,EAAA,IAGArB,EAAAsB,GAAA,SAAAC,GAA8D,MAApBC,QAAAC,MAAAF,GAAoBA","file":"static/js/manifest.2ae2e69a05c33dfc65f8.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tvar parentJsonpFunction = window[\"webpackJsonp\"];\n \twindow[\"webpackJsonp\"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [], result;\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n \t\tif(executeModules) {\n \t\t\tfor(i=0; i < executeModules.length; i++) {\n \t\t\t\tresult = __webpack_require__(__webpack_require__.s = executeModules[i]);\n \t\t\t}\n \t\t}\n \t\treturn result;\n \t};\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// objects to store loaded and loading chunks\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap f3383f2c542efd14ff14"],"sourceRoot":""} {"version":3,"sources":["webpack:///webpack/bootstrap dacecaef394ce7aeb868"],"names":["parentJsonpFunction","window","chunkIds","moreModules","executeModules","moduleId","chunkId","result","i","resolves","length","installedChunks","push","Object","prototype","hasOwnProperty","call","modules","shift","__webpack_require__","s","installedModules","2","exports","module","l","m","c","d","name","getter","o","defineProperty","configurable","enumerable","get","n","__esModule","object","property","p","oe","err","console","error"],"mappings":"aACA,IAAAA,EAAAC,OAAA,aACAA,OAAA,sBAAAC,EAAAC,EAAAC,GAIA,IADA,IAAAC,EAAAC,EAAAC,EAAAC,EAAA,EAAAC,KACQD,EAAAN,EAAAQ,OAAoBF,IAC5BF,EAAAJ,EAAAM,GACAG,EAAAL,IACAG,EAAAG,KAAAD,EAAAL,GAAA,IAEAK,EAAAL,GAAA,EAEA,IAAAD,KAAAF,EACAU,OAAAC,UAAAC,eAAAC,KAAAb,EAAAE,KACAY,EAAAZ,GAAAF,EAAAE,IAIA,IADAL,KAAAE,EAAAC,EAAAC,GACAK,EAAAC,QACAD,EAAAS,OAAAT,GAEA,GAAAL,EACA,IAAAI,EAAA,EAAYA,EAAAJ,EAAAM,OAA2BF,IACvCD,EAAAY,IAAAC,EAAAhB,EAAAI,IAGA,OAAAD,GAIA,IAAAc,KAGAV,GACAW,EAAA,GAIA,SAAAH,EAAAd,GAGA,GAAAgB,EAAAhB,GACA,OAAAgB,EAAAhB,GAAAkB,QAGA,IAAAC,EAAAH,EAAAhB,IACAG,EAAAH,EACAoB,GAAA,EACAF,YAUA,OANAN,EAAAZ,GAAAW,KAAAQ,EAAAD,QAAAC,IAAAD,QAAAJ,GAGAK,EAAAC,GAAA,EAGAD,EAAAD,QAKAJ,EAAAO,EAAAT,EAGAE,EAAAQ,EAAAN,EAGAF,EAAAS,EAAA,SAAAL,EAAAM,EAAAC,GACAX,EAAAY,EAAAR,EAAAM,IACAhB,OAAAmB,eAAAT,EAAAM,GACAI,cAAA,EACAC,YAAA,EACAC,IAAAL,KAMAX,EAAAiB,EAAA,SAAAZ,GACA,IAAAM,EAAAN,KAAAa,WACA,WAA2B,OAAAb,EAAA,SAC3B,WAAiC,OAAAA,GAEjC,OADAL,EAAAS,EAAAE,EAAA,IAAAA,GACAA,GAIAX,EAAAY,EAAA,SAAAO,EAAAC,GAAsD,OAAA1B,OAAAC,UAAAC,eAAAC,KAAAsB,EAAAC,IAGtDpB,EAAAqB,EAAA,IAGArB,EAAAsB,GAAA,SAAAC,GAA8D,MAApBC,QAAAC,MAAAF,GAAoBA","file":"static/js/manifest.2ae2e69a05c33dfc65f8.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tvar parentJsonpFunction = window[\"webpackJsonp\"];\n \twindow[\"webpackJsonp\"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [], result;\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n \t\tif(executeModules) {\n \t\t\tfor(i=0; i < executeModules.length; i++) {\n \t\t\t\tresult = __webpack_require__(__webpack_require__.s = executeModules[i]);\n \t\t\t}\n \t\t}\n \t\treturn result;\n \t};\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// objects to store loaded and loading chunks\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap dacecaef394ce7aeb868"],"sourceRoot":""}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2,8 +2,8 @@
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>dw-tool-ner</title> <title>whale-anno</title>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
@ -15,6 +15,40 @@
width: 100%; width: 100%;
height: 100%; height: 100%;
} }
button, input, span {
-webkit-tap-highlight-color: transparent;
}
*::-webkit-scrollbar { /*滚动条整体样式*/
width: 6px; /*高宽分别对应横竖滚动条的尺寸*/
height: 1px;
}
*::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
/* -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2); */
background: #ffffff;
border-right: 2px solid #054ba8;
}
*::-webkit-scrollbar-track {/*滚动条里面轨道*/
padding: 2px;
background: #cccccc00;
}
</style> </style>
<script>
if (!localStorage.isOldUser) {
let isPhone = false
for (let name of ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"]) {
if (navigator.userAgent.indexOf(name) > -1) {
isPhone = true
}
}
console.log(isPhone?'手机用户':'电脑用户')
if (isPhone) {
alert('NER中,双击删除实体\n待标注文本需要txt格式的压缩包')
} else {
alert('NER中,鼠标右键删除实体\n待标注文本需要txt格式的压缩包')
}
localStorage.isOldUser = Date.now()
}
</script>
</body> </body>
</html> </html>

17289
fe/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,84 @@
<template>
<div class="anno-img-box">
<div class="cls-box">
<img class="anno-img" id="anno-img" :src="`data:image/jpeg;base64,${fileContent}`">
</div>
</div>
</template>
<script>
export default ({
name: 'CVPoint',
props: {
fileContent: {
type: String,
default: '',
required: true
},
annoDetails: {
type: Array,
default: () => [],
required: true
},
nowType: {
type: String,
default: '1234',
required: true
},
types: {
type: Object,
default: () => {},
required: true
},
save: {
type: Function,
required: true
}
},
data () {
return {
points: [],
width: 0,
height: 0
}
},
methods: {
log (...args) {
console.log(args)
}
},
watch: {
annoDetails: {
handler (val) {
// const annoImg = document.getElementById('anno-img')
// annoImg.src = val
// console.log(annoImg.width)
// this.width = annoImg.width
// this.height = annoImg.height
console.log(val)
},
deep: true
}
}
})
</script>
<style>
.anno-img-box {
position: relative;
display: flex;
height: 100%;
align-content: center;
justify-content: center;
}
.anno-img {
width: 100%;
user-select: none;
}
.cls-box {
max-width: 100%;
position: absolute;
font-size: 0;
}
</style>

View File

@ -0,0 +1,135 @@
<template>
<div class="anno-img-box">
<div class="point-box">
<img class="anno-img" id="anno-img" @click="addPoint($event)" :src="`data:image/jpeg;base64,${fileContent}`" @dragstart="$event.preventDefault()" @contextmenu="$event.preventDefault()">
<div v-for="annoDetail in annoDetails" :point="annoDetail" :key="`${annoDetail.points[0][0]}_${annoDetail.points[0][1]}`" :style="{
left: annoDetail.points[0][0]*100 + '%',
top: annoDetail.points[0][1]*100 + '%',
backgroundColor: types[annoDetail.type]?types[annoDetail.type].color:'#f00',
}" class="point" @contextmenu="$event.preventDefault();delPoint(annoDetail, true)" @touchstart="$event.preventDefault();delPoint(annoDetail, false)" @mouseover="overPoint($event, annoDetail)"></div>
</div>
</div>
</template>
<script>
export default ({
name: 'CVPoint',
props: {
fileContent: {
type: String,
default: '',
required: true
},
annoDetails: {
type: Array,
default: () => [],
required: true
},
nowType: {
type: String,
default: '1234',
required: true
},
types: {
type: Object,
default: () => {},
required: true
},
save: {
type: Function,
required: true
}
},
data () {
return {
points: [],
width: 0,
height: 0
}
},
methods: {
log (...args) {
console.log(args)
},
addPoint (ev) {
ev.preventDefault()
if (!this.nowType) {
alert('请先选择标注类型')
return
}
const tar = ev.target
const newPoint = [ev.offsetX / tar.offsetWidth, ev.offsetY / tar.offsetHeight]
// this.points.push(newPoint)
// console.log(this.points)
this.annoDetails.push({
points: [newPoint],
type: this.nowType
})
this.save()
return false
},
delPoint (annoDetail, isForce) {
if (!isForce) {
//
if (this.nowType !== annoDetail.type) {
return
}
}
const idx = this.annoDetails.indexOf(annoDetail)
console.log(annoDetail, this.points)
this.annoDetails.splice(idx, 1)
this.save()
},
overPoint (ev, point) {
if (ev.which === 3) {
this.delPoint(point)
}
}
},
watch: {
annoDetails: {
handler (val) {
// const annoImg = document.getElementById('anno-img')
// annoImg.src = val
// console.log(annoImg.width)
// this.width = annoImg.width
// this.height = annoImg.height
console.log(val)
},
deep: true
}
}
})
</script>
<style>
.anno-img-box {
position: relative;
display: flex;
height: 100%;
align-content: center;
justify-content: center;
}
.anno-img {
width: 100%;
user-select: none;
}
.point-box {
width: 400px;
position: absolute;
font-size: 0;
}
.point {
position: absolute;
width: 8px;
height: 8px;
transform: translateX(-50%) translateY(-50%);
border-radius: 50%;
background-color: #f00;
}
.point:hover {
width: 16px;
height: 16px;
}
</style>

View File

@ -0,0 +1,339 @@
<template>
<div class="anno-img-box">
<div class="seg-box">
<img class="anno-img" id="anno-img" @click="addSeg($event)" :src="`data:image/jpeg;base64,${fileContent}`" @dragstart="$event.preventDefault()" @contextmenu="$event.preventDefault()">
<div v-for="annoDetail in annoDetails" :seg="annoDetail" :key="`${annoDetail.segs[0][0]}_${annoDetail.segs[0][1]}`" :style="{
left: annoDetail.segs[0][0]*100 + '%',
top: annoDetail.segs[0][1]*100 + '%',
backgroundColor: types[annoDetail.type]?types[annoDetail.type].color:'#f00',
}" class="seg" @contextmenu="$event.preventDefault();delSeg(annoDetail, true)" @touchstart="$event.preventDefault();delSeg(annoDetail, false)" @mouseover="overSeg($event, annoDetail)"></div>
</div>
</div>
</template>
<script>
// import npyjs from 'npyjs'
import { InferenceSession, Tensor } from 'onnxruntime-web'
const ort = require('onnxruntime-web')
console.log(ort)
// console.log(npyjs)
// const IMAGE_PATH = '/assets/data/dogs.jpg'
const IMAGE_EMBEDDING = '/assets/data/dogs_embedding.npy'
// const MODEL_DIR = '/assets/data/sam_onnx_quantized_example.onnx'
const MODEL_DIR = './sam_onnx_quantized_example.onnx'
let model = null
async function getModel () {
console.log(InferenceSession, MODEL_DIR)
model = await InferenceSession.create(MODEL_DIR)
console.log('model', model)
// go()
}
getModel()
// Use a Canvas element to produce an image from ImageData
function imageDataToImage (imageData) {
const canvas = imageDataToCanvas(imageData)
const image = new Image()
image.src = canvas.toDataURL()
return image
}
// Convert the onnx model mask prediction to ImageData
function arrayToImageData (input, width, height) {
const [r, g, b, a] = [0, 114, 189, 255] // the masks's blue color
const arr = new Uint8ClampedArray(4 * width * height).fill(0)
for (let i = 0; i < input.length; i++) {
// Threshold the onnx model mask prediction at 0.0
// This is equivalent to thresholding the mask using predictor.model.mask_threshold
// in python
if (input[i] > 0.0) {
arr[4 * i + 0] = r
arr[4 * i + 1] = g
arr[4 * i + 2] = b
arr[4 * i + 3] = a
}
}
return new ImageData(arr, height, width)
}
// Canvas elements can be created from ImageData
function imageDataToCanvas (imageData) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = imageData.width
canvas.height = imageData.height
ctx.putImageData(imageData, 0, 0)
return canvas
}
// Convert the onnx model mask output to an HTMLImageElement
export function onnxMaskToImage (input, width, height) {
return imageDataToImage(arrayToImageData(input, width, height))
}
// async function go () {
// let n = 0
// const pointCoords = new Float32Array(2 * (n + 1))
// const pointLabels = new Float32Array(n + 1)
// // Add in the extra point/label when only clicks and no box
// // The extra point is at (0, 0) with label -1
// pointCoords[2 * n] = 0.0
// pointCoords[2 * n + 1] = 0.0
// pointLabels[n] = -1.0
// const feeds = {
// image_embeddings: new Tensor('float32', [
// 256,
// 64,
// 64
// ]),
// point_coords: new Tensor('float32', pointCoords, [1, n + 1, 2]),
// point_labels: new Tensor('float32', pointLabels, [1, n + 1]),
// orig_im_size: new Tensor('float32', [
// 256,
// 256
// ]),
// mask_input: new Tensor(
// 'float32',
// new Float32Array(256 * 256),
// [1, 1, 256, 256]
// ),
// has_mask_input: new Tensor('float32', [0])
// }
// const results = await model.run(feeds)
// const output = results[model.outputNames[0]]
// // The predicted mask returned from the ONNX model is an array which is
// // rendered as an HTML image using onnxMaskToImage() from maskUtils.tsx.
// let img = onnxMaskToImage(output.data, output.dims[2], output.dims[3])
// console.log(img)
// }
// Decode a Numpy file into a tensor.
const loadNpyTensor = async (tensorFile, dType) => {
// let npLoader = new npyjs()
// const npArray = await npLoader.load(tensorFile)
// const tensor = new ort.Tensor(dType, npArray.data, npArray.shape)
// return tensor
}
// Load the Segment Anything pre-computed embedding
Promise.resolve(loadNpyTensor(IMAGE_EMBEDDING, 'float32')).then(
(embedding) => console.log(embedding)
)
// Run the ONNX model every time clicks has changed
const modelData = ({ clicks, tensor, modelScale }) => {
const imageEmbedding = tensor
let pointCoords
let pointLabels
let pointCoordsTensor
let pointLabelsTensor
// Check there are input click prompts
if (clicks) {
let n = clicks.length
// If there is no box input, a single padding point with
// label -1 and coordinates (0.0, 0.0) should be concatenated
// so initialize the array to support (n + 1) points.
pointCoords = new Float32Array(2 * (n + 1))
pointLabels = new Float32Array(n + 1)
// Add clicks and scale to what SAM expects
for (let i = 0; i < n; i++) {
pointCoords[2 * i] = clicks[i].x * modelScale.samScale
pointCoords[2 * i + 1] = clicks[i].y * modelScale.samScale
pointLabels[i] = clicks[i].clickType
}
// Add in the extra point/label when only clicks and no box
// The extra point is at (0, 0) with label -1
pointCoords[2 * n] = 0.0
pointCoords[2 * n + 1] = 0.0
pointLabels[n] = -1.0
// Create the tensor
pointCoordsTensor = new Tensor('float32', pointCoords, [1, n + 1, 2])
pointLabelsTensor = new Tensor('float32', pointLabels, [1, n + 1])
}
const imageSizeTensor = new Tensor('float32', [
modelScale.height,
modelScale.width
])
if (pointCoordsTensor === undefined || pointLabelsTensor === undefined) {
return
}
// There is no previous mask, so default to an empty tensor
const maskInput = new Tensor(
'float32',
new Float32Array(256 * 256),
[1, 1, 256, 256]
)
// There is no previous mask, so default to 0
const hasMaskInput = new Tensor('float32', [0])
return {
image_embeddings: imageEmbedding,
point_coords: pointCoordsTensor,
point_labels: pointLabelsTensor,
orig_im_size: imageSizeTensor,
mask_input: maskInput,
has_mask_input: hasMaskInput
}
}
console.log(modelData)
// const runONNX = async () => {
// try {
// if (
// model === null ||
// clicks === null ||
// tensor === null ||
// modelScale === null
// ) {
// return
// } else {
// // Preapre the model input in the correct format for SAM.
// // The modelData function is from onnxModelAPI.tsx.
// const feeds = modelData({
// clicks,
// tensor,
// modelScale,
// })
// if (feeds === undefined) return
// // Run the SAM ONNX model with the feeds returned from modelData()
// const results = await model.run(feeds)
// const output = results[model.outputNames[0]]
// // The predicted mask returned from the ONNX model is an array which is
// // rendered as an HTML image using onnxMaskToImage() from maskUtils.tsx.
// setMaskImg(onnxMaskToImage(output.data, output.dims[2], output.dims[3]))
// }
// } catch (e) {
// console.log(e)
// }
// }
export default ({
name: 'CVSeg',
props: {
fileContent: {
type: String,
default: '',
required: true
},
annoDetails: {
type: Array,
default: () => [],
required: true
},
nowType: {
type: String,
default: '1234',
required: true
},
types: {
type: Object,
default: () => {},
required: true
},
save: {
type: Function,
required: true
}
},
data () {
return {
segs: [],
width: 0,
height: 0
}
},
methods: {
log (...args) {
console.log(args)
},
addSeg (ev) {
ev.preventDefault()
if (!this.nowType) {
alert('请先选择标注类型')
return
}
const tar = ev.target
const newSeg = [ev.offsetX / tar.offsetWidth, ev.offsetY / tar.offsetHeight]
// this.segs.push(newSeg)
// console.log(this.segs)
this.annoDetails.push({
segs: [newSeg],
type: this.nowType
})
this.save()
return false
},
delSeg (annoDetail, isForce) {
if (!isForce) {
//
if (this.nowType !== annoDetail.type) {
return
}
}
const idx = this.annoDetails.indexOf(annoDetail)
console.log(annoDetail, this.segs)
this.annoDetails.splice(idx, 1)
this.save()
},
overSeg (ev, seg) {
if (ev.which === 3) {
this.delSeg(seg)
}
}
},
watch: {
annoDetails: {
handler (val) {
// const annoImg = document.getElementById('anno-img')
// annoImg.src = val
// console.log(annoImg.width)
// this.width = annoImg.width
// this.height = annoImg.height
console.log(val)
},
deep: true
}
}
})
</script>
<style>
.anno-img-box {
position: relative;
display: flex;
height: 100%;
align-content: center;
justify-content: center;
}
.anno-img {
width: 100%;
user-select: none;
}
.seg-box {
width: 400px;
position: absolute;
font-size: 0;
}
.seg {
position: absolute;
width: 8px;
height: 8px;
transform: translateX(-50%) translateY(-50%);
border-radius: 50%;
background-color: #f00;
}
.seg:hover {
width: 16px;
height: 16px;
}
</style>

View File

@ -1,11 +1,12 @@
<template> <template>
<div class="layout"> <div class="layout">
<span class="home" @click="goHome">whaleAnno</span> <span class="home" @click="goHome">whaleAnno</span>
<h1 class="out-title">{{projectName}}{{projectType}}</h1> <span class="now-file">{{ nowFile }}</span>
<h1 class="out-title"><span class="out-title-span">{{projectName}}{{projectType}}</span></h1>
<div class="container" @dragover="stopPrev" @drop="setFiles($event)"> <div class="container" @dragover="stopPrev" @drop="setFiles($event)">
<div class="left"> <div class="left">
<div class="file-list"> <div class="file-list" id="file-list">
<div v-for="file in files" :key="file" @click="setNowText(file)" <div v-for="file in files" :key="file" :id="file" @click="setNowText(file)"
:title=file :title=file
:class="['file', nowFile===file?'selected':'', isAnnoDic[`${projectName}_${file}`]||(nersCache[file]&&nersCache[file].length)?'checked':'', ].join(' ')" :class="['file', nowFile===file?'selected':'', isAnnoDic[`${projectName}_${file}`]||(nersCache[file]&&nersCache[file].length)?'checked':'', ].join(' ')"
> >
@ -15,8 +16,8 @@
<div class="process-bar" :style="{width: `${processRate*100}%`}"></div> <div class="process-bar" :style="{width: `${processRate*100}%`}"></div>
</div> </div>
<div class="page-ctl"> <div class="page-ctl">
<span class="page-ctl-last" :style="{opacity: pageNumber === 1 ? 0 : 1}" @click="lastPage">上页</span> <span class="page-ctl-last" :style="{opacity: pageNumber === 1 || isLoadingPage ? 0 : 1}" @click="lastPage">上页</span>
<span class="page-number">{{pageNumber}}</span> <span class="page-number" :style="{opacity: (pageNumber === 1 || isLoadingPage) && files.length < pageSize ? 0 : 1}">{{pageNumber}}</span>
<span class="page-ctl-next" :style="{opacity: files.length < pageSize ? 0 : 1}" @click="nextPage">下页</span> <span class="page-ctl-next" :style="{opacity: files.length < pageSize ? 0 : 1}" @click="nextPage">下页</span>
</div> </div>
<div class="out-btn" @click="outAllNers">导出json结果</div> <div class="out-btn" @click="outAllNers">导出json结果</div>
@ -24,8 +25,9 @@
<div class="right"> <div class="right">
<div class="title"> <div class="title">
<span>选择标签</span> <span>选择标签</span>
<button v-if="projectType === '图片点标注'" @click="autoAnno" class="auto-anno">自动标注</button>
<div class="type-box"> <div class="type-box">
<span v-for="type in typeList" :key="type" @click="setType(type)" @contextmenu="delType(type, $event)" :class="nowType===type?'type selected':'type'" <span v-for="type in typeList" :key="type" @click="setType(type)" @contextmenu="delType(type, $event)" :class="isTypeSelected(type)?'type selected':'type'"
:style="{ :style="{
backgroundColor: types[type] ? types[type].color : '#fff' backgroundColor: types[type] ? types[type].color : '#fff'
}" }"
@ -43,47 +45,78 @@
</span> </span>
</div> </div>
</div> </div>
<div id="ner-box" class="ner-box" @mouseup="setMode('')" @mouseleave="setMode('');setFocus('')" @keydown="setTypeByFastKey" @mouseover="setFocus('ner-box')"> <div id="ner-box" class="ner-box" @mouseup="setMode('')" @touchend="setMode('')" @mouseleave="setMode('');setFocus('')" @keydown="setTypeByFastKey" @mouseover="setFocus('ner-box')">
<div class="word-rect-area"> <!-- <svg style=" position: absolute; z-index: 99999999; overflow: unset; pointer-events: none">
<span class="rect" v-for="(word, idx) in nowNers" :key="idx"> <template class="rect" v-for="(word, idx) in nowNers" >
<span v-for="(w, i) in word.name" :key="`${word}${w}${i}`"> <template v-for="(w, i) in word.name">
<!-- <span class="ner-type" <line
v-if="i===0" v-if="i === 0 || ((word.start%columnWordCount)+i) % columnWordCount === 0"
:style="{ :key="`${word}${w}${i}`"
left: `${((word.start+i)%columnWordCount)*20}px`, :x1="`${((word.start+i)%columnWordCount)*20 + (word.isSmall && i === 0 ? 2 : 0)}px`"
top: `${((word.start+i)/columnWordCount|0)*35 - 14}px`, :y1="`${((word.start+i)/columnWordCount|0)*35 + (word.isSmall ? 0 : -2)}px`"
}" :x2="`${((Math.min(word.end-(word.start+i), columnWordCount, columnWordCount - (word.start+i)%columnWordCount))*20 - (word.isSmall && i === 0 ? 4 : 0)) + ((word.start+i)%columnWordCount)*20 + (word.isSmall && i === 0 ? 2 : 0)}px`"
>{{word.type}}</span> --> :y2="`${word.isSmall?18:22+((word.start+i)/columnWordCount|0)*35 + (word.isSmall ? 0 : -2)}px`"
<span class="ner-anchor" style="stroke:rgb(255,0,0);stroke-width:2"
v-if="i === 0 || ((word.start%columnWordCount)+i) % columnWordCount === 0" ></line>
:style="{ </template>
border: '1px solid #ccc', </template>
position: 'absolute', </span>
display: 'inline-block', <text x="201" y="10" fill="red">关系一</text>
left: `${((word.start+i)%columnWordCount)*20 + (word.isSmall && i === 0 ? 2 : 0)}px`, </svg> -->
top: `${((word.start+i)/columnWordCount|0)*35 + (word.isSmall ? 0 : -2)}px`, <div v-if="nerProjectType.indexOf(projectType) > -1">
width: `${(Math.min(word.end-(word.start+i), columnWordCount, columnWordCount - (word.start+i)%columnWordCount))*20 - (word.isSmall && i === 0 ? 4 : 0)}px`, <span class="word" v-for="(word, idx) in nowText" :key="idx" :id="idx" @contextmenu="stopPrev" @mousedown="startSelect(idx, $event)" @touchstart="startSelect(idx, $event)" @touchend="stopSelect()" @mousemove="pointWord(idx)" @touchmove="pointWordByTouch($event)"
height: `${word.isSmall?18:22}px`, >
background: `${types[word.type]?types[word.type]['color']:'000000'}`, {{ word }}
lineHeight: '25px',
borderTopLeftRadius: `${(i===0)?6:0}px`,
borderBottomLeftRadius: `${(i===0)?6:0}px`,
borderLeft: `${i===0?1:0} solid #ccc`,
borderTopRightRadius: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length <= columnWordCount)?6:0}px`,
borderBottomRightRadius: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length <= columnWordCount)?6:0}px`,
borderRight: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length < columnWordCount)?1:0} solid #ccc`
}"></span>
</span>
</span> </span>
</div> </div>
<span class="word" v-for="(word, idx) in nowText" :key="idx" @contextmenu="stopPrev" @mousedown="startSelect(idx, $event)" @mousemove="pointWord(idx)" <div v-if="nerProjectType.indexOf(projectType) > -1">
> <div class="word-rect-area">
{{ word }} <span class="rect" v-for="(word, idx) in nowNers" :key="idx">
</span> <span v-for="(w, i) in word.name" :key="`${word}${w}${i}`">
<!-- <span class="ner-type"
v-if="i===0"
:style="{
left: `${((word.start+i)%columnWordCount)*20}px`,
top: `${((word.start+i)/columnWordCount|0)*35 - 14}px`,
}"
>{{word.type}}</span> -->
<span class="ner-anchor"
v-if="i === 0 || ((word.start%columnWordCount)+i) % columnWordCount === 0"
:style="{
border: '1px solid #ccc',
position: 'absolute',
display: 'inline-block',
left: `${((word.start+i)%columnWordCount)*20 + (word.isSmall && i === 0 ? 2 : 0)}px`,
top: `${((word.start+i)/columnWordCount|0)*35 + (word.isSmall ? 0 : -2)}px`,
width: `${(Math.min(word.end-(word.start+i), columnWordCount, columnWordCount - (word.start+i)%columnWordCount))*20 - (word.isSmall && i === 0 ? 4 : 0)}px`,
height: `${word.isSmall?18:22}px`,
background: `${types[word.type]?types[word.type]['color']:'000000'}`,
lineHeight: '25px',
borderTopLeftRadius: `${(i===0)?6:0}px`,
borderBottomLeftRadius: `${(i===0)?6:0}px`,
borderLeft: `${i===0?1:0} solid #ccc`,
borderTopRightRadius: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length <= columnWordCount)?6:0}px`,
borderBottomRightRadius: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length <= columnWordCount)?6:0}px`,
borderRight: `${(i!==0 && word.name.length-i <= columnWordCount) || (i===0 && word.start%columnWordCount+word.name.length < columnWordCount)?1:0} solid #ccc`
}"></span>
</span>
</span>
</div>
</div>
<div v-if="projectType === '文本分类'">
<template v-for="(word, idx) in nowText">
<span class="word" v-if="word !== '\n'" :key="idx" @contextmenu="stopPrev" @mousedown="startSelect(idx, $event)" @mousemove="pointWord(idx)">{{ word }}</span>
<br v-if="word === '\n'" :key="idx"/>
</template>
</div>
<CVPoint v-if="projectType === '图片点标注'" :fileContent="nowText" :annoDetails="ners" :nowType="nowType" :types="types" :save="save"></CVPoint>
<CVCls v-if="projectType === '图像分类'" :fileContent="nowText" :annoDetails="ners" :nowType="nowType" :types="types" :save="save"></CVCls>
<RLHF v-if="projectType === '人类反馈强化学习'" :fileContent="nowText" :annoDetails="ners" :nowType="nowType" :types="types" :save="save"></RLHF>
<Rel v-if="projectType === '关系标注'" :relDetails="relDetails" :nowType="nowType" :types="types" :save="save"></Rel>
</div> </div>
<div class="page-btn-box"> <div class="page-btn-box">
<button class="page-btn" @click="changeIdx(-1)" @mouseover="setFocus('page-up')" @mouseleave="setFocus('')">上一个 {{ fastTypeKey['page-up'] ? `${fastTypeKey['page-up']}` : '' }}</button> <button class="page-btn" @click="changeIdx(-1, $event)" @mouseover="setFocus('page-up')" @mouseleave="setFocus('')">上一个 {{ fastTypeKey['page-up'] ? `${fastTypeKey['page-up']}` : '' }}</button>
<button class="page-btn" @click="changeIdx(+1)" @mouseover="setFocus('page-down')" @mouseleave="setFocus('')">下一个 {{ fastTypeKey['page-down'] ? `${fastTypeKey['page-down']}` : '' }}</button> <button class="page-btn" @click="changeIdx(+1, $event)" @mouseover="setFocus('page-down')" @mouseleave="setFocus('')">下一个 {{ fastTypeKey['page-down'] ? `${fastTypeKey['page-down']}` : '' }}</button>
</div> </div>
</div> </div>
<div class="result-box"> <div class="result-box">
@ -93,8 +126,9 @@
backgroundColor: types[ner.type] ? types[ner.type].color : `#fff`, backgroundColor: types[ner.type] ? types[ner.type].color : `#fff`,
}" }"
> >
<span class="result-type">{{ ner.type.substr(0,2) }}</span> <span class="result-name">{{ ner.name }}
<span class="result-name">{{ ner.name }}</span> <svg t="1649340286830" class="result-name-del" @click="del(idx)" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5736" width="17" height="17"><path d="M916.945455 251.345455H768V190.836364c0-48.872727-39.563636-90.763636-88.436364-90.763637h-302.545454c-48.872727 0-90.763636 39.563636-90.763637 90.763637v60.509091H137.309091c-16.290909 0-30.254545 13.963636-30.254546 30.254545 0 16.290909 13.963636 30.254545 30.254546 30.254545h777.309091c16.290909 0 30.254545-13.963636 30.254545-30.254545 0-16.290909-11.636364-30.254545-27.927272-30.254545zM346.763636 190.836364c0-16.290909 13.963636-30.254545 30.254546-30.254546h300.218182c16.290909 0 30.254545 13.963636 30.254545 30.254546v60.509091H346.763636V190.836364z m0 0M646.981818 730.763636V400.290909c0-16.290909-13.963636-30.254545-30.254545-30.254545-16.290909 0-30.254545 13.963636-30.254546 30.254545v328.145455c0 16.290909 13.963636 30.254545 30.254546 30.254545 16.290909 2.327273 30.254545-11.636364 30.254545-27.927273z m0 0M467.781818 730.763636V400.290909c0-16.290909-13.963636-30.254545-30.254545-30.254545-16.290909 0-30.254545 13.963636-30.254546 30.254545v328.145455c0 16.290909 13.963636 30.254545 30.254546 30.254545 16.290909 2.327273 30.254545-11.636364 30.254545-27.927273z m0 0" p-id="5737" fill="#d81e06"></path><path d="M795.927273 372.363636c-16.290909 0-30.254545 13.963636-30.254546 30.254546v449.163636c0 16.290909-13.963636 30.254545-30.254545 30.254546h-418.909091c-16.290909 0-30.254545-13.963636-30.254546-30.254546V400.290909c0-16.290909-13.963636-30.254545-30.254545-30.254545-16.290909 0-30.254545 13.963636-30.254545 30.254545v449.163636c0 48.872727 39.563636 90.763636 90.763636 90.763637h418.909091c48.872727 0 90.763636-39.563636 90.763636-90.763637V402.618182c0-16.290909-13.963636-30.254545-30.254545-30.254546z m0 0" p-id="5738" fill="#d81e06"></path></svg>
</span>
</div> </div>
</div> </div>
</div> </div>
@ -102,34 +136,41 @@
</template> </template>
<script> <script>
function getColor () { import { getColor } from '../../js/color.js'
const idxs = '0123456789abcdef' import CVPoint from '@/components/CV/point.vue'
let color = '#' import CVCls from '@/components/CV/cls.vue'
for (let i = 0; i < 6; i += 1) { import RLHF from '@/components/NLP/rlhf.vue'
color += idxs[Math.random() * idxs.length | 0] import Rel from '@/components/NLP/rel.vue'
}
return color
}
function get (url, cb) { //
query('GET', url, '', cb) const isLocal = false
function get (url, cb, config = {}) {
query('GET', url, '', cb, config)
} }
function post (url, data, cb) { function post (url, data, cb, config = {}) {
query('POST', url, data, cb) query('POST', url, data, cb, config)
} }
function query (method, url, data = '', cb, tryTimes = 0) { function query (method, url, data = '', cb, config = {}) {
config.tryTimes = config.tryTimes || 0
config.isDirect = config.isDirect || false
var xhr = new XMLHttpRequest() var xhr = new XMLHttpRequest()
xhr.open(method, url) xhr.open(method, url)
xhr.setRequestHeader('content-type', 'application/json') xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function () { xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) { if (xhr.readyState === 4 && xhr.status === 200) {
if (config.isDirect) {
return cb(xhr.responseText) //
}
const result = JSON.parse(xhr.responseText) const result = JSON.parse(xhr.responseText)
if (result.errCode !== 0) { if (result.errCode !== 0) {
if (tryTimes >= 2) { if (config.tryTimes >= 2) {
alert(result.errMsg) alert(result.errMsg)
} else { } else {
setTimeout(() => { setTimeout(() => {
query(method, url, data = '', cb, tryTimes + 1) config.tryTimes += 1
query(method, url, data, cb, config)
}, 200) }, 200)
} }
} else { } else {
@ -154,11 +195,18 @@ function updateType2Server (projectName, typeList, types) {
export default { export default {
name: 'NER', name: 'NER',
components: {
CVPoint,
CVCls,
RLHF,
Rel
},
data () { data () {
return { return {
configCanCtlType: false, // configCanCtlType: isLocal, //
pageNumber: 1, pageNumber: 1,
pageSize: 20, pageSize: 20,
isLoadingPage: false,
inputType: '', inputType: '',
projectName: '', // projectName: '', //
projectType: '', // projectType: '', //
@ -195,7 +243,10 @@ export default {
wordsOutType: [], // wordsOutType: [], //
nersCache: { // nersCache: { //
}, },
mode: '' // 'select' mode: '', // 'select'
nerProjectType: ['命名实体识别', '关系标注'],
relStartIdx: '',
relDetails: []
} }
}, },
computed: { computed: {
@ -225,31 +276,44 @@ export default {
} }
}, },
methods: { methods: {
log (...args) {
console.log(args)
},
//
getFiles () {
const that = this
that.isLoadingPage = true
get(`/v1/files/query?projectName=${that.projectName}&pageNumber=${that.pageNumber}&pageSize=${that.pageSize}`, function (info) {
that.isLoadingPage = false
if (!info || info.length === 0) {
that.pageNumber -= 1
}
let newFiles = info.map((item) => {
if (typeof item === 'string') return item
that.isAnnoDic[`${that.projectName}_${item.fileName}`] = item.isAnno
return item.fileName
})
if (that.files.indexOf(newFiles[0]) === -1) {
that.$set(that, 'files', [...that.files, ...newFiles])
}
console.log(that.files)
//
if (that.files[0] && !that.nowFile) {
that.setNowText(that.files[0])
}
})
},
lastPage () { lastPage () {
const that = this const that = this
if (that.pageNumber > 1) { if (that.pageNumber > 1) {
that.pageNumber = that.pageNumber - 1 that.pageNumber = that.pageNumber - 1
get(`/v1/files/query?projectName=${that.projectName}&pageNumber=${that.pageNumber}&pageSize=${that.pageSize}`, function (info) { that.getFiles()
that.$set(that, 'files', info.map((item) => {
if (typeof item === 'string') return item
that.isAnnoDic[`${that.projectName}_${item.fileName}`] = item.isAnno
return item.fileName
}))
})
} }
}, },
nextPage () { nextPage () {
const that = this const that = this
if (that.files.length === that.pageSize) { that.pageNumber = that.pageNumber + 1
that.pageNumber = that.pageNumber + 1 that.getFiles()
get(`/v1/files/query?projectName=${that.projectName}&pageNumber=${that.pageNumber}&pageSize=${that.pageSize}`, function (info) {
that.$set(that, 'files', info.map((item) => {
if (typeof item === 'string') return item
that.isAnnoDic[`${that.projectName}_${item.fileName}`] = item.isAnno
return item.fileName
}))
})
}
}, },
goHome: function () { goHome: function () {
this.$router.push({path: '/'}) this.$router.push({path: '/'})
@ -265,11 +329,15 @@ export default {
} }
const that = this const that = this
// //
post('/v1/anno/create', { let annoInfo = {
projectName: that.projectName, projectName: that.projectName,
fileName: that.nowFile, fileName: that.nowFile,
annoDetails: JSON.stringify(that.ners) annoDetails: that.ners
}) }
if (that.projectType === '关系标注') {
annoInfo.relDetails = that.relDetails
}
post('/v1/anno/create', annoInfo)
that.$set(that.nersCache, that.nowFile, [...that.ners]) that.$set(that.nersCache, that.nowFile, [...that.ners])
return true return true
}, },
@ -285,24 +353,49 @@ export default {
const hasCache = !!that.nersCache[newFile] const hasCache = !!that.nersCache[newFile]
that.$set(that, 'ners', that.nersCache[newFile] ? [...that.nersCache[newFile]] : []) that.$set(that, 'ners', that.nersCache[newFile] ? [...that.nersCache[newFile]] : [])
that.flushWordsType() that.flushWordsType()
if (that.nowText) { if (that.nowText && that.projectType !== '关系标注') {
delete window.isLoadingNowText delete window.isLoadingNowText
return
} else { } else {
get(`/v1/anno/query?projectName=${that.projectName}&fileName=${newFile}`, function (info) { get(`/v1/anno/query?projectName=${that.projectName}&fileName=${newFile}`, function (info) {
delete window.isLoadingNowText delete window.isLoadingNowText
// 线 // 线
if (!hasCache && info.annoDetails) { if (!hasCache && info.annoDetails) {
that.$set(that, 'ners', JSON.parse(info.annoDetails)) console.log(newFile, that.nowFile)
that.$set(that.nersCache, that.nowFile, [...that.ners]) if (newFile === that.nowFile) {
that.flushWordsType() that.$set(that, 'ners', info.annoDetails)
that.flushWordsType()
}
//
that.$set(that.nersCache, newFile, info.annoDetails)
} }
// if (that.projectType === '关系标注' && newFile === that.nowFile) {
console.log('relDetails', info.relDetails)
that.$set(that, 'relDetails', info.relDetails || [])
}
//
that.$set(that.textDic, newFile, info.fileContent) that.$set(that.textDic, newFile, info.fileContent)
that.nowText = that.textDic[newFile] if (newFile === that.nowFile) {
that.nowText = that.textDic[newFile]
}
}) })
} }
if (that.files.indexOf(newFile) >= (that.files.length - 1) - 2) {
// 3
that.pageNumber = that.pageNumber + 1
that.getFiles()
}
//
let selectFileDom = document.getElementById(newFile)
let fileListDom = document.getElementById('file-list')
if (selectFileDom && fileListDom) {
fileListDom.scrollTop = selectFileDom.offsetTop - 12 - 30 //
}
}, },
changeIdx: function (d) { changeIdx: function (d, event) {
if (event) {
event.preventDefault() //
}
const nowIdx = this.files.indexOf(this.nowFile) const nowIdx = this.files.indexOf(this.nowFile)
let newIdx = nowIdx + d let newIdx = nowIdx + d
if (newIdx < 0) newIdx = 0 if (newIdx < 0) newIdx = 0
@ -328,12 +421,51 @@ export default {
return idx return idx
} }
}, },
pointWordByTouch: function (event) {
event.preventDefault() //
let {pageX, pageY} = event.touches[0]
let dom = document.elementFromPoint(pageX, pageY)
if (dom && dom.id) {
this.pointWord(dom.id)
}
},
/** /**
* 配置标注类型 * 配置标注类型
* @param 类型 * @param 类型
*/ */
setType: function (type, ev) { setType: function (type, ev) {
this.$set(this, 'nowType', type) if (!this.nowFile) {
//
return false
}
if (this.nerProjectType.indexOf(this.projectType) > -1) {
this.$set(this, 'nowType', type)
} else if (['文本分类', '图像分类'].indexOf(this.projectType) > -1) {
let typeIdx = -1
this.ners.some((ner, idx) => {
if (ner.type === type) {
typeIdx = idx
return ner.type === type
}
})
if (typeIdx === -1) {
this.ners.push({type})
} else {
this.ners.splice(typeIdx, 1)
}
this.$set(this, 'nowType', type)
this.save()
} else if (this.projectType === '人类反馈强化学习') {
console.log(this.nowText === type, type)
this.$set(this, 'nowType', type)
clearInterval(window.rlhf_inter)
window.rlhf_inter = setInterval(() => {
this.$set(this, 'nowType', '')
}, 200)
} else {
console.log(type)
this.$set(this, 'nowType', type)
}
}, },
delType: function (type, ev) { delType: function (type, ev) {
if (!this.configCanCtlType) return false if (!this.configCanCtlType) return false
@ -375,7 +507,7 @@ export default {
if (!newType) return false if (!newType) return false
if (that.types[newType]) return false if (that.types[newType]) return false
that.$set(that.types, newType, { that.$set(that.types, newType, {
color: getColor() color: getColor(that.types)
}) })
that.typeList.push(newType) that.typeList.push(newType)
updateType2Server(that.projectName, that.typeList, that.types) updateType2Server(that.projectName, that.typeList, that.types)
@ -423,21 +555,63 @@ export default {
} }
this.$set(this, 'wordsOutType', this.wordsOutType) this.$set(this, 'wordsOutType', this.wordsOutType)
}, },
getNerIdxByIdx: function (idx) {
const ners = this.ners
for (let i = ners.length - 1; i >= 0; i -= 1) {
const ner = ners[i]
if (idx >= ner.start && idx < ner.end) {
return i
}
}
},
delIdx: function (idx) {
const nerIdx = this.getNerIdxByIdx(idx)
this.del(nerIdx)
},
del: function (idx) {
const ners = this.ners
ners.splice(idx, 1)
this.$set(this, 'ners', ners)
this.save() //
},
startSelect: function (idx, event) { startSelect: function (idx, event) {
if (this.nerProjectType.indexOf(this.projectType) === -1) return
if (this.nowType.indexOf('关系-') > -1) {
if (event.which === 3) return
if (typeof this.relStartIdx === 'number') {
console.log(this.relStartIdx, idx)
this.relDetails.push({
start: this.relStartIdx,
end: idx,
type: this.nowType
})
this.$set(this, 'relStartIdx', undefined)
this.save()
} else {
this.$set(this, 'relStartIdx', idx)
}
return
}
let that = this
let isNeedDel = false
if (event.touches) {
//
setTimeout(() => {
if (window.delMarkIdx === idx) {
delete window.delMarkIdx
that.delIdx(idx)
}
}, 300)
window.delMarkIdx = idx
}
if (event.which === 3) { if (event.which === 3) {
//
isNeedDel = true
}
if (isNeedDel) {
event.preventDefault() event.preventDefault()
// //
const ners = this.ners this.delIdx(idx)
for (let i = ners.length - 1; i >= 0; i -= 1) {
const ner = ners[i]
if (idx >= ner.start && idx < ner.end) {
ners.splice(i, 1)
this.$set(this, 'ners', ners)
this.flushWordsType()
this.save() //
return true
}
}
return true return true
} }
this.setMode('select') this.setMode('select')
@ -446,6 +620,9 @@ export default {
this.endIdx = idx this.endIdx = idx
this.pointWord(idx, {isDefaultClick: true}) this.pointWord(idx, {isDefaultClick: true})
}, },
stopSelect: function () {
delete window.delMarkIdx
},
checkIsRepeat: function (tarNer) { checkIsRepeat: function (tarNer) {
for (let i = 0; i < this.ners.length; i += 1) { for (let i = 0; i < this.ners.length; i += 1) {
const ner = this.ners[i] const ner = this.ners[i]
@ -460,7 +637,8 @@ export default {
return false return false
} }
const isRepeat = this.checkIsRepeat(this.nowNer) const isRepeat = this.checkIsRepeat(this.nowNer)
if (!isRepeat && this.nowNer.isMove) { if (!isRepeat && this.nowNer.isMove && this.nowNer.name) {
console.log(this.nowNer)
delete this.nowNer.isMove delete this.nowNer.isMove
this.ners.push(this.nowNer) this.ners.push(this.nowNer)
this.$set(this, 'ners', this.ners.sort((a, b) => { this.$set(this, 'ners', this.ners.sort((a, b) => {
@ -481,7 +659,7 @@ export default {
event.preventDefault() event.preventDefault()
// //
var data = event.dataTransfer var data = event.dataTransfer
var files = data.files var files = data.files || []
// //
this.processFiles(files) this.processFiles(files)
}, },
@ -509,12 +687,20 @@ export default {
} }
}, },
outAllNers () { outAllNers () {
if (!isLocal) {
// url
window.open(`/v1/files/get_anno_json?projectName=${this.projectName}`, '_self')
return true
}
this.nersCache[this.nowFile] = this.ners this.nersCache[this.nowFile] = this.ners
const out = [] const out = []
for (const fileName in this.nersCache) { for (const fileName in this.nersCache) {
const file = fileName const file = fileName
const text = this.textDic[fileName] const text = this.textDic[fileName]
const entity = this.nersCache[fileName] const entity = JSON.parse(JSON.stringify(this.nersCache[fileName]))
entity.map((item) => {
delete item.isSmall
})
out.push({ file, text, entity }) out.push({ file, text, entity })
} }
this.saveTxt(`${Date.now()}.json`, JSON.stringify(out)) this.saveTxt(`${Date.now()}.json`, JSON.stringify(out))
@ -546,22 +732,80 @@ export default {
console.log(tarType, ev.target.value) console.log(tarType, ev.target.value)
that.$set(that.types[tarType], 'color', ev.target.value) that.$set(that.types[tarType], 'color', ev.target.value)
updateType2Server(that.projectName, that.typeList, that.types) updateType2Server(that.projectName, that.typeList, that.types)
},
//
isTypeSelected (type) {
if (this.nerProjectType.indexOf(this.projectType) > -1) {
return this.nowType === type
} else if (['文本分类', '图像分类'].indexOf(this.projectType) > -1) {
return this.ners.some((ner) => {
return ner.type === type
})
} else {
return this.nowType === type
}
},
//
autoAnno () {
const that = this
// base64
const img = document.getElementById('anno-img')
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
//
const width = img.naturalWidth
const height = img.naturalHeight
// canvas
canvas.width = width
canvas.height = height
//
ctx.drawImage(img, 0, 0, width, height)
// base64
const base64 = canvas.toDataURL('image/png')
//
const base64Data = base64.replace(/^data:image\/\w+;base64,/, '')
//
// const url = 'http://127.0.0.1:5000/detect'
const url = 'http://127.0.0.1:5000/cv_cls'
post(url, {
projectName: that.projectName,
'image': base64Data,
'types': ['小狗', '小猫']
}, (info) => {
//
const _ners = []
for (let i = 0; i < info.rect_angles.length; i++) {
const point = info.rect_angles[i]
const width = info.width
const height = info.height
console.log(point)
_ners.push({
'type': that.nowType,
'points': [[point.x / width, point.y / height]]
})
}
that.ners = [..._ners]
//
that.save()
})
} }
}, },
watch: { watch: {
ners: function () { ners: function () {
// ner if (this.nerProjectType.indexOf(this.projectType) > -1) {
let nowSmallAreaEnd // ner
for (let i = 0; i < this.ners.length; i++) { let nowSmallAreaEnd
const ner = this.ners[i] for (let i = 0; i < this.ners.length; i++) {
ner.isSmall = false const ner = this.ners[i]
if (nowSmallAreaEnd) { delete ner.isSmall
if (ner.start <= nowSmallAreaEnd) { if (nowSmallAreaEnd) {
ner.isSmall = true if (ner.start <= nowSmallAreaEnd) {
ner.isSmall = true
}
} }
if (!nowSmallAreaEnd) nowSmallAreaEnd = ner.end - 1
nowSmallAreaEnd = Math.max(nowSmallAreaEnd, ner.end - 1)
} }
if (!nowSmallAreaEnd) nowSmallAreaEnd = ner.end - 1
nowSmallAreaEnd = Math.max(nowSmallAreaEnd, ner.end - 1)
} }
} }
}, },
@ -581,15 +825,9 @@ export default {
return entityType.type return entityType.type
}) })
that.types = types that.types = types
// //
if (that.typeList && that.typeList[0]) that.nowType = that.typeList[0] if (that.typeList && that.typeList[0] && projectType.indexOf('分类') === -1 && projectType.indexOf('强化学习') === -1) that.nowType = that.typeList[0]
get(`/v1/files/query?projectName=${projectName}&pageNumber=${that.pageNumber}&pageSize=${that.pageSize}`, function (info) { that.getFiles()
that.$set(that, 'files', info.map((item) => {
if (typeof item === 'string') return item
that.isAnnoDic[`${that.projectName}_${item.fileName}`] = item.isAnno
return item.fileName
}))
})
} }
function calcColumnWordCount () { function calcColumnWordCount () {
const nerBox = document.getElementById('ner-box') const nerBox = document.getElementById('ner-box')
@ -646,7 +884,8 @@ export default {
<!-- Add "scoped" attribute to limit CSS to this component only --> <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped> <style scoped>
.home { .home,
.now-file {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
@ -659,6 +898,14 @@ export default {
font-weight: 700; font-weight: 700;
vertical-align: center; vertical-align: center;
} }
.home {
background: #1161ca;
z-index: 2;
}
.now-file {
left: unset;
right: 0;
}
.out-title { .out-title {
display: inline-block; display: inline-block;
background: #1161ca; background: #1161ca;
@ -671,6 +918,12 @@ export default {
box-sizing: border-box; box-sizing: border-box;
vertical-align: middle; vertical-align: middle;
} }
.out-title>.out-title-span {
position: relative;
padding: 0 4px;
display: inline-block;
background: #1161ca;
}
.layout { .layout {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@ -694,11 +947,13 @@ export default {
} }
.left .file { .left .file {
margin: 12px 0; margin: 12px 0;
padding: 0 4px;
cursor: pointer; cursor: pointer;
width: 100%; width: 100%;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
box-sizing: border-box;
} }
.left .file.checked { .left .file.checked {
position: relative; position: relative;
@ -758,6 +1013,29 @@ export default {
flex-direction: column; flex-direction: column;
user-select: none; user-select: none;
} }
.auto-anno {
float: right;
margin-right: 10px;
cursor: pointer;
box-sizing: content-box;
border: 2px solid #03022c;
text-align: center;
display: inline-block;
padding: 0 4px;
min-width: 100px;
height: 32px;
font-size: 18px;
line-height: 30px;
border-radius: 4px;
background: #03022c;
color: #fff;
font-weight: 500;
vertical-align: middle;
outline: none;
}
button:hover {
opacity: .7;
}
.type-box { .type-box {
display: inline; display: inline;
line-height: 40px; line-height: 40px;
@ -796,22 +1074,28 @@ export default {
.type { .type {
position: relative; position: relative;
box-sizing: content-box; box-sizing: content-box;
border: 1px solid #ccc; border: 2px solid #0000;
border-bottom: 3px solid #ccc;
text-align: center; text-align: center;
opacity: .2;
}
.type:hover {
opacity: .8;
}
@media screen and (max-width: 768px) {
/* 防止手机点击后持续的hover效果 */
.type:hover {
opacity: .2;
}
}
.type.selected {
opacity: 1;
} }
.type.selected,
.result.selected { .result.selected {
position: relative; position: relative;
opacity: 1 !important; opacity: 1 !important;
background: white; background: white;
border: 0; border: 0;
} }
.type.selected {
transform: translateX(0px) translateY(2px);
border: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
.ner-box { .ner-box {
position: relative; position: relative;
flex: 1; flex: 1;
@ -822,6 +1106,10 @@ export default {
overflow: auto; overflow: auto;
/* font-size: 0; */ /* font-size: 0; */
} }
.ner-box::-webkit-scrollbar {
/* 隐藏标注区域的滚动条,防止影响到标注定位 */
width: 0;
}
.ner-box .word { .ner-box .word {
display: inline-block; display: inline-block;
position: relative; position: relative;
@ -851,8 +1139,10 @@ export default {
} }
.result-box { .result-box {
width: 120px; width: 120px;
overflow: auto;
} }
.result { .result {
position: relative;
overflow: hidden; overflow: hidden;
padding: 0 4px; padding: 0 4px;
height: 22px; height: 22px;
@ -876,7 +1166,21 @@ export default {
line-height: 22px; line-height: 22px;
} }
.result-name { .result-name {
width: calc(100% - 30% - 8px); width: calc(100% - 8px);
}
.result-name-del {
display: none;
vertical-align: text-bottom;
position: absolute;
right: 0px;
top: 2px;
}
.result-name-del:hover {
cursor: pointer;
opacity: .6;
}
.result-name:hover .result-name-del {
display: inline-block;
} }
.word-rect-area { .word-rect-area {
@ -891,7 +1195,6 @@ export default {
.word-rect-area .rect { .word-rect-area .rect {
position: absolute; position: absolute;
pointer-events: none;
} }
.color-input { .color-input {
@ -910,4 +1213,28 @@ export default {
top: -9px; top: -9px;
right: -9px; right: -9px;
} }
@media only screen and (max-width: 800px) {
.out-title {
text-align: right !important;
}
.now-file {
display: none;
}
}
@media only screen and (max-width: 600px) {
.out-title {
font-size: 0;
}
.now-file {
display: inline-block;
}
}
@media only screen and (max-width: 800px) {
.result-box {
display: none;
}
.left {
display: none;
}
}
</style> </style>

View File

@ -0,0 +1,119 @@
<template>
<div class="rel-box">
<svg v-for="(relLine, idx) in relLines" :key="idx" class="rel"
xmlns="http://www.w3.org/2000/svg" version="1.1" >
<marker id="arrow" markerUnits="strokeWidth" markerWidth="8" markerHeight="8" viewBox="0 0 12 12" refX="6" refY="6" orient="auto">
<path d="M2,2 L10,6 L2,10 L6,6 L2,2" :style="`fill:${types[relDetails[idx]['type']]['color']}`"/>
</marker>
<path :d="relLine"
:title="relDetails[idx]['type']"
:style="`stroke:${types[relDetails[idx]['type']]['color']};stroke-width:3;fill:#0000;marker-end:url(#arrow)`"
@contextmenu="delRel($event, idx)"
/>
</svg>
</div>
</template>
<script>
export default ({
name: 'Rel',
props: {
nowType: {
type: String,
default: '1234',
required: true
},
relDetails: {
type: Array,
required: true
},
save: {
type: Function,
required: true
},
types: {
type: Object,
required: true
}
},
data () {
return {
points: [],
width: 0,
height: 0,
relLines: []
}
},
methods: {
log (...args) {
console.log(args)
},
delRel (e, idx) {
e.preventDefault()
this.relDetails.splice(idx, 1)
this.save()
},
calRelLines (val) {
if (!val) {
val = this.relDetails
}
console.log(this.types)
let _relLines = []
for (let i = 0; i < val.length; i++) {
const item = val[i]
let startCharDom = document.getElementById(item.start)
let endCharDom = document.getElementById(item.end)
let sx = startCharDom.offsetLeft + startCharDom.offsetWidth / 2
let sy = startCharDom.offsetTop + 9
let ex = endCharDom.offsetLeft + endCharDom.offsetWidth / 2
let ey = endCharDom.offsetTop + 9
let cx = (sx + ex) / 2
let cy = (sy + ey) / 2 - 20
_relLines.push(`M${sx} ${sy} Q${cx} ${cy} ${ex} ${ey}`)
}
console.log(_relLines)
this.relLines = _relLines
}
},
watch: {
relDetails: {
handler (val) {
this.calRelLines(val)
},
deep: true
},
nowType: {
handler (val) {
}
}
},
mounted () {
let that = this
window.onresize = function () {
that.calRelLines()
}
}
})
</script>
<style scoped>
.rel-box,
.rel {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 100;
/* background: rgba(0, 0, 0, 0.5); */
pointer-events: none;
}
.rel path {
pointer-events: all;
cursor: pointer;
}
.rel:hover {
/* 抬起来一些 */
opacity: 0.5;
}
</style>

View File

@ -0,0 +1,132 @@
<template>
<div class="rlhf-box">
<div v-for="(line, idx) in fileContent.split('<whale_n>')" :key="idx" class="line" @click="clickLine(idx)">
<!-- <template v-for="(word, idx) in line">
<span class="word" v-if="word !== '\n'" :key="idx">{{ word }}</span>
<br v-if="word === '\n'" :key="idx"/>
</template> -->
<div class="textarea">{{line}}</div>
<span class="rank" v-if="annoDetails.indexOf(String(idx+1)) !== -1">{{annoDetails.indexOf(String(idx+1)) + 1}}</span>
</div>
</div>
</template>
<script>
export default ({
name: 'RLHF',
props: {
fileContent: {
type: String,
default: '',
required: true
},
annoDetails: {
type: Array,
default: () => [],
required: true
},
nowType: {
type: String,
default: '1234',
required: true
},
types: {
type: Object,
default: () => {},
required: true
},
save: {
type: Function,
required: true
}
},
data () {
return {
points: [],
width: 0,
height: 0
}
},
methods: {
log (...args) {
console.log(args)
},
clickLine (idx) {
let rank = String(idx + 1)
if (this.annoDetails.indexOf(rank) === -1) {
this.annoDetails.push(rank)
} else {
this.annoDetails.splice(this.annoDetails.indexOf(rank), 1)
}
this.save()
}
},
watch: {
annoDetails: {
handler (val) {
console.log(val)
},
deep: true
},
nowType: {
handler (val) {
if (!val) {
return
}
if (this.annoDetails.indexOf(val) === -1) {
this.annoDetails.push(val)
} else {
this.annoDetails.splice(this.annoDetails.indexOf(val), 1)
}
this.save()
}
}
}
})
</script>
<style scoped>
.rlhf-box {
display: flex;
flex-direction: column;
}
.line {
position: relative;
border-bottom: 1px solid;
min-height: 36px;
}
.line:hover {
background-color: #eee;
}
@media screen and (max-width: 768px) {
.line:hover {
background-color: #fff0;
}
}
.line>.rank {
position: absolute;
right: 4px;
top: 0;
bottom: 0;
font-size: 36px;
line-height: 36px;
margin: auto;
}
.word {
display: inline-block;
position: relative;
padding-bottom: 15px;
width: 20px;
height: 20px;
line-height: 20px;
vertical-align: bottom;
box-sizing: content-box;
text-align: center;
font-size: 16px;
z-index: 4;
}
.textarea {
white-space: break-spaces;
}
</style>

View File

@ -26,6 +26,11 @@
<p>类型 <p>类型
<select class="type-input" name="type" @change="setType" :value="projectType"> <select class="type-input" name="type" @change="setType" :value="projectType">
<option value ="命名实体识别">命名实体识别</option> <option value ="命名实体识别">命名实体识别</option>
<option value ="文本分类">文本分类</option>
<option value ="图片点标注">图片点标注</option>
<option value ="图像分类">图像分类</option>
<option value ="人类反馈强化学习">人类反馈强化学习</option>
<option value ="关系标注">关系标注</option>
</select> </select>
</p> </p>
<div class="title"> <div class="title">
@ -48,7 +53,11 @@
</span> </span>
</div> </div>
</div> </div>
<p>上传文本</p>
<p style="font-size:10px">请选择包含文本文件的ziptar文件</p>
<input type="file" id="file-input" accept=".zip,.tar,.jsonl,.txt"/>
<p class="edit-box-btn-area"> <p class="edit-box-btn-area">
<button class="button danger" @click="del" v-if="page==='edit'">删除</button>
<button class="button" @click="submit">提交</button> <button class="button" @click="submit">提交</button>
<button class="button" @click="toList">取消</button> <button class="button" @click="toList">取消</button>
</p> </p>
@ -58,24 +67,23 @@
</template> </template>
<script> <script>
function getColor () { import { getColor } from '../../js/color'
const idxs = '0123456789abcdef'
let color = '#'
for (let i = 0; i < 6; i += 1) {
color += idxs[Math.random() * idxs.length | 0]
}
return color
}
function get (url, cb) { function get (url, cb) {
query('GET', url, '', cb) query('GET', url, '', cb)
} }
function post (url, data, cb) { function post (url, data, cb) {
query('POST', url, data, cb) query('POST', url, data, cb)
} }
function query (method, url, data = '', cb) { function form (url, data, cb) {
query('POST', url, data, cb, {
contentType: 'multipart/form-data'
})
}
function query (method, url, data = '', cb, config = {}) {
var xhr = new XMLHttpRequest() var xhr = new XMLHttpRequest()
xhr.open(method, url) xhr.open(method, url)
xhr.setRequestHeader('content-type', 'application/json') if (!config.contentType) xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function () { xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) { if (xhr.readyState === 4 && xhr.status === 200) {
const result = JSON.parse(xhr.responseText) const result = JSON.parse(xhr.responseText)
@ -86,7 +94,11 @@ function query (method, url, data = '', cb) {
} }
} }
} }
xhr.send(JSON.stringify(data)) if (config.contentType === 'multipart/form-data') {
xhr.send(data)
} else {
xhr.send(JSON.stringify(data))
}
} }
export default { export default {
@ -116,6 +128,30 @@ export default {
setType (ev) { setType (ev) {
this.projectType = ev.target.value this.projectType = ev.target.value
}, },
del () {
//
const that = this
if (prompt(`请输入${this.projectName}来确认删除。`) === this.projectName) {
get(`/v1/project/delete_program?projectName=${this.projectName}`, function () {
that.init()
})
} else {
alert('输入错误,删除失败')
}
},
init () {
//
const that = this
that.type = ''
that.projectName = ''
//
get('/v1/index', function (info) {
that.$set(that, 'projects', info)
that.projectName = ''
that.projectType = ''
that.page = 'list'
})
},
submit () { submit () {
const that = this const that = this
const newEntityTypes = that.typeList.map((type) => { const newEntityTypes = that.typeList.map((type) => {
@ -124,19 +160,30 @@ export default {
color: that.types[type].color color: that.types[type].color
} }
}) })
const projectName = that.projectName
post('/v1/project/create', { post('/v1/project/create', {
projectName: that.projectName, projectName: that.projectName,
projectType: that.projectType, projectType: that.projectType,
entityTypes: JSON.stringify(newEntityTypes) entityTypes: JSON.stringify(newEntityTypes)
}, function () { }, function () {
that.type = '' that.init()
that.projectName = '' //
get('/v1/index', function (info) { const fileInputElement = document.getElementById('file-input')
that.$set(that, 'projects', info) if (fileInputElement.files[0]) {
that.projectName = '' let formData = new FormData()
that.projectType = '' let file = fileInputElement.files[0]
that.page = 'list' formData.append('projectName', projectName)
}) formData.append('file', file)
if (file.name.endsWith('.zip')) {
form('/v1/project/get_zipped_data', formData)
} else if (file.name.endsWith('.tar')) {
form('/v1/project/get_zipped_data', formData)
} else if (file.name.endsWith('.jsonl')) {
form('/v1/project/get_jsonl_data', formData)
} else if (file.name.endsWith('.txt')) {
form('/v1/project/get_txt_data', formData)
}
}
}) })
}, },
toNerAnno (project) { toNerAnno (project) {
@ -146,7 +193,7 @@ export default {
toEdit (project = {}) { toEdit (project = {}) {
console.log('project', project) console.log('project', project)
this.projectName = project.projectName || '' this.projectName = project.projectName || ''
this.projectType = project.projectType || '' this.projectType = project.projectType || '命名实体识别' //
this.page = project.projectName ? 'edit' : 'create' this.page = project.projectName ? 'edit' : 'create'
// //
const that = this const that = this
@ -175,7 +222,7 @@ export default {
if (!newType) return false if (!newType) return false
if (that.types[newType]) return false if (that.types[newType]) return false
that.$set(that.types, newType, { that.$set(that.types, newType, {
color: getColor() color: getColor(that.types)
}) })
that.typeList.push(newType) that.typeList.push(newType)
console.log(that.typeList) console.log(that.typeList)
@ -256,6 +303,7 @@ export default {
display: flex; display: flex;
flex: 1 1; flex: 1 1;
flex-direction: row; flex-direction: row;
margin: 0 10px;
/* height: calc(100% - 92px); */ /* height: calc(100% - 92px); */
} }
.button { .button {
@ -265,6 +313,9 @@ export default {
border: 1px solid #ccc; border: 1px solid #ccc;
padding: 5px 10px; padding: 5px 10px;
} }
.button.danger {
background-color: #ff0000;
}
.project-box-titile { .project-box-titile {
margin: auto; margin: auto;
width: 500px; width: 500px;
@ -302,7 +353,7 @@ export default {
margin: 0; margin: 0;
} }
.edit-box { .edit-box {
width: 260px; width: 280px;
margin: auto; margin: auto;
margin-top: 0; margin-top: 0;
text-align: left; text-align: left;

40
fe/src/js/color.js Normal file
View File

@ -0,0 +1,40 @@
const COLORS = [
'#e12d2d', // 红
'#f5a314', // 橙
'#fff838', // 黄
'#72ca2b', // 绿
'#529dff', // 蓝
'#647cf7', // 靛
'#a855ec', // 紫
'#eb98de', // 粉
'#c08c8e', // 褐
'#d2ff8f' // 青
]
function getColor (types = {}) {
const alreadyColorDic = {}
Object.keys(types).forEach(type => {
const { color } = types[type]
alreadyColorDic[color] = true
})
const remainingColors = []
COLORS.forEach(color => {
if (!alreadyColorDic[color]) remainingColors.push(color)
})
if (remainingColors.length) {
// 优先选用未选择的初始颜色
const idx = Math.random() * remainingColors.length | 0
return remainingColors[idx]
} else {
const idxs = '0123456789abcdef'
let color = '#'
for (let i = 0; i < 6; i += 1) {
color += idxs[Math.random() * idxs.length | 0]
}
return color
}
}
export {
getColor
}

8
fe/src/js/utils.js Normal file
View File

@ -0,0 +1,8 @@
export function saveAsFile (data, name) {
const urlObject = window.URL || window.webkitURL || window
const exportBlob = new Blob([data])
const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
saveLink.href = urlObject.createObjectURL(exportBlob)
saveLink.download = name
saveLink.click()
}

View File

@ -1856,10 +1856,10 @@ chownr@^1.0.1:
resolved "https://registry.npm.taobao.org/chownr/download/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" resolved "https://registry.npm.taobao.org/chownr/download/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b"
integrity sha1-b8nXtC0ypYNZYzdmbn0ICE2izGs= integrity sha1-b8nXtC0ypYNZYzdmbn0ICE2izGs=
chromedriver@^2.27.2: chromedriver@^2.46.0:
version "2.46.0" version "2.46.0"
resolved "https://registry.npm.taobao.org/chromedriver/download/chromedriver-2.46.0.tgz?cache=0&sync_timestamp=1614899323230&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fchromedriver%2Fdownload%2Fchromedriver-2.46.0.tgz#3d78e7eb9bb65dd804fe327a6bf76fced12be053" resolved "https://registry.npmmirror.com/chromedriver/-/chromedriver-2.46.0.tgz#3d78e7eb9bb65dd804fe327a6bf76fced12be053"
integrity sha1-PXjn65u2XdgE/jJ6a/dvztEr4FM= integrity sha512-dLtKIJW3y/PuFrPmcw6Mb8Nh+HwSqgVrK1rWgTARXhHfWvV822X2VRkx2meU/tg2+YQL6/nNgT6n5qWwIDHbwg==
dependencies: dependencies:
del "^3.0.0" del "^3.0.0"
extract-zip "^1.6.7" extract-zip "^1.6.7"