Compare commits

..

6 Commits
main ... local

Author SHA1 Message Date
maxmon b2a519952f v1.2.9 2021-06-17 03:05:11 +08:00
maxmon f01b71868a ^ 隐藏滚动条,防止影响到定位计算、以及左侧文本显示 2021-06-17 03:04:18 +08:00
maxmon 83a6bd1a62 * 默认选中拖拽文件中的第一个 2021-06-17 03:03:44 +08:00
maxmon 44064632be * 默认选择person,防止跳出选择的提示 2021-06-17 02:09:30 +08:00
maxmon 151eac65db + 编译初版单机NER工具前端文件 2021-06-17 01:26:05 +08:00
maxmon 3421ffd12d + 适配一个单机的NER工具 2021-06-17 01:24:29 +08:00
76 changed files with 17894 additions and 2767 deletions

9
.gitignore vendored
View File

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

859
LICENSE
View File

@ -1,674 +1,201 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
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
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
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.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
APPENDIX: How to apply the Apache License to your work.
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 apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
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.
Copyright [Datawhale] [name of copyright owner]
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
http://www.apache.org/licenses/LICENSE-2.0
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>.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,78 +1,19 @@
# whaleAnno
## whale-anno
Datawhale自研数据标注工具让标注更简单
Datawhale自研数据标注工具
<a name="快速体验"></a>
## 快速体验
- 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>许可认证。
- NLP
- [X] 命名实体识别
- [X] 文本分类
- [X] 人类反馈强化学习
- [X] 关系标注
- CV
- [X] 关键点
- [X] 图像分类
- [ ] 目标检测
- [ ] 图像分割
<a name="贡献代码"></a>
## 贡献代码
我们非常欢迎你为whale-anno贡献代码也十分感谢你的反馈。
## 快速开始
### 环境配置
#### 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进行许可。
- 非常感谢 [谢文睿](https://github.com/Sm1les) 贡献了NER标注工具的概念想法
- 非常感谢 [马琦钧](https://github.com/Skypow2012) 贡献了NER标注工具的前端代码并编写了中文文档
- 非常感谢 付文豪 贡献了NER标注工具的后端代码

7
be/.gitignore vendored
View File

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

View File

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

View File

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

View File

@ -1,18 +1,13 @@
from ...config.setting import PROJECT_PATH, ANNO_OUTPUT_PATH, DOWNLOAD_FILE_LOCATION
from app.config.setting import PROJECT_PATH, ANNO_OUTPUT_PATH
from app.libs.redprint import RedPrint
from ...libs.redprint import RedPrint
from flask import request, send_file, Response, send_from_directory, make_response
from flask import request
import json
import os
from ...entities.entities import ReturnInfo, FileInfo
from ...libs.tools import read_json_file, read_txt_file, write_json, get_project_file
import threading
import time
from urllib.parse import urlencode
from app.entities.entities import ReturnInfo, FileInfo
from app.libs.tools import read_json_file
#
api = RedPrint('files')
@ -24,23 +19,34 @@ def query_file():
page_number = int(request.args.get("pageNumber"))
page_size = int(request.args.get("pageSize"))
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')
file_names = os.listdir(PROJECT_PATH.format(project_name))
if 'config.json' in file_names:
file_names.remove('config.json')
if 'anno.json' in file_names:
file_names.remove('anno.json')
anno_output_path = ANNO_OUTPUT_PATH.format(project_name)
# 判断路径是否存在
if not os.path.exists(anno_output_path):
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)
file_info = FileInfo()
file_info.fileName = file_name
file_info.isAnno = os.path.exists(anno_output_path)
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
@ -50,58 +56,3 @@ def query_file():
ret_info.errCode = 404
ret_info.errMsg = str(e)
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,7 +10,6 @@ api = RedPrint('index')
# 访问首页 http://localhost:9060/v1/index
# @api.route('/index')
@api.route('', methods=['GET'])
def index():
@ -18,11 +17,7 @@ def index():
ret_info = ReturnInfo()
try:
project_config_info = []
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:
for project_name in os.listdir(PROJECTS):
project_config_name = PROJECT_CONFIG_PATH.format(project_name)
print(project_config_name)
if os.path.exists(project_config_name):

View File

@ -1,152 +1,24 @@
import shutil
from ...config.setting import PROJECT_NAME, PROJECT_TYPE, ENTITY_TYPES, PROJECTS, PROJECT_PATH, PROJECT_CONFIG_PATH, \
from app.config.setting import PROJECT_NAME, PROJECT_TYPE, ENTITY_TYPES, PROJECTS, PROJECT_PATH, PROJECT_CONFIG_PATH, \
ANNO_OUTPUT_PATH
from ...libs.redprint import RedPrint
from app.libs.redprint import RedPrint
from flask import request
import json
import os
from ...libs.tools import make_dir, write_json, read_json_file, unzip_file, get_cn_name
from ...entities.entities import Project, ReturnInfo
from ...config.setting import FILE_NAME
from ...entities.entities import AnnoContents
from app.libs.tools import make_dir, write_json, read_json_file
from app.entities.entities import Project, ReturnInfo
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'])
def create_project():
ret_info = ReturnInfo()
try:
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')
make_dir(PROJECT_PATH.format(project_name))
write_json(PROJECT_CONFIG_PATH.format(project_name), param)
ret_info.errCode = 0
@ -170,6 +42,8 @@ def update_entity_types():
for entity_type in entity_types:
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
project_config_info = read_json_file(PROJECT_CONFIG_PATH.format(project_name))
project = Project()
@ -178,6 +52,16 @@ def update_entity_types():
project.entityTypes = entity_types
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)
ret_info.errMsg = 'update ok'

View File

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

View File

@ -13,11 +13,8 @@ FILE_NAME = 'fileName'
PROJECTS = 'app/projects'
# 项目路径
PROJECT_PATH = PROJECTS + '/{}/'
PROJECT_PATH = PROJECTS + '/' + "{}"
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,7 +15,6 @@ class ReturnInfo:
class QueryAnno:
def __init__(self):
self.annoDetails = []
self.relDetails = []
self.fileContent = ''
# self.isAnno = False

View File

@ -1,31 +1,18 @@
import os
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):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
os.mkdir(path)
# 将json数据写入.json文件
def write_json(json_file_path, data):
with open(json_file_path, 'w', encoding='utf-8') as fh:
fh.write(json.dumps(data, ensure_ascii=False))
with open(json_file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, default=lambda o: o.__dict__)
# 加载json文件中的json数据
@ -34,67 +21,9 @@ def read_json_file(json_file_name):
data = json.load(f)
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文件
def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
data = f.read()
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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1 @@
[{"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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,49 +0,0 @@
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")

View File

@ -1,46 +0,0 @@
# 使用说明
## 视频教程
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
}
]
}
]
```

View File

@ -1,7 +0,0 @@
# 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

@ -0,0 +1,27 @@
# 环境配置
## 一、下载所需软件
### 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安装以后自带的包管理工具*

24
doc/doc_ch/quickstart.md Normal file
View File

@ -0,0 +1,24 @@
# 快速开始
## 一、环境配置
请参考[环境配置](./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 @@
# whale-anno
# dw-tool-ner
> Datawhale's ner tool.

View File

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

View File

@ -12,13 +12,12 @@ module.exports = {
assetsPublicPath: '/',
proxyTable: {
'/v1/': {
target: 'http://127.0.0.1:9060/',
// target: 'https://tekii.cn/',
target: 'http://localhost:9060/',
}
},
// Various Dev Server settings
host: '0.0.0.0', // can be overwritten by process.env.HOST
host: 'localhost', // 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
autoOpenBrowser: false,
errorOverlay: true,
@ -55,7 +54,7 @@ module.exports = {
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
assetsPublicPath: './',
/**
* Source Maps

35
fe/dist/index.html vendored
View File

@ -1,37 +1,6 @@
<!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 {
<!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.e1d40409042dfb31997f812583e801d9.css rel=stylesheet></head><body><div id=app></div><style>html, body {
display: inline-block;
margin: 0;
width: 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><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>
}</style><script type=text/javascript src=./static/js/manifest.3ad1d5771e9b13dbdad2.js></script><script type=text/javascript src=./static/js/vendor.b6a0dabd8e467dbb8b61.js></script><script type=text/javascript src=./static/js/app.5a41636a2107b770ff58.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,2 +1,2 @@
!function(r){var n=window.webpackJsonp;window.webpackJsonp=function(e,u,c){for(var f,i,p,a=0,l=[];a<e.length;a++)i=e[a],o[i]&&l.push(o[i][0]),o[i]=0;for(f in u)Object.prototype.hasOwnProperty.call(u,f)&&(r[f]=u[f]);for(n&&n(e,u,c);l.length;)l.shift()();if(c)for(a=0;a<c.length;a++)p=t(t.s=c[a]);return p};var e={},o={2:0};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=r,t.c=e,t.d=function(r,n,e){t.o(r,n)||Object.defineProperty(r,n,{configurable:!1,enumerable:!0,get:e})},t.n=function(r){var n=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(n,"a",n),n},t.o=function(r,n){return Object.prototype.hasOwnProperty.call(r,n)},t.p="/",t.oe=function(r){throw console.error(r),r}}([]);
//# sourceMappingURL=manifest.2ae2e69a05c33dfc65f8.js.map
!function(r){var n=window.webpackJsonp;window.webpackJsonp=function(e,u,c){for(var f,i,p,a=0,l=[];a<e.length;a++)i=e[a],o[i]&&l.push(o[i][0]),o[i]=0;for(f in u)Object.prototype.hasOwnProperty.call(u,f)&&(r[f]=u[f]);for(n&&n(e,u,c);l.length;)l.shift()();if(c)for(a=0;a<c.length;a++)p=t(t.s=c[a]);return p};var e={},o={2:0};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=r,t.c=e,t.d=function(r,n,e){t.o(r,n)||Object.defineProperty(r,n,{configurable:!1,enumerable:!0,get:e})},t.n=function(r){var n=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(n,"a",n),n},t.o=function(r,n){return Object.prototype.hasOwnProperty.call(r,n)},t.p="./",t.oe=function(r){throw console.error(r),r}}([]);
//# sourceMappingURL=manifest.3ad1d5771e9b13dbdad2.js.map

View File

@ -1 +1 @@
{"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":""}
{"version":3,"sources":["webpack:///webpack/bootstrap fd93dff672fcdb560817"],"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,KAGArB,EAAAsB,GAAA,SAAAC,GAA8D,MAApBC,QAAAC,MAAAF,GAAoBA","file":"static/js/manifest.3ad1d5771e9b13dbdad2.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 fd93dff672fcdb560817"],"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>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>whale-anno</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>dw-tool-ner</title>
</head>
<body>
<div id="app"></div>
@ -15,40 +15,6 @@
width: 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>
<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>
</html>

17289
fe/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,84 +0,0 @@
<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

@ -1,135 +0,0 @@
<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

@ -1,339 +0,0 @@
<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,12 +1,11 @@
<template>
<div class="layout">
<span class="home" @click="goHome">whaleAnno</span>
<span class="now-file">{{ nowFile }}</span>
<h1 class="out-title"><span class="out-title-span">{{projectName}}{{projectType}}</span></h1>
<h1 class="out-title">{{projectName}}{{projectType}}</h1>
<div class="container" @dragover="stopPrev" @drop="setFiles($event)">
<div class="left">
<div class="file-list" id="file-list">
<div v-for="file in files" :key="file" :id="file" @click="setNowText(file)"
<div class="file-list">
<div v-for="file in files" :key="file" @click="setNowText(file)"
:title=file
:class="['file', nowFile===file?'selected':'', isAnnoDic[`${projectName}_${file}`]||(nersCache[file]&&nersCache[file].length)?'checked':'', ].join(' ')"
>
@ -16,18 +15,15 @@
<div class="process-bar" :style="{width: `${processRate*100}%`}"></div>
</div>
<div class="page-ctl">
<span class="page-ctl-last" :style="{opacity: pageNumber === 1 || isLoadingPage ? 0 : 1}" @click="lastPage">上页</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-tips">拖拽文件至上方</span>
</div>
<div class="out-btn" @click="outAllNers">导出json结果</div>
</div>
<div class="right">
<div class="title">
<span>选择标签</span>
<button v-if="projectType === '图片点标注'" @click="autoAnno" class="auto-anno">自动标注</button>
<div class="type-box">
<span v-for="type in typeList" :key="type" @click="setType(type)" @contextmenu="delType(type, $event)" :class="isTypeSelected(type)?'type selected':'type'"
<span v-for="type in typeList" :key="type" @click="setType(type)" @contextmenu="delType(type, $event)" :class="nowType===type?'type selected':'type'"
:style="{
backgroundColor: types[type] ? types[type].color : '#fff'
}"
@ -45,31 +41,7 @@
</span>
</div>
</div>
<div id="ner-box" class="ner-box" @mouseup="setMode('')" @touchend="setMode('')" @mouseleave="setMode('');setFocus('')" @keydown="setTypeByFastKey" @mouseover="setFocus('ner-box')">
<!-- <svg style=" position: absolute; z-index: 99999999; overflow: unset; pointer-events: none">
<template class="rect" v-for="(word, idx) in nowNers" >
<template v-for="(w, i) in word.name">
<line
v-if="i === 0 || ((word.start%columnWordCount)+i) % columnWordCount === 0"
:key="`${word}${w}${i}`"
:x1="`${((word.start+i)%columnWordCount)*20 + (word.isSmall && i === 0 ? 2 : 0)}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`"
:y2="`${word.isSmall?18:22+((word.start+i)/columnWordCount|0)*35 + (word.isSmall ? 0 : -2)}px`"
style="stroke:rgb(255,0,0);stroke-width:2"
></line>
</template>
</template>
</span>
<text x="201" y="10" fill="red">关系一</text>
</svg> -->
<div v-if="nerProjectType.indexOf(projectType) > -1">
<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)"
>
{{ word }}
</span>
</div>
<div v-if="nerProjectType.indexOf(projectType) > -1">
<div id="ner-box" class="ner-box" @mouseup="setMode('')" @mouseleave="setMode('');setFocus('')" @keydown="setTypeByFastKey" @mouseover="setFocus('ner-box')">
<div class="word-rect-area">
<span class="rect" v-for="(word, idx) in nowNers" :key="idx">
<span v-for="(w, i) in word.name" :key="`${word}${w}${i}`">
@ -102,21 +74,14 @@
</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>
<span class="word" v-for="(word, idx) in nowText" :key="idx" @contextmenu="stopPrev" @mousedown="startSelect(idx, $event)" @mousemove="pointWord(idx)"
>
{{ word }}
</span>
</div>
<div class="page-btn-box">
<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, $event)" @mouseover="setFocus('page-down')" @mouseleave="setFocus('')">下一个 {{ fastTypeKey['page-down'] ? `${fastTypeKey['page-down']}` : '' }}</button>
<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)" @mouseover="setFocus('page-down')" @mouseleave="setFocus('')">下一个 {{ fastTypeKey['page-down'] ? `${fastTypeKey['page-down']}` : '' }}</button>
</div>
</div>
<div class="result-box">
@ -126,9 +91,8 @@
backgroundColor: types[ner.type] ? types[ner.type].color : `#fff`,
}"
>
<span class="result-name">{{ ner.name }}
<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>
<span class="result-type">{{ ner.type.substr(0,2) }}</span>
<span class="result-name">{{ ner.name }}</span>
</div>
</div>
</div>
@ -136,41 +100,37 @@
</template>
<script>
import { getColor } from '../../js/color.js'
import CVPoint from '@/components/CV/point.vue'
import CVCls from '@/components/CV/cls.vue'
import RLHF from '@/components/NLP/rlhf.vue'
import Rel from '@/components/NLP/rel.vue'
const IS_LOCAL = true //
//
const isLocal = false
function get (url, cb, config = {}) {
query('GET', url, '', cb, config)
function getColor () {
const idxs = '0123456789abcdef'
let color = '#'
for (let i = 0; i < 6; i += 1) {
color += idxs[Math.random() * idxs.length | 0]
}
function post (url, data, cb, config = {}) {
query('POST', url, data, cb, config)
return color
}
function query (method, url, data = '', cb, config = {}) {
config.tryTimes = config.tryTimes || 0
config.isDirect = config.isDirect || false
function get (url, cb) {
query('GET', url, '', cb)
}
function post (url, data, cb) {
query('POST', url, data, cb)
}
function query (method, url, data = '', cb, tryTimes = 0) {
if (IS_LOCAL) return
var xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (config.isDirect) {
return cb(xhr.responseText) //
}
const result = JSON.parse(xhr.responseText)
if (result.errCode !== 0) {
if (config.tryTimes >= 2) {
if (tryTimes >= 2) {
alert(result.errMsg)
} else {
setTimeout(() => {
config.tryTimes += 1
query(method, url, data, cb, config)
query(method, url, data = '', cb, tryTimes + 1)
}, 200)
}
} else {
@ -195,18 +155,11 @@ function updateType2Server (projectName, typeList, types) {
export default {
name: 'NER',
components: {
CVPoint,
CVCls,
RLHF,
Rel
},
data () {
return {
configCanCtlType: isLocal, //
configCanCtlType: IS_LOCAL, //
pageNumber: 1,
pageSize: 20,
isLoadingPage: false,
inputType: '',
projectName: '', //
projectType: '', //
@ -221,7 +174,7 @@ export default {
nowText: '', //
ners: [], //
nowNer: {}, //
nowType: '', //
nowType: 'person', //
typeList: ['person', 'location', 'organiztion'], //
isAnnoDic: {}, //
nowFocus: '', // //
@ -243,10 +196,7 @@ export default {
wordsOutType: [], //
nersCache: { //
},
mode: '', // 'select'
nerProjectType: ['命名实体识别', '关系标注'],
relStartIdx: '',
relDetails: []
mode: '' // 'select'
}
},
computed: {
@ -276,44 +226,31 @@ export default {
}
},
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 () {
const that = this
if (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
}))
})
}
},
nextPage () {
const that = this
if (that.files.length === that.pageSize) {
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 () {
this.$router.push({path: '/'})
@ -329,15 +266,11 @@ export default {
}
const that = this
//
let annoInfo = {
post('/v1/anno/create', {
projectName: that.projectName,
fileName: that.nowFile,
annoDetails: that.ners
}
if (that.projectType === '关系标注') {
annoInfo.relDetails = that.relDetails
}
post('/v1/anno/create', annoInfo)
annoDetails: JSON.stringify(that.ners)
})
that.$set(that.nersCache, that.nowFile, [...that.ners])
return true
},
@ -353,49 +286,24 @@ export default {
const hasCache = !!that.nersCache[newFile]
that.$set(that, 'ners', that.nersCache[newFile] ? [...that.nersCache[newFile]] : [])
that.flushWordsType()
if (that.nowText && that.projectType !== '关系标注') {
if (that.nowText) {
delete window.isLoadingNowText
return
} else {
get(`/v1/anno/query?projectName=${that.projectName}&fileName=${newFile}`, function (info) {
delete window.isLoadingNowText
// 线
if (!hasCache && info.annoDetails) {
console.log(newFile, that.nowFile)
if (newFile === that.nowFile) {
that.$set(that, 'ners', info.annoDetails)
that.$set(that, 'ners', JSON.parse(info.annoDetails))
that.$set(that.nersCache, that.nowFile, [...that.ners])
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)
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, event) {
if (event) {
event.preventDefault() //
}
changeIdx: function (d) {
const nowIdx = this.files.indexOf(this.nowFile)
let newIdx = nowIdx + d
if (newIdx < 0) newIdx = 0
@ -421,51 +329,12 @@ export default {
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 类型
*/
setType: function (type, ev) {
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) {
if (!this.configCanCtlType) return false
@ -507,7 +376,7 @@ export default {
if (!newType) return false
if (that.types[newType]) return false
that.$set(that.types, newType, {
color: getColor(that.types)
color: getColor()
})
that.typeList.push(newType)
updateType2Server(that.projectName, that.typeList, that.types)
@ -555,63 +424,21 @@ export default {
}
this.$set(this, 'wordsOutType', this.wordsOutType)
},
getNerIdxByIdx: function (idx) {
startSelect: function (idx, event) {
if (event.which === 3) {
event.preventDefault()
//
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)
ners.splice(i, 1)
this.$set(this, 'ners', ners)
this.flushWordsType()
this.save() //
},
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 true
}
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) {
//
isNeedDel = true
}
if (isNeedDel) {
event.preventDefault()
//
this.delIdx(idx)
return true
}
this.setMode('select')
@ -620,9 +447,6 @@ export default {
this.endIdx = idx
this.pointWord(idx, {isDefaultClick: true})
},
stopSelect: function () {
delete window.delMarkIdx
},
checkIsRepeat: function (tarNer) {
for (let i = 0; i < this.ners.length; i += 1) {
const ner = this.ners[i]
@ -637,8 +461,7 @@ export default {
return false
}
const isRepeat = this.checkIsRepeat(this.nowNer)
if (!isRepeat && this.nowNer.isMove && this.nowNer.name) {
console.log(this.nowNer)
if (!isRepeat && this.nowNer.isMove) {
delete this.nowNer.isMove
this.ners.push(this.nowNer)
this.$set(this, 'ners', this.ners.sort((a, b) => {
@ -659,7 +482,7 @@ export default {
event.preventDefault()
//
var data = event.dataTransfer
var files = data.files || []
var files = data.files
//
this.processFiles(files)
},
@ -678,6 +501,10 @@ export default {
//
that.$set(that.files, i, file.name)
that.$set(that.textDic, file.name, e.target.result)
if (i === 0) {
//
that.setNowText(file.name)
}
}
//
// reader.readAsDataURL(file)
@ -687,20 +514,12 @@ export default {
}
},
outAllNers () {
if (!isLocal) {
// url
window.open(`/v1/files/get_anno_json?projectName=${this.projectName}`, '_self')
return true
}
this.nersCache[this.nowFile] = this.ners
const out = []
for (const fileName in this.nersCache) {
const file = fileName
const text = this.textDic[fileName]
const entity = JSON.parse(JSON.stringify(this.nersCache[fileName]))
entity.map((item) => {
delete item.isSmall
})
const entity = this.nersCache[fileName]
out.push({ file, text, entity })
}
this.saveTxt(`${Date.now()}.json`, JSON.stringify(out))
@ -732,72 +551,15 @@ export default {
console.log(tarType, ev.target.value)
that.$set(that.types[tarType], 'color', ev.target.value)
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: {
ners: function () {
if (this.nerProjectType.indexOf(this.projectType) > -1) {
// ner
let nowSmallAreaEnd
for (let i = 0; i < this.ners.length; i++) {
const ner = this.ners[i]
delete ner.isSmall
ner.isSmall = false
if (nowSmallAreaEnd) {
if (ner.start <= nowSmallAreaEnd) {
ner.isSmall = true
@ -807,7 +569,6 @@ export default {
nowSmallAreaEnd = Math.max(nowSmallAreaEnd, ner.end - 1)
}
}
}
},
mounted () {
const that = this
@ -825,9 +586,15 @@ export default {
return entityType.type
})
that.types = types
//
if (that.typeList && that.typeList[0] && projectType.indexOf('分类') === -1 && projectType.indexOf('强化学习') === -1) that.nowType = that.typeList[0]
that.getFiles()
//
if (that.typeList && that.typeList[0]) that.nowType = that.typeList[0]
get(`/v1/files/query?projectName=${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
}))
})
}
function calcColumnWordCount () {
const nerBox = document.getElementById('ner-box')
@ -884,8 +651,7 @@ export default {
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.home,
.now-file {
.home {
position: absolute;
top: 0;
left: 0;
@ -898,14 +664,6 @@ export default {
font-weight: 700;
vertical-align: center;
}
.home {
background: #1161ca;
z-index: 2;
}
.now-file {
left: unset;
right: 0;
}
.out-title {
display: inline-block;
background: #1161ca;
@ -918,12 +676,6 @@ export default {
box-sizing: border-box;
vertical-align: middle;
}
.out-title>.out-title-span {
position: relative;
padding: 0 4px;
display: inline-block;
background: #1161ca;
}
.layout {
display: flex;
flex-direction: column;
@ -947,13 +699,11 @@ export default {
}
.left .file {
margin: 12px 0;
padding: 0 4px;
cursor: pointer;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
box-sizing: border-box;
}
.left .file.checked {
position: relative;
@ -1001,6 +751,10 @@ export default {
.left .page-ctl .page-number {
min-width: 2em;
}
.left .page-ctl .page-tips {
min-width: 2em;
color: #ccc;
}
.left .page-ctl-last:hover,
.left .page-ctl-next:hover,
.left .out-btn:hover {
@ -1013,29 +767,6 @@ export default {
flex-direction: column;
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 {
display: inline;
line-height: 40px;
@ -1074,28 +805,22 @@ button:hover {
.type {
position: relative;
box-sizing: content-box;
border: 2px solid #0000;
border: 1px solid #ccc;
border-bottom: 3px solid #ccc;
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 {
position: relative;
opacity: 1 !important;
background: white;
border: 0;
}
.type.selected {
transform: translateX(0px) translateY(2px);
border: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
.ner-box {
position: relative;
flex: 1;
@ -1106,9 +831,9 @@ button:hover {
overflow: auto;
/* font-size: 0; */
}
.ner-box::-webkit-scrollbar {
/* 隐藏标注区域的滚动条,防止影响到标注定位 */
width: 0;
/* 隐藏滚动条,防止影响到定位计算、以及左侧文本显示 */
::-webkit-scrollbar {
display: none; /* Chrome Safari */
}
.ner-box .word {
display: inline-block;
@ -1139,10 +864,8 @@ button:hover {
}
.result-box {
width: 120px;
overflow: auto;
}
.result {
position: relative;
overflow: hidden;
padding: 0 4px;
height: 22px;
@ -1166,21 +889,7 @@ button:hover {
line-height: 22px;
}
.result-name {
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;
width: calc(100% - 30% - 8px);
}
.word-rect-area {
@ -1195,6 +904,7 @@ button:hover {
.word-rect-area .rect {
position: absolute;
pointer-events: none;
}
.color-input {
@ -1213,28 +923,4 @@ button:hover {
top: -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>

View File

@ -1,119 +0,0 @@
<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

@ -1,132 +0,0 @@
<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,11 +26,6 @@
<p>类型
<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>
</select>
</p>
<div class="title">
@ -53,11 +48,7 @@
</span>
</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">
<button class="button danger" @click="del" v-if="page==='edit'">删除</button>
<button class="button" @click="submit">提交</button>
<button class="button" @click="toList">取消</button>
</p>
@ -67,23 +58,24 @@
</template>
<script>
import { getColor } from '../../js/color'
function getColor () {
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) {
query('GET', url, '', cb)
}
function post (url, data, cb) {
query('POST', url, data, cb)
}
function form (url, data, cb) {
query('POST', url, data, cb, {
contentType: 'multipart/form-data'
})
}
function query (method, url, data = '', cb, config = {}) {
function query (method, url, data = '', cb) {
var xhr = new XMLHttpRequest()
xhr.open(method, url)
if (!config.contentType) xhr.setRequestHeader('content-type', 'application/json')
xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const result = JSON.parse(xhr.responseText)
@ -94,12 +86,8 @@ function query (method, url, data = '', cb, config = {}) {
}
}
}
if (config.contentType === 'multipart/form-data') {
xhr.send(data)
} else {
xhr.send(JSON.stringify(data))
}
}
export default {
name: 'home',
@ -128,30 +116,6 @@ export default {
setType (ev) {
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 () {
const that = this
const newEntityTypes = that.typeList.map((type) => {
@ -160,30 +124,19 @@ export default {
color: that.types[type].color
}
})
const projectName = that.projectName
post('/v1/project/create', {
projectName: that.projectName,
projectType: that.projectType,
entityTypes: JSON.stringify(newEntityTypes)
}, function () {
that.init()
//
const fileInputElement = document.getElementById('file-input')
if (fileInputElement.files[0]) {
let formData = new FormData()
let file = fileInputElement.files[0]
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)
}
}
that.type = ''
that.projectName = ''
get('/v1/index', function (info) {
that.$set(that, 'projects', info)
that.projectName = ''
that.projectType = ''
that.page = 'list'
})
})
},
toNerAnno (project) {
@ -193,7 +146,7 @@ export default {
toEdit (project = {}) {
console.log('project', project)
this.projectName = project.projectName || ''
this.projectType = project.projectType || '命名实体识别' //
this.projectType = project.projectType || ''
this.page = project.projectName ? 'edit' : 'create'
//
const that = this
@ -222,7 +175,7 @@ export default {
if (!newType) return false
if (that.types[newType]) return false
that.$set(that.types, newType, {
color: getColor(that.types)
color: getColor()
})
that.typeList.push(newType)
console.log(that.typeList)
@ -303,7 +256,6 @@ export default {
display: flex;
flex: 1 1;
flex-direction: row;
margin: 0 10px;
/* height: calc(100% - 92px); */
}
.button {
@ -313,9 +265,6 @@ export default {
border: 1px solid #ccc;
padding: 5px 10px;
}
.button.danger {
background-color: #ff0000;
}
.project-box-titile {
margin: auto;
width: 500px;
@ -353,7 +302,7 @@ export default {
margin: 0;
}
.edit-box {
width: 280px;
width: 260px;
margin: auto;
margin-top: 0;
text-align: left;

View File

@ -1,40 +0,0 @@
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
}

View File

@ -1,8 +0,0 @@
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

@ -8,7 +8,7 @@ Vue.use(Router)
export default new Router({
routes: [
{
path: '/NER',
path: '/',
name: 'NER',
component: NER,
props: {
@ -16,7 +16,7 @@ export default new Router({
}
},
{
path: '/',
path: '/home',
name: 'home',
component: home,
props: true

View File

@ -1856,10 +1856,10 @@ chownr@^1.0.1:
resolved "https://registry.npm.taobao.org/chownr/download/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b"
integrity sha1-b8nXtC0ypYNZYzdmbn0ICE2izGs=
chromedriver@^2.46.0:
chromedriver@^2.27.2:
version "2.46.0"
resolved "https://registry.npmmirror.com/chromedriver/-/chromedriver-2.46.0.tgz#3d78e7eb9bb65dd804fe327a6bf76fced12be053"
integrity sha512-dLtKIJW3y/PuFrPmcw6Mb8Nh+HwSqgVrK1rWgTARXhHfWvV822X2VRkx2meU/tg2+YQL6/nNgT6n5qWwIDHbwg==
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"
integrity sha1-PXjn65u2XdgE/jJ6a/dvztEr4FM=
dependencies:
del "^3.0.0"
extract-zip "^1.6.7"