Repository: neurobiology-ut/PHILOW (language: python)

Issue:
Feature/plugin



Discussion / hints:

Fix patch:
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..a737dcf
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,675 @@
+
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://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.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://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
+<http://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
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..0439384
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,6 @@
+include LICENSE
+include README.md
+include requirements.txt
+
+recursive-exclude * __pycache__
+recursive-exclude * *.py[co]
diff --git a/README.md b/README.md
index a718502..4bb7fd1 100644
--- a/README.md
+++ b/README.md
@@ -1,40 +1,61 @@
+# napari-PHILOW
+
+[![License](https://img.shields.io/pypi/l/napari-PHILOW.svg?color=green)](https://github.com/neurobiology-ut/PHILOW/raw/main/LICENSE)
+[![PyPI](https://img.shields.io/pypi/v/napari-PHILOW.svg?color=green)](https://pypi.org/project/napari-PHILOW)
+[![Python Version](https://img.shields.io/pypi/pyversions/napari-PHILOW.svg?color=green)](https://python.org)
+[![tests](https://github.com/neurobiology-ut/napari-PHILOW/workflows/tests/badge.svg)](https://github.com/neurobiology-ut/PHILOW/actions)
+[![codecov](https://codecov.io/gh/neurobiology-ut/napari-PHILOW/branch/main/graph/badge.svg)](https://codecov.io/gh/neurobiology-ut/PHILOW)
+[![napari hub](https://img.shields.io/endpoint?url=https://api.napari-hub.org/shields/napari-PHILOW)](https://napari-hub.org/plugins/napari-PHILOW)
+
 # PHILOW <br>
 ***P***ython-based platform for ***h***uman-***i***n-the-***lo***op (HITL)  ***w***orkflow (PHILOW) <br>
 
-## Overview 
-PHILOW is an interactive deep learning-based platform for 3D datasets implemented on top of [napari](https://github.com/napari/napari) <br>
+PHILOW is an interactive deep learning-based platform for 3D datasets implemented on top of [napari](https://github.com/napari/napari)
 
-Features:
+----------------------------------
 
-&nbsp;&nbsp;&nbsp;&nbsp; (1) generation of the ground truth data sets with annotation assistance, visualization and data management tools<br>
-&nbsp;&nbsp;&nbsp;&nbsp; (2) model training and prediction <br>
-&nbsp;&nbsp;&nbsp;&nbsp; (3) correcting the results of deep learning-based segmentations <br>
-&nbsp;&nbsp;&nbsp;&nbsp; (4) iterate this process to get efficient and good results in a short time  <br>
-&nbsp;&nbsp;  in a single user-friendly application running on Python.
+This [napari] plugin was generated with [Cookiecutter] using [@napari]'s [cookiecutter-napari-plugin] template.
 
+<!--
+Don't miss the full getting started guide to set up your new package:
+https://github.com/napari/cookiecutter-napari-plugin#getting-started
+
+and review the napari docs for plugin developers:
+https://napari.org/plugins/stable/index.html
+-->
 
 ## Installation
-Clone this repository first.   
-Then install requirements.
+
+You can install `napari-PHILOW` via [pip]:
+
+    pip install napari-PHILOW
+    
+or clone this repository   
+then
 ```angular2
-git clone https://github.com/neurobiology-ut/PHILOW.git
 cd PHILOW
-pip install -r requirements.txt
+pip install -e .
 ```
-
+    
 
 ## Usage
-#### load dataset
+
+Launch napari 
+
 ```angular2
-python launcher_simple.py
+napari
 ```
-1) Select Loader
+
+
+#### load dataset
+
+
+1) Plugins > napari-PHILOW > Annotation Mode
 
 2) Select original dir : all slices must be in separate PNG and must be sequentially numbered (e.g. 000.png, 001.png ...)
 
-3) Start new project?    
-yes → do not need to select mask dir    
-no → select saved labels dir    
+3) Select mask dir : To resume from the middle of the annotation, specify here the name of the directory containing the mask image. The directory must contain the same number of files with the same name as the original image.   
+ If you are starting a completely new annotation, you do not need to specify a directory. The directory for mask is automatically created and blank images are generated and stored.
 
 4) Enter a name for the label or model you want to create (e.g. mito, cristae, ...)   
 This name will be used as the directory name of the newly created mask dir if no mask dir is specified, 
@@ -43,7 +64,7 @@ and as the name of the csv file for training dataset management.
 5) Check if you want to create new dataset (new model)
 When checked, if there is already a csv file for training dataset management, a new csv file with one sequential number will be generated.
 
-6) Launch napari!
+6) Start tracing
 
 
 #### create labels
@@ -74,11 +95,9 @@ If you want to use the currently displayed slice as your training data, click th
 
 ### Train and pred with your gpu machine
 #### Train
-To train on your GPU machine, open launcher at first.
-```angular2
-python launcher_simple.py
-```
-1) Select Trainer   
+To train on your GPU machine (or with CPU), 
+
+1) Plugins > napari-PHILOW > Trainer
    
 2) Select original dir : all slices must be in separate PNG and must be sequentially numbered (e.g. 000.png, 001.png ...)   
    
@@ -88,14 +107,12 @@ python launcher_simple.py
    
 5) Click on the "start training" button   
 
-6) Check the command line for the progress of training. If you want to stop in the middle, click stop button.   
+6) Dice score and dice loss are displayed. For more detail, check the command line for the progress of training. If you want to stop in the middle, click stop button.   
    
 #### Predict
-To predict labels on your machine, open launcher at first.   
-```angular2
-python launcher_simple.py
-```
-1) Select Predicter
+To predict labels on your machine,  
+
+1) Plugins > napari-PHILOW > Predicter
    
 2) Select original dir : all slices must be in separate PNG and must be sequentially numbered (e.g. 000.png, 001.png ...)   
    
@@ -109,7 +126,9 @@ python launcher_simple.py
    
 7) Click on the "predict" button  
 
-8) Check the command line for the progress of prediction. If you want to stop in the middle, use ctrl+C.    
+8) Check the command line for the progress of prediction. If you want to stop in the middle, use ctrl+C.   
+
+9) You can start the next round of annotation by selecting the merged_prediction directory as the mask dir in Annotation mode.
 
 ### Train and predict with Google Colab   
 If you don't have a GPU machine, you can use Google Colab to perform GPU-based training and prediction for free.    
@@ -119,8 +138,20 @@ If you don't have a GPU machine, you can use Google Colab to perform GPU-based t
 2) You can upload your own dataset to train and predict, or try it on demo data   
 
 
- 
- 　
+## Contributing
+
+Contributions are very welcome. Tests can be run with [tox], please ensure
+the coverage at least stays the same before you submit a pull request.
+
+## License
+
+Distributed under the terms of the [GNU GPL v3.0] license,
+"napari-PHILOW" is free and open source software
+
+## Issues
+
+If you encounter any problems, please [file an issue] along with a detailed description.
+
 # Authors <br>
 
 Shogo Suga <br>
@@ -146,3 +177,19 @@ Shogo Suga, Koki Nakamura, Bruno M Humbel, Hiroki Kawai, Yusuke Hirabayashi, An
 	journal = {bioRxiv}
 }
 ```
+
+[napari]: https://github.com/napari/napari
+[Cookiecutter]: https://github.com/audreyr/cookiecutter
+[@napari]: https://github.com/napari
+[MIT]: http://opensource.org/licenses/MIT
+[BSD-3]: http://opensource.org/licenses/BSD-3-Clause
+[GNU GPL v3.0]: http://www.gnu.org/licenses/gpl-3.0.txt
+[GNU LGPL v3.0]: http://www.gnu.org/licenses/lgpl-3.0.txt
+[Apache Software License 2.0]: http://www.apache.org/licenses/LICENSE-2.0
+[Mozilla Public License 2.0]: https://www.mozilla.org/media/MPL/2.0/index.txt
+[cookiecutter-napari-plugin]: https://github.com/napari/cookiecutter-napari-plugin
+
+[napari]: https://github.com/napari/napari
+[tox]: https://tox.readthedocs.io/en/latest/
+[pip]: https://pypi.org/project/pip/
+[PyPI]: https://pypi.org/
diff --git a/_README.md b/_README.md
new file mode 100644
index 0000000..1ed3bde
--- /dev/null
+++ b/_README.md
@@ -0,0 +1,145 @@
+# PHILOW <br>
+***P***ython-based platform for ***h***uman-***i***n-the-***lo***op (HITL)  ***w***orkflow (PHILOW) <br>
+
+## Overview 
+PHILOW is an interactive deep learning-based platform for 3D datasets implemented on top of [napari](https://github.com/napari/napari) <br>
+
+Features:
+
+&nbsp;&nbsp;&nbsp;&nbsp; (1) generation of the ground truth data sets with annotation assistance, visualization and data management tools<br>
+&nbsp;&nbsp;&nbsp;&nbsp; (2) model training and prediction <br>
+&nbsp;&nbsp;&nbsp;&nbsp; (3) correcting the results of deep learning-based segmentations <br>
+&nbsp;&nbsp;&nbsp;&nbsp; (4) iterate this process to get efficient and good results in a short time  <br>
+&nbsp;&nbsp;  in a single user-friendly application running on Python.
+
+
+## Installation
+Clone this repository first.   
+Then install requirements.
+```angular2
+git clone https:_requirements.txt
+```
+
+
+## Usage
+#### load dataset
+```angular2
+python launcher_simple.py
+```
+1) Select Loader
+
+2) Select original dir : all slices must be in separate PNG and must be sequentially numbered (e.g. 000.png, 001.png ...)
+
+3) Start new project?    
+yes → do not need to select mask dir    
+no → select saved labels dir    
+
+4) Enter a name for the label or model you want to create (e.g. mito, cristae, ...)   
+This name will be used as the directory name of the newly created mask dir if no mask dir is specified, 
+and as the name of the csv file for training dataset management.
+
+5) Check if you want to create new dataset (new model)
+When checked, if there is already a csv file for training dataset management, a new csv file with one sequential number will be generated.
+
+6) Launch napari!
+
+
+#### create labels
+Create a label with the brush function.
+more information → https://napari.org/tutorials/fundamentals/labels.html
+
+#### Orthogonal view
+If you want to see orthogonal view, click on the location you want to see while holding down the Shift button.    
+The image from xy, yz, and zx will be displayed on the right side of the screen.
+
+#### Low confident layer
+If you are in the second iteration and you are loading the prediction results, you will see a low confidence layer.    
+This shows the area where the confidence of the prediction result is low.    
+Use this as a reference for correction.   
+
+#### Small object layer
+We provide a small object layer to find small painted areas.   
+This is a layer for displaying small objects.   
+The slider widget on the left allows you to change the maximum object size to be displayed.   
+
+#### save labels
+If you want to save your label, click the "save" button on the bottom right.
+
+#### select training dataset
+We are providing a way to manage the dataset for use in training.   
+If you want to use the currently displayed slice as your training data, click the 'Not Checked' button near the center left to display 'Checked'.
+
+
+### Train and pred with your gpu machine
+#### Train
+To train on your GPU machine, open launcher at first.
+```angular2
+python launcher_simple.py
+```
+1) Select Trainer   
+   
+2) Select original dir : all slices must be in separate PNG and must be sequentially numbered (e.g. 000.png, 001.png ...)   
+   
+3) Select labels dir : all label images should be named same as original images and contains data management csv file   
+   
+4) Select dir for save trained model   
+   
+5) Click on the "start training" button   
+
+6) Check the command line for the progress of training. If you want to stop in the middle, click stop button.   
+   
+#### Predict
+To predict labels on your machine, open launcher at first.   
+```angular2
+python launcher_simple.py
+```
+1) Select Predicter
+   
+2) Select original dir : all slices must be in separate PNG and must be sequentially numbered (e.g. 000.png, 001.png ...)   
+   
+3) (Optional) Select labels dir if you want to keep labels witch were used on training, and data management csv file   
+   
+4) Select model dir contains hdf5 file   
+   
+5) Select output dir for predicted labels   
+
+6) Uncheck the box if you DO NOT want to use TAP (Three-Axis-Prediction)   
+   
+7) Click on the "predict" button  
+
+8) Check the command line for the progress of prediction. If you want to stop in the middle, use ctrl+C.    
+
+### Train and predict with Google Colab   
+If you don't have a GPU machine, you can use Google Colab to perform GPU-based training and prediction for free.    
+
+1) Open [train and predict notebook](https://github.com/neurobiology-ut/PHILOW/blob/develop/notebooks/train_and_pred_using_PHILOW.ipynb) and click "Open in Colab" button
+
+2) You can upload your own dataset to train and predict, or try it on demo data   
+
+ 
+ 　
+# Authors <br>
+
+Shogo Suga <br>
+Hiroki Kawai <br>
+<a href="http://park.itc.u-tokyo.ac.jp/Hirabayashi/WordPress/">Yusuke Hirabayashi</a> 
+
+
+# How to Cite <br>
+Shogo Suga, Koki Nakamura, Bruno M Humbel, Hiroki Kawai, Yusuke Hirabayashi, An interactive deep learning-based approach reveals mitochondrial cristae topologies
+<a href="https://doi.org/10.1101/2021.06.11.448083">https://doi.org/10.1101/2021.06.11.448083</a>
+
+
+```
+@article {Suga2021.06.11.448083,
+	author = {Suga, Shogo and Nakamura, Koki and Humbel, Bruno M and Kawai, Hiroki and Hirabayashi, Yusuke},
+	title = {An interactive deep learning-based approach reveals mitochondrial cristae topologies},
+	elocation-id = {2021.06.11.448083},
+	year = {2021},
+	doi = {10.1101/2021.06.11.448083},
+	publisher = {Cold Spring Harbor Laboratory},
+	URL = {https://www.biorxiv.org/content/early/2021/06/11/2021.06.11.448083},
+	eprint = {https://www.biorxiv.org/content/early/2021/06/11/2021.06.11.448083.full.pdf},
+	journal = {bioRxiv}
+}
+```
diff --git a/_requirements.txt b/_requirements.txt
new file mode 100644
index 0000000..480f425
--- /dev/null
+++ b/_requirements.txt
@@ -0,0 +1,120 @@
+absl-py==0.12.0
+alabaster==0.7.12
+appdirs==1.4.4
+appnope==0.1.2
+astunparse==1.6.3
+attrs==20.3.0
+Babel==2.9.1
+backcall==0.2.0
+cachetools==4.2.2
+cachey==0.2.1
+certifi==2020.12.5
+chardet==4.0.0
+cloudpickle==1.6.0
+cycler==0.10.0
+dask==2021.4.1
+dask-image==0.6.0
+decorator==4.4.2
+docstring-parser==0.7.3
+docutils==0.16
+flatbuffers==1.12
+freetype-py==2.2.0
+fsspec==2021.4.0
+gast==0.4.0
+google-auth==1.30.1
+google-auth-oauthlib==0.4.4
+google-pasta==0.2.0
+grpcio==1.34.1
+h5py==3.1.0
+HeapDict==1.0.1
+idna==2.10
+imageio==2.9.0
+imagesize==1.2.0
+ipykernel==5.5.3
+ipython==7.23.0
+ipython-genutils==0.2.0
+jedi==0.18.0
+Jinja2==2.11.3
+jsonschema==3.2.0
+jupyter-client==6.1.12
+jupyter-core==4.7.1
+keras-nightly==2.5.0.dev2021032900
+Keras-Preprocessing==1.1.2
+kiwisolver==1.3.1
+locket==0.2.1
+magicgui==0.1.6
+Markdown==3.3.4
+MarkupSafe==1.1.1
+matplotlib==3.4.1
+matplotlib-inline==0.1.2
+napari==0.4.0
+napari-console==0.0.3
+napari-plugin-engine==0.1.9
+napari-svg==0.1.5
+networkx==2.5.1
+numpy==1.19.5
+numpydoc==1.1.0
+oauthlib==3.1.1
+opencv-python==4.5.2.54
+opt-einsum==3.3.0
+packaging==20.9
+pandas==1.2.4
+parso==0.8.2
+partd==1.2.0
+pexpect==4.8.0
+pickleshare==0.7.5
+Pillow==8.2.0
+PIMS==0.5
+prompt-toolkit==3.0.18
+protobuf==3.17.2
+psutil==5.8.0
+ptyprocess==0.7.0
+pyasn1==0.4.8
+pyasn1-modules==0.2.8
+pydantic==1.8.1
+Pygments==2.8.1
+PyOpenGL==3.1.5
+pyparsing==2.4.7
+PyQt5==5.14.2
+PyQt5-Qt5==5.15.2
+PyQt5-sip==12.8.1
+pyrsistent==0.17.3
+python-dateutil==2.8.1
+pytz==2021.1
+PyWavelets==1.1.1
+PyYAML==5.4.1
+pyzmq==22.0.3
+qtconsole==5.1.0
+QtPy==1.9.0
+requests==2.25.1
+requests-oauthlib==1.3.0
+rsa==4.7.2
+scikit-image==0.18.1
+scipy==1.6.3
+six==1.15.0
+slicerator==1.0.0
+snowballstemmer==2.1.0
+Sphinx==3.5.4
+sphinxcontrib-applehelp==1.0.2
+sphinxcontrib-devhelp==1.0.2
+sphinxcontrib-htmlhelp==1.0.3
+sphinxcontrib-jsmath==1.0.1
+sphinxcontrib-qthelp==1.0.3
+sphinxcontrib-serializinghtml==1.1.4
+tensorboard==2.5.0
+tensorboard-data-server==0.6.1
+tensorboard-plugin-wit==1.8.0
+tensorflow==2.5.0
+tensorflow-estimator==2.5.0
+termcolor==1.1.0
+tifffile==2021.4.8
+toolz==0.11.1
+tornado==6.1
+tqdm==4.61.0
+traitlets==5.0.5
+typing-extensions==3.7.4.3
+urllib3==1.26.4
+vispy==0.6.6
+wcwidth==0.2.5
+Werkzeug==2.0.1
+wrapt==1.12.1
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..34cf541
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,3 @@
+# Welcome to napari-PHILOW
+
+PHILOW is an interactive deep learning-based platform for 3D datasets
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..95774c8
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,9 @@
+site_name: napari-PHILOW
+site_description: PHILOW is an interactive deep learning-based platform for 3D datasets
+site_author: Hiroki Kawai
+
+theme: readthedocs
+
+
+pages:
+- Home: index.md
diff --git a/requirements.txt b/requirements.txt
index 480f425..8e62ec1 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,120 +1,5 @@
-absl-py==0.12.0
-alabaster==0.7.12
-appdirs==1.4.4
-appnope==0.1.2
-astunparse==1.6.3
-attrs==20.3.0
-Babel==2.9.1
-backcall==0.2.0
-cachetools==4.2.2
-cachey==0.2.1
-certifi==2020.12.5
-chardet==4.0.0
-cloudpickle==1.6.0
-cycler==0.10.0
-dask==2021.4.1
-dask-image==0.6.0
-decorator==4.4.2
-docstring-parser==0.7.3
-docutils==0.16
-flatbuffers==1.12
-freetype-py==2.2.0
-fsspec==2021.4.0
-gast==0.4.0
-google-auth==1.30.1
-google-auth-oauthlib==0.4.4
-google-pasta==0.2.0
-grpcio==1.34.1
-h5py==3.1.0
-HeapDict==1.0.1
-idna==2.10
-imageio==2.9.0
-imagesize==1.2.0
-ipykernel==5.5.3
-ipython==7.23.0
-ipython-genutils==0.2.0
-jedi==0.18.0
-Jinja2==2.11.3
-jsonschema==3.2.0
-jupyter-client==6.1.12
-jupyter-core==4.7.1
-keras-nightly==2.5.0.dev2021032900
-Keras-Preprocessing==1.1.2
-kiwisolver==1.3.1
-locket==0.2.1
-magicgui==0.1.6
-Markdown==3.3.4
-MarkupSafe==1.1.1
-matplotlib==3.4.1
-matplotlib-inline==0.1.2
-napari==0.4.0
-napari-console==0.0.3
-napari-plugin-engine==0.1.9
-napari-svg==0.1.5
-networkx==2.5.1
-numpy==1.19.5
-numpydoc==1.1.0
-oauthlib==3.1.1
-opencv-python==4.5.2.54
-opt-einsum==3.3.0
-packaging==20.9
-pandas==1.2.4
-parso==0.8.2
-partd==1.2.0
-pexpect==4.8.0
-pickleshare==0.7.5
-Pillow==8.2.0
-PIMS==0.5
-prompt-toolkit==3.0.18
-protobuf==3.17.2
-psutil==5.8.0
-ptyprocess==0.7.0
-pyasn1==0.4.8
-pyasn1-modules==0.2.8
-pydantic==1.8.1
-Pygments==2.8.1
-PyOpenGL==3.1.5
-pyparsing==2.4.7
-PyQt5==5.14.2
-PyQt5-Qt5==5.15.2
-PyQt5-sip==12.8.1
-pyrsistent==0.17.3
-python-dateutil==2.8.1
-pytz==2021.1
-PyWavelets==1.1.1
-PyYAML==5.4.1
-pyzmq==22.0.3
-qtconsole==5.1.0
-QtPy==1.9.0
-requests==2.25.1
-requests-oauthlib==1.3.0
-rsa==4.7.2
-scikit-image==0.18.1
-scipy==1.6.3
-six==1.15.0
-slicerator==1.0.0
-snowballstemmer==2.1.0
-Sphinx==3.5.4
-sphinxcontrib-applehelp==1.0.2
-sphinxcontrib-devhelp==1.0.2
-sphinxcontrib-htmlhelp==1.0.3
-sphinxcontrib-jsmath==1.0.1
-sphinxcontrib-qthelp==1.0.3
-sphinxcontrib-serializinghtml==1.1.4
-tensorboard==2.5.0
-tensorboard-data-server==0.6.1
-tensorboard-plugin-wit==1.8.0
-tensorflow==2.5.0
-tensorflow-estimator==2.5.0
-termcolor==1.1.0
-tifffile==2021.4.8
-toolz==0.11.1
-tornado==6.1
-tqdm==4.61.0
-traitlets==5.0.5
-typing-extensions==3.7.4.3
-urllib3==1.26.4
-vispy==0.6.6
-wcwidth==0.2.5
-Werkzeug==2.0.1
-wrapt==1.12.1
+# The requirements listed here are for development. 
+# Requirements of your napari plugin should be listed in setup.cfg
+# See also: https://caremad.io/posts/2013/07/setup-vs-requirement/
+
+-e .
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..04c74cd
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,48 @@
+[metadata]
+name = napari-PHILOW
+version = 0.0.1
+author = Hiroki Kawai
+author_email = h.kawai888@gmail.com
+url = https://github.com/neurobiology-ut/PHILOW
+license = BSD-3-Clause
+description = PHILOW is an interactive deep learning-based platform for 3D datasets
+long_description = file: README.md
+long_description_content_type = text/markdown
+classifiers =
+    Development Status :: 2 - Pre-Alpha
+    Intended Audience :: Developers
+    Framework :: napari
+    Topic :: Software Development :: Testing
+    Programming Language :: Python
+    Programming Language :: Python :: 3
+    Programming Language :: Python :: 3.7
+    Programming Language :: Python :: 3.8
+    Programming Language :: Python :: 3.9
+    Operating System :: OS Independent
+    License :: OSI Approved :: BSD License
+
+
+[options]
+packages = find:
+python_requires = >=3.7
+package_dir =
+    =src
+
+# add your package requirements here
+install_requires =
+    napari-plugin-engine>=0.1.4
+    tensorflow
+    numpy
+    scikit-image
+    dask-image
+    opencv-python
+    matplotlib
+    napari-tools-menu
+    pandas
+
+[options.packages.find]
+where = src
+
+[options.entry_points] 
+napari.plugin = 
+    napari-PHILOW = napari_philow
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..43deb57
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,5 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+from setuptools import setup
+
+setup()
diff --git a/src/napari_philow/__init__.py b/src/napari_philow/__init__.py
new file mode 100644
index 0000000..a100401
--- /dev/null
+++ b/src/napari_philow/__init__.py
@@ -0,0 +1,8 @@
+
+try:
+    from ._version import version as __version__
+except ImportError:
+    __version__ = "unknown"
+
+from ._dock_widget import napari_experimental_provide_dock_widget
+
diff --git a/src/napari_philow/_annotation.py b/src/napari_philow/_annotation.py
new file mode 100644
index 0000000..e523fff
--- /dev/null
+++ b/src/napari_philow/_annotation.py
@@ -0,0 +1,202 @@
+import os
+from pathlib import Path
+
+import matplotlib.pyplot as plt
+import numpy as np
+from magicgui import magicgui
+from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
+from matplotlib.figure import Figure
+from napari._qt.qthreading import thread_worker
+from napari_tools_menu import register_dock_widget
+from qtpy.QtWidgets import QWidget, QPushButton, QSizePolicy, QLineEdit, QCheckBox, QLabel, QVBoxLayout, QFileDialog
+from scipy import ndimage
+from skimage import io
+
+from napari_philow._data_manager import Datamanager
+from napari_philow._utils import combine_blocks, load_images, load_saved_masks, load_raw_masks, label_ct, \
+    label_and_sort, save_masks, crop_img, show_so_layer
+
+
+@register_dock_widget(menu="PHILOW > Annotation mode")
+class AnnotationMode(QWidget):
+    def __init__(self, napari_viewer):
+        super().__init__()
+        self._viewer = napari_viewer
+        self.opath = ""
+        self.modpath = ""
+        self.btn1 = QPushButton('open', self)
+        self.btn1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn1.clicked.connect(self.show_dialog_o)
+        self.btn2 = QPushButton('open', self)
+        self.btn2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn2.clicked.connect(self.show_dialog_mod)
+
+        self.textbox = QLineEdit(self)
+        self.textbox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+
+        self.checkBox = QCheckBox("create new dataset?")
+        self.checkBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+
+        self.btn4 = QPushButton('Start tracing', self)
+        self.btn4.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn4.clicked.connect(self.launch)
+        self.lbl = QLabel('original dir', self)
+        self.lbl2 = QLabel('mask dir', self)
+        self.lbl4 = QLabel('model type (do not use word "train")', self)
+        self.build()
+
+    def build(self):
+        vbox = QVBoxLayout()
+        vbox.addWidget(combine_blocks(self.btn1, self.lbl))
+        vbox.addWidget(combine_blocks(self.btn2, self.lbl2))
+        vbox.addWidget(combine_blocks(self.textbox, self.lbl4))
+        vbox.addWidget(self.checkBox)
+        vbox.addWidget(self.btn4)
+
+        self.setLayout(vbox)
+        self.show()
+
+    def show_dialog_o(self):
+        default_path = max(self.opath, self.modpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.opath = f_name
+            self.lbl.setText(self.opath)
+
+    def show_dialog_mod(self):
+        default_path = max(self.opath, self.modpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.modpath = f_name
+            self.lbl2.setText(self.modpath)
+
+    def launch(self):
+        images = load_images(self.opath)
+        if self.modpath == "":
+            labels = np.zeros_like(images.compute())
+            self.modpath = os.path.join(os.path.dirname(self.opath), self.textbox.text())
+            os.makedirs(self.modpath, exist_ok=True)
+            filenames = [fn.name for fn in sorted(list(Path(self.opath).glob('./*png')))]
+            #for i in range(len(labels)):
+            #    io.imsave(os.path.join(self.modpath, str(i).zfill(4) + '.png'), labels[i])
+            for i, filename in enumerate(filenames):
+                io.imsave(os.path.join(self.modpath, filename), labels[i])
+        else:
+            labels = load_saved_masks(self.modpath)
+        try:
+            labels_raw = load_raw_masks(self.modpath + '_raw')
+        except:
+            labels_raw = None
+        self._viewer.window.remove_dock_widget(self)
+        self.launch_anm(images, labels, labels_raw)
+
+    def launch_anm(self, original, base, raw):
+        global slicer
+        global z_pos
+        global layer
+        global images_original
+        global base_label
+        r_path = self.modpath
+        model_type = self.textbox.text()
+        checkbox = self.checkBox.isChecked()
+        images_original = original
+        base_label = base
+        try:
+            del layer
+        except NameError:
+            pass
+        self._viewer.add_image(images_original, contrast_limits=[0, 255])
+        self._viewer.add_labels(base_label, name='base')
+        if raw is not None:
+            self._viewer.add_image(ndimage.gaussian_filter(raw, sigma=3), colormap='magenta', name='low_confident',
+                                   blending='additive')
+        else:
+            pass
+
+        @thread_worker(connect={"returned": show_so_layer})
+        def create_label(viewer):
+            labeled_sorted, nums = label_and_sort(base_label)
+            print(nums)
+            labeled_c = label_ct(labeled_sorted, nums, 10)
+            return labeled_c, labeled_sorted, nums, viewer
+        if len(np.unique(base_label)) > 1:
+            create_label(self._viewer)
+
+        layer = self._viewer.layers[0]
+        layer1 = self._viewer.layers[1]
+
+        @magicgui(dirname={"mode": "d"}, call_button=False)
+        def dirpicker(dirname=Path(r_path)):
+            """Take a filename and do something with it."""
+            print("The filename is:", dirname)
+            return dirname
+
+        # gui = dirpicker.Gui(show=True)
+        self._viewer.window.add_dock_widget(dirpicker, area='bottom')
+
+        @magicgui(call_button="save")
+        def saver():
+            # out_dir = gui.dirname
+            out_dir = dirpicker.dirname.value
+            print("The directory is:", out_dir)
+            return save_masks(layer1.data, out_dir)
+
+        # gui2 = saver.Gui(show=True)
+        # self._viewer.window.add_dock_widget(gui2, area='bottom')
+        self._viewer.window.add_dock_widget(saver, area='bottom')
+
+        dmg = Datamanager()
+        dmg.prepare(r_path, model_type, checkbox)
+        self._viewer.window.add_dock_widget(dmg, area='left')
+
+        def update_button(axis_event):
+            # axis = axis_event.axis
+            # if axis != 0:
+            #    return
+            slice_num, _, _ = axis_event.value
+            dmg.update(slice_num)
+
+        self._viewer.dims.events.current_step.connect(update_button)
+
+        # draw canvas
+
+        with plt.style.context('dark_background'):
+            canvas = FigureCanvas(Figure(figsize=(3, 15)))
+
+            xy_axes = canvas.figure.add_subplot(3, 1, 1)
+
+            xy_axes.imshow(np.zeros((100, 100), np.uint8))
+            xy_axes.scatter(50, 50, s=10, c='red', alpha=0.15)
+            xy_axes.set_xlabel('x axis')
+            xy_axes.set_ylabel('y axis')
+            yz_axes = canvas.figure.add_subplot(3, 1, 2)
+            yz_axes.imshow(np.zeros((100, 100), np.uint8))
+            yz_axes.scatter(50, 50, s=10, c='red', alpha=0.15)
+            yz_axes.set_xlabel('y axis')
+            yz_axes.set_ylabel('z axis')
+            zx_axes = canvas.figure.add_subplot(3, 1, 3)
+            zx_axes.imshow(np.zeros((100, 100), np.uint8))
+            zx_axes.scatter(50, 50, s=10, c='red', alpha=0.15)
+            zx_axes.set_xlabel('x axis')
+            zx_axes.set_ylabel('z axis')
+
+            # canvas.figure.tight_layout()
+            canvas.figure.subplots_adjust(left=0, bottom=0.1, right=1, top=0.95, wspace=0, hspace=0.4)
+
+        canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
+
+        self._viewer.window.add_dock_widget(canvas, area='right')
+
+        @layer.mouse_drag_callbacks.append
+        def update_canvas_canvas(layer, event):
+            if 'shift' in event.modifiers:
+                try:
+                    m_point = np.round(layer.position).astype(int)
+                    print(m_point)
+                    crop_big = crop_img([m_point[0], m_point[1], m_point[2]], layer)
+                    xy_axes.imshow(crop_big[50], 'gray')
+                    yz_axes.imshow(crop_big.transpose(1, 0, 2)[50], 'gray')
+                    zx_axes.imshow(crop_big.transpose(2, 0, 1)[50], 'gray')
+                    canvas.draw_idle()
+                except Exception as e:
+                    print(e)
diff --git a/src/napari_philow/_data_manager.py b/src/napari_philow/_data_manager.py
new file mode 100644
index 0000000..697bafe
--- /dev/null
+++ b/src/napari_philow/_data_manager.py
@@ -0,0 +1,131 @@
+import os
+import shutil
+from pathlib import Path
+
+import pandas as pd
+from qtpy.QtWidgets import (
+    QWidget,
+    QPushButton,
+    QHBoxLayout,
+    QVBoxLayout,
+)
+
+GUI_MAXIMUM_WIDTH = 225
+GUI_MAXIMUM_HEIGHT = 350
+GUI_MINIMUM_HEIGHT = 300
+
+
+class Datamanager(QWidget):
+
+    def __init__(self, *args, **kwargs):
+
+        super(Datamanager, self).__init__(*args, **kwargs)
+
+        layout = QVBoxLayout()
+
+        # add some buttons
+        self.button = QPushButton('1', self)
+        self.button.clicked.connect(self.button_func)
+
+        io_panel = QWidget()
+        io_layout = QHBoxLayout()
+        io_layout.addWidget(self.button)
+        io_panel.setLayout(io_layout)
+        io_panel.setMaximumWidth(GUI_MAXIMUM_WIDTH)
+        layout.addWidget(io_panel)
+
+        # set the layout
+        #layout.setAlignment(Qt.AlignTop)
+        #layout.setSpacing(4)
+
+        self.setLayout(layout)
+        #self.setMaximumHeight(GUI_MAXIMUM_HEIGHT)
+        #self.setMaximumWidth(GUI_MAXIMUM_WIDTH)
+
+        self.df = ""
+        self.csv_path = ""
+        self.slice_num = 0
+
+    def prepare(self, label_dir, model_type, checkbox):
+        """
+        :param str label_dir:label path
+        :param str model_type:model type
+        :param bool checkbox: create new dataset or not
+        """
+        self.df, self.csv_path = self.load_csv(label_dir, model_type, checkbox)
+        print(self.csv_path, checkbox)
+        self.update(0)
+
+    def load_csv(self, label_dir, model_type, checkbox):
+        """
+        load newes cs or create new csv
+        :param str label_dir: label path
+        :param str model_type:model type
+        :param bool checkbox: create new dataset or not
+        :return: dataframe、csv path
+        :rtype (pandas.DataFrame, str)
+        """
+        csvs = sorted(list(Path(label_dir).glob(f'{model_type}*.csv')))
+        if len(csvs) == 0:
+            #df, train_data_dir, csv_path = self.create(label_dir, model_type)
+            df, csv_path = self.create(label_dir, model_type)
+        else:
+            csv_path = str(csvs[-1])
+            df = pd.read_csv(csv_path, index_col=0)
+            if checkbox is True:
+                csv_path = csv_path.split('_train')[0] + '_train' \
+                           + str(int(os.path.splitext(csv_path.split('_train')[1])[0]) + 1) + '.csv'
+                df.to_csv(csv_path)
+            else:
+                pass
+        return df, csv_path
+
+    def create(self, label_dir, model_type):
+        """
+        Create a new dataframe and save the csv
+        :param str label_dir: label path
+        :param str model_type : model type
+        :return: dataframe, csv path
+        :rtype (pandas.DataFrame, str)
+        """
+        labels = sorted(list(path.name for path in Path(label_dir).glob('./*png')))
+        df = pd.DataFrame({'filename': labels,
+                           'train': ['Not Checked']*len(labels)})
+        csv_path = os.path.join(label_dir, f'{model_type}_train0.csv')
+        df.to_csv(csv_path)
+        return df, csv_path
+
+    def update(self, slice_num):
+        self.slice_num = slice_num
+        self.button.setText(self.df.at[self.df.index[self.slice_num], 'train'])
+
+    def button_func(self):
+        if self.button.text() == 'Not Checked':
+            self.button.setText('Checked')
+            self.df.at[self.df.index[self.slice_num], 'train'] = 'Checked'
+            self.df.to_csv(self.csv_path)
+        else:
+            self.button.setText('Not Checked')
+            self.df.at[self.df.index[self.slice_num], 'train'] = 'Not Checked'
+            self.df.to_csv(self.csv_path)
+
+    def move_data(self):
+        shutil.copy(self.df.at[self.df.index[self.slice_num], 'filename'], self.train_data_dir)
+
+    def delete_data(self):
+        os.remove(os.path.join(self.train_data_dir,
+                               os.path.basename(self.df.at[self.df.index[self.slice_num], 'filename'])))
+
+    def check_all_data_and_mod(self):
+        for i in range(len(self.df)):
+            if self.df.at[self.df.index[i], 'train'] == 'Checked':
+                try:
+                    shutil.copy(self.df.at[self.df.index[i], 'filename'], self.train_data_dir)
+                except:
+                    pass
+            else:
+                try:
+                    os.remove(os.path.join(self.train_data_dir,
+                                           os.path.basename(self.df.at[self.df.index[i], 'filename'])))
+                except:
+                    pass
diff --git a/src/napari_philow/_dock_widget.py b/src/napari_philow/_dock_widget.py
new file mode 100644
index 0000000..a9b1dba
--- /dev/null
+++ b/src/napari_philow/_dock_widget.py
@@ -0,0 +1,10 @@
+from napari_plugin_engine import napari_hook_implementation
+
+from napari_philow._annotation import AnnotationMode
+from napari_philow._prediction import Predicter
+from napari_philow._train import Trainer
+
+
+@napari_hook_implementation
+def napari_experimental_provide_dock_widget():
+    return [AnnotationMode, Trainer, Predicter]
diff --git a/src/napari_philow/_models.py b/src/napari_philow/_models.py
new file mode 100644
index 0000000..630c246
--- /dev/null
+++ b/src/napari_philow/_models.py
@@ -0,0 +1,95 @@
+import tensorflow as tf
+from napari_philow._utils import bce_dice_loss, dice_coeff
+from tensorflow.keras.layers import *
+from tensorflow.keras.models import Model
+from tensorflow.keras.optimizers import RMSprop
+
+
+def standard_uint(input_tensor, nb_filter):
+    x = Conv2D(nb_filter, (3, 3), padding='same')(input_tensor)
+    x = BatchNormalization()(x)
+    x = Activation('relu')(x)
+    x = Conv2D(nb_filter, (3, 3), padding='same')(x)
+    x = BatchNormalization()(x)
+    x = Activation('relu')(x)
+
+    return x
+
+
+def get_nested_unet(input_shape=(512, 512, 1), num_classes=3, deep_supervision=False):
+    #with tf.device('/gpu:0'):
+
+    inputs = Input(shape=input_shape)
+
+    # 512
+    conv1_1 = standard_uint(inputs, nb_filter=16)
+    pool1 = MaxPooling2D((2, 2), strides=(2, 2))(conv1_1)
+
+    # 256
+    conv2_1 = standard_uint(pool1, nb_filter=32)
+    pool2 = MaxPooling2D((2, 2), strides=(2, 2))(conv2_1)
+
+    up1_2 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv2_1)
+    conv1_2 = concatenate([up1_2, conv1_1], axis=3)
+    conv1_2 = standard_uint(conv1_2, nb_filter=16)
+
+    # 128
+    conv3_1 = standard_uint(pool2, nb_filter=64)
+    pool3 = MaxPooling2D((2, 2), strides=(2, 2))(conv3_1)
+
+    up2_2 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv3_1)
+    conv2_2 = concatenate([up2_2, conv2_1], axis=3)
+    conv2_2 = standard_uint(conv2_2, nb_filter=32)
+
+    up1_3 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv2_2)
+    conv1_3 = concatenate([up1_3, conv1_1, conv1_2], axis=3)
+    conv1_3 = standard_uint(conv1_3, nb_filter=16)
+
+    # 64
+    conv4_1 = standard_uint(pool3, nb_filter=128)
+    pool4 = MaxPooling2D((2, 2), strides=(2, 2))(conv4_1)
+
+    up3_2 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv4_1)
+    conv3_2 = concatenate([up3_2, conv3_1], axis=3)
+    conv3_2 = standard_uint(conv3_2, nb_filter=64)
+
+    up2_3 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv3_2)
+    conv2_3 = concatenate([up2_3, conv2_1, conv2_2], axis=3)
+    conv2_3 = standard_uint(conv2_3, nb_filter=32)
+
+    up1_4 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv2_3)
+    conv1_4 = concatenate([up1_4, conv1_2, conv1_3], axis=3)
+    conv1_4 = standard_uint(conv1_4, nb_filter=16)
+
+    # 32
+    conv5_1 = standard_uint(pool4, nb_filter=256)
+
+    up4_2 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv5_1)
+    conv4_2 = concatenate([up4_2, conv4_1], axis=3)
+    conv4_2 = standard_uint(conv4_2, nb_filter=128)
+
+    up3_3 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv4_2)
+    conv3_3 = concatenate([up3_3, conv3_1, conv3_2], axis=3)
+    conv3_3 = standard_uint(conv3_3, nb_filter=64)
+
+    up2_4 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv3_3)
+    conv2_4 = concatenate([up2_4, conv2_1, conv2_2, conv2_3], axis=3)
+    conv2_4 = standard_uint(conv2_4, nb_filter=32)
+
+    up1_5 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same')(conv2_4)
+    conv1_5 = concatenate([up1_5, conv1_1, conv1_2, conv1_3, conv1_4], axis=3)
+    conv1_5 = standard_uint(conv1_5, nb_filter=16)
+
+    nested_output_1 = Conv2D(num_classes, (1, 1), activation='sigmoid')(conv1_2)
+    nested_output_2 = Conv2D(num_classes, (1, 1), activation='sigmoid')(conv1_3)
+    nested_output_3 = Conv2D(num_classes, (1, 1), activation='sigmoid')(conv1_4)
+    nested_output_4 = Conv2D(num_classes, (1, 1), activation='sigmoid')(conv1_5)
+
+    if deep_supervision:
+        model = Model(inputs=inputs, outputs=[nested_output_1, nested_output_2, nested_output_3, nested_output_4])
+    else:
+        model = Model(inputs=inputs, outputs=[nested_output_4])
+
+    model.compile(optimizer=RMSprop(learning_rate=0.0001), loss=bce_dice_loss, metrics=[dice_coeff])
+
+    return model
diff --git a/src/napari_philow/_predict.py b/src/napari_philow/_predict.py
new file mode 100644
index 0000000..f478f55
--- /dev/null
+++ b/src/napari_philow/_predict.py
@@ -0,0 +1,140 @@
+import os
+
+import cv2
+import numpy as np
+
+from napari_philow._utils import denormalize_y, divide_imgs, load_Y_gray, merge_imgs
+
+
+def predict(X_test, model, out_dir):
+    BATCH_SIZE = 1
+    Y_pred = model.predict(X_test, BATCH_SIZE)
+
+    print(Y_pred.shape)
+    os.makedirs(out_dir, exist_ok=True)
+
+    if Y_pred.shape[3] != 1:
+        num = Y_pred.shape[3]
+        for n in range(num):
+            os.makedirs(os.path.join(out_dir, str(n + 1)), exist_ok=True)
+        for i, y in enumerate(Y_pred):
+            for n in range(num):
+                cv2.imwrite(os.path.join(out_dir, str(n + 1), str(i).zfill(6) + '.png'), denormalize_y(y[:, :, n]))
+
+    else:
+        for i, y in enumerate(Y_pred):
+            cv2.imwrite(os.path.join(out_dir, str(i).zfill(6) + '.png'), denormalize_y(y))
+
+
+def predict_3ax(ori_imgs, model, out_dir, filenames):
+    os.makedirs(out_dir, exist_ok=True)
+
+    # XY
+    seped_xy_imgs = divide_imgs(ori_imgs)
+
+    predict(
+        X_test=seped_xy_imgs,
+        model=model,
+        out_dir=os.path.join(out_dir, "pred_xy"),
+    )
+
+    # YZ
+    seped_yz_imgs = divide_imgs(ori_imgs.transpose(2, 0, 1, 3))
+
+    predict(
+        X_test=seped_yz_imgs,
+        model=model,
+        out_dir=os.path.join(out_dir, "pred_yz"),
+    )
+
+    # ZX
+    seped_zx_imgs = divide_imgs(ori_imgs.transpose(1, 2, 0, 3))
+
+    predict(
+        X_test=seped_zx_imgs,
+        model=model,
+        out_dir=os.path.join(out_dir, "pred_zx"),
+    )
+
+    ori_image_shape = ori_imgs.shape
+
+    pred_xy_imgs, _ = load_Y_gray(os.path.join(out_dir, "pred_xy"))
+    merged_imgs_xy = merge_imgs(pred_xy_imgs, ori_image_shape)
+
+    pred_yz_imgs, _ = load_Y_gray(os.path.join(out_dir, "pred_yz"))
+    merged_imgs_yz = merge_imgs(pred_yz_imgs,
+                                (ori_image_shape[2], ori_image_shape[0], ori_image_shape[1], ori_image_shape[3]))
+
+    pred_zx_imgs, _ = load_Y_gray(os.path.join(out_dir, "pred_zx"))
+    merged_imgs_zx = merge_imgs(pred_zx_imgs,
+                                (ori_image_shape[1], ori_image_shape[2], ori_image_shape[0], ori_image_shape[3]))
+
+    mito_imgs_ave = merged_imgs_xy * 255 // 3 + merged_imgs_yz.transpose(1, 2, 0, 3) * 255 // 3 \
+                    + merged_imgs_zx.transpose(2, 0, 1, 3) * 255 // 3
+
+    out_dir_merge = os.path.join(out_dir, 'merged_prediction')
+    os.makedirs(out_dir_merge, exist_ok=True)
+    os.makedirs(f"{out_dir_merge}_raw", exist_ok=True)
+
+    for i in range(mito_imgs_ave.shape[0]):
+        # threshed
+        img = np.where(
+            mito_imgs_ave[:, :, :, 0][i] >= 127,
+            1,
+            0
+        )
+        # cv2.imwrite(f'{out_dir_merge}/{str(i).zfill(4)}.png', img)
+        cv2.imwrite(f'{out_dir_merge}/{filenames[i]}', img)
+
+        # averaged
+        img_ = np.where(
+            mito_imgs_ave[:, :, :, 0][i] >= 127,
+            mito_imgs_ave[:, :, :, 0][i],
+            0
+        )
+        # cv2.imwrite(f'{out_dir_merge}_raw/{str(i).zfill(4)}.png', img_)
+        cv2.imwrite(f'{out_dir_merge}_raw/{filenames[i]}', img_)
+
+
+def predict_1ax(ori_imgs, model, out_dir, filenames):
+    os.makedirs(out_dir, exist_ok=True)
+
+    # XY
+    seped_xy_imgs = divide_imgs(ori_imgs)
+
+    predict(
+        X_test=seped_xy_imgs,
+        model=model,
+        out_dir=os.path.join(out_dir, "pred_xy"),
+    )
+
+    ori_image_shape = ori_imgs.shape
+
+    pred_xy_imgs, _ = load_Y_gray(os.path.join(out_dir, "pred_xy"))
+    merged_imgs_xy = merge_imgs(pred_xy_imgs, ori_image_shape)
+
+    # mito_imgs_ave = merged_imgs_xy * 255
+    mito_imgs_ave = merged_imgs_xy
+
+    out_dir_merge = os.path.join(out_dir, 'merged_prediction')
+    os.makedirs(out_dir_merge, exist_ok=True)
+    os.makedirs(f"{out_dir_merge}_raw", exist_ok=True)
+
+    for i in range(mito_imgs_ave.shape[0]):
+        # threshed
+        img = np.where(
+            mito_imgs_ave[:, :, :, 0][i] >= 127,
+            1,
+            0
+        )
+        # cv2.imwrite(f'{out_dir_merge}/{str(i).zfill(4)}.png', img)
+        cv2.imwrite(f'{out_dir_merge}/{filenames[i]}', img)
+
+        # averaged
+        img_ = np.where(
+            mito_imgs_ave[:, :, :, 0][i] >= 127,
+            mito_imgs_ave[:, :, :, 0][i],
+            0
+        )
+        # cv2.imwrite(f'{out_dir_merge}_raw/{str(i).zfill(4)}.png', img_)
+        cv2.imwrite(f'{out_dir_merge}_raw/{filenames[i]}', img_)
diff --git a/src/napari_philow/_prediction.py b/src/napari_philow/_prediction.py
new file mode 100644
index 0000000..90c47fb
--- /dev/null
+++ b/src/napari_philow/_prediction.py
@@ -0,0 +1,159 @@
+import os
+import shutil
+from pathlib import Path
+
+import pandas as pd
+from napari_tools_menu import register_dock_widget
+from qtpy.QtWidgets import (QWidget, QVBoxLayout, QPushButton, QSizePolicy, QLabel, QFileDialog,
+                            QCheckBox)
+
+from napari_philow._models import get_nested_unet
+from napari_philow._predict import predict_3ax, predict_1ax
+from napari_philow._utils import combine_blocks, load_X_gray
+
+
+@register_dock_widget(menu="PHILOW > Prediction mode")
+class Predicter(QWidget):
+    def __init__(self):
+        super().__init__()
+        self.opath = ""
+        self.labelpath = ""
+        self.modelpath = ""
+        self.outpath = ""
+        self.btn1 = QPushButton('open', self)
+        self.btn1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn1.clicked.connect(self.show_dialog_o)
+        self.btn2 = QPushButton('open', self)
+        self.btn2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn2.clicked.connect(self.show_dialog_label)
+        self.btn3 = QPushButton('open', self)
+        self.btn3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn3.clicked.connect(self.show_dialog_model)
+        self.btn4 = QPushButton('open', self)
+        self.btn4.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn4.clicked.connect(self.show_dialog_outdir)
+
+        self.checkBox = QCheckBox("Check the box if you want to use TAP (Three-Axis-Prediction")
+        self.checkBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.checkBox.toggle()
+
+        self.btn5 = QPushButton('predict', self)
+        self.btn5.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn5.clicked.connect(self.predicter)
+        self.lbl = QLabel('original dir', self)
+        self.lbl2 = QLabel('label dir', self)
+        self.lbl3 = QLabel('model dir (contains model.hdf5)', self)
+        self.lbl4 = QLabel('output dir', self)
+        self.build()
+
+        self.model = None
+        self.worker_pred = None
+
+    def build(self):
+        vbox = QVBoxLayout()
+        vbox.addWidget(combine_blocks(self.btn1, self.lbl))
+        vbox.addWidget(combine_blocks(self.btn2, self.lbl2))
+        vbox.addWidget(combine_blocks(self.btn3, self.lbl3))
+        vbox.addWidget(combine_blocks(self.btn4, self.lbl4))
+        vbox.addWidget(self.checkBox)
+        vbox.addWidget(self.btn5)
+
+        self.setLayout(vbox)
+        self.show()
+
+    def show_dialog_o(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.opath = f_name
+            self.lbl.setText(self.opath)
+
+    def show_dialog_label(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.labelpath = f_name
+            self.lbl2.setText(self.labelpath)
+
+    def show_dialog_model(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.modelpath = f_name
+            self.lbl3.setText(self.modelpath)
+
+    def show_dialog_outdir(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.outpath = f_name
+            self.lbl4.setText(self.outpath)
+
+    def get_newest_csv(self):
+        csvs = sorted(list(Path(self.labelpath).glob('./*csv')))
+        try:
+            csv = pd.read_csv(str(csvs[-1]), index_col=0)
+        except:
+            csv = None
+        return csv, str(csvs[-1])
+
+    def predicter(self):
+        ori_imgs, ori_filenames = load_X_gray(self.opath)
+        print(ori_imgs.shape)
+        input_shape = (512, 512, 1)
+        num_classes = 1
+
+        self.model = get_nested_unet(input_shape=input_shape, num_classes=num_classes)
+        self.model.load_weights(os.path.join(self.modelpath, "model.hdf5"))
+
+        self.btn5.setText('predicting')
+
+        if self.checkBox.isChecked() is True:
+            self.predict(ori_imgs, ori_filenames)
+        else:
+            self.predict_single(ori_imgs, ori_filenames)
+
+    def predict(self, ori_imgs, filenames):
+        try:
+            predict_3ax(ori_imgs, self.model, self.outpath, filenames)
+        except Exception as e:
+            print(e)
+        if self.labelpath != "":
+            try:
+                csv, csv_path = self.get_newest_csv()
+                if csv is None:
+                    pass
+                else:
+                    label_names = [node.filename for node in csv.itertuples() if node.train == "Checked"]
+                    for ln in label_names:
+                        shutil.copy(os.path.join(self.labelpath, ln), os.path.join(self.outpath, 'merged_prediction'))
+                    shutil.copy(str(csv_path), os.path.join(self.outpath, 'merged_prediction'))
+            except Exception as e:
+                print(e)
+
+        self.btn5.setText('predict')
+
+    def predict_single(self, ori_imgs, filenames):
+        try:
+            predict_1ax(ori_imgs, self.model, self.outpath, filenames)
+        except Exception as e:
+            print(e)
+        if self.labelpath != "":
+            print('copy previous mask')
+            try:
+                csv, csv_path = self.get_newest_csv()
+                print('find csv', csv_path)
+                if csv is None:
+                    pass
+                else:
+                    label_names = [node.filename for node in csv.itertuples() if node.train == "Checked"]
+                    print(label_names)
+                    for ln in label_names:
+                        print('copy ln')
+                        shutil.copy(os.path.join(self.labelpath, ln), os.path.join(self.outpath, 'merged_prediction'))
+                    shutil.copy(str(csv_path), os.path.join(self.outpath, 'merged_prediction'))
+                    print('csv copied')
+            except Exception as e:
+                print(e)
+
+        self.btn5.setText('predict')
diff --git a/src/napari_philow/_train.py b/src/napari_philow/_train.py
new file mode 100644
index 0000000..b9a4a3d
--- /dev/null
+++ b/src/napari_philow/_train.py
@@ -0,0 +1,210 @@
+import io as IO
+import os
+import time
+from pathlib import Path
+
+import matplotlib.pyplot as plt
+import numpy as np
+import pandas as pd
+from PIL import Image
+from napari.qt import thread_worker
+from napari_tools_menu import register_dock_widget
+from qtpy.QtWidgets import QWidget, QPushButton, QSizePolicy, QLabel, QVBoxLayout, QFileDialog
+from tensorflow.keras.callbacks import CSVLogger, ModelCheckpoint
+from tensorflow.keras.preprocessing.image import ImageDataGenerator
+
+from napari_philow._models import get_nested_unet
+from napari_philow._utils import combine_blocks, load_X_gray, load_Y_gray, select_train_data, divide_imgs
+
+
+@register_dock_widget(menu="PHILOW > Train mode")
+class Trainer(QWidget):
+    def __init__(self, napari_viewer):
+        super().__init__()
+        self._viewer = napari_viewer
+        self.opath = ""
+        self.labelpath = ""
+        self.modelpath = ""
+        self.btn1 = QPushButton('open', self)
+        self.btn1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn1.clicked.connect(self.show_dialog_o)
+        self.btn2 = QPushButton('open', self)
+        self.btn2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn2.clicked.connect(self.show_dialog_label)
+        self.btn3 = QPushButton('open', self)
+        self.btn3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn3.clicked.connect(self.show_dialog_model)
+
+        self.btn4 = QPushButton('start training', self)
+        self.btn4.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
+        self.btn4.clicked.connect(self.trainer)
+        self.lbl = QLabel('original dir', self)
+        self.lbl2 = QLabel('label dir', self)
+        self.lbl3 = QLabel('model output dir', self)
+        self.build()
+
+        self.model = None
+        self.worker = None
+        self.worker2 = None
+
+    def build(self):
+        vbox = QVBoxLayout()
+        vbox.addWidget(combine_blocks(self.btn1, self.lbl))
+        vbox.addWidget(combine_blocks(self.btn2, self.lbl2))
+        vbox.addWidget(combine_blocks(self.btn3, self.lbl3))
+        vbox.addWidget(self.btn4)
+
+        self.setLayout(vbox)
+        self.show()
+
+    def show_dialog_o(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.opath = f_name
+            self.lbl.setText(self.opath)
+
+    def show_dialog_label(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.labelpath = f_name
+            self.lbl2.setText(self.labelpath)
+
+    def show_dialog_model(self):
+        default_path = max(self.opath, self.labelpath, os.path.expanduser('~'))
+        f_name = QFileDialog.getExistingDirectory(self, 'Open Directory', default_path)
+        if f_name:
+            self.modelpath = f_name
+            self.lbl3.setText(self.modelpath)
+
+    def get_newest_csv(self):
+        csvs = sorted(list(Path(self.labelpath).glob('./*csv')))
+        csv = pd.read_csv(str(csvs[-1]), index_col=0)
+        return csv
+
+    def update_layer(self, df):
+        plt.figure(figsize=(10, 5))
+        plt.subplot(1, 2, 1)
+        plt.plot(list(df['epoch']), list(df['dice_coeff']), label='dice_coeff')
+        plt.xlim(0, 400)
+        plt.ylim(0, 1)
+        plt.legend()
+        plt.subplot(1, 2, 2)
+        plt.plot(list(df['epoch']), list(df['loss']), label='loss')
+        plt.legend()
+        plt.xlim(0, 400)
+        buf = IO.BytesIO()
+        plt.savefig(buf, format='png')
+        plt.close()
+        buf.seek(0)
+        im = Image.open(buf)
+        im = np.array(im)
+        buf.close()
+        try:
+            self._viewer.layers['result'].data = im
+        except KeyError:
+            self._viewer.add_image(
+                im, name='result'
+            )
+
+    def trainer(self):
+        if self.worker:
+            if self.worker.is_running:
+                pass
+            else:
+                self.worker.start()
+                self.btn4.setText('stop')
+        else:
+            ori_imgs, ori_filenames = load_X_gray(self.opath)
+            label_imgs, label_filenames = load_Y_gray(self.labelpath, normalize=False)
+            train_csv = self.get_newest_csv()
+            train_ori_imgs, train_label_imgs = select_train_data(
+                dataframe=train_csv,
+                ori_imgs=ori_imgs,
+                label_imgs=label_imgs,
+                ori_filenames=ori_filenames,
+            )
+            devided_train_ori_imgs = divide_imgs(train_ori_imgs)
+            devided_train_label_imgs = divide_imgs(train_label_imgs)
+            devided_train_label_imgs = np.where(
+                devided_train_label_imgs < 0,
+                0,
+                devided_train_label_imgs
+            )
+
+            self.model = get_nested_unet(input_shape=(512, 512, 1), num_classes=1)
+
+            self.worker = self.train(devided_train_ori_imgs, devided_train_label_imgs, self.model)
+            self.worker.started.connect(lambda: print("worker is running..."))
+            self.worker.finished.connect(lambda: print("worker stopped"))
+            self.worker2 = self.yield_csv()
+            self.worker2.yielded.connect(self.update_layer)
+            self.worker2.start()
+
+        if self.worker.is_running:
+            self.model.stop_training = True
+            print("stop training requested")
+            self.btn4.setText('start training')
+            self.worker = None
+        else:
+            self.worker.start()
+            self.btn4.setText('stop')
+
+    @thread_worker
+    def train(self, devided_train_ori_imgs, devided_train_label_imgs, model):
+        train_unet(
+            X_train=devided_train_ori_imgs,
+            Y_train=devided_train_label_imgs,
+            csv_path=os.path.join(self.modelpath, "train_log.csv"),
+            model_path=os.path.join(self.modelpath, "model.hdf5"),
+            model=model
+        )
+
+    @thread_worker
+    def yield_csv(self):
+        while True:
+            try:
+                df = pd.read_csv(os.path.join(self.modelpath, "train_log.csv"))
+                df['epoch'] = df['epoch'] + 1
+                yield df
+            except Exception as e:
+                print(e)
+            time.sleep(30)
+
+
+def train_unet(X_train, Y_train, csv_path, model_path, model):
+    Y_train = Y_train
+    X_train = X_train
+
+    data_gen_args = dict(
+        rotation_range=90.,
+        width_shift_range=0.1,
+        height_shift_range=0.1,
+        zoom_range=0.2,
+        horizontal_flip=True,
+        vertical_flip=True
+    )
+    image_datagen = ImageDataGenerator(**data_gen_args)
+    mask_datagen = ImageDataGenerator(**data_gen_args)
+
+    # Provide the same seed and keyword arguments to the fit and flow methods
+    seed = 1
+    image_datagen.fit(X_train, augment=True, seed=seed)
+    mask_datagen.fit(Y_train, augment=True, seed=seed)
+
+    image_generator = image_datagen.flow(X_train, seed=seed, batch_size=8)
+    mask_generator = mask_datagen.flow(Y_train, seed=seed, batch_size=8)
+
+    # combine generators into one which yields image and masks
+    train_generator = (pair for pair in zip(image_generator, mask_generator))
+
+    BATCH_SIZE = 4
+    NUM_EPOCH = 400
+
+    callbacks = []
+    callbacks.append(CSVLogger(csv_path))
+    callbacks.append(ModelCheckpoint(model_path))
+    history = model.fit(train_generator, steps_per_epoch=np.ceil(len(X_train / BATCH_SIZE)), epochs=NUM_EPOCH,
+                        verbose=1, callbacks=callbacks)
+    model.save_weights(model_path)
diff --git a/src/napari_philow/_utils.py b/src/napari_philow/_utils.py
new file mode 100644
index 0000000..a173cfd
--- /dev/null
+++ b/src/napari_philow/_utils.py
@@ -0,0 +1,529 @@
+import copy
+import os
+from pathlib import Path
+
+import cv2
+import dask_image.imread
+from qtpy.QtWidgets import QWidget, QHBoxLayout, QSlider, QLabel
+from qtpy.QtCore import Qt
+import numpy as np
+from scipy import ndimage
+from skimage import io
+from skimage.filters import gaussian
+import pandas as pd
+from tqdm import tqdm
+
+import tensorflow.keras.backend as K
+from tensorflow.keras.losses import binary_crossentropy
+
+
+def combine_blocks(block1, block2):
+    temp_widget = QWidget()
+    temp_layout = QHBoxLayout()
+    temp_layout.addWidget(block1)
+    temp_layout.addWidget(block2)
+    temp_widget.setLayout(temp_layout)
+    return temp_widget
+
+
+def normalize_x(image):
+    image = image / 127.5 - 1
+    return image
+
+
+def normalize_y(image):
+    image = image / 255
+    return image
+
+
+def denormalize_y(image):
+    return image * 255
+
+
+def annotation_to_input(label_ermito):
+    mito = (label_ermito == 1) * 255
+    er = (label_ermito == 2) * 255
+    mito = normalize_y(mito)
+    er = normalize_y(er)
+    mito_anno = np.zeros_like(mito)
+    er_anno = np.zeros_like(er)
+    mito = gaussian(mito, sigma=2) * 255
+    er = gaussian(er, sigma=2) * 255
+    mito_anno[:, :] = mito
+    er_anno[:, :] = er
+    anno = np.concatenate([mito_anno[:, :, np.newaxis], er_anno[:, :, np.newaxis]], 2)
+    anno = normalize_x(anno[np.newaxis, :, :, :])
+    return anno
+
+
+def check_csv(project_path, ext):
+    if not os.path.isfile(os.path.join(project_path, os.path.basename(project_path) + '.csv')):
+        cols = ['project', 'type', 'ext', 'z', 'y', 'x', 'z_size', 'y_size', 'x_size', 'created_date', 'update_date',
+                'path', 'notes']
+        df = pd.DataFrame(index=[], columns=cols)
+        filename_pattern_original = os.path.join(project_path, f'dataset/Original_size/Original/*{ext}')
+        images_original = dask_image.imread.imread(filename_pattern_original)
+        z, y, x = images_original.shape
+        record = pd.Series(
+            [os.path.basename(project_path), 'dataset', '.tif', 0, 0, 0, z, y, x, datetime.datetime.now(),
+             '', os.path.join(project_path, 'dataset/Original_size/Original'), ''], index=df.columns)
+        df = df.append(record, ignore_index=True)
+        df.to_csv(os.path.join(project_path, os.path.basename(project_path) + '.csv'))
+    else:
+        pass
+
+
+def check_annotations_dir(project_path):
+    if not os.path.isdir(os.path.join(project_path, 'annotations/Original_size/master')):
+        os.makedirs(os.path.join(project_path, 'annotations/Original_size/master'))
+    else:
+        pass
+
+
+def check_zarr(project_path, ext):
+    if not len(list((Path(project_path) / 'dataset' / 'Original_size').glob('./*.zarr'))):
+        filename_pattern_original = os.path.join(project_path, f'dataset/Original_size/Original/*{ext}')
+        images_original = dask_image.imread.imread(filename_pattern_original)
+        images_original.to_zarr(os.path.join(project_path, f'dataset/Original_size/Original.zarr'))
+    else:
+        pass
+
+
+def check(project_path, ext):
+    check_csv(project_path, ext)
+    check_zarr(project_path, ext)
+    check_annotations_dir(project_path)
+
+
+def load_images(directory):
+    filename_pattern_original = os.path.join(directory, '*png')
+    images_original = dask_image.imread.imread(filename_pattern_original)
+    return images_original
+
+
+def load_predicted_masks(mito_mask_dir, er_mask_dir):
+    filename_pattern_mito_label = os.path.join(mito_mask_dir, '*png')
+    filename_pattern_er_label = os.path.join(er_mask_dir, '*png')
+    images_mito_label = dask_image.imread.imread(filename_pattern_mito_label)
+    images_mito_label = images_mito_label.compute()
+    images_er_label = dask_image.imread.imread(filename_pattern_er_label)
+    images_er_label = images_er_label.compute()
+    base_label = (images_mito_label > 127) * 1 + (images_er_label > 127) * 2
+    return base_label
+
+
+def load_saved_masks(mod_mask_dir):
+    filename_pattern_label = os.path.join(mod_mask_dir, '*png')
+    images_label = dask_image.imread.imread(filename_pattern_label)
+    images_label = images_label.compute()
+    base_label = images_label
+    return base_label
+
+
+def load_raw_masks(raw_mask_dir):
+    filename_pattern_raw = os.path.join(raw_mask_dir, '*png')
+    images_raw = dask_image.imread.imread(filename_pattern_raw)
+    images_raw = images_raw.compute()
+    base_label = np.where((126 < images_raw) & (images_raw < 171), 255, 0)
+    return base_label
+
+
+def combine_blocks(block1, block2):
+    temp_widget = QWidget()
+    temp_layout = QHBoxLayout()
+    temp_layout.addWidget(block1)
+    temp_layout.addWidget(block2)
+    temp_widget.setLayout(temp_layout)
+    return temp_widget
+
+
+def save_masks(labels, out_path):
+    num = labels.shape[0]
+    os.makedirs(out_path, exist_ok=True)
+    for i in range(num):
+        label = labels[i]
+        io.imsave(os.path.join(out_path, str(i).zfill(4) + '.png'), label)
+
+
+def label_and_sort(base_label):
+    labeled = ndimage.label(base_label, structure=np.ones((3, 3, 3)))[0]
+
+    mks, nums = np.unique(labeled, return_counts=True)
+
+    idx_list = list(np.argsort(nums[1:]))
+    nums = np.sort(nums[1:])
+    labeled_sorted = np.zeros_like(labeled)
+    for i, idx in enumerate(idx_list):
+        labeled_sorted = np.where(labeled == mks[1:][idx], i + 1, labeled_sorted)
+    return labeled_sorted, nums
+
+
+def label_ct(labeled_array, nums, value):
+    labeled_temp = copy.copy(labeled_array)
+    idx = np.abs(nums - value).argmin()
+    labeled_temp = np.where((labeled_temp < idx) & (labeled_temp != 0), 255, 0)
+    return labeled_temp
+
+
+def crop_img(points, layer):
+    min_vals = [x - 50 for x in points]
+    max_vals = [x + 50 for x in points]
+    yohaku_minus = [n if n < 0 else 0 for n in min_vals]
+    yohaku_plus = [x - layer.data.shape[i] if layer.data.shape[i] < x else 0 for i, x in
+                   enumerate(max_vals)]
+    crop_slice = tuple(slice(np.maximum(0, n), x) for n, x in zip(min_vals, max_vals))
+    crop_temp = layer.data[crop_slice].persist().compute()
+    cropped_img = np.zeros((100, 100, 100), np.uint8)
+    cropped_img[-yohaku_minus[0]:100 - yohaku_plus[0], -yohaku_minus[1]:100 - yohaku_plus[1]
+    , -yohaku_minus[2]:100 - yohaku_plus[2]] = crop_temp
+    return cropped_img
+
+
+def deletewidgets(layout):
+    while True:
+        count = layout.count()
+        print(count)
+        if count == 1:
+            break
+        item = layout.itemAt(count - 2)
+        widget = item.widget()
+        widget.deleteLater()
+
+
+def show_so_layer(args):
+    labeled_c, labeled_sorted, nums, viewer = args
+    so_layer = viewer.add_image(labeled_c, colormap='cyan', name='small_object', blending='additive')
+
+    object_slider = QSlider(Qt.Horizontal)
+    object_slider.setMinimum(0)
+    object_slider.setMaximum(100)
+    object_slider.setSingleStep(10)
+    object_slider.setValue(10)
+
+    object_slider.valueChanged[int].connect(lambda value=object_slider: calc_object_callback(so_layer, value,
+                                                                                             labeled_sorted,
+                                                                                             nums))
+    lbl = QLabel('object size')
+    slider_widget = combine_blocks(lbl, object_slider)
+    viewer.window.add_dock_widget(slider_widget, name='object_size_slider', area='left')
+
+    def calc_object_callback(t_layer, value, labeled_array, nums):
+        t_layer.data = label_ct(labeled_array, nums, value)
+
+
+def load_X_gray(folder_path):
+    image_files = []
+    for file in os.listdir(folder_path):
+        base, ext = os.path.splitext(file)
+        if ext == '.png':
+            image_files.append(file)
+        else:
+            pass
+
+    image_files.sort()
+
+    img = cv2.imread(folder_path + os.sep + image_files[0], cv2.IMREAD_GRAYSCALE)
+
+    images = np.zeros((len(image_files), img.shape[0], img.shape[1], 1), np.float32)
+    for i, image_file in tqdm(enumerate(image_files)):
+        image = cv2.imread(folder_path + os.sep + image_file, cv2.IMREAD_GRAYSCALE)
+        image = image[:, :, np.newaxis]
+        images[i] = normalize_x(image)
+
+    print(images.shape)
+
+    return images, image_files
+
+
+def load_Y_gray(folder_path, thresh=None, normalize=False):
+    image_files = []
+    for file in os.listdir(folder_path):
+        base, ext = os.path.splitext(file)
+        if ext == '.png':
+            image_files.append(file)
+        else:
+            pass
+
+    image_files.sort()
+
+    img = cv2.imread(folder_path + os.sep + image_files[0], cv2.IMREAD_GRAYSCALE)
+
+    images = np.zeros((len(image_files), img.shape[0], img.shape[1], 1), np.float32)
+
+    for i, image_file in tqdm(enumerate(image_files)):
+        image = cv2.imread(folder_path + os.sep + image_file, cv2.IMREAD_GRAYSCALE)
+        if thresh:
+            ret, image = cv2.threshold(image, thresh, 255, cv2.THRESH_BINARY)
+        image = image[:, :, np.newaxis]
+        if normalize:
+            images[i] = normalize_y(image)
+        else:
+            images[i] = image
+
+    print(images.shape)
+
+    return images, image_files
+
+
+def select_train_data(dataframe, ori_imgs, label_imgs, ori_filenames):
+    train_img_names = list()
+    for node in dataframe.itertuples():
+        if node.train == "Checked":
+            train_img_names.append(node.filename)
+    train_ori_imgs = list()
+    train_label_imgs = list()
+    for ori_img, label_img, train_filename in zip(ori_imgs, label_imgs, ori_filenames):
+        if train_filename in train_img_names:
+            train_ori_imgs.append(ori_img)
+            train_label_imgs.append(label_img)
+    print(ori_filenames)
+    return np.array(train_ori_imgs), np.array(train_label_imgs)
+
+
+def dice_coeff(y_true, y_pred):
+    smooth = 1.
+    y_true_f = K.flatten(y_true)
+    y_pred_f = K.flatten(y_pred)
+    intersection = K.sum(y_true_f * y_pred_f)
+    score = (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
+    return score
+
+
+def dice_loss(y_true, y_pred):
+    loss = 1 - dice_coeff(y_true, y_pred)
+    return loss
+
+
+def bce_dice_loss(y_true, y_pred):
+    loss = binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)
+    return loss
+
+
+def divide_imgs(images):
+    H = -(-images.shape[1] // 412)
+    W = -(-images.shape[2] // 412)
+
+    diveded_imgs = np.zeros((images.shape[0] * H * W, 512, 512, 1), np.float32)
+    print(H, W)
+
+    for z in range(images.shape[0]):
+        image = images[z]
+        for h in range(H):
+            for w in range(W):
+                cropped_img = np.zeros((512, 512, 1), np.float32)
+                cropped_img -= 1
+
+                if images.shape[1] < 412:
+                    h = -1
+                if images.shape[2] < 412:
+                    w = -1
+
+                if h == -1:
+                    if w == -1:
+                        cropped_img[50:images.shape[1] + 50, 50:images.shape[2] + 50, 0] = image[0:images.shape[1],
+                                                                                           0:images.shape[2], 0]
+                    elif w == 0:
+                        cropped_img[50:images.shape[1] + 50, 50:512, 0] = image[0:images.shape[1], 0:462, 0]
+                    elif w == W - 1:
+                        cropped_img[50:images.shape[1] + 50, 0:images.shape[2] - 412 * W - 50, 0] = image[
+                                                                                                    0:images.shape[1],
+                                                                                                    w * 412 - 50:
+                                                                                                    images.shape[2], 0]
+                    else:
+                        cropped_img[50:images.shape[1] + 50, :, 0] = image[0:images.shape[1],
+                                                                     w * 412 - 50:(w + 1) * 412 + 50, 0]
+                elif h == 0:
+                    if w == -1:
+                        cropped_img[50:512, 50:images.shape[2] + 50, 0] = image[0:462, 0:images.shape[2], 0]
+                    elif w == 0:
+                        cropped_img[50:512, 50:512, 0] = image[0:462, 0:462, 0]
+                    elif w == W - 1:
+                        cropped_img[50:512, 0:images.shape[2] - 412 * W - 50, 0] = image[0:462,
+                                                                                   w * 412 - 50:images.shape[2], 0]
+                    else:
+                        # cropped_img[50:512, :, 0] = image[0:462, w*412-50:(w+1)*412+50, 0]
+                        try:
+                            cropped_img[50:512, :, 0] = image[0:462, w * 412 - 50:(w + 1) * 412 + 50, 0]
+                        except:
+                            cropped_img[50:512, 0:images.shape[2] - 412 * (W - 1) - 50, 0] = image[0:462, w * 412 - 50:(
+                                                                                                                               w + 1) * 412 + 50,
+                                                                                             0]
+                elif h == H - 1:
+                    if w == -1:
+                        cropped_img[0:images.shape[1] - 412 * H - 50, 50:images.shape[2] + 50, 0] = image[h * 412 - 50:
+                                                                                                          images.shape[
+                                                                                                              1],
+                                                                                                    0:images.shape[2],
+                                                                                                    0]
+                    elif w == 0:
+                        cropped_img[0:images.shape[1] - 412 * H - 50, 50:512, 0] = image[h * 412 - 50:images.shape[1],
+                                                                                   0:462, 0]
+                    elif w == W - 1:
+                        cropped_img[0:images.shape[1] - 412 * H - 50, 0:images.shape[2] - 412 * W - 50, 0] = image[
+                                                                                                             h * 412 - 50:
+                                                                                                             images.shape[
+                                                                                                                 1],
+                                                                                                             w * 412 - 50:
+                                                                                                             images.shape[
+                                                                                                                 2], 0]
+                    else:
+                        try:
+                            cropped_img[0:images.shape[1] - 412 * H - 50, :, 0] = image[h * 412 - 50:images.shape[1],
+                                                                                  w * 412 - 50:(w + 1) * 412 + 50, 0]
+                        except:
+                            cropped_img[0:images.shape[1] - 412 * H - 50, 0:images.shape[2] - 412 * (W - 1) - 50,
+                            0] = image[h * 412 - 50:images.shape[1], w * 412 - 50:(w + 1) * 412 + 50, 0]
+                else:
+                    if w == -1:
+                        cropped_img[:, 50:images.shape[2] + 50, 0] = image[h * 412 - 50:(h + 1) * 412 + 50,
+                                                                     0:images.shape[2], 0]
+                    elif w == 0:
+                        # cropped_img[:, 50:512, 0] = image[h*412-50:(h+1)*412+50, 0:462, 0]
+                        try:
+                            cropped_img[:, 50:512, 0] = image[h * 412 - 50:(h + 1) * 412 + 50, 0:462, 0]
+                        except:
+                            cropped_img[0:images.shape[1] - 412 * H - 50 + 412, 50:512, 0] = image[h * 412 - 50:(
+                                                                                                                        h + 1) * 412 + 50,
+                                                                                             0:462, 0]
+                    elif w == W - 1:
+                        # cropped_img[:, 0:images.shape[2]-412*W-50, 0] = image[h*412-50:(h+1)*412+50, w*412-50:images.shape[2], 0]
+                        try:
+                            cropped_img[:, 0:images.shape[2] - 412 * W - 50, 0] = image[h * 412 - 50:(h + 1) * 412 + 50,
+                                                                                  w * 412 - 50:images.shape[2], 0]
+                        except:
+                            cropped_img[0:images.shape[1] - 412 * H - 50 + 412, 0:images.shape[2] - 412 * W - 50,
+                            0] = image[h * 412 - 50:(h + 1) * 412 + 50, w * 412 - 50:images.shape[2], 0]
+                    else:
+                        # cropped_img[:, :, 0] = image[h*412-50:(h+1)*412+50, w*412-50:(w+1)*412+50, 0]
+                        try:
+                            cropped_img[:, :, 0] = image[h * 412 - 50:(h + 1) * 412 + 50,
+                                                   w * 412 - 50:(w + 1) * 412 + 50, 0]
+                        except:
+                            try:
+                                cropped_img[:, 0:images.shape[2] - 412 * (W - 1) - 50, 0] = image[h * 412 - 50:(
+                                                                                                                       h + 1) * 412 + 50,
+                                                                                            w * 412 - 50:(
+                                                                                                                 w + 1) * 412 + 50,
+                                                                                            0]
+                            except:
+                                cropped_img[0:images.shape[1] - 412 * (H - 1) - 50, :, 0] = image[h * 412 - 50:(
+                                                                                                                       h + 1) * 412 + 50,
+                                                                                            w * 412 - 50:(
+                                                                                                                 w + 1) * 412 + 50,
+                                                                                            0]
+                h = max(0, h)
+                w = max(0, w)
+                diveded_imgs[z * H * W + w * H + h] = cropped_img
+                # print(z*H*W+ w*H+h)
+
+    return diveded_imgs
+
+
+def merge_imgs(imgs, original_image_shape):
+    merged_imgs = np.zeros((original_image_shape[0], original_image_shape[1], original_image_shape[2], 1), np.float32)
+    H = -(-original_image_shape[1] // 412)
+    W = -(-original_image_shape[2] // 412)
+
+    for z in range(original_image_shape[0]):
+        for h in range(H):
+            for w in range(W):
+
+                if original_image_shape[1] < 412:
+                    h = -1
+                if original_image_shape[2] < 412:
+                    w = -1
+
+                # print(z*H*W+ max(w, 0)*H+max(h, 0))
+                if h == -1:
+                    if w == -1:
+                        merged_imgs[z, 0:original_image_shape[1], 0:original_image_shape[2], 0] = imgs[
+                                                                                                      z * H * W + 0 * H + 0][
+                                                                                                  50:
+                                                                                                  original_image_shape[
+                                                                                                      1] + 50, 50:
+                                                                                                               original_image_shape[
+                                                                                                                   2] + 50,
+                                                                                                  0]
+                    elif w == 0:
+                        merged_imgs[z, 0:original_image_shape[1], 0:412, 0] = imgs[z * H * W + w * H + 0][
+                                                                              50:original_image_shape[1] + 50, 50:462,
+                                                                              0]
+                    elif w == W - 1:
+                        merged_imgs[z, 0:original_image_shape[1], w * 412:original_image_shape[2], 0] = imgs[
+                                                                                                            z * H * W + w * H + 0][
+                                                                                                        50:
+                                                                                                        original_image_shape[
+                                                                                                            1] + 50, 50:
+                                                                                                                     original_image_shape[
+                                                                                                                         2] - 412 * W - 50,
+                                                                                                        0]
+                    else:
+                        merged_imgs[z, 0:original_image_shape[1], w * 412:(w + 1) * 412, 0] = imgs[
+                                                                                                  z * H * W + w * H + 0][
+                                                                                              50:original_image_shape[
+                                                                                                     1] + 50, 50:462, 0]
+                elif h == 0:
+                    if w == -1:
+                        merged_imgs[z, 0:412, 0:original_image_shape[2], 0] = imgs[z * H * W + 0 * H + h][50:462,
+                                                                              50:original_image_shape[2] + 50, 0]
+                    elif w == 0:
+                        merged_imgs[z, 0:412, 0:412, 0] = imgs[z * H * W + w * H + h][50:462, 50:462, 0]
+                    elif w == W - 1:
+                        merged_imgs[z, 0:412, w * 412:original_image_shape[2], 0] = imgs[z * H * W + w * H + h][50:462,
+                                                                                    50:original_image_shape[
+                                                                                           2] - 412 * W - 50, 0]
+                    else:
+                        merged_imgs[z, 0:412, w * 412:(w + 1) * 412, 0] = imgs[z * H * W + w * H + h][50:462, 50:462, 0]
+                elif h == H - 1:
+                    if w == -1:
+                        merged_imgs[z, h * 412:original_image_shape[1], 0:original_image_shape[2], 0] = imgs[
+                                                                                                            z * H * W + 0 * H + h][
+                                                                                                        50:
+                                                                                                        original_image_shape[
+                                                                                                            1] - 412 * H - 50,
+                                                                                                        50:
+                                                                                                        original_image_shape[
+                                                                                                            2] + 50, 0]
+                    elif w == 0:
+                        merged_imgs[z, h * 412:original_image_shape[1], 0:412, 0] = imgs[z * H * W + w * H + h][
+                                                                                    50:original_image_shape[
+                                                                                           1] - 412 * H - 50, 50:462, 0]
+                    elif w == W - 1:
+                        merged_imgs[z, h * 412:original_image_shape[1], w * 412:original_image_shape[2], 0] = imgs[
+                                                                                                                  z * H * W + w * H + h][
+                                                                                                              50:
+                                                                                                              original_image_shape[
+                                                                                                                  1] - 412 * H - 50,
+                                                                                                              50:
+                                                                                                              original_image_shape[
+                                                                                                                  2] - 412 * W - 50,
+                                                                                                              0]
+                    else:
+                        merged_imgs[z, h * 412:original_image_shape[1], w * 412:(w + 1) * 412, 0] = imgs[
+                                                                                                        z * H * W + w * H + h][
+                                                                                                    50:
+                                                                                                    original_image_shape[
+                                                                                                        1] - 412 * H - 50,
+                                                                                                    50:462, 0]
+                else:
+                    if w == -1:
+                        merged_imgs[z, h * 412:(h + 1) * 412, 0:original_image_shape[2], 0] = imgs[
+                                                                                                  z * H * W + 0 * H + h][
+                                                                                              50:462,
+                                                                                              50:original_image_shape[
+                                                                                                     2] + 50, 0]
+                    elif w == 0:
+                        merged_imgs[z, h * 412:(h + 1) * 412, 0:412, 0] = imgs[z * H * W + w * H + h][50:462, 50:462, 0]
+                    elif w == W - 1:
+                        merged_imgs[z, h * 412:(h + 1) * 412, w * 412:original_image_shape[2], 0] = imgs[
+                                                                                                        z * H * W + w * H + h][
+                                                                                                    50:462, 50:
+                                                                                                            original_image_shape[
+                                                                                                                2] - 412 * W - 50,
+                                                                                                    0]
+                    else:
+                        merged_imgs[z, h * 412:(h + 1) * 412, w * 412:(w + 1) * 412, 0] = imgs[z * H * W + w * H + h][
+                                                                                          50:462, 50:462, 0]
+
+    print(merged_imgs.shape)
+    return merged_imgs
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..a3bd235
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,38 @@
+# For more information about tox, see https://tox.readthedocs.io/en/latest/
+[tox]
+envlist = py{37,38,39}-{linux,macos,windows}
+
+[gh-actions]
+python =
+    3.7: py37
+    3.8: py38
+    3.9: py39
+    
+[gh-actions:env]
+PLATFORM =
+    ubuntu-latest: linux
+    macos-latest: macos
+    windows-latest: windows
+
+[testenv]
+platform = 
+    macos: darwin
+    linux: linux
+    windows: win32
+passenv = 
+    CI
+    GITHUB_ACTIONS
+    DISPLAY XAUTHORITY
+    NUMPY_EXPERIMENTAL_ARRAY_FUNCTION
+    PYVISTA_OFF_SCREEN
+deps = 
+    pytest  # https://docs.pytest.org/en/latest/contents.html
+    pytest-cov  # https://pytest-cov.readthedocs.io/en/latest/
+    pytest-xvfb ; sys_platform == 'linux'
+    # you can remove these if you don't use them
+    napari
+    magicgui
+    pytest-qt
+    qtpy
+    pyqt5
+commands = pytest -v --color=yes --cov=napari_philow --cov-report=xml


Test patch:
diff --git a/src/napari_philow/_tests/__init__.py b/src/napari_philow/_tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/napari_philow/_tests/test_dock_widget.py b/src/napari_philow/_tests/test_dock_widget.py
new file mode 100644
index 0000000..dbba710
--- /dev/null
+++ b/src/napari_philow/_tests/test_dock_widget.py
@@ -0,0 +1,18 @@
+import napari_philow
+import pytest
+
+# this is your plugin name declared in your napari.plugins entry point
+MY_PLUGIN_NAME = "napari-PHILOW"
+# the name of your widget(s)
+MY_WIDGET_NAMES = ["Example Q Widget", "example_magic_widget"]
+
+
+@pytest.mark.parametrize("widget_name", MY_WIDGET_NAMES)
+def test_something_with_viewer(widget_name, make_napari_viewer, napari_plugin_manager):
+    napari_plugin_manager.register(napari_philow, name=MY_PLUGIN_NAME)
+    viewer = make_napari_viewer()
+    num_dw = len(viewer.window._dock_widgets)
+    viewer.window.add_plugin_dock_widget(
+        plugin_name=MY_PLUGIN_NAME, widget_name=widget_name
+    )
+    assert len(viewer.window._dock_widgets) == num_dw + 1