diff --git a/myenv/bin/Activate.ps1 b/myenv/bin/Activate.ps1 new file mode 100644 index 0000000..b49d77b --- /dev/null +++ b/myenv/bin/Activate.ps1 @@ -0,0 +1,247 @@ +<# +.Synopsis +Activate a Python virtual environment for the current PowerShell session. + +.Description +Pushes the python executable for a virtual environment to the front of the +$Env:PATH environment variable and sets the prompt to signify that you are +in a Python virtual environment. Makes use of the command line switches as +well as the `pyvenv.cfg` file values present in the virtual environment. + +.Parameter VenvDir +Path to the directory that contains the virtual environment to activate. The +default value for this is the parent of the directory that the Activate.ps1 +script is located within. + +.Parameter Prompt +The prompt prefix to display when this virtual environment is activated. By +default, this prompt is the name of the virtual environment folder (VenvDir) +surrounded by parentheses and followed by a single space (ie. '(.venv) '). + +.Example +Activate.ps1 +Activates the Python virtual environment that contains the Activate.ps1 script. + +.Example +Activate.ps1 -Verbose +Activates the Python virtual environment that contains the Activate.ps1 script, +and shows extra information about the activation as it executes. + +.Example +Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv +Activates the Python virtual environment located in the specified location. + +.Example +Activate.ps1 -Prompt "MyPython" +Activates the Python virtual environment that contains the Activate.ps1 script, +and prefixes the current prompt with the specified string (surrounded in +parentheses) while the virtual environment is active. + +.Notes +On Windows, it may be required to enable this Activate.ps1 script by setting the +execution policy for the user. You can do this by issuing the following PowerShell +command: + +PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser + +For more information on Execution Policies: +https://go.microsoft.com/fwlink/?LinkID=135170 + +#> +Param( + [Parameter(Mandatory = $false)] + [String] + $VenvDir, + [Parameter(Mandatory = $false)] + [String] + $Prompt +) + +<# Function declarations --------------------------------------------------- #> + +<# +.Synopsis +Remove all shell session elements added by the Activate script, including the +addition of the virtual environment's Python executable from the beginning of +the PATH variable. + +.Parameter NonDestructive +If present, do not remove this function from the global namespace for the +session. + +#> +function global:deactivate ([switch]$NonDestructive) { + # Revert to original values + + # The prior prompt: + if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) { + Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt + Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT + } + + # The prior PYTHONHOME: + if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) { + Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME + Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME + } + + # The prior PATH: + if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) { + Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH + Remove-Item -Path Env:_OLD_VIRTUAL_PATH + } + + # Just remove the VIRTUAL_ENV altogether: + if (Test-Path -Path Env:VIRTUAL_ENV) { + Remove-Item -Path env:VIRTUAL_ENV + } + + # Just remove VIRTUAL_ENV_PROMPT altogether. + if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) { + Remove-Item -Path env:VIRTUAL_ENV_PROMPT + } + + # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether: + if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) { + Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force + } + + # Leave deactivate function in the global namespace if requested: + if (-not $NonDestructive) { + Remove-Item -Path function:deactivate + } +} + +<# +.Description +Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the +given folder, and returns them in a map. + +For each line in the pyvenv.cfg file, if that line can be parsed into exactly +two strings separated by `=` (with any amount of whitespace surrounding the =) +then it is considered a `key = value` line. The left hand string is the key, +the right hand is the value. + +If the value starts with a `'` or a `"` then the first and last character is +stripped from the value before being captured. + +.Parameter ConfigDir +Path to the directory that contains the `pyvenv.cfg` file. +#> +function Get-PyVenvConfig( + [String] + $ConfigDir +) { + Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg" + + # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue). + $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue + + # An empty map will be returned if no config file is found. + $pyvenvConfig = @{ } + + if ($pyvenvConfigPath) { + + Write-Verbose "File exists, parse `key = value` lines" + $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath + + $pyvenvConfigContent | ForEach-Object { + $keyval = $PSItem -split "\s*=\s*", 2 + if ($keyval[0] -and $keyval[1]) { + $val = $keyval[1] + + # Remove extraneous quotations around a string value. + if ("'""".Contains($val.Substring(0, 1))) { + $val = $val.Substring(1, $val.Length - 2) + } + + $pyvenvConfig[$keyval[0]] = $val + Write-Verbose "Adding Key: '$($keyval[0])'='$val'" + } + } + } + return $pyvenvConfig +} + + +<# Begin Activate script --------------------------------------------------- #> + +# Determine the containing directory of this script +$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition +$VenvExecDir = Get-Item -Path $VenvExecPath + +Write-Verbose "Activation script is located in path: '$VenvExecPath'" +Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)" +Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)" + +# Set values required in priority: CmdLine, ConfigFile, Default +# First, get the location of the virtual environment, it might not be +# VenvExecDir if specified on the command line. +if ($VenvDir) { + Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values" +} +else { + Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir." + $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/") + Write-Verbose "VenvDir=$VenvDir" +} + +# Next, read the `pyvenv.cfg` file to determine any required value such +# as `prompt`. +$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir + +# Next, set the prompt from the command line, or the config file, or +# just use the name of the virtual environment folder. +if ($Prompt) { + Write-Verbose "Prompt specified as argument, using '$Prompt'" +} +else { + Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value" + if ($pyvenvCfg -and $pyvenvCfg['prompt']) { + Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'" + $Prompt = $pyvenvCfg['prompt']; + } + else { + Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)" + Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'" + $Prompt = Split-Path -Path $venvDir -Leaf + } +} + +Write-Verbose "Prompt = '$Prompt'" +Write-Verbose "VenvDir='$VenvDir'" + +# Deactivate any currently active virtual environment, but leave the +# deactivate function in place. +deactivate -nondestructive + +# Now set the environment variable VIRTUAL_ENV, used by many tools to determine +# that there is an activated venv. +$env:VIRTUAL_ENV = $VenvDir + +if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) { + + Write-Verbose "Setting prompt to '$Prompt'" + + # Set the prompt to include the env name + # Make sure _OLD_VIRTUAL_PROMPT is global + function global:_OLD_VIRTUAL_PROMPT { "" } + Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT + New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt + + function global:prompt { + Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) " + _OLD_VIRTUAL_PROMPT + } + $env:VIRTUAL_ENV_PROMPT = $Prompt +} + +# Clear PYTHONHOME +if (Test-Path -Path Env:PYTHONHOME) { + Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME + Remove-Item -Path Env:PYTHONHOME +} + +# Add the venv to the PATH +Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH +$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH" diff --git a/myenv/bin/activate b/myenv/bin/activate new file mode 100644 index 0000000..d7a60e2 --- /dev/null +++ b/myenv/bin/activate @@ -0,0 +1,69 @@ +# This file must be used with "source bin/activate" *from bash* +# you cannot run it directly + +deactivate () { + # reset old environment variables + if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then + PATH="${_OLD_VIRTUAL_PATH:-}" + export PATH + unset _OLD_VIRTUAL_PATH + fi + if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then + PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" + export PYTHONHOME + unset _OLD_VIRTUAL_PYTHONHOME + fi + + # This should detect bash and zsh, which have a hash command that must + # be called to get it to forget past commands. Without forgetting + # past commands the $PATH changes we made may not be respected + if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then + hash -r 2> /dev/null + fi + + if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then + PS1="${_OLD_VIRTUAL_PS1:-}" + export PS1 + unset _OLD_VIRTUAL_PS1 + fi + + unset VIRTUAL_ENV + unset VIRTUAL_ENV_PROMPT + if [ ! "${1:-}" = "nondestructive" ] ; then + # Self destruct! + unset -f deactivate + fi +} + +# unset irrelevant variables +deactivate nondestructive + +VIRTUAL_ENV="/home/abdelrahman-lila/Repositories/image2image/myenv" +export VIRTUAL_ENV + +_OLD_VIRTUAL_PATH="$PATH" +PATH="$VIRTUAL_ENV/bin:$PATH" +export PATH + +# unset PYTHONHOME if set +# this will fail if PYTHONHOME is set to the empty string (which is bad anyway) +# could use `if (set -u; : $PYTHONHOME) ;` in bash +if [ -n "${PYTHONHOME:-}" ] ; then + _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" + unset PYTHONHOME +fi + +if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then + _OLD_VIRTUAL_PS1="${PS1:-}" + PS1="(myenv) ${PS1:-}" + export PS1 + VIRTUAL_ENV_PROMPT="(myenv) " + export VIRTUAL_ENV_PROMPT +fi + +# This should detect bash and zsh, which have a hash command that must +# be called to get it to forget past commands. Without forgetting +# past commands the $PATH changes we made may not be respected +if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then + hash -r 2> /dev/null +fi diff --git a/myenv/bin/activate.csh b/myenv/bin/activate.csh new file mode 100644 index 0000000..6485b78 --- /dev/null +++ b/myenv/bin/activate.csh @@ -0,0 +1,26 @@ +# This file must be used with "source bin/activate.csh" *from csh*. +# You cannot run it directly. +# Created by Davide Di Blasi . +# Ported to Python 3.3 venv by Andrew Svetlov + +alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate' + +# Unset irrelevant variables. +deactivate nondestructive + +setenv VIRTUAL_ENV "/home/abdelrahman-lila/Repositories/image2image/myenv" + +set _OLD_VIRTUAL_PATH="$PATH" +setenv PATH "$VIRTUAL_ENV/bin:$PATH" + + +set _OLD_VIRTUAL_PROMPT="$prompt" + +if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then + set prompt = "(myenv) $prompt" + setenv VIRTUAL_ENV_PROMPT "(myenv) " +endif + +alias pydoc python -m pydoc + +rehash diff --git a/myenv/bin/activate.fish b/myenv/bin/activate.fish new file mode 100644 index 0000000..e7649bc --- /dev/null +++ b/myenv/bin/activate.fish @@ -0,0 +1,69 @@ +# This file must be used with "source /bin/activate.fish" *from fish* +# (https://fishshell.com/); you cannot run it directly. + +function deactivate -d "Exit virtual environment and return to normal shell environment" + # reset old environment variables + if test -n "$_OLD_VIRTUAL_PATH" + set -gx PATH $_OLD_VIRTUAL_PATH + set -e _OLD_VIRTUAL_PATH + end + if test -n "$_OLD_VIRTUAL_PYTHONHOME" + set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME + set -e _OLD_VIRTUAL_PYTHONHOME + end + + if test -n "$_OLD_FISH_PROMPT_OVERRIDE" + set -e _OLD_FISH_PROMPT_OVERRIDE + # prevents error when using nested fish instances (Issue #93858) + if functions -q _old_fish_prompt + functions -e fish_prompt + functions -c _old_fish_prompt fish_prompt + functions -e _old_fish_prompt + end + end + + set -e VIRTUAL_ENV + set -e VIRTUAL_ENV_PROMPT + if test "$argv[1]" != "nondestructive" + # Self-destruct! + functions -e deactivate + end +end + +# Unset irrelevant variables. +deactivate nondestructive + +set -gx VIRTUAL_ENV "/home/abdelrahman-lila/Repositories/image2image/myenv" + +set -gx _OLD_VIRTUAL_PATH $PATH +set -gx PATH "$VIRTUAL_ENV/bin" $PATH + +# Unset PYTHONHOME if set. +if set -q PYTHONHOME + set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME + set -e PYTHONHOME +end + +if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" + # fish uses a function instead of an env var to generate the prompt. + + # Save the current fish_prompt function as the function _old_fish_prompt. + functions -c fish_prompt _old_fish_prompt + + # With the original prompt function renamed, we can override with our own. + function fish_prompt + # Save the return status of the last command. + set -l old_status $status + + # Output the venv prompt; color taken from the blue of the Python logo. + printf "%s%s%s" (set_color 4B8BBE) "(myenv) " (set_color normal) + + # Restore the return status of the previous command. + echo "exit $old_status" | . + # Output the original/"old" prompt. + _old_fish_prompt + end + + set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" + set -gx VIRTUAL_ENV_PROMPT "(myenv) " +end diff --git a/myenv/bin/chardetect b/myenv/bin/chardetect new file mode 100755 index 0000000..0181c09 --- /dev/null +++ b/myenv/bin/chardetect @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from chardet.cli.chardetect import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/convert-caffe2-to-onnx b/myenv/bin/convert-caffe2-to-onnx new file mode 100755 index 0000000..ba2ccb9 --- /dev/null +++ b/myenv/bin/convert-caffe2-to-onnx @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from caffe2.python.onnx.bin.conversion import caffe2_to_onnx +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(caffe2_to_onnx()) diff --git a/myenv/bin/convert-onnx-to-caffe2 b/myenv/bin/convert-onnx-to-caffe2 new file mode 100755 index 0000000..9eda324 --- /dev/null +++ b/myenv/bin/convert-onnx-to-caffe2 @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from caffe2.python.onnx.bin.conversion import onnx_to_caffe2 +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(onnx_to_caffe2()) diff --git a/myenv/bin/coverage b/myenv/bin/coverage new file mode 100755 index 0000000..7bc5712 --- /dev/null +++ b/myenv/bin/coverage @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from coverage.cmdline import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/coverage-3.10 b/myenv/bin/coverage-3.10 new file mode 100755 index 0000000..7bc5712 --- /dev/null +++ b/myenv/bin/coverage-3.10 @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from coverage.cmdline import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/coverage3 b/myenv/bin/coverage3 new file mode 100755 index 0000000..7bc5712 --- /dev/null +++ b/myenv/bin/coverage3 @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from coverage.cmdline import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/dmypy b/myenv/bin/dmypy new file mode 100755 index 0000000..f9693d0 --- /dev/null +++ b/myenv/bin/dmypy @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from mypy.dmypy.client import console_entry +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(console_entry()) diff --git a/myenv/bin/f2py b/myenv/bin/f2py new file mode 100755 index 0000000..e6029a7 --- /dev/null +++ b/myenv/bin/f2py @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from numpy.f2py.f2py2e import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/flask b/myenv/bin/flask new file mode 100755 index 0000000..6954012 --- /dev/null +++ b/myenv/bin/flask @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from flask.cli import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/imageio_download_bin b/myenv/bin/imageio_download_bin new file mode 100755 index 0000000..fc75c78 --- /dev/null +++ b/myenv/bin/imageio_download_bin @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from imageio.__main__ import download_bin_main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(download_bin_main()) diff --git a/myenv/bin/imageio_remove_bin b/myenv/bin/imageio_remove_bin new file mode 100755 index 0000000..528e5d9 --- /dev/null +++ b/myenv/bin/imageio_remove_bin @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from imageio.__main__ import remove_bin_main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(remove_bin_main()) diff --git a/myenv/bin/isympy b/myenv/bin/isympy new file mode 100755 index 0000000..abcb7cf --- /dev/null +++ b/myenv/bin/isympy @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from isympy import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/lsm2bin b/myenv/bin/lsm2bin new file mode 100755 index 0000000..b23ba2c --- /dev/null +++ b/myenv/bin/lsm2bin @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile.lsm2bin import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/markdown_py b/myenv/bin/markdown_py new file mode 100755 index 0000000..f32a013 --- /dev/null +++ b/myenv/bin/markdown_py @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from markdown.__main__ import run +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(run()) diff --git a/myenv/bin/mypy b/myenv/bin/mypy new file mode 100755 index 0000000..d9d032a --- /dev/null +++ b/myenv/bin/mypy @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from mypy.__main__ import console_entry +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(console_entry()) diff --git a/myenv/bin/mypyc b/myenv/bin/mypyc new file mode 100755 index 0000000..2cddf1d --- /dev/null +++ b/myenv/bin/mypyc @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from mypyc.__main__ import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/normalizer b/myenv/bin/normalizer new file mode 100755 index 0000000..28d00e0 --- /dev/null +++ b/myenv/bin/normalizer @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from charset_normalizer.cli import cli_detect +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(cli_detect()) diff --git a/myenv/bin/pip b/myenv/bin/pip new file mode 100755 index 0000000..ddc2c25 --- /dev/null +++ b/myenv/bin/pip @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/pip3 b/myenv/bin/pip3 new file mode 100755 index 0000000..ddc2c25 --- /dev/null +++ b/myenv/bin/pip3 @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/pip3.10 b/myenv/bin/pip3.10 new file mode 100755 index 0000000..ddc2c25 --- /dev/null +++ b/myenv/bin/pip3.10 @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/py.test b/myenv/bin/py.test new file mode 100755 index 0000000..80e3e8d --- /dev/null +++ b/myenv/bin/py.test @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pytest import console_main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(console_main()) diff --git a/myenv/bin/pytest b/myenv/bin/pytest new file mode 100755 index 0000000..80e3e8d --- /dev/null +++ b/myenv/bin/pytest @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from pytest import console_main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(console_main()) diff --git a/myenv/bin/python b/myenv/bin/python new file mode 120000 index 0000000..b8a0adb --- /dev/null +++ b/myenv/bin/python @@ -0,0 +1 @@ +python3 \ No newline at end of file diff --git a/myenv/bin/python3 b/myenv/bin/python3 new file mode 120000 index 0000000..ae65fda --- /dev/null +++ b/myenv/bin/python3 @@ -0,0 +1 @@ +/usr/bin/python3 \ No newline at end of file diff --git a/myenv/bin/python3.10 b/myenv/bin/python3.10 new file mode 120000 index 0000000..b8a0adb --- /dev/null +++ b/myenv/bin/python3.10 @@ -0,0 +1 @@ +python3 \ No newline at end of file diff --git a/myenv/bin/ruff b/myenv/bin/ruff new file mode 100755 index 0000000..746dc14 Binary files /dev/null and b/myenv/bin/ruff differ diff --git a/myenv/bin/stubgen b/myenv/bin/stubgen new file mode 100755 index 0000000..5c635df --- /dev/null +++ b/myenv/bin/stubgen @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from mypy.stubgen import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/stubtest b/myenv/bin/stubtest new file mode 100755 index 0000000..146fd7d --- /dev/null +++ b/myenv/bin/stubtest @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from mypy.stubtest import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/tensorboard b/myenv/bin/tensorboard new file mode 100755 index 0000000..bff974b --- /dev/null +++ b/myenv/bin/tensorboard @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tensorboard.main import run_main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(run_main()) diff --git a/myenv/bin/tiff2fsspec b/myenv/bin/tiff2fsspec new file mode 100755 index 0000000..09ab942 --- /dev/null +++ b/myenv/bin/tiff2fsspec @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile.tiff2fsspec import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/tiffcomment b/myenv/bin/tiffcomment new file mode 100755 index 0000000..ff4fdfa --- /dev/null +++ b/myenv/bin/tiffcomment @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile.tiffcomment import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/tifffile b/myenv/bin/tifffile new file mode 100755 index 0000000..6ad5b94 --- /dev/null +++ b/myenv/bin/tifffile @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tifffile import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/torchrun b/myenv/bin/torchrun new file mode 100755 index 0000000..9469470 --- /dev/null +++ b/myenv/bin/torchrun @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from torch.distributed.run import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/tox b/myenv/bin/tox new file mode 100755 index 0000000..5cd11bd --- /dev/null +++ b/myenv/bin/tox @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tox.run import run +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(run()) diff --git a/myenv/bin/tqdm b/myenv/bin/tqdm new file mode 100755 index 0000000..02924dc --- /dev/null +++ b/myenv/bin/tqdm @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from tqdm.cli import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/myenv/bin/virtualenv b/myenv/bin/virtualenv new file mode 100755 index 0000000..d3bfbf8 --- /dev/null +++ b/myenv/bin/virtualenv @@ -0,0 +1,8 @@ +#!/home/abdelrahman-lila/Repositories/image2image/myenv/bin/python3 +# -*- coding: utf-8 -*- +import re +import sys +from virtualenv.__main__ import run_with_catch +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(run_with_catch()) diff --git a/myenv/lib64 b/myenv/lib64 new file mode 120000 index 0000000..7951405 --- /dev/null +++ b/myenv/lib64 @@ -0,0 +1 @@ +lib \ No newline at end of file diff --git a/myenv/pyvenv.cfg b/myenv/pyvenv.cfg new file mode 100644 index 0000000..0537ffc --- /dev/null +++ b/myenv/pyvenv.cfg @@ -0,0 +1,3 @@ +home = /usr/bin +include-system-site-packages = false +version = 3.10.12 diff --git a/myenv/share/man/man1/isympy.1 b/myenv/share/man/man1/isympy.1 new file mode 100644 index 0000000..0ff9661 --- /dev/null +++ b/myenv/share/man/man1/isympy.1 @@ -0,0 +1,188 @@ +'\" -*- coding: us-ascii -*- +.if \n(.g .ds T< \\FC +.if \n(.g .ds T> \\F[\n[.fam]] +.de URL +\\$2 \(la\\$1\(ra\\$3 +.. +.if \n(.g .mso www.tmac +.TH isympy 1 2007-10-8 "" "" +.SH NAME +isympy \- interactive shell for SymPy +.SH SYNOPSIS +'nh +.fi +.ad l +\fBisympy\fR \kx +.if (\nx>(\n(.l/2)) .nr x (\n(.l/5) +'in \n(.iu+\nxu +[\fB-c\fR | \fB--console\fR] [\fB-p\fR ENCODING | \fB--pretty\fR ENCODING] [\fB-t\fR TYPE | \fB--types\fR TYPE] [\fB-o\fR ORDER | \fB--order\fR ORDER] [\fB-q\fR | \fB--quiet\fR] [\fB-d\fR | \fB--doctest\fR] [\fB-C\fR | \fB--no-cache\fR] [\fB-a\fR | \fB--auto\fR] [\fB-D\fR | \fB--debug\fR] [ +-- | PYTHONOPTIONS] +'in \n(.iu-\nxu +.ad b +'hy +'nh +.fi +.ad l +\fBisympy\fR \kx +.if (\nx>(\n(.l/2)) .nr x (\n(.l/5) +'in \n(.iu+\nxu +[ +{\fB-h\fR | \fB--help\fR} +| +{\fB-v\fR | \fB--version\fR} +] +'in \n(.iu-\nxu +.ad b +'hy +.SH DESCRIPTION +isympy is a Python shell for SymPy. It is just a normal python shell +(ipython shell if you have the ipython package installed) that executes +the following commands so that you don't have to: +.PP +.nf +\*(T< +>>> from __future__ import division +>>> from sympy import * +>>> x, y, z = symbols("x,y,z") +>>> k, m, n = symbols("k,m,n", integer=True) + \*(T> +.fi +.PP +So starting isympy is equivalent to starting python (or ipython) and +executing the above commands by hand. It is intended for easy and quick +experimentation with SymPy. For more complicated programs, it is recommended +to write a script and import things explicitly (using the "from sympy +import sin, log, Symbol, ..." idiom). +.SH OPTIONS +.TP +\*(T<\fB\-c \fR\*(T>\fISHELL\fR, \*(T<\fB\-\-console=\fR\*(T>\fISHELL\fR +Use the specified shell (python or ipython) as +console backend instead of the default one (ipython +if present or python otherwise). + +Example: isympy -c python + +\fISHELL\fR could be either +\&'ipython' or 'python' +.TP +\*(T<\fB\-p \fR\*(T>\fIENCODING\fR, \*(T<\fB\-\-pretty=\fR\*(T>\fIENCODING\fR +Setup pretty printing in SymPy. By default, the most pretty, unicode +printing is enabled (if the terminal supports it). You can use less +pretty ASCII printing instead or no pretty printing at all. + +Example: isympy -p no + +\fIENCODING\fR must be one of 'unicode', +\&'ascii' or 'no'. +.TP +\*(T<\fB\-t \fR\*(T>\fITYPE\fR, \*(T<\fB\-\-types=\fR\*(T>\fITYPE\fR +Setup the ground types for the polys. By default, gmpy ground types +are used if gmpy2 or gmpy is installed, otherwise it falls back to python +ground types, which are a little bit slower. You can manually +choose python ground types even if gmpy is installed (e.g., for testing purposes). + +Note that sympy ground types are not supported, and should be used +only for experimental purposes. + +Note that the gmpy1 ground type is primarily intended for testing; it the +use of gmpy even if gmpy2 is available. + +This is the same as setting the environment variable +SYMPY_GROUND_TYPES to the given ground type (e.g., +SYMPY_GROUND_TYPES='gmpy') + +The ground types can be determined interactively from the variable +sympy.polys.domains.GROUND_TYPES inside the isympy shell itself. + +Example: isympy -t python + +\fITYPE\fR must be one of 'gmpy', +\&'gmpy1' or 'python'. +.TP +\*(T<\fB\-o \fR\*(T>\fIORDER\fR, \*(T<\fB\-\-order=\fR\*(T>\fIORDER\fR +Setup the ordering of terms for printing. The default is lex, which +orders terms lexicographically (e.g., x**2 + x + 1). You can choose +other orderings, such as rev-lex, which will use reverse +lexicographic ordering (e.g., 1 + x + x**2). + +Note that for very large expressions, ORDER='none' may speed up +printing considerably, with the tradeoff that the order of the terms +in the printed expression will have no canonical order + +Example: isympy -o rev-lax + +\fIORDER\fR must be one of 'lex', 'rev-lex', 'grlex', +\&'rev-grlex', 'grevlex', 'rev-grevlex', 'old', or 'none'. +.TP +\*(T<\fB\-q\fR\*(T>, \*(T<\fB\-\-quiet\fR\*(T> +Print only Python's and SymPy's versions to stdout at startup, and nothing else. +.TP +\*(T<\fB\-d\fR\*(T>, \*(T<\fB\-\-doctest\fR\*(T> +Use the same format that should be used for doctests. This is +equivalent to '\fIisympy -c python -p no\fR'. +.TP +\*(T<\fB\-C\fR\*(T>, \*(T<\fB\-\-no\-cache\fR\*(T> +Disable the caching mechanism. Disabling the cache may slow certain +operations down considerably. This is useful for testing the cache, +or for benchmarking, as the cache can result in deceptive benchmark timings. + +This is the same as setting the environment variable SYMPY_USE_CACHE +to 'no'. +.TP +\*(T<\fB\-a\fR\*(T>, \*(T<\fB\-\-auto\fR\*(T> +Automatically create missing symbols. Normally, typing a name of a +Symbol that has not been instantiated first would raise NameError, +but with this option enabled, any undefined name will be +automatically created as a Symbol. This only works in IPython 0.11. + +Note that this is intended only for interactive, calculator style +usage. In a script that uses SymPy, Symbols should be instantiated +at the top, so that it's clear what they are. + +This will not override any names that are already defined, which +includes the single character letters represented by the mnemonic +QCOSINE (see the "Gotchas and Pitfalls" document in the +documentation). You can delete existing names by executing "del +name" in the shell itself. You can see if a name is defined by typing +"'name' in globals()". + +The Symbols that are created using this have default assumptions. +If you want to place assumptions on symbols, you should create them +using symbols() or var(). + +Finally, this only works in the top level namespace. So, for +example, if you define a function in isympy with an undefined +Symbol, it will not work. +.TP +\*(T<\fB\-D\fR\*(T>, \*(T<\fB\-\-debug\fR\*(T> +Enable debugging output. This is the same as setting the +environment variable SYMPY_DEBUG to 'True'. The debug status is set +in the variable SYMPY_DEBUG within isympy. +.TP +-- \fIPYTHONOPTIONS\fR +These options will be passed on to \fIipython (1)\fR shell. +Only supported when ipython is being used (standard python shell not supported). + +Two dashes (--) are required to separate \fIPYTHONOPTIONS\fR +from the other isympy options. + +For example, to run iSymPy without startup banner and colors: + +isympy -q -c ipython -- --colors=NoColor +.TP +\*(T<\fB\-h\fR\*(T>, \*(T<\fB\-\-help\fR\*(T> +Print help output and exit. +.TP +\*(T<\fB\-v\fR\*(T>, \*(T<\fB\-\-version\fR\*(T> +Print isympy version information and exit. +.SH FILES +.TP +\*(T<\fI${HOME}/.sympy\-history\fR\*(T> +Saves the history of commands when using the python +shell as backend. +.SH BUGS +The upstreams BTS can be found at \(lahttps://github.com/sympy/sympy/issues\(ra +Please report all bugs that you find in there, this will help improve +the overall quality of SymPy. +.SH "SEE ALSO" +\fBipython\fR(1), \fBpython\fR(1) diff --git a/src/img2img/models/cyclegan/config.py b/src/img2img/models/cyclegan/config.py new file mode 100644 index 0000000..19c1535 --- /dev/null +++ b/src/img2img/models/cyclegan/config.py @@ -0,0 +1,29 @@ +import torch +import albumentations as A +from albumentations.pytorch import ToTensorV2 + +DEVICE = "cuda" if torch.cuda.is_available() else "cpu" +TRAIN_DIR = "data/train" +VAL_DIR = "data/val" +BATCH_SIZE = 1 +LEARNING_RATE = 2e-4 +LAMBDA_IDENTITY = 0.0 +LAMBDA_CYCLE = 10 +NUM_WORKERS = 4 +NUM_EPOCHS = 200 +LOAD_MODEL = True +SAVE_MODEL = True +CHECKPOINT_GEN_H = "genh.pth.tar" +CHECKPOINT_GEN_Z = "genz.pth.tar" +CHECKPOINT_CRITIC_H = "critich.pth.tar" +CHECKPOINT_CRITIC_Z = "criticz.pth.tar" + +transforms = A.Compose( + [ + A.Resize(width=256, height=256), + A.HorizontalFlip(p=0.5), + A.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], max_pixel_value=255), + ToTensorV2(), + ], + additional_targets={"image0": "image"}, +) \ No newline at end of file diff --git a/src/img2img/models/cyclegan/dataset.py b/src/img2img/models/cyclegan/dataset.py new file mode 100644 index 0000000..3cee6bb --- /dev/null +++ b/src/img2img/models/cyclegan/dataset.py @@ -0,0 +1,36 @@ +from PIL import Image +import os +from torch.utils.data import Dataset +import numpy as np + +class HorseZebraDataset(Dataset): + def __init__(self, root_zebra, root_horse, transform=None): + self.root_zebra = root_zebra + self.root_horse = root_horse + self.transform = transform + + self.zebra_images = os.listdir(root_zebra) + self.horse_images = os.listdir(root_horse) + self.length_dataset = max(len(self.zebra_images), len(self.horse_images)) + self.zebra_len = len(self.zebra_images) + self.horse_len = len(self.horse_images) + + def __len__(self): + return self.length_dataset + + def __getitem__(self, index): + zebra_img = self.zebra_images[index % self.zebra_len] + horse_img = self.horse_images[index % self.horse_len] + + zebra_path = os.path.join(self.root_zebra, zebra_img) + horse_path = os.path.join(self.root_horse, horse_img) + + zebra_img = np.array(Image.open(zebra_path).convert("RGB")) + horse_img = np.array(Image.open(horse_path).convert("RGB")) + + if self.transform: + augmentations = self.transform(image=zebra_img, image0=horse_img) + zebra_img = augmentations["image"] + horse_img = augmentations["image0"] + + return zebra_img, horse_img \ No newline at end of file diff --git a/src/img2img/models/cyclegan/discriminator.py b/src/img2img/models/cyclegan/discriminator.py new file mode 100644 index 0000000..50ccba0 --- /dev/null +++ b/src/img2img/models/cyclegan/discriminator.py @@ -0,0 +1,55 @@ +import torch +import torch.nn as nn + +class Block(nn.Module): + def __init__(self, in_channels, out_channels, stride): + super().__init__() + self.conv = nn.Sequential( + nn.Conv2d(in_channels, out_channels, 4, stride, 1,bias=True, padding_mode="reflect"), + nn.InstanceNorm2d(out_channels), + nn.LeakyReLU(0.2), + ) + + + def forward(self, x): + return self.conv(x) + + +class Discriminator(nn.Module): + def __init__(self, in_channels=3, features=[64, 128, 256, 512]): + super().__init__() + self.initial = nn.Sequential( + nn.Conv2d( + in_channels, + features[0], + kernel_size=4, + stride=2, + padding=1, + padding_mode="reflect", + ), + nn.LeakyReLU(0.2), + ) + + layers = [] + in_channels = features[0] + for feature in features[1:]: + layers.append(Block(in_channels, feature, stride=1 if feature == features[-1] else 2)) + in_channels = feature + layers.append(nn.Conv2d(in_channels, 1, kernel_size=4, stride=1, padding=1, padding_mode="reflect")) + self.model = nn.Sequential(*layers) + + + def forward(self, x): + x = self.initial(x) + return torch.sigmoid(self.model(x)) + +def test(): + x = torch.randn((1, 3, 256, 256)) + model = Discriminator(in_channels=3) + preds = model(x) + print(model) + print(preds.shape) + + +if __name__ == "__main__": + test() \ No newline at end of file diff --git a/src/img2img/models/cyclegan/generator.py b/src/img2img/models/cyclegan/generator.py new file mode 100644 index 0000000..aed443c --- /dev/null +++ b/src/img2img/models/cyclegan/generator.py @@ -0,0 +1,72 @@ +import torch +import torch.nn as nn + +class convBlock(nn.Module): + def __init__(self, in_channels, out_channels, down = True, use_act = True, **kwargs): + super().__init__() + self.conv = nn.Sequential( + nn.Conv2d(in_channels, out_channels, padding_mode="reflect", **kwargs) + if down + else nn.ConvTranspose2d(in_channels, out_channels, **kwargs), + nn.InstanceNorm2d(out_channels), + nn.ReLU(inplace=True) if use_act else nn.Identity() + ) + + def forward(self, x): + return self.conv(x) + + +class ResidualBlock(nn.Module): + def __init__(self, channels): + super().__init__() + self.block = nn.Sequential( + convBlock(channels, channels, kernel_size = 3, padding = 1), + convBlock(channels, channels, use_act=False, kernel_size = 3, padding = 1), + ) + + def forward(self, x): + return x + self.block(x) + +class Generator(nn.Module): + def __init__(self, img_channels,num_features=64, num_residuals = 9): + super().__init__() + self.initial = nn.Sequential( + nn.Conv2d(img_channels, num_features, kernel_size=7, stride=1, padding=3, padding_mode="reflect"), + nn.ReLU(inplace=True), + ) + self.down_blocks = nn.ModuleList( + [ + convBlock(num_features, num_features*2, kernel_size = 3, stride=2, padding=1), + convBlock(num_features*2, num_features*4, kernel_size=3, stride=2, padding=1), + ] + ) + self.residual_blocks = nn.Sequential( + *[ResidualBlock(num_features*4) for _ in range(num_residuals)] + ) + self.up_blocks = nn.ModuleList( + [ + convBlock(num_features*4, num_features*2, down=False, kernel_size=3, stride=2, padding=1, output_padding=1), + convBlock(num_features*2, num_features*1, down=False, kernel_size=3, stride=2, padding=1, output_padding=1), + ] + ) + self.last = nn.Conv2d(num_features*1, img_channels, kernel_size=7, stride=1, padding=3, padding_mode="reflect") + + def forward(self, x): + x = self.initial(x) + for layer in self.down_blocks: + x = layer(x) + x = self.residual_blocks(x) + for layer in self.up_blocks: + x = layer(x) + return torch.tanh(self.last(x)) + +def test(): + img_channels = 3 + img_size = 256 + x = torch.randn((2, img_channels, img_size, img_size)) + gen = Generator(img_channels, 9) + print(gen(x).shape) + + +if __name__ == "__main__": + test() \ No newline at end of file diff --git a/src/img2img/models/cyclegan/train.py b/src/img2img/models/cyclegan/train.py new file mode 100644 index 0000000..366b5a0 --- /dev/null +++ b/src/img2img/models/cyclegan/train.py @@ -0,0 +1,189 @@ +import torch +from dataset import HorseZebraDataset +import sys +from utils import save_checkpoint, load_checkpoint +from torch.utils.data import DataLoader +import torch.nn as nn +import torch.optim as optim +import config +from tqdm import tqdm +from torchvision.utils import save_image +from discriminator import Discriminator +from generator import Generator + + +def train_fn( + disc_H, disc_Z, gen_Z, gen_H, loader, opt_disc, opt_gen, l1, mse, d_scaler, g_scaler +): + H_reals = 0 + H_fakes = 0 + loop = tqdm(loader, leave=True) + + for idx, (zebra, horse) in enumerate(loop): + zebra = zebra.to(config.DEVICE) + horse = horse.to(config.DEVICE) + + # Train Discriminators H and Z + with torch.cuda.amp.autocast(): + fake_horse = gen_H(zebra) + D_H_real = disc_H(horse) + D_H_fake = disc_H(fake_horse.detach()) + H_reals += D_H_real.mean().item() + H_fakes += D_H_fake.mean().item() + D_H_real_loss = mse(D_H_real, torch.ones_like(D_H_real)) + D_H_fake_loss = mse(D_H_fake, torch.zeros_like(D_H_fake)) + D_H_loss = D_H_real_loss + D_H_fake_loss + + fake_zebra = gen_Z(horse) + D_Z_real = disc_Z(zebra) + D_Z_fake = disc_Z(fake_zebra.detach()) + D_Z_real_loss = mse(D_Z_real, torch.ones_like(D_Z_real)) + D_Z_fake_loss = mse(D_Z_fake, torch.zeros_like(D_Z_fake)) + D_Z_loss = D_Z_real_loss + D_Z_fake_loss + + # put it togethor + D_loss = (D_H_loss + D_Z_loss) / 2 + + opt_disc.zero_grad() + d_scaler.scale(D_loss).backward() + d_scaler.step(opt_disc) + d_scaler.update() + + # Train Generators H and Z + with torch.cuda.amp.autocast(): + # adversarial loss for both generators + D_H_fake = disc_H(fake_horse) + D_Z_fake = disc_Z(fake_zebra) + loss_G_H = mse(D_H_fake, torch.ones_like(D_H_fake)) + loss_G_Z = mse(D_Z_fake, torch.ones_like(D_Z_fake)) + + # cycle loss + cycle_zebra = gen_Z(fake_horse) + cycle_horse = gen_H(fake_zebra) + cycle_zebra_loss = l1(zebra, cycle_zebra) + cycle_horse_loss = l1(horse, cycle_horse) + + # identity loss (remove these for efficiency if you set lambda_identity=0) + identity_zebra = gen_Z(zebra) + identity_horse = gen_H(horse) + identity_zebra_loss = l1(zebra, identity_zebra) + identity_horse_loss = l1(horse, identity_horse) + + # add all togethor + G_loss = ( + loss_G_Z + + loss_G_H + + cycle_zebra_loss * config.LAMBDA_CYCLE + + cycle_horse_loss * config.LAMBDA_CYCLE + + identity_horse_loss * config.LAMBDA_IDENTITY + + identity_zebra_loss * config.LAMBDA_IDENTITY + ) + + opt_gen.zero_grad() + g_scaler.scale(G_loss).backward() + g_scaler.step(opt_gen) + g_scaler.update() + + if idx % 200 == 0: + save_image(fake_horse * 0.5 + 0.5, f"saved_images/horse_{idx}.png") + save_image(fake_zebra * 0.5 + 0.5, f"saved_images/zebra_{idx}.png") + + loop.set_postfix(H_real=H_reals / (idx + 1), H_fake=H_fakes / (idx + 1)) + + +def main(): + disc_H = Discriminator(in_channels=3).to(config.DEVICE) + disc_Z = Discriminator(in_channels=3).to(config.DEVICE) + gen_Z = Generator(img_channels=3, num_residuals=9).to(config.DEVICE) + gen_H = Generator(img_channels=3, num_residuals=9).to(config.DEVICE) + opt_disc = optim.Adam( + list(disc_H.parameters()) + list(disc_Z.parameters()), + lr=config.LEARNING_RATE, + betas=(0.5, 0.999), + ) + + opt_gen = optim.Adam( + list(gen_Z.parameters()) + list(gen_H.parameters()), + lr=config.LEARNING_RATE, + betas=(0.5, 0.999), + ) + + L1 = nn.L1Loss() + mse = nn.MSELoss() + + if config.LOAD_MODEL: + load_checkpoint( + config.CHECKPOINT_GEN_H, + gen_H, + opt_gen, + config.LEARNING_RATE, + ) + load_checkpoint( + config.CHECKPOINT_GEN_Z, + gen_Z, + opt_gen, + config.LEARNING_RATE, + ) + load_checkpoint( + config.CHECKPOINT_CRITIC_H, + disc_H, + opt_disc, + config.LEARNING_RATE, + ) + load_checkpoint( + config.CHECKPOINT_CRITIC_Z, + disc_Z, + opt_disc, + config.LEARNING_RATE, + ) + + dataset = HorseZebraDataset( + root_horse=config.TRAIN_DIR + "/horses", + root_zebra=config.TRAIN_DIR + "/zebras", + transform=config.transforms, + ) + val_dataset = HorseZebraDataset( + root_horse="cyclegan_test/horse1", + root_zebra="cyclegan_test/zebra1", + transform=config.transforms, + ) + val_loader = DataLoader( + val_dataset, + batch_size=1, + shuffle=False, + pin_memory=True, + ) + loader = DataLoader( + dataset, + batch_size=config.BATCH_SIZE, + shuffle=True, + num_workers=config.NUM_WORKERS, + pin_memory=True, + ) + g_scaler = torch.cuda.amp.GradScaler() + d_scaler = torch.cuda.amp.GradScaler() + + for epoch in range(config.NUM_EPOCHS): + train_fn( + disc_H, + disc_Z, + gen_Z, + gen_H, + loader, + opt_disc, + opt_gen, + L1, + mse, + d_scaler, + g_scaler, + ) + + if config.SAVE_MODEL: + save_checkpoint(gen_H, opt_gen, filename=config.CHECKPOINT_GEN_H) + save_checkpoint(gen_Z, opt_gen, filename=config.CHECKPOINT_GEN_Z) + save_checkpoint(disc_H, opt_disc, filename=config.CHECKPOINT_CRITIC_H) + save_checkpoint(disc_Z, opt_disc, filename=config.CHECKPOINT_CRITIC_Z) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/img2img/models/cyclegan/utils.py b/src/img2img/models/cyclegan/utils.py new file mode 100644 index 0000000..25044a9 --- /dev/null +++ b/src/img2img/models/cyclegan/utils.py @@ -0,0 +1,35 @@ +import random, torch, os, numpy as np +import torch.nn as nn +import config +import copy + +def save_checkpoint(model, optimizer, filename="my_checkpoint.pth.tar"): + print("=> Saving checkpoint") + checkpoint = { + "state_dict": model.state_dict(), + "optimizer": optimizer.state_dict(), + } + torch.save(checkpoint, filename) + + +def load_checkpoint(checkpoint_file, model, optimizer, lr): + print("=> Loading checkpoint") + checkpoint = torch.load(checkpoint_file, map_location=config.DEVICE) + model.load_state_dict(checkpoint["state_dict"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + + # If we don't do this then it will just have learning rate of old checkpoint + # and it will lead to many hours of debugging \: + for param_group in optimizer.param_groups: + param_group["lr"] = lr + + +def seed_everything(seed=42): + os.environ["PYTHONHASHSEED"] = str(seed) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False \ No newline at end of file