First commit.

This commit is contained in:
Nataniel Ruiz Gutierrez
2020-03-09 17:37:40 -04:00
parent ff375d8d41
commit d05a264d06
253 changed files with 1034 additions and 5609 deletions
Vendored
BIN
View File
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
*.png
*.jpg
*.jpeg
*.pth
*.npy
-674
View File
@@ -1,674 +0,0 @@
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>.
View File
@@ -1,25 +0,0 @@
import torch.utils.data
from data.dataset import DatasetFactory
class CustomDatasetDataLoader:
def __init__(self, opt, is_for_train=True):
self._opt = opt
self._is_for_train = is_for_train
self._num_threds = opt.n_threads_train if is_for_train else opt.n_threads_test
self._create_dataset()
def _create_dataset(self):
self._dataset = DatasetFactory.get_by_name(self._opt.dataset_mode, self._opt, self._is_for_train)
self._dataloader = torch.utils.data.DataLoader(
self._dataset,
batch_size=self._opt.batch_size,
shuffle=not self._opt.serial_batches,
num_workers=int(self._num_threds),
drop_last=True)
def load_data(self):
return self._dataloader
def __len__(self):
return len(self._dataset)
-68
View File
@@ -1,68 +0,0 @@
import torch.utils.data as data
from PIL import Image
import torchvision.transforms as transforms
import os
import os.path
class DatasetFactory:
def __init__(self):
pass
@staticmethod
def get_by_name(dataset_name, opt, is_for_train):
if dataset_name == 'aus':
from data.dataset_aus import AusDataset
dataset = AusDataset(opt, is_for_train)
else:
raise ValueError("Dataset [%s] not recognized." % dataset_name)
print('Dataset {} was created'.format(dataset.name))
return dataset
class DatasetBase(data.Dataset):
def __init__(self, opt, is_for_train):
super(DatasetBase, self).__init__()
self._name = 'BaseDataset'
self._root = None
self._opt = opt
self._is_for_train = is_for_train
self._create_transform()
self._IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
@property
def name(self):
return self._name
@property
def path(self):
return self._root
def _create_transform(self):
self._transform = transforms.Compose([])
def get_transform(self):
return self._transform
def _is_image_file(self, filename):
return any(filename.endswith(extension) for extension in self._IMG_EXTENSIONS)
def _is_csv_file(self, filename):
return filename.endswith('.csv')
def _get_all_files_in_subfolders(self, dir, is_file):
images = []
assert os.path.isdir(dir), '%s is not a valid directory' % dir
for root, _, fnames in sorted(os.walk(dir)):
for fname in fnames:
if is_file(fname):
path = os.path.join(root, fname)
images.append(path)
return images
-117
View File
@@ -1,117 +0,0 @@
import os.path
import torchvision.transforms as transforms
from data.dataset import DatasetBase
from PIL import Image
import random
import numpy as np
import pickle
from utils import cv_utils
class AusDataset(DatasetBase):
def __init__(self, opt, is_for_train):
super(AusDataset, self).__init__(opt, is_for_train)
self._name = 'AusDataset'
# read dataset
self._read_dataset_paths()
def __getitem__(self, index):
assert (index < self._dataset_size)
# start_time = time.time()
real_img = None
real_cond = None
while real_img is None or real_cond is None:
# if sample randomly: overwrite index
if not self._opt.serial_batches:
index = random.randint(0, self._dataset_size - 1)
# get sample data
sample_id = self._ids[index]
real_img, real_img_path = self._get_img_by_id(sample_id)
real_cond = self._get_cond_by_id(sample_id)
if real_img is None:
print 'error reading image %s, skipping sample' % sample_id
if real_cond is None:
print 'error reading aus %s, skipping sample' % sample_id
desired_cond = self._generate_random_cond()
# transform data
img = self._transform(Image.fromarray(real_img))
# pack data
sample = {'real_img': img,
'real_cond': real_cond,
'desired_cond': desired_cond,
'sample_id': sample_id,
'real_img_path': real_img_path
}
# print (time.time() - start_time)
return sample
def __len__(self):
return self._dataset_size
def _read_dataset_paths(self):
self._root = self._opt.data_dir
self._imgs_dir = os.path.join(self._root, self._opt.images_folder)
# read ids
use_ids_filename = self._opt.train_ids_file if self._is_for_train else self._opt.test_ids_file
use_ids_filepath = os.path.join(self._root, use_ids_filename)
self._ids = self._read_ids(use_ids_filepath)
# read aus
conds_filepath = os.path.join(self._root, self._opt.aus_file)
self._conds = self._read_conds(conds_filepath)
self._ids = list(set(self._ids).intersection(set(self._conds.keys())))
# dataset size
self._dataset_size = len(self._ids)
def _create_transform(self):
if self._is_for_train:
transform_list = [transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5]),
]
else:
transform_list = [transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5]),
]
self._transform = transforms.Compose(transform_list)
def _read_ids(self, file_path):
ids = np.loadtxt(file_path, delimiter='\t', dtype=np.str)
return [id[:-4] for id in ids]
def _read_conds(self, file_path):
with open(file_path, 'rb') as f:
return pickle.load(f)
def _get_cond_by_id(self, id):
if id in self._conds:
return self._conds[id]/5.0
else:
return None
def _get_img_by_id(self, id):
filepath = os.path.join(self._imgs_dir, id+'.jpg')
return cv_utils.read_cv2_img(filepath), filepath
def _generate_random_cond(self):
cond = None
while cond is None:
rand_sample_id = self._ids[random.randint(0, self._dataset_size - 1)]
cond = self._get_cond_by_id(rand_sample_id)
cond += np.random.uniform(-0.1, 0.1, cond.shape)
return cond
-39
View File
@@ -1,39 +0,0 @@
import numpy as np
import os
from tqdm import tqdm
import argparse
import glob
import re
import pickle
parser = argparse.ArgumentParser()
parser.add_argument('-ia', '--input_aus_filesdir', type=str, help='Dir with imgs aus files')
parser.add_argument('-op', '--output_path', type=str, help='Output path')
args = parser.parse_args()
def get_data(filepaths):
data = dict()
for filepath in tqdm(filepaths):
content = np.loadtxt(filepath, delimiter=', ', skiprows=1)
data[os.path.basename(filepath[:-4])] = content[2:19]
return data
def save_dict(data, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
def main():
filepaths = glob.glob(os.path.join(args.input_aus_filesdir, '*.csv'))
filepaths.sort()
# create aus file
data = get_data(filepaths)
if not os.path.isdir(args.output_path):
os.makedirs(args.output_path)
save_dict(data, os.path.join(args.output_path, "aus"))
if __name__ == '__main__':
main()
-6
View File
@@ -1,6 +0,0 @@
#!/usr/bin/env bash
python train.py \
--data_dir path/to/dataset/ \
--name experiment_1 \
--batch_size 25 \
View File
@@ -1,30 +0,0 @@
import torch.nn as nn
import numpy as np
from .networks import NetworkBase
class Discriminator(NetworkBase):
"""Discriminator. PatchGAN."""
def __init__(self, image_size=128, conv_dim=64, c_dim=5, repeat_num=6):
super(Discriminator, self).__init__()
self._name = 'discriminator_wgan'
layers = []
layers.append(nn.Conv2d(3, conv_dim, kernel_size=4, stride=2, padding=1))
layers.append(nn.LeakyReLU(0.01, inplace=True))
curr_dim = conv_dim
for i in range(1, repeat_num):
layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1))
layers.append(nn.LeakyReLU(0.01, inplace=True))
curr_dim = curr_dim * 2
k_size = int(image_size / np.power(2, repeat_num))
self.main = nn.Sequential(*layers)
self.conv1 = nn.Conv2d(curr_dim, 1, kernel_size=3, stride=1, padding=1, bias=False)
self.conv2 = nn.Conv2d(curr_dim, c_dim, kernel_size=k_size, bias=False)
def forward(self, x):
h = self.main(x)
out_real = self.conv1(h)
out_aux = self.conv2(h)
return out_real.squeeze(), out_aux.squeeze()
@@ -1,68 +0,0 @@
import torch.nn as nn
import numpy as np
from .networks import NetworkBase
import torch
class Generator(NetworkBase):
"""Generator. Encoder-Decoder Architecture."""
def __init__(self, conv_dim=64, c_dim=5, repeat_num=6):
super(Generator, self).__init__()
self._name = 'generator_wgan'
layers = []
layers.append(nn.Conv2d(3+c_dim, conv_dim, kernel_size=7, stride=1, padding=3, bias=False))
layers.append(nn.InstanceNorm2d(conv_dim, affine=True))
layers.append(nn.ReLU(inplace=True))
# Down-Sampling
curr_dim = conv_dim
for i in range(2):
layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1, bias=False))
layers.append(nn.InstanceNorm2d(curr_dim*2, affine=True))
layers.append(nn.ReLU(inplace=True))
curr_dim = curr_dim * 2
# Bottleneck
for i in range(repeat_num):
layers.append(ResidualBlock(dim_in=curr_dim, dim_out=curr_dim))
# Up-Sampling
for i in range(2):
layers.append(nn.ConvTranspose2d(curr_dim, curr_dim//2, kernel_size=4, stride=2, padding=1, bias=False))
layers.append(nn.InstanceNorm2d(curr_dim//2, affine=True))
layers.append(nn.ReLU(inplace=True))
curr_dim = curr_dim // 2
self.main = nn.Sequential(*layers)
layers = []
layers.append(nn.Conv2d(curr_dim, 3, kernel_size=7, stride=1, padding=3, bias=False))
layers.append(nn.Tanh())
self.img_reg = nn.Sequential(*layers)
layers = []
layers.append(nn.Conv2d(curr_dim, 1, kernel_size=7, stride=1, padding=3, bias=False))
layers.append(nn.Sigmoid())
self.attetion_reg = nn.Sequential(*layers)
def forward(self, x, c):
# replicate spatially and concatenate domain information
c = c.unsqueeze(2).unsqueeze(3)
c = c.expand(c.size(0), c.size(1), x.size(2), x.size(3))
x = torch.cat([x, c], dim=1)
features = self.main(x)
return self.img_reg(features), self.attetion_reg(features)
class ResidualBlock(nn.Module):
"""Residual Block."""
def __init__(self, dim_in, dim_out):
super(ResidualBlock, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
nn.InstanceNorm2d(dim_out, affine=True),
nn.ReLU(inplace=True),
nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
nn.InstanceNorm2d(dim_out, affine=True))
def forward(self, x):
return x + self.main(x)
-57
View File
@@ -1,57 +0,0 @@
import torch.nn as nn
import functools
class NetworksFactory:
def __init__(self):
pass
@staticmethod
def get_by_name(network_name, *args, **kwargs):
if network_name == 'generator_wasserstein_gan':
from .generator_wasserstein_gan import Generator
network = Generator(*args, **kwargs)
elif network_name == 'discriminator_wasserstein_gan':
from .discriminator_wasserstein_gan import Discriminator
network = Discriminator(*args, **kwargs)
else:
raise ValueError("Network %s not recognized." % network_name)
print "Network %s was created" % network_name
return network
class NetworkBase(nn.Module):
def __init__(self):
super(NetworkBase, self).__init__()
self._name = 'BaseNetwork'
@property
def name(self):
return self._name
def init_weights(self):
self.apply(self._weights_init_fn)
def _weights_init_fn(self, m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
if hasattr(m.bias, 'data'):
m.bias.data.fill_(0)
elif classname.find('BatchNorm2d') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
def _get_norm_layer(self, norm_type='batch'):
if norm_type == 'batch':
norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
elif norm_type == 'instance':
norm_layer = functools.partial(nn.InstanceNorm2d, affine=False)
elif norm_type =='batchnorm2d':
norm_layer = nn.BatchNorm2d
else:
raise NotImplementedError('normalization layer [%s] is not found' % norm_type)
return norm_layer
View File
-108
View File
@@ -1,108 +0,0 @@
import argparse
import os
from utils import util
import torch
class BaseOptions():
def __init__(self):
self._parser = argparse.ArgumentParser()
self._initialized = False
def initialize(self):
self._parser.add_argument('--data_dir', type=str, help='path to dataset')
self._parser.add_argument('--train_ids_file', type=str, default='train_ids.csv', help='file containing train ids')
self._parser.add_argument('--test_ids_file', type=str, default='test_ids.csv', help='file containing test ids')
self._parser.add_argument('--images_folder', type=str, default='imgs', help='images folder')
self._parser.add_argument('--aus_file', type=str, default='aus_openface.pkl', help='file containing samples aus')
self._parser.add_argument('--load_epoch', type=int, default=-1, help='which epoch to load? set to -1 to use latest cached model')
self._parser.add_argument('--batch_size', type=int, default=4, help='input batch size')
self._parser.add_argument('--image_size', type=int, default=128, help='input image size')
self._parser.add_argument('--cond_nc', type=int, default=17, help='# of conditions')
self._parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')
self._parser.add_argument('--name', type=str, default='experiment_1', help='name of the experiment. It decides where to store samples and models')
self._parser.add_argument('--dataset_mode', type=str, default='aus', help='chooses dataset to be used')
self._parser.add_argument('--model', type=str, default='ganimation', help='model to run[au_net_model]')
self._parser.add_argument('--n_threads_test', default=1, type=int, help='# threads for loading data')
self._parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')
self._parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')
self._parser.add_argument('--do_saturate_mask', action="store_true", default=False, help='do use mask_fake for mask_cyc')
self._initialized = True
def parse(self):
if not self._initialized:
self.initialize()
self._opt = self._parser.parse_args()
# set is train or set
self._opt.is_train = self.is_train
# set and check load_epoch
self._set_and_check_load_epoch()
# get and set gpus
self._get_set_gpus()
args = vars(self._opt)
# print in terminal args
self._print(args)
# save args to file
self._save(args)
return self._opt
def _set_and_check_load_epoch(self):
models_dir = os.path.join(self._opt.checkpoints_dir, self._opt.name)
if os.path.exists(models_dir):
if self._opt.load_epoch == -1:
load_epoch = 0
for file in os.listdir(models_dir):
if file.startswith("net_epoch_"):
load_epoch = max(load_epoch, int(file.split('_')[2]))
self._opt.load_epoch = load_epoch
else:
found = False
for file in os.listdir(models_dir):
if file.startswith("net_epoch_"):
found = int(file.split('_')[2]) == self._opt.load_epoch
if found: break
assert found, 'Model for epoch %i not found' % self._opt.load_epoch
else:
assert self._opt.load_epoch < 1, 'Model for epoch %i not found' % self._opt.load_epoch
self._opt.load_epoch = 0
def _get_set_gpus(self):
# get gpu ids
str_ids = self._opt.gpu_ids.split(',')
self._opt.gpu_ids = []
for str_id in str_ids:
id = int(str_id)
if id >= 0:
self._opt.gpu_ids.append(id)
# set gpu ids
if len(self._opt.gpu_ids) > 0:
torch.cuda.set_device(self._opt.gpu_ids[0])
def _print(self, args):
print('------------ Options -------------')
for k, v in sorted(args.items()):
print('%s: %s' % (str(k), str(v)))
print('-------------- End ----------------')
def _save(self, args):
expr_dir = os.path.join(self._opt.checkpoints_dir, self._opt.name)
print(expr_dir)
util.mkdirs(expr_dir)
file_name = os.path.join(expr_dir, 'opt_%s.txt' % ('train' if self.is_train else 'test'))
with open(file_name, 'wt') as opt_file:
opt_file.write('------------ Options -------------\n')
for k, v in sorted(args.items()):
opt_file.write('%s: %s\n' % (str(k), str(v)))
opt_file.write('-------------- End ----------------\n')
-9
View File
@@ -1,9 +0,0 @@
from .base_options import BaseOptions
class TestOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self._parser.add_argument('--input_path', type=str, help='path to image')
self._parser.add_argument('--output_dir', type=str, default='./output', help='output path')
self.is_train = False
-31
View File
@@ -1,31 +0,0 @@
from .base_options import BaseOptions
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self._parser.add_argument('--n_threads_train', default=4, type=int, help='# threads for loading data')
self._parser.add_argument('--num_iters_validate', default=1, type=int, help='# batches to use when validating')
self._parser.add_argument('--print_freq_s', type=int, default=60, help='frequency of showing training results on console')
self._parser.add_argument('--display_freq_s', type=int, default=300, help='frequency [s] of showing training results on screen')
self._parser.add_argument('--save_latest_freq_s', type=int, default=3600, help='frequency of saving the latest results')
self._parser.add_argument('--nepochs_no_decay', type=int, default=20, help='# of epochs at starting learning rate')
self._parser.add_argument('--nepochs_decay', type=int, default=10, help='# of epochs to linearly decay learning rate to zero')
self._parser.add_argument('--train_G_every_n_iterations', type=int, default=5, help='train G every n interations')
self._parser.add_argument('--poses_g_sigma', type=float, default=0.06, help='initial learning rate for adam')
self._parser.add_argument('--lr_G', type=float, default=0.0001, help='initial learning rate for G adam')
self._parser.add_argument('--G_adam_b1', type=float, default=0.5, help='beta1 for G adam')
self._parser.add_argument('--G_adam_b2', type=float, default=0.999, help='beta2 for G adam')
self._parser.add_argument('--lr_D', type=float, default=0.0001, help='initial learning rate for D adam')
self._parser.add_argument('--D_adam_b1', type=float, default=0.5, help='beta1 for D adam')
self._parser.add_argument('--D_adam_b2', type=float, default=0.999, help='beta2 for D adam')
self._parser.add_argument('--lambda_D_prob', type=float, default=1, help='lambda for real/fake discriminator loss')
self._parser.add_argument('--lambda_D_cond', type=float, default=4000, help='lambda for condition discriminator loss')
self._parser.add_argument('--lambda_cyc', type=float, default=10, help='lambda cycle loss')
self._parser.add_argument('--lambda_mask', type=float, default=0.1, help='lambda mask loss')
self._parser.add_argument('--lambda_D_gp', type=float, default=10, help='lambda gradient penalty loss')
self._parser.add_argument('--lambda_mask_smooth', type=float, default=1e-5, help='lambda mask smooth loss')
self.is_train = True
-6
View File
@@ -1,6 +0,0 @@
numpy
matplotlib
tqdm
dlib
face_recognition
opencv-contrib-python
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

-2
View File
@@ -1,2 +0,0 @@
N_0000001507_00202.jpg
N_0000001939_00054.jpg
1 N_0000001507_00202.jpg
2 N_0000001939_00054.jpg
-2
View File
@@ -1,2 +0,0 @@
N_0000000437_00540.jpg
N_0000000356_00190.jpg
1 N_0000000437_00540.jpg
2 N_0000000356_00190.jpg
-74
View File
@@ -1,74 +0,0 @@
import os
import argparse
import glob
import cv2
from utils import face_utils
from utils import cv_utils
import face_recognition
from PIL import Image
import torchvision.transforms as transforms
import torch
import pickle
import numpy as np
from models.models import ModelsFactory
from options.test_options import TestOptions
class MorphFacesInTheWild:
def __init__(self, opt):
self._opt = opt
self._model = ModelsFactory.get_by_name(self._opt.model, self._opt)
self._model.set_eval()
self._transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
])
def morph_file(self, img_path, expresion):
img = cv_utils.read_cv2_img(img_path)
morphed_img = self._img_morph(img, expresion)
output_name = '%s_out.png' % os.path.basename(img_path)
self._save_img(morphed_img, output_name)
def _img_morph(self, img, expresion):
bbs = face_recognition.face_locations(img)
if len(bbs) > 0:
y, right, bottom, x = bbs[0]
bb = x, y, (right - x), (bottom - y)
face = face_utils.crop_face_with_bb(img, bb)
face = face_utils.resize_face(face)
else:
face = face_utils.resize_face(img)
morphed_face = self._morph_face(face, expresion)
return morphed_face
def _morph_face(self, face, expresion):
face = torch.unsqueeze(self._transform(Image.fromarray(face)), 0)
expresion = torch.unsqueeze(torch.from_numpy(expresion/5.0), 0)
test_batch = {'real_img': face, 'real_cond': expresion, 'desired_cond': expresion, 'sample_id': torch.FloatTensor(), 'real_img_path': []}
self._model.set_input(test_batch)
imgs, _ = self._model.forward(keep_data_for_visuals=False, return_estimates=True)
return imgs['concat']
def _save_img(self, img, filename):
filepath = os.path.join(self._opt.output_dir, filename)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite(filepath, img)
def main():
opt = TestOptions().parse()
if not os.path.isdir(opt.output_dir):
os.makedirs(opt.output_dir)
morph = MorphFacesInTheWild(opt)
image_path = opt.input_path
expression = np.random.uniform(0, 1, opt.cond_nc)
morph.morph_file(image_path, expression)
if __name__ == '__main__':
main()
-141
View File
@@ -1,141 +0,0 @@
import time
from options.train_options import TrainOptions
from data.custom_dataset_data_loader import CustomDatasetDataLoader
from models.models import ModelsFactory
from utils.tb_visualizer import TBVisualizer
from collections import OrderedDict
import os
class Train:
def __init__(self):
self._opt = TrainOptions().parse()
data_loader_train = CustomDatasetDataLoader(self._opt, is_for_train=True)
data_loader_test = CustomDatasetDataLoader(self._opt, is_for_train=False)
self._dataset_train = data_loader_train.load_data()
self._dataset_test = data_loader_test.load_data()
self._dataset_train_size = len(data_loader_train)
self._dataset_test_size = len(data_loader_test)
print('#train images = %d' % self._dataset_train_size)
print('#test images = %d' % self._dataset_test_size)
self._model = ModelsFactory.get_by_name(self._opt.model, self._opt)
self._tb_visualizer = TBVisualizer(self._opt)
self._train()
def _train(self):
self._total_steps = self._opt.load_epoch * self._dataset_train_size
self._iters_per_epoch = self._dataset_train_size / self._opt.batch_size
self._last_display_time = None
self._last_save_latest_time = None
self._last_print_time = time.time()
for i_epoch in range(self._opt.load_epoch + 1, self._opt.nepochs_no_decay + self._opt.nepochs_decay + 1):
epoch_start_time = time.time()
# train epoch
self._train_epoch(i_epoch)
# save model
print('saving the model at the end of epoch %d, iters %d' % (i_epoch, self._total_steps))
self._model.save(i_epoch)
# print epoch info
time_epoch = time.time() - epoch_start_time
print('End of epoch %d / %d \t Time Taken: %d sec (%d min or %d h)' %
(i_epoch, self._opt.nepochs_no_decay + self._opt.nepochs_decay, time_epoch,
time_epoch / 60, time_epoch / 3600))
# update learning rate
if i_epoch > self._opt.nepochs_no_decay:
self._model.update_learning_rate()
def _train_epoch(self, i_epoch):
epoch_iter = 0
self._model.set_train()
for i_train_batch, train_batch in enumerate(self._dataset_train):
iter_start_time = time.time()
# display flags
do_visuals = self._last_display_time is None or time.time() - self._last_display_time > self._opt.display_freq_s
do_print_terminal = time.time() - self._last_print_time > self._opt.print_freq_s or do_visuals
# train model
self._model.set_input(train_batch)
train_generator = ((i_train_batch+1) % self._opt.train_G_every_n_iterations == 0) or do_visuals
self._model.optimize_parameters(keep_data_for_visuals=do_visuals, train_generator=train_generator)
# update epoch info
self._total_steps += self._opt.batch_size
epoch_iter += self._opt.batch_size
# display terminal
if do_print_terminal:
self._display_terminal(iter_start_time, i_epoch, i_train_batch, do_visuals)
self._last_print_time = time.time()
# display visualizer
if do_visuals:
self._display_visualizer_train(self._total_steps)
self._display_visualizer_val(i_epoch, self._total_steps)
self._last_display_time = time.time()
# save model
if self._last_save_latest_time is None or time.time() - self._last_save_latest_time > self._opt.save_latest_freq_s:
print('saving the latest model (epoch %d, total_steps %d)' % (i_epoch, self._total_steps))
self._model.save(i_epoch)
self._last_save_latest_time = time.time()
def _display_terminal(self, iter_start_time, i_epoch, i_train_batch, visuals_flag):
errors = self._model.get_current_errors()
t = (time.time() - iter_start_time) / self._opt.batch_size
self._tb_visualizer.print_current_train_errors(i_epoch, i_train_batch, self._iters_per_epoch, errors, t, visuals_flag)
def _display_visualizer_train(self, total_steps):
self._tb_visualizer.display_current_results(self._model.get_current_visuals(), total_steps, is_train=True)
self._tb_visualizer.plot_scalars(self._model.get_current_errors(), total_steps, is_train=True)
self._tb_visualizer.plot_scalars(self._model.get_current_scalars(), total_steps, is_train=True)
def _display_visualizer_val(self, i_epoch, total_steps):
val_start_time = time.time()
# set model to eval
self._model.set_eval()
# evaluate self._opt.num_iters_validate epochs
val_errors = OrderedDict()
for i_val_batch, val_batch in enumerate(self._dataset_test):
if i_val_batch == self._opt.num_iters_validate:
break
# evaluate model
self._model.set_input(val_batch)
self._model.forward(keep_data_for_visuals=(i_val_batch == 0))
errors = self._model.get_current_errors()
# store current batch errors
for k, v in errors.iteritems():
if k in val_errors:
val_errors[k] += v
else:
val_errors[k] = v
# normalize errors
for k in val_errors.iterkeys():
val_errors[k] /= self._opt.num_iters_validate
# visualize
t = (time.time() - val_start_time)
self._tb_visualizer.print_current_validate_errors(i_epoch, val_errors, t)
self._tb_visualizer.plot_scalars(val_errors, total_steps, is_train=False)
self._tb_visualizer.display_current_results(self._model.get_current_visuals(), total_steps, is_train=False)
# set model back to train
self._model.set_train()
if __name__ == "__main__":
Train()
View File
-54
View File
@@ -1,54 +0,0 @@
import cv2
from matplotlib import pyplot as plt
import numpy as np
def read_cv2_img(path):
'''
Read color images
:param path: Path to image
:return: Only returns color images
'''
img = cv2.imread(path, -1)
if img is not None:
if len(img.shape) != 3:
return None
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
def show_cv2_img(img, title='img'):
'''
Display cv2 image
:param img: cv::mat
:param title: title
:return: None
'''
plt.imshow(img)
plt.title(title)
plt.axis('off')
plt.show()
def show_images_row(imgs, titles, rows=1):
'''
Display grid of cv2 images image
:param img: list [cv::mat]
:param title: titles
:return: None
'''
assert ((titles is None) or (len(imgs) == len(titles)))
num_images = len(imgs)
if titles is None:
titles = ['Image (%d)' % i for i in range(1, num_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(imgs, titles)):
ax = fig.add_subplot(rows, np.ceil(num_images / float(rows)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
ax.set_title(title)
plt.axis('off')
plt.show()
-71
View File
@@ -1,71 +0,0 @@
import face_recognition
import cv2
import numpy as np
import skimage
import skimage.transform
import warnings
def detect_faces(img):
'''
Detect faces in image
:param img: cv::mat HxWx3 RGB
:return: yield 4 <x,y,w,h>
'''
# detect faces
bbs = face_recognition.face_locations(img)
for y, right, bottom, x in bbs:
# Scale back up face bb
yield x, y, (right - x), (bottom - y)
def detect_biggest_face(img):
'''
Detect biggest face in image
:param img: cv::mat HxWx3 RGB
:return: 4 <x,y,w,h>
'''
# detect faces
bbs = face_recognition.face_locations(img)
max_area = float('-inf')
max_area_i = 0
for i, (y, right, bottom, x) in enumerate(bbs):
area = (right - x) * (bottom - y)
if max_area < area:
max_area = area
max_area_i = i
if max_area != float('-inf'):
y, right, bottom, x = bbs[max_area_i]
return x, y, (right - x), (bottom - y)
return None
def crop_face_with_bb(img, bb):
'''
Crop face in image given bb
:param img: cv::mat HxWx3
:param bb: 4 (<x,y,w,h>)
:return: HxWx3
'''
x, y, w, h = bb
return img[y:y+h, x:x+w, :]
def place_face(img, face, bb):
x, y, w, h = bb
face = resize_face(face, size=(w, h))
img[y:y+h, x:x+w] = face
return img
def resize_face(face_img, size=(128, 128)):
'''
Resize face to a given size
:param face_img: cv::mat HxWx3
:param size: new H and W (size x size). 128 by default.
:return: cv::mat size x size x 3
'''
return cv2.resize(face_img, size)
def detect_landmarks(face_img):
landmakrs = face_recognition.face_landmarks(face_img)
return landmakrs[0] if len(landmakrs) > 0 else None
-67
View File
@@ -1,67 +0,0 @@
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
def plot_au(img, aus, title=None):
'''
Plot action units
:param img: HxWx3
:param aus: N
:return:
'''
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.axis('off')
fig.subplots_adjust(0, 0, 0.8, 1) # get rid of margins
# display img
ax.imshow(img)
if len(aus) == 11:
au_ids = ['1','2','4','5','6','9','12','17','20','25','26']
x = 0.1
y = 0.39
i = 0
for au, id in zip(aus, au_ids):
if id == '9':
x = 0.5
y -= .15
i = 0
elif id == '12':
x = 0.1
y -= .15
i = 0
ax.text(x + i * 0.2, y, id, horizontalalignment='center', verticalalignment='center',
transform=ax.transAxes, color='r', fontsize=20)
ax.text((x-0.001)+i*0.2, y-0.07, au, horizontalalignment='center', verticalalignment='center',
transform=ax.transAxes, color='b', fontsize=20)
i+=1
else:
au_ids = ['1', '2', '4', '5', '6', '7', '9', '10', '12', '14', '15', '17', '20', '23', '25', '26', '45']
x = 0.1
y = 0.39
i = 0
for au, id in zip(aus, au_ids):
if id == '9' or id == '20':
x = 0.1
y -= .15
i = 0
ax.text(x + i * 0.2, y, id, horizontalalignment='center', verticalalignment='center',
transform=ax.transAxes, color='r', fontsize=20)
ax.text((x-0.001)+i*0.2, y-0.07, au, horizontalalignment='center', verticalalignment='center',
transform=ax.transAxes, color='b', fontsize=20)
i+=1
if title is not None:
ax.text(0.5, 0.95, title, horizontalalignment='center', verticalalignment='center',
transform=ax.transAxes, color='r', fontsize=20)
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
plt.close(fig)
return data
-66
View File
@@ -1,66 +0,0 @@
import numpy as np
import os
import time
from . import util
from tensorboardX import SummaryWriter
class TBVisualizer:
def __init__(self, opt):
self._opt = opt
self._save_path = os.path.join(opt.checkpoints_dir, opt.name)
self._log_path = os.path.join(self._save_path, 'loss_log2.txt')
self._tb_path = os.path.join(self._save_path, 'summary.json')
self._writer = SummaryWriter(self._save_path)
with open(self._log_path, "a") as log_file:
now = time.strftime("%c")
log_file.write('================ Training Loss (%s) ================\n' % now)
def __del__(self):
self._writer.close()
def display_current_results(self, visuals, it, is_train, save_visuals=False):
for label, image_numpy in visuals.items():
sum_name = '{}/{}'.format('Train' if is_train else 'Test', label)
self._writer.add_image(sum_name, image_numpy, it)
if save_visuals:
util.save_image(image_numpy,
os.path.join(self._opt.checkpoints_dir, self._opt.name,
'event_imgs', sum_name, '%08d.png' % it))
self._writer.export_scalars_to_json(self._tb_path)
def plot_scalars(self, scalars, it, is_train):
for label, scalar in scalars.items():
sum_name = '{}/{}'.format('Train' if is_train else 'Test', label)
self._writer.add_scalar(sum_name, scalar, it)
def print_current_train_errors(self, epoch, i, iters_per_epoch, errors, t, visuals_were_stored):
log_time = time.strftime("[%d/%m/%Y %H:%M:%S]")
visuals_info = "v" if visuals_were_stored else ""
message = '%s (T%s, epoch: %d, it: %d/%d, t/smpl: %.3fs) ' % (log_time, visuals_info, epoch, i, iters_per_epoch, t)
for k, v in errors.items():
message += '%s:%.3f ' % (k, v)
print(message)
with open(self._log_path, "a") as log_file:
log_file.write('%s\n' % message)
def print_current_validate_errors(self, epoch, errors, t):
log_time = time.strftime("[%d/%m/%Y %H:%M:%S]")
message = '%s (V, epoch: %d, time_to_val: %ds) ' % (log_time, epoch, t)
for k, v in errors.items():
message += '%s:%.3f ' % (k, v)
print(message)
with open(self._log_path, "a") as log_file:
log_file.write('%s\n' % message)
def save_images(self, visuals):
for label, image_numpy in visuals.items():
image_name = '%s.png' % label
save_path = os.path.join(self._save_path, "samples", image_name)
util.save_image(image_numpy, save_path)
-53
View File
@@ -1,53 +0,0 @@
from __future__ import print_function
from PIL import Image
import numpy as np
import os
import torchvision
import math
def tensor2im(img, imtype=np.uint8, unnormalize=True, idx=0, nrows=None):
# select a sample or create grid if img is a batch
if len(img.shape) == 4:
nrows = nrows if nrows is not None else int(math.sqrt(img.size(0)))
img = img[idx] if idx >= 0 else torchvision.utils.make_grid(img, nrows)
img = img.cpu().float()
if unnormalize:
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
for i, m, s in zip(img, mean, std):
i.mul_(s).add_(m)
image_numpy = img.numpy()
image_numpy_t = np.transpose(image_numpy, (1, 2, 0))
image_numpy_t = image_numpy_t*254.0
return image_numpy_t.astype(imtype)
def tensor2maskim(mask, imtype=np.uint8, idx=0, nrows=1):
im = tensor2im(mask, imtype=imtype, idx=idx, unnormalize=False, nrows=nrows)
if im.shape[2] == 1:
im = np.repeat(im, 3, axis=-1)
return im
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths)
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def save_image(image_numpy, image_path):
mkdir(os.path.dirname(image_path))
image_pil = Image.fromarray(image_numpy)
image_pil.save(image_path)
def save_str_data(data, path):
mkdir(os.path.dirname(path))
np.savetxt(path, data, delimiter=",", fmt="%s")
+26
View File
@@ -0,0 +1,26 @@
# Disrupting Deepfakes: Adversarial Attacks on Conditional Image Translation Networks
## StarGAN Testing
```
python main.py --mode test --dataset CelebA --image_size 256 --c_dim 5 --selected_attrs Black_Hair Blond_Hair Brown_Hair Male Young --model_save_dir='stargan_celeba_256/models' --result_dir='stargan_celeba_256/results_test' --test_iters 200000 --batch_size 1
```
## StarGAN Training
```
python main.py --mode train --dataset CelebA --image_size 256 --c_dim 5 --sample_dir stargan_both/samples --log_dir stargan_both/logs --model_save_dir stargan_both/models --result_dir stargan_both/results --selected_attrs Black_Hair Blond_Hair Brown_Hair Male Young
```
## GANimation
```
python main.py --mode animation
```
## pix2pixHD
```
python test.py --name label2city_1024p --netG local --ngf 32 --resize_or_crop none
```
## CycleGAN
```
python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout
```
+1
View File
@@ -0,0 +1 @@
/home/grad3/nruiz9/research/fsynth/cyclegan/checkpoints
+1
View File
@@ -0,0 +1 @@
/scratch2/fsynth/cyclegan/datasets/horse2zebra
+1
View File
@@ -0,0 +1 @@
/scratch2/fsynth/cyclegan/datasets/monet2photo
+9 -5
View File
@@ -71,13 +71,12 @@ class TestModel(BaseModel):
"""Run forward pass."""
self.fake_noattack = self.netG(self.real) # G(real)
def attack(self):
def attack(self, target):
image = self.real
# Attack
pgd_attack = attacks.LinfPGDAttack(model=self.netG)
black = np.zeros((1, 3, image.size(2), image.size(3)))
black = torch.FloatTensor(black).cuda()
input_adv, perturb = pgd_attack.perturb(image, black)
input_adv, perturb = pgd_attack.perturb(image, target)
return input_adv, perturb
@@ -92,8 +91,13 @@ class TestModel(BaseModel):
l2 = F.mse_loss(generated, generated_noattack)
l0 = (generated - generated_noattack).norm(0)
d = (generated - generated_noattack).norm(float('-inf'))
if F.mse_loss(generated, generated_noattack) > 0.05:
n_dist = 1
else:
n_dist = 0
return l1, l2, l0, d
return l1, l2, l0, d, n_dist
def optimize_parameters(self):
"""No optimization for test model."""
+14 -8
View File
@@ -61,29 +61,35 @@ if __name__ == '__main__':
torch.manual_seed(0)
# Initialize Metrics
l1_error, l2_error, min_dist, l0_error, perceptual_error = 0.0, 0.0, 0.0, 0.0, 0.0
n_samples = 0
l1_error, l2_error, min_dist, l0_error = 0.0, 0.0, 0.0, 0.0
n_dist, n_samples = 0, 0
for i, data in enumerate(dataset):
if i >= opt.num_test: # only apply our model to opt.num_test images.
break
model.set_input(data) # unpack data from data loader
# Get ground-truth output
with torch.no_grad():
model.forward_noattack()
if i == 0:
input_adv, perturb = model.attack()
# input_adv, perturb = model.attack()
# Attack
input_adv, perturb = model.attack(target=model.fake_noattack)
# Get output from adversarial sample
with torch.no_grad():
model.forward_attack(perturb)
model.compute_visuals()
# Compute metrics
l1, l2, l0, d = model.compute_errors()
l1, l2, l0, d, above = model.compute_errors()
l1_error += l1
l2_error += l2
l0_error += l0
min_dist += d
n_dist += above
n_samples += 1
# model.test() # run inference
visuals = model.get_current_visuals() # get image results
img_path = model.get_image_paths() # get image paths
@@ -92,8 +98,8 @@ if __name__ == '__main__':
save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize)
# Print metrics
print('{} images. L1 error: {}. L2 error: {}. L0 error: {}. L_-inf error: {}. Perceptual error: {}.'.format(n_samples,
l1_error / n_samples, l2_error / n_samples, l0_error / n_samples, min_dist / n_samples, perceptual_error / n_samples))
print('{} images. L1 error: {}. L2 error: {}. prop_dist: {}. L0 error: {}. L_-inf error: {}.'.format(n_samples,
l1_error / n_samples, l2_error / n_samples, float(n_dist) / n_samples, l0_error / n_samples, min_dist / n_samples))
webpage.save() # save the HTML
+18 -5
View File
@@ -7,26 +7,39 @@ import torch
import torch.nn as nn
class LinfPGDAttack(object):
def __init__(self, model=None, epsilon=0.05, k=1, a=0.05):
def __init__(self, model=None, epsilon=0.05, k=10, a=0.01):
"""
FGSM, I-FGSM and PGD attacks
epsilon: magnitude of attack
k: iterations
a: step size
"""
self.model = model
self.epsilon = epsilon
self.k = k
self.a = a
self.loss_fn = nn.MSELoss()
# PGD or I-FGSM?
self.rand = True
def perturb(self, X_nat, y):
"""
Given examples (X_nat, y), returns adversarial
examples within epsilon of X_nat in l_infinity norm.
Vanilla Attack.
"""
X = X_nat.clone().detach_()
if self.rand:
X = X_nat.clone().detach_() + torch.tensor(np.random.uniform(-self.epsilon, self.epsilon, X_nat.shape).astype('float32')).cuda()
else:
X = X_nat.clone().detach_()
# use the following if FGSM or I-FGSM and random seeds are fixed
# X = X_nat.clone().detach_() + torch.tensor(np.random.uniform(-0.001, 0.001, X_nat.shape).astype('float32')).cuda()
for i in range(self.k):
print('test', i)
X.requires_grad = True
output = self.model(X)
self.model.zero_grad()
# Minus in the loss means "towards" and plus means "away from"
loss = self.loss_fn(output, y)
loss.backward()
grad = X.grad
+30 -48
View File
@@ -7,7 +7,13 @@ import torch
import torch.nn as nn
class LinfPGDAttack(object):
def __init__(self, model=None, device=None, epsilon=0.03, k=80, a=0.01):
def __init__(self, model=None, device=None, epsilon=0.05, k=10, a=0.01):
"""
FGSM, I-FGSM and PGD attacks
epsilon: magnitude of attack
k: iterations
a: step size
"""
self.model = model
self.epsilon = epsilon
self.k = k
@@ -15,23 +21,34 @@ class LinfPGDAttack(object):
self.loss_fn = nn.MSELoss().to(device)
self.device = device
# PGD or I-FGSM?
self.rand = True
def perturb(self, X_nat, y, c_trg):
"""
Given examples (X_nat, y), returns adversarial
examples within epsilon of X_nat in l_infinity norm.
Vanilla Attack.
"""
X = X_nat.clone().detach_()
if self.rand:
X = X_nat.clone().detach_() + torch.tensor(np.random.uniform(-self.epsilon, self.epsilon, X_nat.shape).astype('float32')).to(self.device)
else:
X = X_nat.clone().detach_()
# use the following if FGSM or I-FGSM and random seeds are fixed
# X = X_nat.clone().detach_() + torch.tensor(np.random.uniform(-0.001, 0.001, X_nat.shape).astype('float32')).cuda()
for i in range(self.k):
# print(i)
X.requires_grad = True
output_att, output_img = self.model(X, c_trg)
out = imFromAttReg(output_att, output_img, X)
self.model.zero_grad()
loss = self.loss_fn(output_att, y)
# loss = -self.loss_fn(out, y)
# Attention attack
# loss = self.loss_fn(output_att, y)
# Output attack
# Minus in the loss means "towards" and plus means "away from"
loss = self.loss_fn(out, y)
loss.backward()
grad = X.grad
@@ -40,41 +57,8 @@ class LinfPGDAttack(object):
eta = torch.clamp(X_adv - X_nat, min=-self.epsilon, max=self.epsilon)
X = torch.clamp(X_nat + eta, min=-1, max=1).detach_()
return X, eta
def perturb_iter_data(self, X_nat, X_all, y, c_trg):
"""
X_nat is a tensor with several different images.
This does not work at all yet..
"""
X = X_nat.clone().detach_()
# X_all_local = X_all.clone().detach_()
j = 0
J = X_all.size(0)
J = 1
for i in range(self.k):
# print(i,j)
X_j = X_all[j].unsqueeze(0)
X_j.requires_grad = True
output_att, output_img = self.model(X_j, c_trg)
out = imFromAttReg(output_att, output_img, X_j)
self.model.zero_grad()
loss = -self.loss_fn(out, y)
loss.backward()
grad = X_j.grad
X_adv = X + self.a * grad.sign()
eta = torch.clamp(X_adv - X_nat, min=-self.epsilon, max=self.epsilon)
X = torch.clamp(X_nat + eta, min=-1, max=1).detach_()
j += 1
if j == J:
j = 0
# Debug
# X_adv, loss, grad, output_att, output_img = None, None, None, None, None
return X, eta
@@ -88,7 +72,6 @@ class LinfPGDAttack(object):
J = c_trg.size(0)
for i in range(self.k):
# print(i)
X.requires_grad = True
output_att, output_img = self.model(X, c_trg[j,:].unsqueeze(0))
@@ -96,8 +79,8 @@ class LinfPGDAttack(object):
self.model.zero_grad()
loss = self.loss_fn(output_att, y)
# loss = -self.loss_fn(out, y)
# loss = self.loss_fn(output_att, y)
loss = self.loss_fn(out, y)
loss.backward()
grad = X.grad
@@ -126,13 +109,12 @@ class LinfPGDAttack(object):
self.model.zero_grad()
for j in range(J):
# print(i, j)
output_att, output_img = self.model(X, c_trg[j,:].unsqueeze(0))
out = imFromAttReg(output_att, output_img, X)
loss = self.loss_fn(output_att, y)
# loss = -self.loss_fn(out, y)
# loss = self.loss_fn(output_att, y)
loss = self.loss_fn(out, y)
full_loss += loss
full_loss.backward()
+1 -1
View File
@@ -75,7 +75,7 @@ def get_config():
# parser.add_argument('--animation_images_dir', type=str,
# default='animations/eric_andre/images_to_animate')
parser.add_argument('--animation_images_dir', type=str,
default='data/celeba_small/')
default='data/celeba/images_aligned/new_small')
parser.add_argument('--animation_attribute_images_dir', type=str,
default='animations/eric_andre/attribute_images')
parser.add_argument('--animation_attributes_path', type=str,
+1 -1
View File
@@ -1 +1 @@
/scratch2/ganimation/models
/home/grad3/nruiz9/research/fsynth/ganimation/models
+46 -90
View File
@@ -384,66 +384,51 @@ class Solver(Utils):
reference_expression_images[target_idx]))
if mode == 'animate_image':
black = np.zeros((1,3,128,128))
black = torch.FloatTensor(black).to(self.device)
# Initialize Metrics
l1_error = 0.0
l2_error = 0.0
min_dist = 0.0
l0_error = 0.0
perceptual_error = 0.0
n_samples = 0
l1_error, l2_error, min_dist, l0_error = 0.0, 0.0, 0.0, 0.0
n_dist, n_samples = 0, 0
pgd_attack = attacks.LinfPGDAttack(model=self.G, device=self.device)
images_to_animate_path = sorted(glob.glob(
self.animation_images_dir + '/*'))
x_advs = []
for idx, image_path in enumerate(images_to_animate_path):
image_to_animate = regular_image_transform(Image.open(image_path)).unsqueeze(0).cuda()
all_images = torch.cat([regular_image_transform(Image.open(path)).unsqueeze(0) for path in images_to_animate_path], dim=0).cuda()
for target_idx in range(targets.size(0)-1):
print('image', idx, 'AU', target_idx)
# Transfer to different images
# if idx == 0:
# for target_idx in range(targets.size(0)):
# x_adv, perturb = pgd_attack.perturb(image_to_animate, black, targets[target_idx, :].unsqueeze(0).cuda())
# x_advs.append((x_adv, perturb))
for target_idx in range(targets.size(0)):
# Transfer to different classes
# if target_idx == 0:
# img = regular_image_transform(Image.open(images_to_animate_path[idx])).unsqueeze(0).cuda()
# Wrong Class
# x_adv, perturb = pgd_attack.perturb(image_to_animate, black, targets[0, :].unsqueeze(0).cuda())
# Joint Class Conditional
# x_adv, perturb = pgd_attack.perturb_joint_class(image_to_animate, black, targets[:, :].cuda())
# Iterative Class Conditional
# x_adv, perturb = pgd_attack.perturb_iter_class(image_to_animate, black, targets[:, :].cuda())
# Iterative Data
# _, perturb = pgd_attack.perturb_iter_data(image_to_animate, all_images, black, targets[68, :].unsqueeze(0).cuda())
targets_au = targets[target_idx, :].unsqueeze(0).cuda()
with torch.no_grad():
resulting_images_att_noattack, resulting_images_reg_noattack = self.G(
image_to_animate, targets_au)
resulting_image_noattack = self.imFromAttReg(
resulting_images_att_noattack, resulting_images_reg_noattack, image_to_animate).cuda()
# Transfer to different classes
# if target_idx == 0:
# Wrong Class
# x_adv, perturb = pgd_attack.perturb(image_to_animate, image_to_animate, targets[0, :].unsqueeze(0).cuda())
# Joint Class Conditional
# x_adv, perturb = pgd_attack.perturb_joint_class(image_to_animate, image_to_animate, targets[:, :].cuda())
# Iterative Class Conditional
# x_adv, perturb = pgd_attack.perturb_iter_class(image_to_animate, image_to_animate, targets[:, :].cuda())
# Iterative Data
# _, perturb = pgd_attack.perturb_iter_data(image_to_animate, all_images, image_to_animate, targets[68, :].unsqueeze(0).cuda())
# Normal Attack
# x_adv, perturb = pgd_attack.perturb(image_to_animate, black, targets_au)
x_adv, perturb = pgd_attack.perturb(image_to_animate, resulting_image_noattack, targets_au)
# x_adv, perturb = x_advs[target_idx]
# x_adv = image_to_animate + perturb
# Use this line if transferring attacks
x_adv = image_to_animate + perturb
# No Attack
x_adv = image_to_animate
# print(image_to_animate.shape, x_adv.shape)
# x_adv = image_to_animate
with torch.no_grad():
resulting_images_att, resulting_images_reg = self.G(
@@ -451,12 +436,6 @@ class Solver(Utils):
resulting_image = self.imFromAttReg(
resulting_images_att, resulting_images_reg, x_adv).cuda()
# with torch.no_grad():
# resulting_images_att_noattack, resulting_images_reg_noattack = self.G(
# image_to_animate, targets_au)
# resulting_image_noattack = self.imFromAttReg(
# resulting_images_att_noattack, resulting_images_reg_noattack, image_to_animate).cuda()
save_image((resulting_image+1)/2, os.path.join(self.animation_results_dir,
image_path.split('/')[-1].split('.')[0]
+ '_' + reference_expression_images[target_idx]))
@@ -465,50 +444,27 @@ class Solver(Utils):
image_path.split('/')[-1].split('.')[0]
+ '_ref.jpg'))
# l1_error += F.l1_loss(resulting_image, resulting_image_noattack)
# l2_error += F.mse_loss(resulting_image, resulting_image_noattack)
# l0_error += (resulting_image - resulting_image_noattack).norm(0)
# min_dist += (resulting_image - resulting_image_noattack).norm(float('-inf'))
# Compare to ground-truth output
l1_error += F.l1_loss(resulting_image, resulting_image_noattack)
l2_error += F.mse_loss(resulting_image, resulting_image_noattack)
l0_error += (resulting_image - resulting_image_noattack).norm(0)
min_dist += (resulting_image - resulting_image_noattack).norm(float('-inf'))
# Compare to input image
l1_error += F.l1_loss(resulting_image, image_to_animate)
l2_error += F.mse_loss(resulting_image, image_to_animate)
l0_error += (resulting_image - image_to_animate).norm(0)
min_dist += (resulting_image - image_to_animate).norm(float('-inf'))
# l1_error += F.l1_loss(resulting_image, x_adv)
# l2_error += F.mse_loss(resulting_image, x_adv)
# l0_error += (resulting_image - x_adv).norm(0)
# min_dist += (resulting_image - x_adv).norm(float('-inf'))
if F.mse_loss(resulting_image, resulting_image_noattack) > 0.05:
n_dist += 1
n_samples += 1
# Debug
# x_adv, targets_au, resulting_image, resulting_images_att, resulting_images_reg = None, None, None, None, None
image_to_animate = None
# Print metrics
print('{} images. L1 error: {}. L2 error: {}. L0 error: {}. L_-inf error: {}. Perceptual error: {}.'.format(n_samples,
l1_error / n_samples, l2_error / n_samples, l0_error / n_samples, min_dist / n_samples, perceptual_error / n_samples))
# """ Code to modify single Action Units """
# Set data loader.
# self.data_loader = self.data_loader
# with torch.no_grad():
# for i, (self.x_real, c_org) in enumerate(self.data_loader):
# # Prepare input images and target domain labels.
# self.x_real = self.x_real.to(self.device)
# c_org = c_org.to(self.device)
# # c_trg_list = self.create_labels(self.data_loader)
# crit, cl_regression = self.D(self.x_real)
# # print(crit)
# print("ORIGINAL", c_org[0])
# print("REGRESSION", cl_regression[0])
# for au in range(17):
# alpha = np.linspace(-0.3,0.3,10)
# for j, a in enumerate(alpha):
# new_emotion = c_org.clone()
# new_emotion[:,au]=torch.clamp(new_emotion[:,au]+a, 0, 1)
# attention, reg = self.G(self.x_real, new_emotion)
# x_fake = self.imFromAttReg(attention, reg, self.x_real)
# save_image((x_fake+1)/2, os.path.join(self.result_dir, '{}-{}-{}-images.jpg'.format(i,au,j)))
# if i >= 3:
# break
print('{} images. L1 error: {}. L2 error: {}. prop_dist: {}. L0 error: {}. L_-inf error: {}.'.format(n_samples,
l1_error / n_samples, l2_error / n_samples, float(n_dist) / float(n_samples), l0_error / n_samples, min_dist / n_samples))
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 938 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1 +1 @@
/scratch2/fsynth/checkpoints
/home/grad3/nruiz9/research/fsynth/pix2pixHD_attack/checkpoints
-51
View File
@@ -1,51 +0,0 @@
import os
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
from data import landmarks
from torchvision import transforms
from torch.utils.data.dataset import Dataset
import glob
import random
class AVSpeech(Dataset):
def __init__(self, transform):
self.frame_folder = 'datasets/avspeech/frames'
self.meta_folder = 'datasets/avspeech/meta'
self.user_folders = glob.glob(os.path.join(self.frame_folder, '*'))
self.users = [x.split('/')[-1] for x in self.user_folders]
self.transform = transform
self.length = len(self.users)
def __getitem__(self, index):
# Get list of frames for user
user = self.users[index]
meta = dict(np.load(os.path.join(self.meta_folder, '{}.npz'.format(user))))
frame_list = glob.glob(os.path.join(self.frame_folder, '{}/*.png'.format(user)))
frame_list = [int(x.split('/')[-1].split('.')[0]) for x in frame_list]
ref_frame = random.choice(frame_list)
tgt_frame = random.choice(frame_list)
ref_img = Image.open(os.path.join(self.frame_folder, '{}/{}.png'.format(user, ref_frame)))
tgt_img = Image.open(os.path.join(self.frame_folder, '{}/{}.png'.format(user, tgt_frame)))
# Make reference and target landmarks
ref_lnd = landmarks.plot_landmarks(landmarks.get_relative_landmarks(meta, ref_frame))
tgt_lnd = landmarks.plot_landmarks(landmarks.get_relative_landmarks(meta, tgt_frame))
ref_img = self.transform(ref_img)
tgt_img = self.transform(tgt_img)
ref_lnd = self.transform(ref_lnd)
tgt_lnd = self.transform(tgt_lnd)
input_dict = {'ref_img': ref_img, 'tgt_img': tgt_img, 'ref_lnd': ref_lnd,
'tgt_lnd': tgt_lnd, 'user': user}
return input_dict
def __len__(self):
return self.length
-61
View File
@@ -1,61 +0,0 @@
import cv2
from matplotlib import pyplot as plt
from PIL import Image
import numpy as np
def get_relative_landmarks(meta, frame_num):
centerx, centery, l = meta['bbox'][frame_num - 1]
orig_height = meta['length'].item()
orig_width = meta['width'].item()
landmarks = meta['landmarks_2d'][frame_num - 1]
# Go from frame landmarks to cropped and resized frame landmarks
x_left = max(0, centerx-l)
x_right = min(centerx+l, orig_height)
y_up = max(0, centery-l)
y_down = min(centery+l, orig_width)
w = x_right - x_left
h = y_down - y_up
ar_h = 255. / h
ar_w = 255. / w
landmarks[:,0] -= (centery - l)
landmarks[:,1] -= (centerx - l)
landmarks[:,0] *= ar_h
landmarks[:,1] *= ar_w
return landmarks
def plot_landmarks(landmarks):
fig = plt.figure(figsize=(256, 256), dpi=1)
ax = fig.add_subplot(111)
ax.axis('off')
plt.imshow(np.ones((256, 256, 3)))
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
lw = 100
# Head
ax.plot(landmarks[0:17, 0], landmarks[0:17, 1], linestyle='-', color='green', lw=lw)
# Eyebrows
ax.plot(landmarks[17:22, 0], landmarks[17:22, 1], linestyle='-', color='orange', lw=lw)
ax.plot(landmarks[22:27, 0], landmarks[22:27, 1], linestyle='-', color='orange', lw=lw)
# Nose
ax.plot(landmarks[27:31, 0], landmarks[27:31, 1], linestyle='-', color='blue', lw=lw)
ax.plot(landmarks[31:36, 0], landmarks[31:36, 1], linestyle='-', color='blue', lw=lw)
# Eyes
ax.plot(landmarks[36:42, 0], landmarks[36:42, 1], linestyle='-', color='red', lw=lw)
ax.plot(landmarks[42:48, 0], landmarks[42:48, 1], linestyle='-', color='red', lw=lw)
ax.plot([landmarks[36, 0], landmarks[41, 0]], [landmarks[36, 1], landmarks[41, 1]],
linestyle='-', color='red', lw=lw)
ax.plot([landmarks[42, 0], landmarks[47, 0]], [landmarks[42, 1], landmarks[47, 1]],
linestyle='-', color='red', lw=lw)
# Mouth
ax.plot(landmarks[48:60, 0], landmarks[48:60, 1], linestyle='-', color='purple', lw=lw)
ax.plot([landmarks[48, 0], landmarks[59, 0]], [landmarks[48, 1], landmarks[59, 1]],
linestyle='-', color='purple', lw=lw)
fig.canvas.draw()
data = Image.frombuffer('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb(), 'raw', 'RGB', 0, 1)
plt.close(fig)
return data
-1
View File
@@ -1 +0,0 @@
/scratch2/avspeech_process/avspeech/
+1
View File
@@ -0,0 +1 @@
/home/grad3/nruiz9/research/fsynth/pix2pixHD_attack/datasets/cityscapes
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Some files were not shown because too many files have changed in this diff Show More