Purge the old files

This commit is contained in:
deeppomf 2019-08-06 17:22:07 -04:00
parent 1ae8cf99cf
commit 3721295c58
31 changed files with 2 additions and 2312 deletions

View File

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

View File

@ -1,7 +1,8 @@
# DeepCreamPy
*Decensoring Hentai with Deep Neural Networks.*
*DeepCreamPyV2 coming August 6, 2019*
*DeepCreamPyV2 under construction.*
*Please bear with me. Many, many things will be broken.*
[![GitHub release](https://img.shields.io/github/release/deeppomf/DeepCreamPy.svg)](https://github.com/deeppomf/DeepCreamPy/releases/latest)
[![GitHub downloads](https://img.shields.io/github/downloads/deeppomf/DeepCreamPy/latest/total.svg)](https://github.com/deeppomf/DeepCreamPy/releases/latest)

View File

@ -1,39 +0,0 @@
import argparse
def str2floatarr(v):
if type(v) == str:
try:
return [float(v) for v in v.split(',')]
except:
raise argparse.ArgumentTypeError('Integers seperated by commas expected.')
else:
raise argparse.ArgumentTypeError('Integers seperated by commas expected.')
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1', True):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0', False):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def get_args():
parser = argparse.ArgumentParser(description='')
#Input output folders settings
parser.add_argument('--decensor_input_path', dest='decensor_input_path', default='./decensor_input/', help='input images with censored regions colored green to be decensored by decensor.py path')
parser.add_argument('--decensor_input_original_path', dest='decensor_input_original_path', default='./decensor_input_original/', help='input images with no modifications to be decensored by decensor.py path')
parser.add_argument('--decensor_output_path', dest='decensor_output_path', default='./decensor_output/', help='output images generated from running decensor.py path')
#Decensor settings
parser.add_argument('--mask_color', dest='mask_color', default=[0,255,0], type=str2floatarr, help='rgb color of the mask, comma seperated.')
parser.add_argument('--is_mosaic', dest='is_mosaic', default='False', type=str2bool, help='true if image has mosaic censoring, false otherwise')
#Misc settings
parser.add_argument('--autoclose', dest='autoclose', default='False', type=str2bool, help='true will close the program when it finishes')
args = parser.parse_args()
return args
if __name__ == '__main__':
get_args()

View File

@ -1,233 +0,0 @@
#!/usr/bin/env python3
try:
import numpy as np
from PIL import Image
import os
from copy import deepcopy
import config
import file
from libs.pconv_hybrid_model import PConvUnet
from libs.utils import *
except ImportError as err:
print("Error: ", err)
print("Could not import modules. Make sure all dependencies are installed.")
exit(1)
class Decensor:
def __init__(self):
self.args = config.get_args()
self.is_mosaic = self.args.is_mosaic
self.mask_color = [float(v/255) for v in self.args.mask_color] # normalize mask color
if not os.path.exists(self.args.decensor_output_path):
os.makedirs(self.args.decensor_output_path)
self.load_model()
def get_mask(self, colored):
mask = np.ones(colored.shape, np.uint8)
i, j = np.where(np.all(colored[0] == self.mask_color, axis=-1))
mask[0, i, j] = 0
return mask
def load_model(self):
self.model = PConvUnet()
self.model.load(
r"./models/model.h5",
train_bn=False,
lr=0.00005
)
def decensor_all_images_in_folder(self):
# load model once at beginning and reuse same model
# self.load_model()
color_dir = self.args.decensor_input_path
file_names = os.listdir(color_dir)
input_dir = self.args.decensor_input_path
output_dir = self.args.decensor_output_path
# Change False to True before release --> file.check_file( input_dir, output_dir, True)
file_names, self.files_removed = file.check_file(input_dir, output_dir, False)
# convert all images into np arrays and put them in a list
for file_name in file_names:
color_file_path = os.path.join(color_dir, file_name)
color_bn, color_ext = os.path.splitext(file_name)
if os.path.isfile(color_file_path) and color_ext.casefold() == ".png":
print("--------------------------------------------------------------------------")
print("Decensoring the image {}".format(color_file_path))
try:
colored_img = Image.open(color_file_path)
except:
print("Cannot identify image file (" + str(color_file_path)+")")
self.files_removed.append((color_file_path, 3))
# incase of abnormal file format change (ex : text.txt -> text.png)
continue
# if we are doing a mosaic decensor
if self.is_mosaic:
# get the original file that hasn't been colored
ori_dir = self.args.decensor_input_original_path
# since the original image might not be a png, test multiple file formats
valid_formats = {".png", ".jpg", ".jpeg"}
for test_file_name in os.listdir(ori_dir):
test_bn, test_ext = os.path.splitext(test_file_name)
if (test_bn == color_bn) and (test_ext.casefold() in valid_formats):
ori_file_path = os.path.join(ori_dir, test_file_name)
ori_img = Image.open(ori_file_path)
# colored_img.show()
self.decensor_image(ori_img, colored_img, file_name)
break
else: # for...else, i.e if the loop finished without encountering break
print("Corresponding original, uncolored image not found in {}".format(color_file_path))
print("Check if it exists and is in the PNG or JPG format.")
else:
self.decensor_image(colored_img, colored_img, file_name)
else:
print("--------------------------------------------------------------------------")
print("Iregular file deteced : "+str(color_file_path))
print("--------------------------------------------------------------------------")
if(self.files_removed is not None):
file.error_messages(None, self.files_removed)
if(self.args.autoclose == False):
input("\nPress anything to end...")
#decensors one image at a time
#TODO: decensor all cropped parts of the same image in a batch (then i need input for colored an array of those images and make additional changes)
def decensor_image(self, ori, colored, file_name=None):
width, height = ori.size
# save the alpha channel if the image has an alpha channel
has_alpha = False
if (ori.mode == "RGBA"):
has_alpha = True
alpha_channel = np.asarray(ori)[:, :, 3]
alpha_channel = np.expand_dims(alpha_channel, axis=-1)
ori = ori.convert('RGB')
ori_array = image_to_array(ori)
ori_array = np.expand_dims(ori_array, axis=0)
if self.is_mosaic:
# if mosaic decensor, mask is empty
# mask = np.ones(ori_array.shape, np.uint8)
# print(mask.shape)
colored = colored.convert('RGB')
color_array = image_to_array(colored)
color_array = np.expand_dims(color_array, axis=0)
mask = self.get_mask(color_array)
# mask_reshaped = mask[0,:,:,:] * 255.0
# mask_img = Image.fromarray(mask_reshaped.astype('uint8'))
# mask_img.show()
else:
mask = self.get_mask(ori_array)
# colored image is only used for finding the regions
regions = find_regions(mask) # use mask to find all the colored regions
print("Found {region_count} censored regions in this image!".format(region_count=len(regions)))
if len(regions) == 0 and not self.is_mosaic:
print("No green regions detected! Make sure you're using exactly the right color.")
return
output_img_array = ori_array[0].copy()
for region_counter, region in enumerate(regions, 1):
bounding_box = expand_bounding(ori, region)
crop_img = ori.crop(bounding_box)
# crop_img.show()
# convert mask back to image
mask_reshaped = mask[0, :, :, :] * 255.0
mask_img = Image.fromarray(mask_reshaped.astype('uint8'))
# resize the cropped images
crop_img = crop_img.resize((512, 512))
crop_img_array = image_to_array(crop_img)
crop_img_array = np.expand_dims(crop_img_array, axis=0)
# resize the mask images
mask_img = mask_img.crop(bounding_box)
mask_img = mask_img.resize((512, 512))
# mask_img.show()
# convert mask_img back to array
mask_array = image_to_array(mask_img)
# the mask has been upscaled so there will be values not equal to 0 or 1
mask_array[mask_array > 0] = 1
if self.is_mosaic:
a, b = np.where(np.all(mask_array == 0, axis=-1))
print(a, b)
coords = [coord for coord in zip(a, b) if ((coord[0] + coord[1]) % 2 == 0)]
a, b = zip(*coords)
mask_array[a, b] = 1
# mask_array = mask_array * 255.0
# img = Image.fromarray(mask_array.astype('uint8'))
# img.show()
# return
mask_array = np.expand_dims(mask_array, axis=0)
# Run predictions for this batch of images
pred_img_array = self.model.predict([crop_img_array, mask_array, mask_array])
pred_img_array = pred_img_array * 255.0
pred_img_array = np.squeeze(pred_img_array, axis=0)
# scale prediction image back to original size
bounding_width = bounding_box[2]-bounding_box[0]
bounding_height = bounding_box[3]-bounding_box[1]
# convert np array to image
# print(bounding_width,bounding_height)
# print(pred_img_array.shape)
pred_img = Image.fromarray(pred_img_array.astype('uint8'))
# pred_img.show()
pred_img = pred_img.resize((bounding_width, bounding_height), resample=Image.BICUBIC)
pred_img_array = image_to_array(pred_img)
# print(pred_img_array.shape)
pred_img_array = np.expand_dims(pred_img_array, axis=0)
# copy the decensored regions into the output image
for i in range(len(ori_array)):
for col in range(bounding_width):
for row in range(bounding_height):
bounding_width_index = col + bounding_box[0]
bounding_height_index = row + bounding_box[1]
if (bounding_width_index, bounding_height_index) in region:
output_img_array[bounding_height_index][bounding_width_index] = pred_img_array[i, :, :, :][row][col]
print("{region_counter} out of {region_count} regions decensored.".format(region_counter=region_counter, region_count=len(regions)))
output_img_array = output_img_array * 255.0
# restore the alpha channel if the image had one
if has_alpha:
output_img_array = np.concatenate((output_img_array, alpha_channel), axis=2)
output_img = Image.fromarray(output_img_array.astype('uint8'))
if file_name != None:
# save the decensored image
#file_name, _ = os.path.splitext(file_name)
save_path = os.path.join(self.args.decensor_output_path, file_name)
output_img.save(save_path)
print("Decensored image saved to {save_path}!".format(save_path=save_path))
return
else:
print("Decensored image. Returning it.")
return output_img
if __name__ == '__main__':
decensor = Decensor()
decensor.decensor_all_images_in_folder()

View File

@ -1,70 +0,0 @@
FROM debian:stretch-slim
ENV BUILD_PACKAGES="\
build-essential \
linux-headers-4.9 \
python3-dev \
cmake \
tcl-dev \
xz-utils \
zlib1g-dev \
git \
curl \
unzip" \
APT_PACKAGES="\
ca-certificates \
openssl \
bash \
graphviz \
fonts-noto \
libpng16-16 \
libfreetype6 \
libjpeg62-turbo \
libgomp1 \
python3 \
python3-pip" \
PYTHON_VERSION=3.6.7 \
PATH=/usr/local/bin:$PATH \
PYTHON_PIP_VERSION=9.0.1 \
MODELS=1byrmn6wp0r27lSXcT9MC4j-RQ2R04P1Z \
LANG=C.UTF-8
COPY gd.sh /opt
WORKDIR /opt
RUN set -ex; \
apt-get update -y; \
apt-get upgrade -y; \
apt-get install -y --no-install-recommends ${APT_PACKAGES}; \
apt-get install -y --no-install-recommends ${BUILD_PACKAGES}; \
ln -s /usr/bin/idle3 /usr/bin/idle; \
ln -s /usr/bin/pydoc3 /usr/bin/pydoc; \
ln -s /usr/bin/python3 /usr/bin/python; \
ln -s /usr/bin/python3-config /usr/bin/python-config; \
ln -s /usr/bin/pip3 /usr/bin/pip; \
pip install -U -v setuptools wheel; \
cd /opt && \
git clone https://github.com/deeppomf/DeepCreamPy.git && \
cd /opt/DeepCreamPy && \
pip install -U -v -r requirements.txt && \
mkdir -p models/ && \
bash /opt/gd.sh ${MODELS}; \
unzip model.zip && \
mv model.h5 models && \
apt-get remove --purge --auto-remove -y ${BUILD_PACKAGES}; \
apt-get clean; \
apt-get autoclean; \
apt-get autoremove; \
rm -rf /tmp/* /var/tmp/*; \
rm -rf /var/lib/apt/lists/*; \
rm -f /var/cache/apt/archives/*.deb \
/var/cache/apt/archives/partial/*.deb \
/var/cache/apt/*.bin; \
find /usr/lib/python3 -name __pycache__ | xargs rm -r; \
rm -rf /root/.[acpw]*;
VOLUME [ "/opt/DeepCreamPy/decensor_input", "/opt/DeepCreamPy/decensor_output" ]
WORKDIR /opt/DeepCreamPy
ENTRYPOINT [ "/usr/bin/python", "/opt/DeepCreamPy/decensor.py" ]

View File

@ -1,15 +0,0 @@
Docker image
------------
Build:
```bash
cd docker && docker build -t deeppomf/DeepCreamPy:latest .
```
Run:
```bash
docker run -v <input_path>:/opt/DeepCreamPy/decensor_input -v <output_path>:/opt/DeepCreamPy/decensor_output deeppomf/DeepCreamPy:latest
```
where
<input_path> - full path to input directory
<output_path> - full path to output directory

View File

@ -1,6 +0,0 @@
#!/bin/bash
ggID=$1
ggURL='https://drive.google.com/uc?export=download'
filename="$(curl -sc /opt/gcokie "${ggURL}&id=${ggID}" | grep -o '="uc-name.*</span>' | sed 's/.*">//;s/<.a> .*//')"
getcode="$(awk '/_warning_/ {print $NF}' /opt/gcokie)"
curl -Lb /opt/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" -o "${filename}"

56
file.py
View File

@ -1,56 +0,0 @@
import os
def check_file(input_dir, output_dir, Release_version = True):
file_list = []
output_file_list = []
files_removed = []
input_dir = os.listdir(input_dir)
output_dir = os.listdir(output_dir)
for file_in in input_dir:
if not file_in.startswith('.'):
file_list.append(file_in)
if(Release_version is True):
print("\nChecking valid files...")
for file_out in output_dir:
if file_out.lower().endswith('.png'):
output_file_list.append(file_out)
# solving https://github.com/deeppomf/DeepCreamPy/issues/25
# appending in list with reason as tuple (file name, reason)
for lhs in file_list:
lhs.lower()
if not lhs.lower().endswith('.png') :
files_removed.append((lhs, 0))
for rhs in output_file_list:
if(lhs == rhs):
files_removed.append((lhs, 1))
# seperated detecteing same file names and deleting file name list
# just in case of index_error and show list of files which will not go though
# decensor process
print("\n These files will not be decensored for following reason \n")
error_messages(file_list, files_removed)
input("\nPress anything to continue...")
print("\n\n")
return file_list, files_removed
def error_messages(file_list, files_removed):
if files_removed is None:
return
for remove_this,reason in files_removed:
if(file_list is not None):
file_list.remove(remove_this)
if reason == 0:
print(" REMOVED : (" + str(remove_this) +") is not PNG file format")
elif reason == 1:
print(" REMOVED : (" + str(remove_this) +") already exists")
elif reason == 2:
print(" REMOVED : (" + str(remove_this) +") file unreadable")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 388 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 600 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 605 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 541 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 569 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 597 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 369 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 298 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 996 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 281 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 303 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 329 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 577 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 B

View File

@ -1,88 +0,0 @@
"""
Chapter 6: Paint Application
Developing a Tiny Framework
Tkinter GUI Application Development Blueprints
"""
import tkinter as tk
class Framework():
"""
GUIFramework is a class that provides a higher level of abstraction for
the development of Tkinter graphic user interfaces (GUIs).
Every class that uses this GUI framework must inherit from this class
and should pass the root window as an argument to this class by calling
the super method as follows:
super().__init__(root)
Building Menus:
To build a menu, call build_menu() method with one argument for
menu_definition, where menu_definition is a tuple where each item is a string of the
format:
'Top Level Menu Name - MenuItemName/Accelrator/Commandcallback/Underlinenumber'.
MenuSeparator is denoted by a string 'sep'.
For instance, passing this tuple as an argument to this method
menu_definition = (
'File - &New/Ctrl+N/new_file, &Open/Ctrl+O/openfile, &Save/Ctrl+S/save, Save&As//saveas, sep, Exit/Alt+F4/close',
'Edit - Cut/Ctrl+X/cut, Copy/Ctrl+C/copy, Paste/Ctrl+V/paste, Sep',
)
will generate a File and Edit Menu Buttons with listed menu items for each of the buttons.
"""
menu_items = None
def __init__(self, root):
self.root = root
def build_menu(self, menu_definitions):
menu_bar = tk.Menu(self.root)
for definition in menu_definitions:
menu = tk.Menu(menu_bar, tearoff=0)
top_level_menu, pull_down_menus = definition.split('-')
menu_items = map(str.strip, pull_down_menus.split(','))
for item in menu_items:
self._add_menu_command(menu, item)
menu_bar.add_cascade(label=top_level_menu, menu=menu)
self.root.config(menu=menu_bar)
def _add_menu_command(self, menu, item):
if item == 'sep':
menu.add_separator()
else:
menu_label, accelrator_key, command_callback = item.split('/')
try:
underline = menu_label.index('&')
menu_label = menu_label.replace('&', '', 1)
except ValueError:
underline = None
menu.add_command(label=menu_label, underline=underline,
accelerator=accelrator_key, command=eval(command_callback))
class TestThisFramework(Framework):
def new_file(self):
print('new tested OK')
def open_file(self):
print ('open tested OK')
def undo(self):
print ('undo tested OK')
def options(self):
print ('options tested OK')
def about(self):
print ('about tested OK')
if __name__ == '__main__':
root = tk.Tk()
menu_items = (
'File- &New/Ctrl+N/self.new_file, &Open/Ctrl+O/self.open_file',
'Edit- Undo/Ctrl+Z/self.undo, sep, Options/Ctrl+T/self.options',
'About- About//self.about'
)
app = TestThisFramework(root)
app.build_menu(menu_items)
root.mainloop()

View File

@ -1,278 +0,0 @@
import os
from datetime import datetime
from keras.models import Model
from keras.models import load_model
from keras.optimizers import Adam
from keras.layers import Input, Conv2D, UpSampling2D, Dropout, LeakyReLU, BatchNormalization, Activation
from keras.layers.merge import Concatenate
#from keras.applications import VGG16
from keras import backend as K
from libs.pconv_layer import PConv2D
class PConvUnet(object):
def __init__(self, img_rows=512, img_cols=512, weight_filepath=None):
"""Create the PConvUnet. If variable image size, set img_rows and img_cols to None"""
# Settings
self.weight_filepath = weight_filepath
self.img_rows = img_rows
self.img_cols = img_cols
assert self.img_rows >= 256, 'Height must be >256 pixels'
assert self.img_cols >= 256, 'Width must be >256 pixels'
# Set current epoch
self.current_epoch = 0
# # VGG layers to extract features from (first maxpooling layers, see pp. 7 of paper)
# self.vgg_layers = [3, 6, 10]
# # Get the vgg16 model for perceptual loss
# self.vgg = self.build_vgg()
# Create UNet-like model
self.model = self.build_pconv_unet()
# def build_vgg(self):
# """
# Load pre-trained VGG16 from keras applications
# Extract features to be used in loss function from last conv layer, see architecture at:
# https://github.com/keras-team/keras/blob/master/keras/applications/vgg16.py
# """
# # Input image to extract features from
# img = Input(shape=(self.img_rows, self.img_cols, 3))
# # Get the vgg network from Keras applications
# vgg = VGG16(weights="imagenet", include_top=False)
# # Output the first three pooling layers
# vgg.outputs = [vgg.layers[i].output for i in self.vgg_layers]
# # Create model and compile
# model = Model(inputs=img, outputs=vgg(img))
# model.trainable = False
# model.compile(loss='mse', optimizer='adam')
# return model
def build_pconv_unet(self, train_bn=True, lr=0.0002):
# INPUTS
inputs_img = Input((self.img_rows, self.img_cols, 3))
inputs_mask = Input((self.img_rows, self.img_cols, 3))
loss_mask = Input((self.img_rows, self.img_cols, 3))
# ENCODER
def encoder_layer(img_in, mask_in, filters, kernel_size, bn=True):
conv, mask = PConv2D(filters, kernel_size, strides=2, padding='same')([img_in, mask_in])
if bn:
conv = BatchNormalization(name='EncBN'+str(encoder_layer.counter))(conv, training=train_bn)
conv = Activation('relu')(conv)
encoder_layer.counter += 1
return conv, mask
encoder_layer.counter = 0
e_conv1, e_mask1 = encoder_layer(inputs_img, inputs_mask, 64, 7, bn=False)
e_conv2, e_mask2 = encoder_layer(e_conv1, e_mask1, 128, 5)
e_conv3, e_mask3 = encoder_layer(e_conv2, e_mask2, 256, 5)
e_conv4, e_mask4 = encoder_layer(e_conv3, e_mask3, 512, 3)
e_conv5, e_mask5 = encoder_layer(e_conv4, e_mask4, 512, 3)
e_conv6, e_mask6 = encoder_layer(e_conv5, e_mask5, 512, 3)
e_conv7, e_mask7 = encoder_layer(e_conv6, e_mask6, 512, 3)
e_conv8, e_mask8 = encoder_layer(e_conv7, e_mask7, 512, 3)
# DECODER
def decoder_layer(img_in, mask_in, e_conv, e_mask, filters, kernel_size, bn=True):
up_img = UpSampling2D(size=(2,2))(img_in)
up_mask = UpSampling2D(size=(2,2))(mask_in)
concat_img = Concatenate(axis=3)([e_conv,up_img])
concat_mask = Concatenate(axis=3)([e_mask,up_mask])
conv, mask = PConv2D(filters, kernel_size, padding='same')([concat_img, concat_mask])
if bn:
conv = BatchNormalization()(conv)
conv = LeakyReLU(alpha=0.2)(conv)
return conv, mask
d_conv9, d_mask9 = decoder_layer(e_conv8, e_mask8, e_conv7, e_mask7, 512, 3)
d_conv10, d_mask10 = decoder_layer(d_conv9, d_mask9, e_conv6, e_mask6, 512, 3)
d_conv11, d_mask11 = decoder_layer(d_conv10, d_mask10, e_conv5, e_mask5, 512, 3)
d_conv12, d_mask12 = decoder_layer(d_conv11, d_mask11, e_conv4, e_mask4, 512, 3)
d_conv13, d_mask13 = decoder_layer(d_conv12, d_mask12, e_conv3, e_mask3, 256, 3)
d_conv14, d_mask14 = decoder_layer(d_conv13, d_mask13, e_conv2, e_mask2, 128, 3)
d_conv15, d_mask15 = decoder_layer(d_conv14, d_mask14, e_conv1, e_mask1, 64, 3)
d_conv16, d_mask16 = decoder_layer(d_conv15, d_mask15, inputs_img, inputs_mask, 3, 3, bn=False)
outputs = Conv2D(3, 1, activation = 'sigmoid')(d_conv16)
# Setup the model inputs / outputs
model = Model(inputs=[inputs_img, inputs_mask, loss_mask], outputs=outputs)
# Compile the model
model.compile(
optimizer = Adam(lr=lr),
loss='mse'
#loss really isn't mse, but we don't need the vgg16 model for inference so we don't to have to download the vgg16 model
#loss=self.loss_total(loss_mask)
)
return model
# def loss_total(self, mask):
# """
# Creates a loss function which sums all the loss components
# and multiplies by their weights. See paper eq. 7.
# """
# def loss(y_true, y_pred):
# # Compute predicted image with non-hole pixels set to ground truth
# y_comp = mask * y_true + (1-mask) * y_pred
# # Compute the vgg features
# vgg_out = self.vgg(y_pred)
# vgg_gt = self.vgg(y_true)
# vgg_comp = self.vgg(y_comp)
# # Compute loss components
# l1 = self.loss_valid(mask, y_true, y_pred)
# l2 = self.loss_hole(mask, y_true, y_pred)
# l3 = self.loss_perceptual(vgg_out, vgg_gt, vgg_comp)
# l4 = self.loss_style(vgg_out, vgg_gt)
# l5 = self.loss_style(vgg_comp, vgg_gt)
# l6 = self.loss_tv(mask, y_comp)
# # Return loss function
# return l1 + 6*l2 + 0.05*l3 + 120*(l4+l5) + 0.1*l6
# return loss
# def loss_hole(self, mask, y_true, y_pred):
# """Pixel L1 loss within the hole / mask"""
# return self.l1((1-mask) * y_true, (1-mask) * y_pred)
# def loss_valid(self, mask, y_true, y_pred):
# """Pixel L1 loss outside the hole / mask"""
# return self.l1(mask * y_true, mask * y_pred)
# def loss_perceptual(self, vgg_out, vgg_gt, vgg_comp):
# """Perceptual loss based on VGG16, see. eq. 3 in paper"""
# loss = 0
# for o, c, g in zip(vgg_out, vgg_comp, vgg_gt):
# loss += self.l1(o, g) + self.l1(c, g)
# return loss
# def loss_style(self, output, vgg_gt):
# """Style loss based on output/computation, used for both eq. 4 & 5 in paper"""
# loss = 0
# for o, g in zip(output, vgg_gt):
# loss += self.l1(self.gram_matrix(o), self.gram_matrix(g))
# return loss
# def loss_tv(self, mask, y_comp):
# """Total variation loss, used for smoothing the hole region, see. eq. 6"""
# # Create dilated hole region using a 3x3 kernel of all 1s.
# kernel = K.ones(shape=(3, 3, mask.shape[3], mask.shape[3]))
# dilated_mask = K.conv2d(1-mask, kernel, data_format='channels_last', padding='same')
# # Cast values to be [0., 1.], and compute dilated hole region of y_comp
# dilated_mask = K.cast(K.greater(dilated_mask, 0), 'float32')
# P = dilated_mask * y_comp
# # Calculate total variation loss
# a = self.l1(P[:,1:,:,:], P[:,:-1,:,:])
# b = self.l1(P[:,:,1:,:], P[:,:,:-1,:])
# return a+b
def fit(self, generator, epochs=10, plot_callback=None, *args, **kwargs):
"""Fit the U-Net to a (images, targets) generator
param generator: training generator yielding (maskes_image, original_image) tuples
param epochs: number of epochs to train for
param plot_callback: callback function taking Unet model as parameter
"""
# Loop over epochs
for _ in range(epochs):
# Fit the model
self.model.fit_generator(
generator,
epochs=self.current_epoch+1,
initial_epoch=self.current_epoch,
*args, **kwargs
)
# Update epoch
self.current_epoch += 1
# After each epoch predict on test images & show them
if plot_callback:
plot_callback(self.model)
# Save logfile
if self.weight_filepath:
self.save()
def predict(self, sample):
"""Run prediction using this model"""
return self.model.predict(sample)
def summary(self):
"""Get summary of the UNet model"""
print(self.model.summary())
def save(self):
self.model.save_weights(self.current_weightfile())
def load(self, filepath, train_bn=True, lr=0.0002):
# Create UNet-like model
self.model = self.build_pconv_unet(train_bn, lr)
# Load weights into model
#epoch = 50
# epoch = int(os.path.basename(filepath).split("_")[0])
# assert epoch > 0, "Could not parse weight file. Should start with 'X_', with X being the epoch"
# self.current_epoch = epoch
self.model.load_weights(filepath)
def current_weightfile(self):
assert self.weight_filepath != None, 'Must specify location of logs'
return self.weight_filepath + "{}_weights_{}.h5".format(self.current_epoch, self.current_timestamp())
@staticmethod
def current_timestamp():
return datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
@staticmethod
def l1(y_true, y_pred):
"""Calculate the L1 loss used in all loss calculations"""
if K.ndim(y_true) == 4:
return K.sum(K.abs(y_pred - y_true), axis=[1,2,3])
elif K.ndim(y_true) == 3:
return K.sum(K.abs(y_pred - y_true), axis=[1,2])
else:
raise NotImplementedError("Calculating L1 loss on 1D tensors? should not occur for this network")
@staticmethod
def gram_matrix(x, norm_by_channels=False):
"""Calculate gram matrix used in style loss"""
# Assertions on input
assert K.ndim(x) == 4, 'Input tensor should be a 4d (B, H, W, C) tensor'
assert K.image_data_format() == 'channels_last', "Please use channels-last format"
# Permute channels and get resulting shape
x = K.permute_dimensions(x, (0, 3, 1, 2))
shape = K.shape(x)
B, C, H, W = shape[0], shape[1], shape[2], shape[3]
# Reshape x and do batch dot product
features = K.reshape(x, K.stack([B, C, H*W]))
gram = K.batch_dot(features, features, axes=2)
# Normalize with channels, height and width
gram = gram / K.cast(C * H * W, x.dtype)
return gram

View File

@ -1,126 +0,0 @@
from keras.utils import conv_utils
from keras import backend as K
from keras.engine import InputSpec
from keras.layers import Conv2D
class PConv2D(Conv2D):
def __init__(self, *args, n_channels=3, mono=False, **kwargs):
super().__init__(*args, **kwargs)
self.input_spec = [InputSpec(ndim=4), InputSpec(ndim=4)]
def build(self, input_shape):
"""Adapted from original _Conv() layer of Keras
param input_shape: list of dimensions for [img, mask]
"""
if self.data_format == 'channels_first':
channel_axis = 1
else:
channel_axis = -1
if input_shape[0][channel_axis] is None:
raise ValueError('The channel dimension of the inputs should be defined. Found `None`.')
self.input_dim = input_shape[0][channel_axis]
# Image kernel
kernel_shape = self.kernel_size + (self.input_dim, self.filters)
self.kernel = self.add_weight(shape=kernel_shape,
initializer=self.kernel_initializer,
name='img_kernel',
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint)
# Mask kernel
self.kernel_mask = K.ones(shape=self.kernel_size + (self.input_dim, self.filters))
if self.use_bias:
self.bias = self.add_weight(shape=(self.filters,),
initializer=self.bias_initializer,
name='bias',
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
else:
self.bias = None
self.built = True
def call(self, inputs, mask=None):
'''
We will be using the Keras conv2d method, and essentially we have
to do here is multiply the mask with the input X, before we apply the
convolutions. For the mask itself, we apply convolutions with all weights
set to 1.
Subsequently, we set all mask values >0 to 1, and otherwise 0
'''
# Both image and mask must be supplied
if type(inputs) is not list or len(inputs) != 2:
raise Exception('PartialConvolution2D must be called on a list of two tensors [img, mask]. Instead got: ' + str(inputs))
# Create normalization. Slight change here compared to paper, using mean mask value instead of sum
normalization = K.mean(inputs[1], axis=[1,2], keepdims=True)
normalization = K.repeat_elements(normalization, inputs[1].shape[1], axis=1)
normalization = K.repeat_elements(normalization, inputs[1].shape[2], axis=2)
# Apply convolutions to image
img_output = K.conv2d(
(inputs[0]*inputs[1]) / normalization, self.kernel,
strides=self.strides,
padding=self.padding,
data_format=self.data_format,
dilation_rate=self.dilation_rate
)
# Apply convolutions to mask
mask_output = K.conv2d(
inputs[1], self.kernel_mask,
strides=self.strides,
padding=self.padding,
data_format=self.data_format,
dilation_rate=self.dilation_rate
)
# Where something happened, set 1, otherwise 0
mask_output = K.cast(K.greater(mask_output, 0), 'float32')
# Apply bias only to the image (if chosen to do so)
if self.use_bias:
img_output = K.bias_add(
img_output,
self.bias,
data_format=self.data_format)
# Apply activations on the image
if self.activation is not None:
img_output = self.activation(img_output)
return [img_output, mask_output]
def compute_output_shape(self, input_shape):
if self.data_format == 'channels_last':
space = input_shape[0][1:-1]
new_space = []
for i in range(len(space)):
new_dim = conv_utils.conv_output_length(
space[i],
self.kernel_size[i],
padding=self.padding,
stride=self.strides[i],
dilation=self.dilation_rate[i])
new_space.append(new_dim)
new_shape = (input_shape[0][0],) + tuple(new_space) + (self.filters,)
return [new_shape, new_shape]
if self.data_format == 'channels_first':
space = input_shape[2:]
new_space = []
for i in range(len(space)):
new_dim = conv_utils.conv_output_length(
space[i],
self.kernel_size[i],
padding=self.padding,
stride=self.strides[i],
dilation=self.dilation_rate[i])
new_space.append(new_dim)
new_shape = (input_shape[0], self.filters) + tuple(new_space)
return [new_shape, new_shape]

View File

@ -1,165 +0,0 @@
from PIL import Image, ImageDraw
import numpy as np
# Return a mask based off the specified color
# Color should have a shape of (r, g, b) and a float value from 0.0 to 1.0
# Colored should be the image in array form, with expanded dimensions of axis=0,
# and the array has values from 0.0 to 1.0, same as color array.
def get_mask(colored, color):
mask = np.ones(colored.shape, np.uint8)
i, j = np.where(np.all(colored[0] == color, axis=-1))
mask[0, i, j] = 0
return mask
def image_to_array(image):
array = np.asarray(image)
return np.array(array / 255.0)
# Find all the regions of the masked picture
# All marked regions should have the value 0, all else should be 1
def find_regions(mask):
# Gets all of the coordinates where the mask exists
i, j = np.where(np.all(mask[0], axis=-1) == 0)
if len(i) == 0:
return []
# Creates a tuple of the coordinates
coords = [coord for coord in zip(j, i)]
# Creates a dictionary with the coordinates as both key and value.
neighbors = dict((y, {y}) for y in coords)
for x, y in neighbors:
candidates = (x + 1, y), (x, y + 1)
for candidate in candidates:
if candidate in neighbors:
neighbors[x, y].add(candidate)
neighbors[candidate].add((x, y))
closed_list = set()
def connected_component(pixel):
region = set()
open_list = {pixel}
while open_list:
pixel = open_list.pop()
closed_list.add(pixel)
open_list |= neighbors[pixel] - closed_list
region.add(pixel)
return region
regions = []
for pixel in neighbors:
if pixel not in closed_list:
regions.append(connected_component(pixel))
regions.sort(key=len, reverse=True)
return regions
# risk of box being bigger than the image
def expand_bounding(img, region, expand_factor=1.5, min_size = 256):
#expand bounding box to capture more context
x, y = zip(*region)
min_x, min_y, max_x, max_y = min(x), min(y), max(x), max(y)
width, height = img.size
width_center = width//2
height_center = height//2
bb_width = max_x - min_x
bb_height = max_y - min_y
x_center = (min_x + max_x)//2
y_center = (min_y + max_y)//2
current_size = max(bb_width, bb_height)
current_size = int(current_size * expand_factor)
max_size = min(width, height)
if current_size > max_size:
current_size = max_size
elif current_size < min_size:
current_size = min_size
x1 = x_center - current_size//2
x2 = x_center + current_size//2
y1 = y_center - current_size//2
y2 = y_center + current_size//2
x1_square = x1
y1_square = y1
x2_square = x2
y2_square = y2
#move bounding boxes that are partially outside of the image inside the image
if (y1_square < 0 or y2_square > (height - 1)) and (x1_square < 0 or x2_square > (width - 1)):
#conservative square region
if x1_square < 0 and y1_square < 0:
x1_square = 0
y1_square = 0
x2_square = current_size
y2_square = current_size
elif x2_square > (width - 1) and y1_square < 0:
x1_square = width - current_size - 1
y1_square = 0
x2_square = width - 1
y2_square = current_size
elif x1_square < 0 and y2_square > (height - 1):
x1_square = 0
y1_square = height - current_size - 1
x2_square = current_size
y2_square = height - 1
elif x2_square > (width - 1) and y2_square > (height - 1):
x1_square = width - current_size - 1
y1_square = height - current_size - 1
x2_square = width - 1
y2_square = height - 1
else:
x1_square = x1
y1_square = y1
x2_square = x2
y2_square = y2
else:
if x1_square < 0:
difference = x1_square
x1_square -= difference
x2_square -= difference
if x2_square > (width - 1):
difference = x2_square - width + 1
x1_square -= difference
x2_square -= difference
if y1_square < 0:
difference = y1_square
y1_square -= difference
y2_square -= difference
if y2_square > (height - 1):
difference = y2_square - height + 1
y1_square -= difference
y2_square -= difference
# if y1_square < 0 or y2_square > (height - 1):
#if bounding box goes outside of the image for some reason, set bounds to original, unexpanded values
#print(width, height)
if x2_square > width or y2_square > height:
print("bounding box out of bounds!")
print(x1_square, y1_square, x2_square, y2_square)
x1_square, y1_square, x2_square, y2_square = min_x, min_y, max_x, max_y
return x1_square, y1_square, x2_square, y2_square
def is_right_color(pixel, r2, g2, b2):
r1, g1, b1 = pixel
return r1 == r2 and g1 == g2 and b1 == b2
# Draws boxes around the found censor regions.
if __name__ == '__main__':
image = Image.open(r'D:\VirtualPython\venv\DeepCreamPy\decensor_input\mermaid_censored.png')
no_alpha_image = image.convert('RGB')
draw = ImageDraw.Draw(no_alpha_image)
### Original
# for region in find_regions(no_alpha_image, [0, 255, 0]):
# draw.rectangle(expand_bounding(no_alpha_image, region), outline=(0, 255, 0))
# no_alpha_image.show()
### END OF ORIGINAL
### With new mask region finder
ori_array = np.asarray(no_alpha_image)
ori_array = np.array(ori_array / 255.0)
ori_array = np.expand_dims(ori_array, axis=0)
mask = get_mask(ori_array, [0.0, 1.0, 0.0])
regions = find_regions(mask)
for region in regions:
draw.rectangle(expand_bounding(no_alpha_image, region), outline=(0, 255, 0))
no_alpha_image.show()
### END OF NEW MASK REGION FINDER

View File

@ -1,24 +0,0 @@
tensorflow==1.13.1
absl-py==0.5.0
altgraph==0.16.1
astor==0.7.1
future==0.16.0
gast==0.2.0
grpcio==1.15.0
h5py==2.8.0
Keras==2.2.4
Keras-Applications==1.0.6
Keras-Preprocessing==1.0.5
macholib==1.11
Markdown==3.0.1
numpy==1.14.5
pefile==2018.8.8
Pillow==5.3.0
protobuf==3.6.1
pywin32-ctypes==0.2.0
PyYAML==4.2b1
scipy==1.1.0
six==1.11.0
tensorboard==1.10.0
termcolor==1.1.0
Werkzeug==0.14.1

550
ui.py
View File

@ -1,550 +0,0 @@
#!/usr/bin/env python3
"""
Code illustration: 6.09
Modules imported here:
from tkinter import messagebox
from tkinter import filedialog
Attributes added here:
file_name = "untitled"
Methods modified here:
on_new_file_menu_clicked()
on_save_menu_clicked()
on_save_as_menu_clicked()
on_close_menu_clicked()
on_undo_menu_clicked()
on_canvas_zoom_in_menu_clicked()
on_canvas_zoom_out_menu_clicked()
on_about_menu_clicked()
Methods added here
start_new_project()
actual_save()
close_window()
undo()
canvas_zoom_in()
canvas_zoom_out()
@ Tkinter GUI Application Development Blueprints
"""
import math
from PIL import Image, ImageTk, ImageDraw
import tkinter as tk
from tkinter import colorchooser
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import libs.framework as framework
import decensor
import os
class PaintApplication(framework.Framework):
def __init__(self, root):
super().__init__(root)
self.circle = 0
self.drawn_img = None
self.screen_width = root.winfo_screenwidth()
self.screen_height = root.winfo_screenheight()
self.start_x, self.start_y = 0, 0
self.end_x, self.end_y = 0, 0
self.current_item = None
self.fill = "#00ff00"
self.fill_pil = (0,255,0,255)
self.outline = "#00ff00"
self.brush_width = 2
self.background = 'white'
self.foreground = "#00ff00"
self.file_name = "Untitled"
self.tool_bar_functions = (
"draw_line", "draw_irregular_line"
)
self.selected_tool_bar_function = self.tool_bar_functions[0]
self.create_gui()
self.bind_mouse()
# Create blank image to avoid errors with irregular line drawing on blank canvas
self.canvas.img = Image.new('RGB', (800,1280), (255, 255, 255))
self.canvas.img_width, self.canvas.img_height = self.canvas.img.size
# make reference to image to prevent garbage collection
# https://stackoverflow.com/questions/20061396/image-display-on-tkinter-canvas-not-working
self.canvas.tk_img = ImageTk.PhotoImage(self.canvas.img)
self.canvas.config(width=self.canvas.img_width, height=self.canvas.img_height)
self.canvas.create_image(self.canvas.img_width / 2.0, self.canvas.img_height / 2.0, image=self.canvas.tk_img)
self.drawn_img = Image.new("RGBA", self.canvas.img.size)
self.drawn_img_draw = ImageDraw.Draw(self.drawn_img)
def on_new_file_menu_clicked(self, event=None):
self.start_new_project()
def start_new_project(self):
self.canvas.delete(tk.ALL)
self.canvas.config(bg="#ffffff")
self.root.title('untitled')
def on_open_image_menu_clicked(self, event=None):
self.open_image()
def open_image(self):
self.file_name = filedialog.askopenfilename(master=self.root, title="Open...")
print(self.file_name)
self.canvas.img = Image.open(self.file_name)
self.canvas.img_width, self.canvas.img_height = self.canvas.img.size
#make reference to image to prevent garbage collection
#https://stackoverflow.com/questions/20061396/image-display-on-tkinter-canvas-not-working
self.canvas.tk_img = ImageTk.PhotoImage(self.canvas.img)
self.canvas.config(width=self.canvas.img_width, height=self.canvas.img_height)
self.canvas.create_image(self.canvas.img_width/2.0,self.canvas.img_height/2.0,image=self.canvas.tk_img)
self.drawn_img = Image.new("RGBA", self.canvas.img.size)
self.drawn_img_draw = ImageDraw.Draw(self.drawn_img)
def on_import_mask_clicked(self, event=None):
self.import_mask()
def display_canvas(self):
composite_img = Image.alpha_composite(self.canvas.img.convert('RGBA'), self.drawn_img).convert('RGB')
self.canvas.tk_img = ImageTk.PhotoImage(composite_img)
self.canvas.create_image(self.canvas.img_width/2.0,self.canvas.img_height/2.0,image=self.canvas.tk_img)
def import_mask(self):
file_name_mask = filedialog.askopenfilename(master=self.root, filetypes = [("All Files","*.*")], title="Import mask...")
mask_img = Image.open(file_name_mask)
if (mask_img.size != self.canvas.img.size):
messagebox.showerror("Import mask", "Mask image size does not match the original image size! Mask image not imported.")
return
self.drawn_img = mask_img
self.drawn_img_draw = ImageDraw.Draw(self.drawn_img)
self.display_canvas()
def on_save_menu_clicked(self, event=None):
if self.file_name == 'untitled':
self.on_save_as_menu_clicked()
else:
self.actual_save()
def on_save_as_menu_clicked(self):
file_name = filedialog.asksaveasfilename(
master=self.root, filetypes=[('All Files', ('*.png'))], title="Save...")
if not file_name:
return
self.file_name = file_name
self.actual_save()
def actual_save(self):
self.canvas.postscript(file=self.file_name, colormode='color')
self.root.title(self.file_name)
def on_close_menu_clicked(self):
self.close_window()
def close_window(self):
if messagebox.askokcancel("Quit", "Do you really want to quit?"):
self.root.destroy()
def on_undo_menu_clicked(self, event=None):
self.undo()
def undo(self):
self.canvas.delete(self.circle)
items_stack = list(self.canvas.find("all"))
try:
last_item_id = items_stack.pop()
except IndexError:
return
self.canvas.delete(last_item_id)
def on_canvas_zoom_in_menu_clicked(self):
self.canvas_zoom_in()
def on_canvas_zoom_out_menu_clicked(self):
self.canvas_zoom_out()
def canvas_zoom_in(self):
self.canvas.scale("all", 0, 0, 1.2, 1.2)
self.canvas.config(scrollregion=self.canvas.bbox(tk.ALL))
self.canvas.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.BOTH)
def canvas_zoom_out(self):
self.canvas.scale("all", 0, 0, .8, .8)
self.canvas.config(scrollregion=self.canvas.bbox(tk.ALL))
self.canvas.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.BOTH)
def on_decensor_menu_clicked(self, event=None):
combined_img = Image.alpha_composite(self.canvas.img.convert('RGBA'), self.drawn_img)
decensorer = decensor.Decensor()
orig_name = self.file_name
path, file = os.path.split(self.file_name)
name, ext = os.path.splitext(file)
name = name + "_decensored"
self.file_name = os.path.join(path, name + ext)
decensorer.decensor_image(combined_img.convert('RGB'),combined_img.convert('RGB'), self.file_name)
messagebox.showinfo(
"Decensoring", "Decensoring complete! image saved to {save_path}".format(save_path=self.file_name))
self.file_name = orig_name
def on_about_menu_clicked(self, event=None):
# messagebox.showinfo(
# "Decensoring", "Decensoring in progress.")
messagebox.showinfo(
"About", "Tkinter GUI Application\n Development Blueprints")
def get_all_configurations_for_item(self):
configuration_dict = {}
for key, value in self.canvas.itemconfig("current").items():
if value[-1] and value[-1] not in ["0", "0.0", "0,0", "current"]:
configuration_dict[key] = value[-1]
return configuration_dict
def canvas_function_wrapper(self, function_name, *arg, **kwargs):
func = getattr(self.canvas, function_name)
func(*arg, **kwargs)
def adjust_canvas_coords(self, x_coordinate, y_coordinate):
# low_x, high_x = self.x_scroll.get()
# percent_x = low_x/(1+low_x-high_x)
# low_y, high_y = self.y_scroll.get()
# percent_y = low_y/(1+low_y-high_y)
low_x, high_x = self.x_scroll.get()
low_y, high_y = self.y_scroll.get()
#length_y = high_y - low_y
return low_x * 800 + x_coordinate, low_y * 800 + y_coordinate
def create_circle(self, x, y, r, **kwargs):
return self.canvas.create_oval(x-r, y-r, x+r, y+r, **kwargs)
def draw_irregular_line(self):
# self.current_item = self.canvas.create_line(
# self.start_x, self.start_y, self.end_x, self.end_y, fill=self.fill, width=self.brush_width)
# self.current_item = self.create_circle(self.end_x, self.end_y, self.brush_width/2.0, fill=self.fill, width=0)
#draw in PIL
self.drawn_img_draw.line((self.start_x, self.start_y, self.end_x, self.end_y), fill=self.fill_pil, width=int(self.brush_width))
self.drawn_img_draw.ellipse((self.end_x - self.brush_width/2.0, self.end_y - self.brush_width/2.0, self.end_x + self.brush_width/2.0, self.end_y + self.brush_width/2.0), fill=self.fill_pil)
self.display_canvas()
# composite_img = Image.alpha_composite(self.canvas.img.convert('RGBA'), self.drawn_img).convert('RGB')
# self.canvas.tk_img = ImageTk.PhotoImage(composite_img)
# self.canvas.create_image(self.canvas.img_width/2.0,self.canvas.img_height/2.0,image=self.canvas.tk_img)
self.canvas.bind("<B1-Motion>", self.draw_irregular_line_update_x_y)
# Creates circular indicator for brush size, modified from https://stackoverflow.com/questions/42631060/draw-a-defined-size-circle-around-cursor-in-tkinter-python
def motion(self, event=None):
x, y = event.x, event.y
# the addition is just to center the oval around the center of the mouse
# remove the the +3 and +7 if you want to center it around the point of the mouse
self.canvas.delete(self.circle) # to refresh the circle each motion
radius = self.brush_width/2.0 # change this for the size of your circle
x_max = x + radius
x_min = x - radius
y_max = y + radius
y_min = y - radius
self.circle = self.canvas.create_oval(x_max, y_max, x_min, y_min, outline="black")
def draw_irregular_line_update_x_y(self, event=None):
self.start_x, self.start_y = self.end_x, self.end_y
self.end_x, self.end_y = self.adjust_canvas_coords(event.x, event.y)
# self.motion(event)
self.draw_irregular_line()
self.motion(event)
def draw_line_update_x_y(self, event=None):
self.start_x, self.start_y = self.end_x, self.end_y
# self.end_x, self.end_y = self.adjust_canvas_coords(event.x, event.y)
# self.motion(event)
self.draw_line()
self.motion(event)
def draw_irregular_line_options(self):
self.create_fill_options_combobox()
self.create_width_options_combobox()
def on_tool_bar_button_clicked(self, button_index):
self.selected_tool_bar_function = self.tool_bar_functions[button_index]
self.remove_options_from_top_bar()
self.display_options_in_the_top_bar()
self.bind_mouse()
def float_range(self, x, y, step):
while x < y:
yield x
x += step
def set_foreground_color(self, event=None):
self.foreground = self.get_color_from_chooser(
self.foreground, "foreground")
self.color_palette.itemconfig(
self.foreground_palette, width=0, fill=self.foreground)
def set_background_color(self, event=None):
self.background = self.get_color_from_chooser(
self.background, "background")
self.color_palette.itemconfig(
self.background_palette, width=0, fill=self.background)
def get_color_from_chooser(self, initial_color, color_type="a"):
color = colorchooser.askcolor(
color=initial_color,
title="select {} color".format(color_type)
)[-1]
if color:
return color
# dialog has been cancelled
else:
return initial_color
def try_to_set_fill_after_palette_change(self):
try:
self.set_fill()
except:
pass
def try_to_set_outline_after_palette_change(self):
try:
self.set_outline()
except:
pass
def display_options_in_the_top_bar(self):
self.show_selected_tool_icon_in_top_bar(
self.selected_tool_bar_function)
options_function_name = "{}_options".format(self.selected_tool_bar_function)
func = getattr(self, options_function_name, self.function_not_defined)
func()
def draw_line_options(self):
self.create_fill_options_combobox()
self.create_width_options_combobox()
def create_fill_options_combobox(self):
tk.Label(self.top_bar, text='Fill:').pack(side="left")
self.fill_combobox = ttk.Combobox(
self.top_bar, state='readonly', width=5)
self.fill_combobox.pack(side="left")
self.fill_combobox['values'] = ('none', 'fg', 'bg', 'black', 'white')
self.fill_combobox.bind('<<ComboboxSelected>>', self.set_fill)
self.fill_combobox.set(self.fill)
def create_outline_options_combobox(self):
tk.Label(self.top_bar, text='Outline:').pack(side="left")
self.outline_combobox = ttk.Combobox(
self.top_bar, state='readonly', width=5)
self.outline_combobox.pack(side="left")
self.outline_combobox['values'] = (
'none', 'fg', 'bg', 'black', 'white')
self.outline_combobox.bind('<<ComboboxSelected>>', self.set_outline)
self.outline_combobox.set(self.outline)
def create_width_options_combobox(self):
tk.Label(self.top_bar, text='Width:').pack(side="left")
self.width_combobox = ttk.Combobox(
self.top_bar, state='readonly', width=3)
self.width_combobox.pack(side="left")
self.width_combobox['values'] = (
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50)
self.width_combobox.bind('<<ComboboxSelected>>', self.set_brush_width)
self.width_combobox.set(self.brush_width)
def set_fill(self, event=None):
fill_color = self.fill_combobox.get()
if fill_color == 'none':
self.fill = '' # transparent
elif fill_color == 'fg':
self.fill = self.foreground
elif fill_color == 'bg':
self.fill = self.background
else:
self.fill = fill_color
def set_outline(self, event=None):
outline_color = self.outline_combobox.get()
if outline_color == 'none':
self.outline = '' # transparent
elif outline_color == 'fg':
self.outline = self.foreground
elif outline_color == 'bg':
self.outline = self.background
else:
self.outline = outline_color
def set_brush_width(self, event):
self.brush_width = float(self.width_combobox.get())
def create_color_palette(self):
self.color_palette = tk.Canvas(self.tool_bar, height=55, width=55)
self.color_palette.grid(row=10, column=1, columnspan=2, pady=5, padx=3)
self.background_palette = self.color_palette.create_rectangle(
15, 15, 48, 48, outline=self.background, fill=self.background)
self.foreground_palette = self.color_palette.create_rectangle(
1, 1, 33, 33, outline=self.foreground, fill=self.foreground)
self.bind_color_palette()
def bind_color_palette(self):
self.color_palette.tag_bind(
self.background_palette, "<Button-1>", self.set_background_color)
self.color_palette.tag_bind(
self.foreground_palette, "<Button-1>", self.set_foreground_color)
def create_current_coordinate_label(self):
self.current_coordinate_label = tk.Label(
self.tool_bar, text='x:0\ny: 0 ')
self.current_coordinate_label.grid(
row=13, column=1, columnspan=2, pady=5, padx=1, sticky='w')
def show_current_coordinates(self, event=None):
x_coordinate = event.x
y_coordinate = event.y
coordinate_string = "x:{0}\ny:{1}".format(x_coordinate, y_coordinate)
self.current_coordinate_label.config(text=coordinate_string)
def function_not_defined(self):
pass
def execute_selected_method(self):
self.current_item = None
func = getattr(
self, self.selected_tool_bar_function, self.function_not_defined)
func()
#TODO: fix this function. Lines made by this disappear upon using irregular line tool
def draw_line(self):
self.current_item = self.canvas.create_line(
self.start_x, self.start_y, self.end_x, self.end_y, fill=self.fill, width=self.brush_width)
# self.drawn_img_draw.line((self.start_x, self.start_y, self.end_x, self.end_y), fill=self.fill_pil, width=int(self.brush_width))
# self.display_canvas()
# self.canvas.bind("<B1-Motion>", self.draw_line_update_x_y)
def create_tool_bar_buttons(self):
for index, name in enumerate(self.tool_bar_functions):
icon = tk.PhotoImage(file='icons/' + name + '.gif')
self.button = tk.Button(
self.tool_bar, image=icon, command=lambda index=index: self.on_tool_bar_button_clicked(index))
self.button.grid(
row=index // 2, column=1 + index % 2, sticky='nsew')
self.button.image = icon
def remove_options_from_top_bar(self):
for child in self.top_bar.winfo_children():
child.destroy()
def show_selected_tool_icon_in_top_bar(self, function_name):
display_name = function_name.replace("_", " ").capitalize() + ":"
tk.Label(self.top_bar, text=display_name).pack(side="left")
photo = tk.PhotoImage(
file='icons/' + function_name + '.gif')
label = tk.Label(self.top_bar, image=photo)
label.image = photo
label.pack(side="left")
def bind_mouse(self):
self.canvas.bind("<Button-1>", self.on_mouse_button_pressed)
self.canvas.bind(
"<Button1-Motion>", self.on_mouse_button_pressed_motion)
self.canvas.bind(
"<Button1-ButtonRelease>", self.on_mouse_button_released)
self.canvas.bind("<Motion>", self.on_mouse_unpressed_motion)
def on_mouse_button_pressed(self, event):
self.start_x = self.end_x = self.canvas.canvasx(event.x)
self.start_y = self.end_y = self.canvas.canvasy(event.y)
self.execute_selected_method()
self.motion(event)
def on_mouse_button_pressed_motion(self, event):
self.end_x = self.canvas.canvasx(event.x)
self.end_y = self.canvas.canvasy(event.y)
self.canvas.delete(self.current_item)
self.motion(event)
self.execute_selected_method()
def on_mouse_button_released(self, event):
self.end_x = self.canvas.canvasx(event.x)
self.end_y = self.canvas.canvasy(event.y)
self.motion(event)
def on_mouse_unpressed_motion(self, event):
self.show_current_coordinates(event)
self.motion(event)
def create_gui(self):
self.create_menu()
self.create_top_bar()
self.create_tool_bar()
self.create_tool_bar_buttons()
self.create_drawing_canvas()
self.create_color_palette()
self.create_current_coordinate_label()
self.bind_menu_accelrator_keys()
self.show_selected_tool_icon_in_top_bar("draw_line")
self.draw_line_options()
def create_menu(self):
self.menubar = tk.Menu(self.root)
menu_definitions = (
'File- &New/Ctrl+N/self.on_new_file_menu_clicked, Open/Ctrl+O/self.on_open_image_menu_clicked, Import Mask/Ctrl+M/self.on_import_mask_clicked, Save/Ctrl+S/self.on_save_menu_clicked, SaveAs/ /self.on_save_as_menu_clicked, sep, Exit/Alt+F4/self.on_close_menu_clicked',
'Edit- Undo/Ctrl+Z/self.on_undo_menu_clicked, sep',
'View- Zoom in//self.on_canvas_zoom_in_menu_clicked,Zoom Out//self.on_canvas_zoom_out_menu_clicked',
'Decensor- Decensor/Ctrl+D/self.on_decensor_menu_clicked',
'About- About/F1/self.on_about_menu_clicked'
)
self.build_menu(menu_definitions)
def create_top_bar(self):
self.top_bar = tk.Frame(self.root, height=25, relief="raised")
self.top_bar.pack(fill="x", side="top", pady=2)
def create_tool_bar(self):
self.tool_bar = tk.Frame(self.root, relief="raised", width=50)
self.tool_bar.pack(fill="y", side="left", pady=3)
def create_drawing_canvas(self):
self.canvas_frame = tk.Frame(self.root, width=900, height=900)
self.canvas_frame.pack(side="right", expand="yes", fill="both")
self.canvas = tk.Canvas(self.canvas_frame, background="white",
width=512, height=512, scrollregion=(0, 0, 512, 512))
self.create_scroll_bar()
self.canvas.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.BOTH)
self.canvas.img = Image.open('./icons/canvas_top_test.png').convert('RGBA')
self.canvas.img = self.canvas.img.resize((512,512))
self.canvas.tk_img = ImageTk.PhotoImage(self.canvas.img)
self.canvas.create_image(256,256,image=self.canvas.tk_img)
def create_scroll_bar(self):
self.x_scroll = tk.Scrollbar(self.canvas_frame, orient="horizontal")
self.x_scroll.pack(side="bottom", fill="x")
self.x_scroll.config(command=self.canvas.xview)
self.y_scroll = tk.Scrollbar(self.canvas_frame, orient="vertical")
self.y_scroll.pack(side="right", fill="y")
self.y_scroll.config(command=self.canvas.yview)
self.canvas.config(
xscrollcommand=self.x_scroll.set, yscrollcommand=self.y_scroll.set)
def bind_menu_accelrator_keys(self):
self.root.bind('<KeyPress-F1>', self.on_about_menu_clicked)
self.root.bind('<Control-N>', self.on_new_file_menu_clicked)
self.root.bind('<Control-n>', self.on_new_file_menu_clicked)
self.root.bind('<Control-s>', self.on_save_menu_clicked)
self.root.bind('<Control-S>', self.on_save_menu_clicked)
self.root.bind('<Control-z>', self.on_undo_menu_clicked)
self.root.bind('<Control-Z>', self.on_undo_menu_clicked)
if __name__ == '__main__':
root = tk.Tk()
app = PaintApplication(root)
root.mainloop()