init
commit
ddb2202429
@ -0,0 +1,17 @@
|
|||||||
|
.git
|
||||||
|
.vscode
|
||||||
|
.venv-sdr
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
|
||||||
|
# Heavy host-only SDR sources
|
||||||
|
gnuradio/
|
||||||
|
gr-osmosdr/
|
||||||
|
gr-osmosdr-0.2.6/
|
||||||
|
|
||||||
|
# Local runtime artifacts
|
||||||
|
NN_server/result/
|
||||||
|
|
||||||
|
# Legacy install artifacts not needed in docker image
|
||||||
|
install_scripts/
|
||||||
@ -0,0 +1,184 @@
|
|||||||
|
# ---> JupyterNotebooks
|
||||||
|
# gitignore template for Jupyter Notebooks
|
||||||
|
# website: http://jupyter.org/
|
||||||
|
|
||||||
|
NN_server/NN/
|
||||||
|
.env
|
||||||
|
.ipynb_checkpoints
|
||||||
|
*/.ipynb_checkpoints/*
|
||||||
|
volk/
|
||||||
|
torchsig/
|
||||||
|
gnuradio/
|
||||||
|
gr_osmosdr/
|
||||||
|
gr_osmosdr-0.2.6/
|
||||||
|
/.vscode
|
||||||
|
/docs
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# Remove previous ipynb_checkpoints
|
||||||
|
# git rm -r .ipynb_checkpoints/
|
||||||
|
|
||||||
|
# ---> Python
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# PyInstaller
|
||||||
|
# Usually these files are written by a python script from a template
|
||||||
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
*.manifest
|
||||||
|
*.spec
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
*.cover
|
||||||
|
*.py,cover
|
||||||
|
.hypothesis/
|
||||||
|
.pytest_cache/
|
||||||
|
cover/
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
local_settings.py
|
||||||
|
db.sqlite3
|
||||||
|
db.sqlite3-journal
|
||||||
|
|
||||||
|
# Flask stuff:
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# Scrapy stuff:
|
||||||
|
.scrapy
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
||||||
|
|
||||||
|
# PyBuilder
|
||||||
|
.pybuilder/
|
||||||
|
target/
|
||||||
|
|
||||||
|
# Jupyter Notebook
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# pyenv
|
||||||
|
# For a library or package, you might want to ignore these files since the code is
|
||||||
|
# intended to run in multiple environments; otherwise, check them in:
|
||||||
|
# .python-version
|
||||||
|
|
||||||
|
# pipenv
|
||||||
|
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||||
|
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||||
|
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||||
|
# install all needed dependencies.
|
||||||
|
#Pipfile.lock
|
||||||
|
|
||||||
|
# poetry
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||||
|
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||||
|
# commonly ignored for libraries.
|
||||||
|
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||||
|
#poetry.lock
|
||||||
|
|
||||||
|
# pdm
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||||
|
#pdm.lock
|
||||||
|
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||||
|
# in version control.
|
||||||
|
# https://pdm.fming.dev/#use-with-ide
|
||||||
|
.pdm.toml
|
||||||
|
|
||||||
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||||
|
__pypackages__/
|
||||||
|
|
||||||
|
# Celery stuff
|
||||||
|
celerybeat-schedule
|
||||||
|
celerybeat.pid
|
||||||
|
|
||||||
|
# SageMath parsed files
|
||||||
|
*.sage.py
|
||||||
|
|
||||||
|
# Environments
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# Spyder project settings
|
||||||
|
.spyderproject
|
||||||
|
.spyproject
|
||||||
|
|
||||||
|
# Rope project settings
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# mkdocs documentation
|
||||||
|
/site
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
.mypy_cache/
|
||||||
|
.dmypy.json
|
||||||
|
dmypy.json
|
||||||
|
|
||||||
|
# Pyre type checker
|
||||||
|
.pyre/
|
||||||
|
|
||||||
|
# pytype static type analyzer
|
||||||
|
.pytype/
|
||||||
|
|
||||||
|
# Cython debug symbols
|
||||||
|
cython_debug/
|
||||||
|
|
||||||
|
# PyCharm
|
||||||
|
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||||
|
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||||
|
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||||
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
|
#.idea/
|
||||||
|
|
||||||
@ -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"
|
||||||
@ -0,0 +1,70 @@
|
|||||||
|
# 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
|
||||||
|
|
||||||
|
# Call hash to forget past commands. Without forgetting
|
||||||
|
# past commands the $PATH changes we made may not be respected
|
||||||
|
hash -r 2> /dev/null
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# on Windows, a path can contain colons and backslashes and has to be converted:
|
||||||
|
if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then
|
||||||
|
# transform D:\path\to\venv to /d/path/to/venv on MSYS
|
||||||
|
# and to /cygdrive/d/path/to/venv on Cygwin
|
||||||
|
export VIRTUAL_ENV=$(cygpath /home/sibscience-4/from_ssh/DroneDetector/.venv-sdr)
|
||||||
|
else
|
||||||
|
# use the path as-is
|
||||||
|
export VIRTUAL_ENV=/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr
|
||||||
|
fi
|
||||||
|
|
||||||
|
_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='(.venv-sdr) '"${PS1:-}"
|
||||||
|
export PS1
|
||||||
|
VIRTUAL_ENV_PROMPT='(.venv-sdr) '
|
||||||
|
export VIRTUAL_ENV_PROMPT
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Call hash to forget past commands. Without forgetting
|
||||||
|
# past commands the $PATH changes we made may not be respected
|
||||||
|
hash -r 2> /dev/null
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
# This file must be used with "source bin/activate.csh" *from csh*.
|
||||||
|
# You cannot run it directly.
|
||||||
|
|
||||||
|
# Created by Davide Di Blasi <davidedb@gmail.com>.
|
||||||
|
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
|
||||||
|
|
||||||
|
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/sibscience-4/from_ssh/DroneDetector/.venv-sdr
|
||||||
|
|
||||||
|
set _OLD_VIRTUAL_PATH="$PATH"
|
||||||
|
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
|
||||||
|
|
||||||
|
|
||||||
|
set _OLD_VIRTUAL_PROMPT="$prompt"
|
||||||
|
|
||||||
|
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
|
||||||
|
set prompt = '(.venv-sdr) '"$prompt"
|
||||||
|
setenv VIRTUAL_ENV_PROMPT '(.venv-sdr) '
|
||||||
|
endif
|
||||||
|
|
||||||
|
alias pydoc python -m pydoc
|
||||||
|
|
||||||
|
rehash
|
||||||
@ -0,0 +1,69 @@
|
|||||||
|
# This file must be used with "source <venv>/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/sibscience-4/from_ssh/DroneDetector/.venv-sdr
|
||||||
|
|
||||||
|
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) '(.venv-sdr) ' (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 '(.venv-sdr) '
|
||||||
|
end
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
#!/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr/bin/python3
|
||||||
|
import sys
|
||||||
|
from numpy.f2py.f2py2e import main
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||||
|
sys.exit(main())
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
#!/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr/bin/python3
|
||||||
|
import sys
|
||||||
|
from charset_normalizer.cli import cli_detect
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||||
|
sys.exit(cli_detect())
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
#!/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr/bin/python3
|
||||||
|
import sys
|
||||||
|
from numpy._configtool import main
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||||
|
sys.exit(main())
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
#!/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr/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())
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
#!/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr/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())
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
#!/home/sibscience-4/from_ssh/DroneDetector/.venv-sdr/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())
|
||||||
@ -0,0 +1 @@
|
|||||||
|
python3
|
||||||
@ -0,0 +1 @@
|
|||||||
|
/usr/bin/python3
|
||||||
@ -0,0 +1 @@
|
|||||||
|
python3
|
||||||
@ -0,0 +1 @@
|
|||||||
|
lib
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
home = /usr/bin
|
||||||
|
include-system-site-packages = true
|
||||||
|
version = 3.12.3
|
||||||
|
executable = /usr/bin/python3.12
|
||||||
|
command = /usr/bin/python3 -m venv --system-site-packages /home/sibscience-4/from_ssh/DroneDetector/.venv-sdr
|
||||||
@ -0,0 +1,41 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
from torch.nn import functional as F
|
||||||
|
from torchvision import datasets, transforms
|
||||||
|
from torchensemble import VotingClassifier
|
||||||
|
|
||||||
|
|
||||||
|
class Ensemble(nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super(Ensemble, self).__init__()
|
||||||
|
self.linear1 = nn.Linear(2048, 512)
|
||||||
|
self.linear2 = nn.Linear(512, 128)
|
||||||
|
self.linear3 = nn.Linear(128, 32)
|
||||||
|
self.linear4 = nn.Linear(32, 3)
|
||||||
|
|
||||||
|
def forward(self, data):
|
||||||
|
data = data.view(data.size(0), -1)
|
||||||
|
output = F.relu(self.linear1(data))
|
||||||
|
output = F.relu(self.linear2(output))
|
||||||
|
output = self.linear3(output)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
transform = transforms.Compose([
|
||||||
|
transforms.ToTensor(),
|
||||||
|
transforms.Normalize((0.1307,), (0.3081,))
|
||||||
|
])
|
||||||
|
|
||||||
|
train = datasets.VisionDataset('../Dataset', train=True, download=True, transform=transform)
|
||||||
|
test = datasets.VisionDataset('../Dataset', train=False, transform=transform)
|
||||||
|
train_loader = torch.utils.data.DataLoader(train, batch_size=128, shuffle=True)
|
||||||
|
test_loader = torch.utils.data.DataLoader(test, batch_size=128, shuffle=True)
|
||||||
|
|
||||||
|
model = VotingClassifier(estimator=Ensemble, n_estimators=10, cuda=True)
|
||||||
|
|
||||||
|
criterion = nn.CrossEntropyLoss()
|
||||||
|
model.set_criterion(criterion)
|
||||||
|
|
||||||
|
model.set_optimizer('Adam', lr=1e-3, weight_decay=5e-4)
|
||||||
|
|
||||||
|
model.fit(train_loader, epochs=50, test_loader=test_loader)
|
||||||
@ -0,0 +1,192 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import matplotlib
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 32
|
||||||
|
|
||||||
|
# if int(ind_inference) <= 1500:
|
||||||
|
# np.save(src + '_inference_2400_' + str(ind_inference) + '.npy', data)
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
|
||||||
|
del sig_real
|
||||||
|
del sig_imag
|
||||||
|
del fig1
|
||||||
|
del fig2
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
print(device)
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
output = output.cpu()
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del img
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
'''
|
||||||
|
if int(ind_inference) <= 100:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
'''
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,132 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,132 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,132 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,134 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.Linear(in_features=32, out_features=num_classes, bias=True))
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,134 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
# model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
# padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.Linear(in_features=32, out_features=num_classes, bias=True))
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,136 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet50(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet50(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=2048, out_features=512, bias=True),
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.Linear(in_features=128, out_features=num_classes, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet50(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet50(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,135 @@
|
|||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet50(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 8)
|
||||||
|
dpi = 80
|
||||||
|
|
||||||
|
fig1 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_real = data[0]
|
||||||
|
plt.plot(sig_real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sig_imag = data[1]
|
||||||
|
plt.plot(sig_imag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
img = np.asarray([img1, img2], dtype=np.float32)
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet50(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(nn.Linear(in_features=2048, out_features=512, bias=True),
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.Linear(in_features=32, out_features=num_classes, bias=True))
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet50(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet50(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,146 @@
|
|||||||
|
import sklearn
|
||||||
|
from sklearn.ensemble import BaggingClassifier
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch.utils._contextlib import F
|
||||||
|
from torch.utils.data import TensorDataset, DataLoader
|
||||||
|
import torch.nn as nn
|
||||||
|
from torch.optim import Adam
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleCNN(nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super(SimpleCNN, self).__init__()
|
||||||
|
|
||||||
|
self.conv1 = nn.Conv2d(in_channels=1, out_channels=3, kernel_size=5, stride=1, padding=2)
|
||||||
|
self.conv1_s = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=5, stride=2, padding=2)
|
||||||
|
self.conv2 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=3, stride=1, padding=1)
|
||||||
|
self.conv2_s = nn.Conv2d(in_channels=6, out_channels=6, kernel_size=3, stride=2, padding=1)
|
||||||
|
self.conv3 = nn.Conv2d(in_channels=6, out_channels=10, kernel_size=3, stride=1, padding=1)
|
||||||
|
self.conv3_s = nn.Conv2d(in_channels=10, out_channels=10, kernel_size=3, stride=2, padding=1)
|
||||||
|
|
||||||
|
self.flatten = nn.Flatten()
|
||||||
|
self.fc1 = nn.Linear(10, 10)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
x = F.relu(self.conv1(x))
|
||||||
|
x = F.relu(self.conv1_s(x))
|
||||||
|
x = F.relu(self.conv2(x))
|
||||||
|
x = F.relu(self.conv2_s(x))
|
||||||
|
x = F.relu(self.conv3(x))
|
||||||
|
x = F.relu(self.conv3_s(x))
|
||||||
|
|
||||||
|
x = self.flatten(x)
|
||||||
|
x = self.fc1(x)
|
||||||
|
x = F.softmax(x)
|
||||||
|
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class PytorchModel(sklearn.base.BaseEstimator):
|
||||||
|
def __init__(self, net_type, net_params, optim_type, optim_params, loss_fn,
|
||||||
|
input_shape, batch_size=32, accuracy_tol=0.02, tol_epochs=10,
|
||||||
|
cuda=True):
|
||||||
|
self.classes_ = None
|
||||||
|
self.optim = None
|
||||||
|
self.net = None
|
||||||
|
self.net_type = net_type
|
||||||
|
self.net_params = net_params
|
||||||
|
self.optim_type = optim_type
|
||||||
|
self.optim_params = optim_params
|
||||||
|
self.loss_fn = loss_fn
|
||||||
|
|
||||||
|
self.input_shape = input_shape
|
||||||
|
self.batch_size = batch_size
|
||||||
|
self.accuracy_tol = accuracy_tol
|
||||||
|
self.tol_epochs = tol_epochs
|
||||||
|
self.cuda = cuda
|
||||||
|
|
||||||
|
def fit(self, X, y):
|
||||||
|
self.net = self.net_type(**self.net_params)
|
||||||
|
if self.cuda:
|
||||||
|
self.net = self.net.cuda()
|
||||||
|
self.optim = self.optim_type(self.net.parameters(), **self.optim_params)
|
||||||
|
|
||||||
|
uniq_classes = np.sort(np.unique(y))
|
||||||
|
self.classes_ = uniq_classes
|
||||||
|
|
||||||
|
X = X.reshape(-1, *self.input_shape)
|
||||||
|
x_tensor = torch.tensor(X.astype(np.float32))
|
||||||
|
y_tensor = torch.tensor(y.astype(np.long))
|
||||||
|
train_dataset = TensorDataset(x_tensor, y_tensor)
|
||||||
|
train_loader = DataLoader(train_dataset, batch_size=self.batch_size,
|
||||||
|
shuffle=True, drop_last=False)
|
||||||
|
last_accuracies = []
|
||||||
|
epoch = 0
|
||||||
|
keep_training = True
|
||||||
|
while keep_training:
|
||||||
|
self.net.train()
|
||||||
|
train_samples_count = 0
|
||||||
|
true_train_samples_count = 0
|
||||||
|
|
||||||
|
for batch in train_loader:
|
||||||
|
x_data, y_data = batch[0], batch[1]
|
||||||
|
if self.cuda:
|
||||||
|
x_data = x_data.cuda()
|
||||||
|
y_data = y_data.cuda()
|
||||||
|
|
||||||
|
y_pred = self.net(x_data)
|
||||||
|
loss = self.loss_fn(y_pred, y_data)
|
||||||
|
|
||||||
|
self.optim.zero_grad()
|
||||||
|
loss.backward()
|
||||||
|
self.optim.step()
|
||||||
|
|
||||||
|
y_pred = y_pred.argmax(dim=1, keepdim=False)
|
||||||
|
true_classified = (y_pred == y_data).sum().item()
|
||||||
|
true_train_samples_count += true_classified
|
||||||
|
train_samples_count += len(x_data)
|
||||||
|
|
||||||
|
train_accuracy = true_train_samples_count / train_samples_count
|
||||||
|
last_accuracies.append(train_accuracy)
|
||||||
|
|
||||||
|
if len(last_accuracies) > self.tol_epochs:
|
||||||
|
last_accuracies.pop(0)
|
||||||
|
|
||||||
|
if len(last_accuracies) == self.tol_epochs:
|
||||||
|
accuracy_difference = max(last_accuracies) - min(last_accuracies)
|
||||||
|
if accuracy_difference <= self.accuracy_tol:
|
||||||
|
keep_training = False
|
||||||
|
|
||||||
|
def predict_proba(self, X, y=None):
|
||||||
|
X = X.reshape(-1, *self.input_shape)
|
||||||
|
x_tensor = torch.tensor(X.astype(np.float32))
|
||||||
|
if y:
|
||||||
|
y_tensor = torch.tensor(y.astype(np.float32))
|
||||||
|
else:
|
||||||
|
y_tensor = torch.zeros(len(X), dtype=torch.long)
|
||||||
|
test_dataset = TensorDataset(x_tensor, y_tensor)
|
||||||
|
test_loader = DataLoader(test_dataset, batch_size=self.batch_size,
|
||||||
|
shuffle=False, drop_last=False)
|
||||||
|
|
||||||
|
self.net.eval()
|
||||||
|
predictions = []
|
||||||
|
for batch in test_loader:
|
||||||
|
x_data, y_data = batch[0], batch[1]
|
||||||
|
if self.cuda:
|
||||||
|
x_data = x_data.cuda()
|
||||||
|
y_data = y_data.cuda()
|
||||||
|
|
||||||
|
y_pred = self.net(x_data)
|
||||||
|
|
||||||
|
predictions.append(y_pred.detach().cpu().numpy())
|
||||||
|
|
||||||
|
predictions = np.concatenate(predictions)
|
||||||
|
return predictions
|
||||||
|
|
||||||
|
def predict(self, x, y=None):
|
||||||
|
predictions = self.predict_proba(x, y)
|
||||||
|
predictions = predictions.argmax(axis=1)
|
||||||
|
return predictions
|
||||||
|
|
||||||
|
|
||||||
|
base_model = PytorchModel(net_type=SimpleCNN, net_params=dict(), optim_type=Adam,
|
||||||
|
optim_params={"lr": 1e-3}, loss_fn=nn.CrossEntropyLoss(),
|
||||||
|
input_shape=(1, 8, 8), batch_size=32, accuracy_tol=0.02,
|
||||||
|
tol_epochs=10, cuda=True)
|
||||||
@ -0,0 +1,154 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256,256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, resized_spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,154 @@
|
|||||||
|
import torchsig.torchsig.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256, 256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, resized_spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,154 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256, 256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, resized_spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,151 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
img = np.array([img2, img3, spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = torch.nn.Sequential(torch.nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
print(model)
|
||||||
|
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,252 @@
|
|||||||
|
import torchsig.transforms.dataset_transforms as transform
|
||||||
|
import torchsig.transforms.functional as F
|
||||||
|
from importlib import import_module
|
||||||
|
from torchvision import models
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_ensemble(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 16
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
|
||||||
|
# if int(ind_inference) <= 1500:
|
||||||
|
# np.save(src + '_inference_1200_' + str(ind_inference) + '.npy', signal)
|
||||||
|
print(0)
|
||||||
|
spectr = np.asarray(F.spectrogram(signal,fft_size=256,fft_stride=256), dtype=np.float32)
|
||||||
|
print('a')
|
||||||
|
print(spectr.shape)
|
||||||
|
print('b')
|
||||||
|
fig1 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
print(1)
|
||||||
|
|
||||||
|
plt.plot(sigr, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig1)
|
||||||
|
print(2)
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigi, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
print(3)
|
||||||
|
|
||||||
|
img = np.array([img1, img2, spectr[:,:figsize[0]*dpi]])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spectr
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del sigr
|
||||||
|
del sigi
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_ensemble(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
model1 = models.resnet18(pretrained=False)
|
||||||
|
model2 = models.resnet50(pretrained=False)
|
||||||
|
model3 = models.resnet101(pretrained=False)
|
||||||
|
|
||||||
|
num_classes = 2
|
||||||
|
|
||||||
|
model1.fc = nn.Linear(model1.fc.in_features, num_classes)
|
||||||
|
model2.fc = nn.Linear(model2.fc.in_features, num_classes)
|
||||||
|
model3.fc = nn.Linear(model3.fc.in_features, num_classes)
|
||||||
|
|
||||||
|
class Ensemble(nn.Module):
|
||||||
|
def __init__(self, model1, model2, model3):
|
||||||
|
super(Ensemble, self).__init__()
|
||||||
|
self.model1 = model1
|
||||||
|
self.model2 = model2
|
||||||
|
self.model3 = model3
|
||||||
|
self.fc = nn.Linear(3 * num_classes, num_classes)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
x1 = self.model1(x)
|
||||||
|
x2 = self.model2(x)
|
||||||
|
x3 = self.model3(x)
|
||||||
|
x = torch.cat((x1, x2, x3), dim=1)
|
||||||
|
x = self.fc(x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
model = Ensemble(model1, model2, model3)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del model1
|
||||||
|
del model2
|
||||||
|
del model3
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_ensemble(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data).cpu(), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
output = output.cpu()
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del img
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_ensemble(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
if int(ind_inference) <= 100:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_mod_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,252 @@
|
|||||||
|
import torchsig.transforms.dataset_transforms as transform
|
||||||
|
import torchsig.transforms.functional as F
|
||||||
|
from importlib import import_module
|
||||||
|
from torchvision import models
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_ensemble(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 16
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
|
||||||
|
# if int(ind_inference) <= 1500:
|
||||||
|
# np.save(src + '_inference_2400_' + str(ind_inference) + '.npy', signal)
|
||||||
|
print(0)
|
||||||
|
spectr = np.asarray(F.spectrogram(signal,fft_size=256,fft_stride=256), dtype=np.float32)
|
||||||
|
print('a')
|
||||||
|
print(spectr.shape)
|
||||||
|
print('b')
|
||||||
|
fig1 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
print(1)
|
||||||
|
|
||||||
|
plt.plot(sigr, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig1)
|
||||||
|
print(2)
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigi, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
print(3)
|
||||||
|
|
||||||
|
img = np.array([img1, img2, spectr[:,:figsize[0]*dpi]])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spectr
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del sigr
|
||||||
|
del sigi
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_ensemble(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
model1 = models.resnet18(pretrained=False)
|
||||||
|
model2 = models.resnet50(pretrained=False)
|
||||||
|
model3 = models.resnet101(pretrained=False)
|
||||||
|
|
||||||
|
num_classes = 2
|
||||||
|
|
||||||
|
model1.fc = nn.Linear(model1.fc.in_features, num_classes)
|
||||||
|
model2.fc = nn.Linear(model2.fc.in_features, num_classes)
|
||||||
|
model3.fc = nn.Linear(model3.fc.in_features, num_classes)
|
||||||
|
|
||||||
|
class Ensemble(nn.Module):
|
||||||
|
def __init__(self, model1, model2, model3):
|
||||||
|
super(Ensemble, self).__init__()
|
||||||
|
self.model1 = model1
|
||||||
|
self.model2 = model2
|
||||||
|
self.model3 = model3
|
||||||
|
self.fc = nn.Linear(3 * num_classes, num_classes)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
x1 = self.model1(x)
|
||||||
|
x2 = self.model2(x)
|
||||||
|
x3 = self.model3(x)
|
||||||
|
x = torch.cat((x1, x2, x3), dim=1)
|
||||||
|
x = self.fc(x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
model = Ensemble(model1, model2, model3)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del model1
|
||||||
|
del model2
|
||||||
|
del model3
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_ensemble(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data).cpu(), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
output = output.cpu()
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del img
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_ensemble(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
if int(ind_inference) <= 100:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_mod_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,252 @@
|
|||||||
|
import torchsig.transforms.dataset_transforms as transform
|
||||||
|
import torchsig.transforms.functional as F
|
||||||
|
from importlib import import_module
|
||||||
|
from torchvision import models
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_ensemble(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 16
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
|
||||||
|
# if int(ind_inference) <= 1500:
|
||||||
|
# np.save(src + '_inference_915_' + str(ind_inference) + '.npy', signal)
|
||||||
|
print(0)
|
||||||
|
spectr = np.asarray(F.spectrogram(signal,fft_size=256,fft_stride=256), dtype=np.float32)
|
||||||
|
print('a')
|
||||||
|
print(spectr.shape)
|
||||||
|
print('b')
|
||||||
|
fig1 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
print(1)
|
||||||
|
|
||||||
|
plt.plot(sigr, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig1)
|
||||||
|
print(2)
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigi, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
print(3)
|
||||||
|
|
||||||
|
img = np.array([img1, img2, spectr[:,:figsize[0]*dpi]])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spectr
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del sigr
|
||||||
|
del sigi
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_ensemble(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
model1 = models.resnet18(pretrained=False)
|
||||||
|
model2 = models.resnet50(pretrained=False)
|
||||||
|
model3 = models.resnet101(pretrained=False)
|
||||||
|
|
||||||
|
num_classes = 2
|
||||||
|
|
||||||
|
model1.fc = nn.Linear(model1.fc.in_features, num_classes)
|
||||||
|
model2.fc = nn.Linear(model2.fc.in_features, num_classes)
|
||||||
|
model3.fc = nn.Linear(model3.fc.in_features, num_classes)
|
||||||
|
|
||||||
|
class Ensemble(nn.Module):
|
||||||
|
def __init__(self, model1, model2, model3):
|
||||||
|
super(Ensemble, self).__init__()
|
||||||
|
self.model1 = model1
|
||||||
|
self.model2 = model2
|
||||||
|
self.model3 = model3
|
||||||
|
self.fc = nn.Linear(3 * num_classes, num_classes)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
x1 = self.model1(x)
|
||||||
|
x2 = self.model2(x)
|
||||||
|
x3 = self.model3(x)
|
||||||
|
x = torch.cat((x1, x2, x3), dim=1)
|
||||||
|
x = self.fc(x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
model = Ensemble(model1, model2, model3)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del model1
|
||||||
|
del model2
|
||||||
|
del model3
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_ensemble(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data).cpu(), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
output = output.cpu()
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del img
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_ensemble(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
if int(ind_inference) <= 100:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_mod_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,163 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256, 256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, resized_spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(2, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=5, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,163 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256, 256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, resized_spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(3, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=5, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img)
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,208 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (8, 8)
|
||||||
|
dpi = 32
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=256)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256, 256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
# resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, spectr])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spec
|
||||||
|
del spectr
|
||||||
|
del real
|
||||||
|
del mag
|
||||||
|
del buf2
|
||||||
|
del img_arr2
|
||||||
|
del img2
|
||||||
|
del buf3
|
||||||
|
del img_arr3
|
||||||
|
del img3
|
||||||
|
del resized_real
|
||||||
|
del resized_mag
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(3, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=5, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,163 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 64
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=1024)
|
||||||
|
spectr = np.array(spec(signal)[:, :figsize[0] * dpi])
|
||||||
|
mag = np.abs(signal)
|
||||||
|
real = signal.real
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(real, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf2 = io.BytesIO()
|
||||||
|
fig2.savefig(buf2, format="png", dpi=dpi)
|
||||||
|
buf2.seek(0)
|
||||||
|
img_arr2 = np.frombuffer(buf2.getvalue(), dtype=np.uint8)
|
||||||
|
buf2.close()
|
||||||
|
img2 = cv2.imdecode(img_arr2, 1)
|
||||||
|
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
fig3 = plt.figure(figsize=figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
|
||||||
|
plt.plot(mag, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
||||||
|
plt.margins(0, 0)
|
||||||
|
buf3 = io.BytesIO()
|
||||||
|
fig3.savefig(buf3, format="png", dpi=dpi)
|
||||||
|
buf3.seek(0)
|
||||||
|
img_arr3 = np.frombuffer(buf3.getvalue(), dtype=np.uint8)
|
||||||
|
buf3.close()
|
||||||
|
img3 = cv2.imdecode(img_arr3, 1)
|
||||||
|
img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig3)
|
||||||
|
|
||||||
|
resize = (256, 256)
|
||||||
|
resized_real = cv2.resize(img2, resize)
|
||||||
|
resized_mag = cv2.resize(img3, resize)
|
||||||
|
resized_spectr = cv2.resize(spectr, resize)
|
||||||
|
img = np.array([resized_real, resized_mag, resized_spectr])
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(3, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=5, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,216 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
import torchsig.transforms.functional as F
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (16, 16)
|
||||||
|
dpi = 16
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
|
||||||
|
# if int(ind_inference) <= 1500:
|
||||||
|
# np.save(src + '_inference_2400_' + str(ind_inference) + '.npy', signal)
|
||||||
|
print(0)
|
||||||
|
spectr = np.asarray(F.spectrogram(signal,fft_size=256,fft_stride=256), dtype=np.float32)
|
||||||
|
print('a')
|
||||||
|
print(spectr.shape)
|
||||||
|
print('b')
|
||||||
|
fig1 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
print(1)
|
||||||
|
|
||||||
|
plt.plot(sigr, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig1)
|
||||||
|
print(2)
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigi, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
print(3)
|
||||||
|
|
||||||
|
img = np.array([img1, img2, spectr[:,:figsize[0]*dpi]])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spectr
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del sigr
|
||||||
|
del sigi
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(3, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=16, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.5, inplace=False),
|
||||||
|
nn.Linear(in_features=16, out_features=3, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,206 @@
|
|||||||
|
import torchsig.transforms.transforms as transform
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (8, 8)
|
||||||
|
dpi = 32
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
spec = transform.Spectrogram(nperseg=256)
|
||||||
|
spectr = np.array(spec(signal)[:,:figsize[0] * dpi])
|
||||||
|
fig1 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigr, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig1)
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigi, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
img = np.array([img1, img2, spectr])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spec
|
||||||
|
del spectr
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del sigr
|
||||||
|
del sigi
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(3, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.7, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.7, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=16, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.7, inplace=False),
|
||||||
|
nn.Linear(in_features=16, out_features=3, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
@ -0,0 +1,208 @@
|
|||||||
|
import torchsig.transforms.dataset_transforms as transform
|
||||||
|
import torchsig.transforms.functional as F
|
||||||
|
from importlib import import_module
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn as nn
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import mlconfig
|
||||||
|
import torch
|
||||||
|
import cv2
|
||||||
|
import gc
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def pre_func_resnet18(data=None, src ='', ind_inference=0):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
figsize = (8, 8)
|
||||||
|
dpi = 32
|
||||||
|
|
||||||
|
signal = np.vectorize(complex)(data[0], data[1])
|
||||||
|
np.save(src + '_inference_' + str(ind_inference) + '.npy', signal)
|
||||||
|
spec = transform.Spectrogram(nperseg=256, fft_size=32)
|
||||||
|
spectr = np.array(spec(signal)[:,:figsize[0] * dpi])
|
||||||
|
fig1 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigr, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf1 = io.BytesIO()
|
||||||
|
fig1.savefig(buf1, format="png", dpi=dpi)
|
||||||
|
buf1.seek(0)
|
||||||
|
img_arr1 = np.frombuffer(buf1.getvalue(), dtype=np.uint8)
|
||||||
|
buf1.close()
|
||||||
|
img1 = cv2.imdecode(img_arr1, 1)
|
||||||
|
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig1)
|
||||||
|
|
||||||
|
fig2 = plt.figure(figsize = figsize)
|
||||||
|
plt.axes(ylim=(-1, 1))
|
||||||
|
sigr = signal.real
|
||||||
|
sigi = signal.imag
|
||||||
|
|
||||||
|
plt.plot(sigi, color='black')
|
||||||
|
plt.gca().set_axis_off()
|
||||||
|
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
|
||||||
|
plt.margins(0,0)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig2.savefig(buf, format="png", dpi=dpi)
|
||||||
|
buf.seek(0)
|
||||||
|
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
|
||||||
|
buf.close()
|
||||||
|
img = cv2.imdecode(img_arr, 1)
|
||||||
|
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
img = np.array([img1, img2, spectr])
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
del signal
|
||||||
|
del spec
|
||||||
|
del spectr
|
||||||
|
del img1
|
||||||
|
del img2
|
||||||
|
del sigr
|
||||||
|
del sigi
|
||||||
|
del buf
|
||||||
|
del buf1
|
||||||
|
del img_arr
|
||||||
|
del img_arr1
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Подготовка данных завершена')
|
||||||
|
print()
|
||||||
|
return img
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_func_resnet18(file_model='', file_config='', num_classes=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
config = mlconfig.load(file_config)
|
||||||
|
model = getattr(import_module(config.model.architecture.rsplit('.', maxsplit=1)[0]),
|
||||||
|
config.model.architecture.rsplit('.', maxsplit=1)[1])()
|
||||||
|
model.conv1 = nn.Sequential(nn.Conv2d(3, 3, kernel_size=(7, 7), stride=(2, 2),
|
||||||
|
padding=(3, 3), bias=False), model.conv1)
|
||||||
|
model.fc = nn.Sequential(
|
||||||
|
nn.Linear(in_features=512, out_features=128, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.7, inplace=False),
|
||||||
|
nn.Linear(in_features=128, out_features=32, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.7, inplace=False),
|
||||||
|
nn.Linear(in_features=32, out_features=16, bias=True),
|
||||||
|
nn.ReLU(inplace=True),
|
||||||
|
nn.Dropout(p=0.7, inplace=False),
|
||||||
|
nn.Linear(in_features=16, out_features=3, bias=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
if device != 'cpu':
|
||||||
|
model = model.to(device)
|
||||||
|
model.load_state_dict(torch.load(file_model, map_location=device))
|
||||||
|
model.eval()
|
||||||
|
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Инициализация модели завершена')
|
||||||
|
print()
|
||||||
|
return model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inference_func_resnet18(data=None, model=None, mapping=None, shablon=''):
|
||||||
|
try:
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||||
|
img = torch.unsqueeze(torch.tensor(data), 0).to(device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
output = model(img.float())
|
||||||
|
_, predict = torch.max(output.data, 1)
|
||||||
|
prediction = mapping[int(np.asarray(predict.cpu())[0])]
|
||||||
|
print('PREDICTION' + shablon + ': ' + prediction)
|
||||||
|
|
||||||
|
label = np.asarray(np.argmax(output, axis=1))[0]
|
||||||
|
output = np.asarray(torch.squeeze(output, 0))
|
||||||
|
expon = np.exp(output - np.max(output))
|
||||||
|
probability = round((expon / expon.sum())[label], 2)
|
||||||
|
|
||||||
|
del label
|
||||||
|
del expon
|
||||||
|
del output
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
print('Уверенность' + shablon + ' в предсказании: ' + str(probability))
|
||||||
|
|
||||||
|
print('Инференс завершен')
|
||||||
|
print()
|
||||||
|
return [prediction, probability]
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def post_func_resnet18(src='', model_type='', prediction='', model_id=0, ind_inference=0, data=None):
|
||||||
|
try:
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[0], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_real_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[1], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_imag_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
fig, ax = plt.subplots()
|
||||||
|
ax.imshow(data[2], cmap='gray')
|
||||||
|
plt.savefig(src + '_inference_' + str(ind_inference) + '_' + prediction + '_spec_' + str(
|
||||||
|
model_id) + '_' + model_type + '.png')
|
||||||
|
plt.clf()
|
||||||
|
plt.cla()
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
del fig
|
||||||
|
del ax
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
print('Постобработка завершена')
|
||||||
|
print()
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
return None
|
||||||
Binary file not shown.
@ -0,0 +1,312 @@
|
|||||||
|
from flask import Flask, request, jsonify
|
||||||
|
from dotenv import dotenv_values
|
||||||
|
from common.runtime import load_root_env, validate_env, as_int, as_str
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from Model import Model
|
||||||
|
import numpy as np
|
||||||
|
import matplotlib
|
||||||
|
import importlib
|
||||||
|
import threading
|
||||||
|
import requests
|
||||||
|
import asyncio
|
||||||
|
import shutil
|
||||||
|
import json
|
||||||
|
import gc
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
queue = asyncio.Queue()
|
||||||
|
semaphore = asyncio.Semaphore(3)
|
||||||
|
|
||||||
|
prediction_list = []
|
||||||
|
result_msg = {}
|
||||||
|
results = []
|
||||||
|
matplotlib.use('Agg')
|
||||||
|
plt.ioff()
|
||||||
|
|
||||||
|
alg_list = []
|
||||||
|
model_list = []
|
||||||
|
ROOT_ENV = load_root_env(__file__)
|
||||||
|
validate_env("NN_server/server.py", {
|
||||||
|
"GENERAL_SERVER_IP": as_str,
|
||||||
|
"GENERAL_SERVER_PORT": as_int,
|
||||||
|
"SERVER_IP": as_str,
|
||||||
|
"SERVER_PORT": as_int,
|
||||||
|
"PATH_TO_NN": as_str,
|
||||||
|
"SRC_RESULT": as_str,
|
||||||
|
"SRC_EXAMPLE": as_str,
|
||||||
|
})
|
||||||
|
config = dict(dotenv_values(ROOT_ENV))
|
||||||
|
|
||||||
|
if not config:
|
||||||
|
raise RuntimeError("[NN_server/server.py] .env was loaded but no keys were parsed")
|
||||||
|
if not any(key.startswith("NN_") for key in config):
|
||||||
|
raise RuntimeError("[NN_server/server.py] no NN_* model entries configured")
|
||||||
|
logging.info("NN config loaded from %s", ROOT_ENV)
|
||||||
|
gen_server_ip = config['GENERAL_SERVER_IP']
|
||||||
|
gen_server_port = config['GENERAL_SERVER_PORT']
|
||||||
|
|
||||||
|
def init_data_for_inference():
|
||||||
|
try:
|
||||||
|
if os.path.isdir(config['SRC_RESULT']):
|
||||||
|
shutil.rmtree(config['SRC_RESULT'])
|
||||||
|
os.mkdir(config['SRC_RESULT'])
|
||||||
|
if os.path.isdir(config['SRC_EXAMPLE']):
|
||||||
|
shutil.rmtree(config['SRC_EXAMPLE'])
|
||||||
|
os.mkdir(config['SRC_EXAMPLE'])
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
print()
|
||||||
|
|
||||||
|
try:
|
||||||
|
global model_list
|
||||||
|
for key in config.keys():
|
||||||
|
if key.startswith('NN_'):
|
||||||
|
params = config[key].split(' && ')
|
||||||
|
module = importlib.import_module('Models.' + params[4])
|
||||||
|
classes = {}
|
||||||
|
for value in params[9][1:-1].split(','):
|
||||||
|
classes[len(classes)] = value
|
||||||
|
model = Model(file_model=params[0], file_config=params[1], src_example=params[2], src_result=params[3],
|
||||||
|
type_model=params[4], build_model_func=getattr(module, params[5]),
|
||||||
|
pre_func=getattr(module, params[6]), inference_func=getattr(module, params[7]),
|
||||||
|
post_func=getattr(module, params[8]), classes=classes, number_synthetic_examples=int(params[10]),
|
||||||
|
number_src_data_for_one_synthetic_example=int(params[11]), path_to_src_dataset=params[12])
|
||||||
|
model_list.append(model)
|
||||||
|
# if key.startswith('ALG_'):
|
||||||
|
# params = config[key].split(' && ')
|
||||||
|
# module = importlib.import_module('Algorithms.' + params[2])
|
||||||
|
# classes = {}
|
||||||
|
# for value in params[6][1:-1].split(','):
|
||||||
|
# classes[len(classes)] = value
|
||||||
|
# alg = Algorithm(src_example=params[0], src_result=params[1], type_alg=params[2], pre_func=getattr(module, params[3]),
|
||||||
|
# inference_func=getattr(module, params[4]), post_func=getattr(module, params[5]), classes=classes,
|
||||||
|
# number_synthetic_examples=int(params[7]), number_src_data_for_one_synthetic_example=int(params[8]), path_to_src_dataset=params[9])
|
||||||
|
# alg_list.append(alg)
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
def run_example():
|
||||||
|
try:
|
||||||
|
for model in model_list:
|
||||||
|
model.get_test_inference()
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/receive_data', methods=['POST'])
|
||||||
|
def receive_data():
|
||||||
|
try:
|
||||||
|
print()
|
||||||
|
data = json.loads(request.json)
|
||||||
|
print('#' * 100)
|
||||||
|
print('Получен пакет ' + str(Model.get_ind_inference()))
|
||||||
|
freq = int(data['freq'])
|
||||||
|
print('Частота: ' + str(freq))
|
||||||
|
# print('Канал: ' + str(data['channel']))
|
||||||
|
|
||||||
|
result_msg = {}
|
||||||
|
data_to_send = {}
|
||||||
|
prediction_list = []
|
||||||
|
for model in model_list:
|
||||||
|
if str(freq) in model.get_model_name():
|
||||||
|
print('-' * 100)
|
||||||
|
print(str(model))
|
||||||
|
result_msg[str(model.get_model_name())] = {'freq': freq}
|
||||||
|
prediction, probability = model.get_inference([np.asarray(data['data_real'], dtype=np.float32), np.asarray(data['data_imag'], dtype=np.float32)])
|
||||||
|
result_msg[str(model.get_model_name())]['prediction'] = prediction
|
||||||
|
result_msg[str(model.get_model_name())]['probability'] = str(probability)
|
||||||
|
prediction_list.append(prediction)
|
||||||
|
print('-' * 100)
|
||||||
|
print()
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = 0
|
||||||
|
if (int(freq) == 2400 and (prediction_list[0] in ['drone', 'drone_noise'] or (prediction_list[0] == 'wifi' and float(probability) >= 0.95))) or (int(freq) == 1200 and (prediction_list[0] in ['drone'] and float(probability) >= 0.95)):
|
||||||
|
result += 8
|
||||||
|
if int(freq) in [915]:
|
||||||
|
result = 0
|
||||||
|
if int(freq) in []:
|
||||||
|
result = 8
|
||||||
|
data_to_send={
|
||||||
|
'freq': str(freq),
|
||||||
|
'amplitude': result
|
||||||
|
#'triggered': False if result < 7 else True,
|
||||||
|
#'light_len': result
|
||||||
|
}
|
||||||
|
response = requests.post("http://{0}:{1}/process_data".format(gen_server_ip, gen_server_port), json=data_to_send)
|
||||||
|
if response.status_code == 200:
|
||||||
|
print("Данные успешно отправлены!")
|
||||||
|
print("Частота: " + str(freq))
|
||||||
|
print("Отправлено светодиодов: " + str(result))
|
||||||
|
else:
|
||||||
|
print("Ошибка при отправке данных: ", response.status_code)
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
break
|
||||||
|
|
||||||
|
Model.get_inc_ind_inference()
|
||||||
|
print()
|
||||||
|
print('#' * 100)
|
||||||
|
|
||||||
|
for alg in alg_list:
|
||||||
|
print('-' * 100)
|
||||||
|
print(str(alg))
|
||||||
|
alg.get_inference([np.asarray(data['data_real'], dtype=np.float32), np.asarray(data['data_imag'], dtype=np.float32)])
|
||||||
|
print('-' * 100)
|
||||||
|
print()
|
||||||
|
|
||||||
|
#Algorithm.get_inc_ind_inference()
|
||||||
|
print()
|
||||||
|
print('#' * 100)
|
||||||
|
|
||||||
|
del data
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
return jsonify(result_msg)
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
def run_flask():
|
||||||
|
app.run(host=config['SERVER_IP'], port=int(config['SERVER_PORT']))
|
||||||
|
|
||||||
|
|
||||||
|
async def process_tasks():
|
||||||
|
workers = [asyncio.create_task(worker(queue=queue, semaphore=semaphore)) for _ in range(2)]
|
||||||
|
await asyncio.gather(*workers)
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
asyncio.create_task(process_tasks())
|
||||||
|
|
||||||
|
flask_thread = threading.Thread(target=run_flask)
|
||||||
|
flask_thread.start()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
if queue.qsize() <= 1:
|
||||||
|
asyncio.create_task(process_tasks())
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/receive_data', methods=['POST'])
|
||||||
|
def add_task():
|
||||||
|
queue_size = queue.qsize()
|
||||||
|
if queue_size > 1:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
print()
|
||||||
|
data = json.loads(request.json)
|
||||||
|
print('#' * 100)
|
||||||
|
print('Получен пакет ' + str(Model.get_ind_inference()))
|
||||||
|
freq = int(data['freq'])
|
||||||
|
print('Частота ' + str(freq))
|
||||||
|
|
||||||
|
|
||||||
|
result_msg = {}
|
||||||
|
for model in model_list:
|
||||||
|
if str(freq) in model.get_model_name():
|
||||||
|
print('-' * 100)
|
||||||
|
print(str(model))
|
||||||
|
result_msg[str(model.get_model_name())] = {'freq': freq}
|
||||||
|
asyncio.run_coroutine_threadsafe(queue.put({'freq': freq, 'model': model, 'data': data}), loop)
|
||||||
|
do_inference(model=model, data=data, freq=freq)
|
||||||
|
break
|
||||||
|
|
||||||
|
del data
|
||||||
|
gc.collect()
|
||||||
|
return jsonify(result_msg)
|
||||||
|
|
||||||
|
|
||||||
|
async def worker(queue, semaphore):
|
||||||
|
while True:
|
||||||
|
task = await queue.get()
|
||||||
|
if task is None:
|
||||||
|
break
|
||||||
|
async with semaphore:
|
||||||
|
try:
|
||||||
|
await do_inference(model=task['model'], data=task['data'], freq=task['freq'])
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(results)
|
||||||
|
queue.task_done()
|
||||||
|
|
||||||
|
|
||||||
|
async def do_inference(model=None, data=None, freq=0):
|
||||||
|
prediction_list = []
|
||||||
|
print("Длина очереди" + str(queue.qsize()))
|
||||||
|
inference(model=model, data=data, freq=freq)
|
||||||
|
|
||||||
|
try:
|
||||||
|
results = []
|
||||||
|
for pred in prediction_list:
|
||||||
|
if pred[1] == 'drone':
|
||||||
|
results.append([pred[0],8])
|
||||||
|
else:
|
||||||
|
results.append([pred[0],0])
|
||||||
|
for result in results:
|
||||||
|
try:
|
||||||
|
data_to_send={
|
||||||
|
'freq': result[0],
|
||||||
|
'amplitude': result[1],
|
||||||
|
'triggered': False if result[1] < 7 else True,
|
||||||
|
'light_len': result[1]
|
||||||
|
}
|
||||||
|
response = requests.post("http://{0}:{1}/process_data".format(gen_server_ip, gen_server_port), json=data_to_send)
|
||||||
|
await response.text
|
||||||
|
if response.status_code == 200:
|
||||||
|
print("Данные успешно отправлены!")
|
||||||
|
print("Отправлено светодиодов: " + str(data_to_send['light_len']))
|
||||||
|
else:
|
||||||
|
print("Ошибка при отправке данных: ", response.status_code)
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
|
||||||
|
Model.get_inc_ind_inference()
|
||||||
|
print()
|
||||||
|
print('#' * 100)
|
||||||
|
|
||||||
|
del data
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
|
||||||
|
def inference(model=None, data=None, freq=0):
|
||||||
|
prediction, probability = model.get_inference([np.asarray(data['data_real'], dtype=np.float32), np.asarray(data['data_imag'], dtype=np.float32)])
|
||||||
|
result_msg[str(model.get_model_name())]['prediction'] = prediction
|
||||||
|
result_msg[str(model.get_model_name())]['probability'] = str(probability)
|
||||||
|
queue_size = queue.qsize()
|
||||||
|
print(queue_size)
|
||||||
|
prediction_list.append([freq, prediction])
|
||||||
|
print('-' * 100)
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
init_data_for_inference()
|
||||||
|
#asyncio.run(main)
|
||||||
|
loop.run_until_complete(main())
|
||||||
|
'''
|
||||||
|
|
||||||
|
def run_flask():
|
||||||
|
print(config['SERVER_IP'])
|
||||||
|
app.run(host=config['SERVER_IP'], port=int(config['SERVER_PORT']))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
init_data_for_inference()
|
||||||
|
|
||||||
|
flask_thread = threading.Thread(target=run_flask)
|
||||||
|
flask_thread.start()
|
||||||
|
|
||||||
|
#app.run(host=config['SERVER_IP'], port=int(config['SERVER_PORT']))
|
||||||
@ -0,0 +1 @@
|
|||||||
|
"""Shared runtime helpers for DroneDetector."""
|
||||||
@ -0,0 +1,99 @@
|
|||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable, Dict, Any
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
||||||
|
class EnvValidationError(RuntimeError):
|
||||||
|
"""Raised when required environment variables are missing or malformed."""
|
||||||
|
|
||||||
|
|
||||||
|
def load_root_env(file_path: str) -> Path:
|
||||||
|
"""Load repository root .env by walking up from file_path."""
|
||||||
|
start = Path(file_path).resolve()
|
||||||
|
for parent in [start.parent, *start.parents]:
|
||||||
|
env_file = parent / ".env"
|
||||||
|
if env_file.exists():
|
||||||
|
load_dotenv(env_file, override=True)
|
||||||
|
return env_file
|
||||||
|
raise EnvValidationError(f"Root .env was not found for {file_path}")
|
||||||
|
|
||||||
|
|
||||||
|
def as_int(raw: str) -> int:
|
||||||
|
return int(str(raw).strip())
|
||||||
|
|
||||||
|
|
||||||
|
def as_float(raw: str) -> float:
|
||||||
|
return float(str(raw).strip())
|
||||||
|
|
||||||
|
|
||||||
|
def as_str(raw: str) -> str:
|
||||||
|
value = str(raw).strip()
|
||||||
|
if value.startswith("\"") and value.endswith("\""):
|
||||||
|
value = value[1:-1]
|
||||||
|
if value.startswith("'") and value.endswith("'"):
|
||||||
|
value = value[1:-1]
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def as_bool(raw: str) -> bool:
|
||||||
|
value = as_str(raw).lower()
|
||||||
|
if value in {"1", "true", "yes", "y", "on"}:
|
||||||
|
return True
|
||||||
|
if value in {"0", "false", "no", "n", "off"}:
|
||||||
|
return False
|
||||||
|
raise ValueError("expected one of 1/0 true/false yes/no on/off")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_env(source: str, schema: Dict[str, Callable[[str], Any]]) -> Dict[str, Any]:
|
||||||
|
"""Validate required env vars against simple caster schema."""
|
||||||
|
values: Dict[str, Any] = {}
|
||||||
|
errors = []
|
||||||
|
|
||||||
|
for key, caster in schema.items():
|
||||||
|
raw = os.getenv(key)
|
||||||
|
if raw is None or str(raw).strip() == "":
|
||||||
|
errors.append(f"{key}: missing")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
values[key] = caster(raw)
|
||||||
|
except Exception as exc: # pragma: no cover - used in runtime only
|
||||||
|
errors.append(f"{key}: invalid value {raw!r} ({exc})")
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
msg = "\n - " + "\n - ".join(errors)
|
||||||
|
raise EnvValidationError(f"[{source}] invalid .env configuration:{msg}")
|
||||||
|
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_hackrf_index(serial_env_key: str, source: str) -> str:
|
||||||
|
"""Resolve HackRF index from expected serial in env."""
|
||||||
|
serial = validate_env(source, {serial_env_key: as_str})[serial_env_key]
|
||||||
|
|
||||||
|
try:
|
||||||
|
output = subprocess.check_output(
|
||||||
|
"lsusb -v -d 1d50:6089 | grep iSerial",
|
||||||
|
shell=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
except subprocess.CalledProcessError as exc:
|
||||||
|
raise EnvValidationError(
|
||||||
|
f"[{source}] could not read HackRF serials via lsusb: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
lines = [line.strip() for line in output.splitlines() if line.strip()]
|
||||||
|
if not lines:
|
||||||
|
raise EnvValidationError(
|
||||||
|
f"[{source}] no HackRF devices found (lsusb returned empty serial list)"
|
||||||
|
)
|
||||||
|
|
||||||
|
serials = [line.split()[-1] for line in lines]
|
||||||
|
if serial not in serials:
|
||||||
|
raise EnvValidationError(
|
||||||
|
f"[{source}] serial {serial!r} not found among connected HackRF devices: {serials}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return str(serials.index(serial))
|
||||||
@ -0,0 +1,34 @@
|
|||||||
|
FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu22.04
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PYTHONPATH=/app
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
python3 \
|
||||||
|
python3-pip \
|
||||||
|
python3-venv \
|
||||||
|
git \
|
||||||
|
libglib2.0-0 \
|
||||||
|
libsm6 \
|
||||||
|
libxext6 \
|
||||||
|
libxrender-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY deploy/requirements/nn_gpu_pinned.txt /tmp/nn_gpu_pinned.txt
|
||||||
|
COPY deploy/requirements/nn_common.txt /tmp/nn_common.txt
|
||||||
|
|
||||||
|
RUN python3 -m pip install --no-cache-dir --upgrade pip && \
|
||||||
|
python3 -m pip install --no-cache-dir -r /tmp/nn_gpu_pinned.txt && \
|
||||||
|
python3 -m pip install --no-cache-dir -r /tmp/nn_common.txt
|
||||||
|
|
||||||
|
COPY . /app
|
||||||
|
|
||||||
|
RUN python3 -m pip install --no-cache-dir -e /app/torchsig
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["python3", "-m", "NN_server.server"]
|
||||||
@ -0,0 +1,20 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PYTHONPATH=/app
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
gcc \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY deploy/requirements/server_to_master.txt /tmp/requirements.txt
|
||||||
|
RUN pip install --no-cache-dir --upgrade pip && \
|
||||||
|
pip install --no-cache-dir -r /tmp/requirements.txt
|
||||||
|
|
||||||
|
COPY . /app
|
||||||
|
|
||||||
|
EXPOSE 5000
|
||||||
|
CMD ["python3", "-m", "src.server_to_master"]
|
||||||
@ -0,0 +1,43 @@
|
|||||||
|
services:
|
||||||
|
dronedetector-server-to-master:
|
||||||
|
container_name: dronedetector-server-to-master
|
||||||
|
build:
|
||||||
|
context: ../..
|
||||||
|
dockerfile: deploy/docker/Dockerfile.server_to_master
|
||||||
|
env_file:
|
||||||
|
- ../../.env
|
||||||
|
environment:
|
||||||
|
- PYTHONPATH=/app
|
||||||
|
working_dir: /app
|
||||||
|
command: ["python3", "-m", "src.server_to_master"]
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "5000:5000"
|
||||||
|
networks:
|
||||||
|
- dronedetector-net
|
||||||
|
|
||||||
|
dronedetector-nn-server:
|
||||||
|
container_name: dronedetector-nn-server
|
||||||
|
build:
|
||||||
|
context: ../..
|
||||||
|
dockerfile: deploy/docker/Dockerfile.nn_server
|
||||||
|
env_file:
|
||||||
|
- ../../.env
|
||||||
|
environment:
|
||||||
|
- PYTHONPATH=/app
|
||||||
|
working_dir: /app
|
||||||
|
command: ["python3", "-m", "NN_server.server"]
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
- dronedetector-server-to-master
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
volumes:
|
||||||
|
- ../../NN_server/result:/app/NN_server/result
|
||||||
|
gpus: all
|
||||||
|
networks:
|
||||||
|
- dronedetector-net
|
||||||
|
|
||||||
|
networks:
|
||||||
|
dronedetector-net:
|
||||||
|
name: dronedetector-net
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
flask==3.1.0
|
||||||
|
python-dotenv==1.0.1
|
||||||
|
numpy==2.1.3
|
||||||
|
matplotlib==3.10.0
|
||||||
|
tqdm==4.67.1
|
||||||
|
requests==2.32.3
|
||||||
|
pyyaml==6.0.2
|
||||||
|
mlconfig==0.3.2
|
||||||
|
scikit-learn==1.6.0
|
||||||
|
torchensemble==0.2.0
|
||||||
|
opencv-python-headless==4.10.0.84
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
--index-url https://download.pytorch.org/whl/cu128
|
||||||
|
--extra-index-url https://pypi.org/simple
|
||||||
|
|
||||||
|
torch==2.10.0+cu128
|
||||||
|
torchvision==0.25.0+cu128
|
||||||
|
torchaudio==2.10.0+cu128
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
python-dotenv==1.0.1
|
||||||
|
numpy==1.26.4
|
||||||
|
requests==2.32.3
|
||||||
|
pysmb==1.2.10
|
||||||
|
pynmea2==1.19.0
|
||||||
|
pyserial==3.5
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
fastapi==0.115.6
|
||||||
|
uvicorn[standard]==0.32.1
|
||||||
|
httpx==0.28.1
|
||||||
|
requests==2.32.3
|
||||||
|
websockets==12.0
|
||||||
|
python-dotenv==1.0.1
|
||||||
@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector Docker Compose Services
|
||||||
|
After=network-online.target docker.service
|
||||||
|
Wants=network-online.target
|
||||||
|
Requires=docker.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
RemainAfterExit=yes
|
||||||
|
ExecStart=/usr/bin/docker compose -f __PROJECT_ROOT__/deploy/docker/docker-compose.yml up -d --build
|
||||||
|
ExecStop=/usr/bin/docker compose -f __PROJECT_ROOT__/deploy/docker/docker-compose.yml down
|
||||||
|
ExecReload=/usr/bin/docker compose -f __PROJECT_ROOT__/deploy/docker/docker-compose.yml up -d --build
|
||||||
|
TimeoutStartSec=0
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 1200 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python orange_scripts/main_1200.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 2400 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python orange_scripts/main_2400.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 3300 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_3300.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 433 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_433.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 4500 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_4500.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 5200 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_5200.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 5800 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_5800.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 750 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_750.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 868 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python src/main_868.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=DroneDetector SDR Scanner 915 MHz
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=__RUN_USER__
|
||||||
|
Group=__RUN_GROUP__
|
||||||
|
WorkingDirectory=__PROJECT_ROOT__
|
||||||
|
EnvironmentFile=__PROJECT_ROOT__/.env
|
||||||
|
Environment=PYTHONPATH=__PROJECT_ROOT__
|
||||||
|
ExecStartPre=/usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
ExecStart=__PROJECT_ROOT__/.venv-sdr/bin/python orange_scripts/main_915.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if ! command -v hackrf_info >/dev/null 2>&1; then
|
||||||
|
echo "[dronedetector-precheck] hackrf_info not found. Install hackrf-tools/hackrf package." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! command -v gnuradio-config-info >/dev/null 2>&1; then
|
||||||
|
echo "[dronedetector-precheck] gnuradio-config-info not found. Install gnuradio." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! python3 -c "import osmosdr" >/dev/null 2>&1; then
|
||||||
|
echo "[dronedetector-precheck] Python module osmosdr not importable." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! hackrf_info 2>/dev/null | grep -q "Found HackRF"; then
|
||||||
|
echo "[dronedetector-precheck] HackRF device was not detected by hackrf_info." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@ -0,0 +1,246 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
COMPOSE_FILE="${PROJECT_ROOT}/deploy/docker/docker-compose.yml"
|
||||||
|
SYSTEMD_TARGET_DIR="/etc/systemd/system"
|
||||||
|
RUN_USER="${SUDO_USER:-${USER}}"
|
||||||
|
RUN_GROUP="$(id -gn "${RUN_USER}")"
|
||||||
|
|
||||||
|
SDR_UNITS=(
|
||||||
|
dronedetector-sdr-433.service
|
||||||
|
dronedetector-sdr-750.service
|
||||||
|
dronedetector-sdr-868.service
|
||||||
|
dronedetector-sdr-3300.service
|
||||||
|
dronedetector-sdr-4500.service
|
||||||
|
dronedetector-sdr-5200.service
|
||||||
|
dronedetector-sdr-5800.service
|
||||||
|
dronedetector-sdr-915.service
|
||||||
|
dronedetector-sdr-1200.service
|
||||||
|
dronedetector-sdr-2400.service
|
||||||
|
)
|
||||||
|
|
||||||
|
log() {
|
||||||
|
printf '[install_all] %s\n' "$*"
|
||||||
|
}
|
||||||
|
|
||||||
|
die() {
|
||||||
|
printf '[install_all] ERROR: %s\n' "$*" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
print_failure_logs() {
|
||||||
|
log "Collecting diagnostics..."
|
||||||
|
systemctl --no-pager --full status dronedetector-compose.service || true
|
||||||
|
for unit in "${SDR_UNITS[@]}"; do
|
||||||
|
systemctl --no-pager --full status "$unit" || true
|
||||||
|
done
|
||||||
|
|
||||||
|
if command -v docker >/dev/null 2>&1; then
|
||||||
|
docker compose -f "$COMPOSE_FILE" ps || true
|
||||||
|
docker compose -f "$COMPOSE_FILE" logs --tail=150 dronedetector-server-to-master || true
|
||||||
|
docker compose -f "$COMPOSE_FILE" logs --tail=150 dronedetector-nn-server || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
journalctl -u dronedetector-compose.service -n 150 --no-pager || true
|
||||||
|
for unit in "${SDR_UNITS[@]}"; do
|
||||||
|
journalctl -u "$unit" -n 120 --no-pager || true
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
trap 'rc=$?; if [[ $rc -ne 0 ]]; then print_failure_logs; fi' EXIT
|
||||||
|
|
||||||
|
require_root() {
|
||||||
|
if [[ "${EUID}" -ne 0 ]]; then
|
||||||
|
log "Switching to root via sudo..."
|
||||||
|
exec sudo -E bash "$0" "$@"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
preflight() {
|
||||||
|
log "Preflight checks"
|
||||||
|
[[ -f "${PROJECT_ROOT}/.env" ]] || die "Missing ${PROJECT_ROOT}/.env"
|
||||||
|
[[ -f "${COMPOSE_FILE}" ]] || die "Missing ${COMPOSE_FILE}"
|
||||||
|
|
||||||
|
if ! command -v apt-get >/dev/null 2>&1; then
|
||||||
|
die "This installer currently supports Debian/Ubuntu only (apt-get required)."
|
||||||
|
fi
|
||||||
|
|
||||||
|
local free_mb
|
||||||
|
free_mb="$(df -Pm "${PROJECT_ROOT}" | awk 'NR==2 {print $4}')"
|
||||||
|
if [[ -z "$free_mb" || "$free_mb" -lt 10240 ]]; then
|
||||||
|
die "At least 10 GB free disk space is required."
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! command -v nvidia-smi >/dev/null 2>&1; then
|
||||||
|
die "nvidia-smi is required. GPU/NVIDIA driver is not available on host."
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "Preflight OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_host_non_python_deps() {
|
||||||
|
log "Installing host non-python dependencies"
|
||||||
|
apt-get update
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
curl \
|
||||||
|
gnupg \
|
||||||
|
lsb-release \
|
||||||
|
jq \
|
||||||
|
git \
|
||||||
|
python3 \
|
||||||
|
python3-pip \
|
||||||
|
python3-venv \
|
||||||
|
build-essential \
|
||||||
|
pkg-config \
|
||||||
|
libusb-1.0-0 \
|
||||||
|
libusb-1.0-0-dev \
|
||||||
|
hackrf \
|
||||||
|
gnuradio \
|
||||||
|
gr-osmosdr
|
||||||
|
}
|
||||||
|
|
||||||
|
setup_sdr_python_env() {
|
||||||
|
log "Setting up SDR python environment"
|
||||||
|
local venv_path="${PROJECT_ROOT}/.venv-sdr"
|
||||||
|
|
||||||
|
if [[ ! -d "$venv_path" ]]; then
|
||||||
|
python3 -m venv --system-site-packages "$venv_path"
|
||||||
|
fi
|
||||||
|
|
||||||
|
"$venv_path/bin/pip" install --upgrade pip
|
||||||
|
"$venv_path/bin/pip" install -r "${PROJECT_ROOT}/deploy/requirements/sdr_host.txt"
|
||||||
|
|
||||||
|
chown -R "${RUN_USER}:${RUN_GROUP}" "$venv_path"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_docker_if_needed() {
|
||||||
|
if command -v docker >/dev/null 2>&1; then
|
||||||
|
log "Docker already installed"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "Installing Docker Engine"
|
||||||
|
. /etc/os-release
|
||||||
|
local distro_id="${ID}"
|
||||||
|
if [[ "$distro_id" != "ubuntu" && "$distro_id" != "debian" ]]; then
|
||||||
|
die "Unsupported distro for Docker auto-install: ${distro_id}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
install -m 0755 -d /etc/apt/keyrings
|
||||||
|
curl -fsSL "https://download.docker.com/linux/${distro_id}/gpg" | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
|
||||||
|
chmod a+r /etc/apt/keyrings/docker.gpg
|
||||||
|
|
||||||
|
echo \
|
||||||
|
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/${distro_id} \
|
||||||
|
${VERSION_CODENAME} stable" | tee /etc/apt/sources.list.d/docker.list >/dev/null
|
||||||
|
apt-get update
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
|
||||||
|
|
||||||
|
systemctl enable --now docker
|
||||||
|
}
|
||||||
|
|
||||||
|
install_nvidia_container_toolkit() {
|
||||||
|
log "Installing/Configuring NVIDIA Container Toolkit"
|
||||||
|
|
||||||
|
if ! dpkg -s nvidia-container-toolkit >/dev/null 2>&1; then
|
||||||
|
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | \
|
||||||
|
gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
|
||||||
|
|
||||||
|
curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
|
||||||
|
sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
|
||||||
|
tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
|
||||||
|
|
||||||
|
apt-get update
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends nvidia-container-toolkit
|
||||||
|
fi
|
||||||
|
|
||||||
|
nvidia-ctk runtime configure --runtime=docker
|
||||||
|
systemctl restart docker
|
||||||
|
}
|
||||||
|
|
||||||
|
build_and_run_compose() {
|
||||||
|
log "Building and starting Docker services"
|
||||||
|
docker compose -f "$COMPOSE_FILE" up -d --build
|
||||||
|
}
|
||||||
|
|
||||||
|
install_systemd_units() {
|
||||||
|
log "Installing systemd units"
|
||||||
|
|
||||||
|
install -m 0755 "${PROJECT_ROOT}/deploy/systemd/precheck-sdr.sh" /usr/local/bin/dronedetector-precheck-sdr.sh
|
||||||
|
|
||||||
|
local src dst
|
||||||
|
for src in "${PROJECT_ROOT}"/deploy/systemd/*.service; do
|
||||||
|
dst="${SYSTEMD_TARGET_DIR}/$(basename "$src")"
|
||||||
|
sed \
|
||||||
|
-e "s|__PROJECT_ROOT__|${PROJECT_ROOT}|g" \
|
||||||
|
-e "s|__RUN_USER__|${RUN_USER}|g" \
|
||||||
|
-e "s|__RUN_GROUP__|${RUN_GROUP}|g" \
|
||||||
|
"$src" > "$dst"
|
||||||
|
done
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable dronedetector-compose.service
|
||||||
|
systemctl restart dronedetector-compose.service
|
||||||
|
|
||||||
|
for unit in "${SDR_UNITS[@]}"; do
|
||||||
|
systemctl enable "$unit"
|
||||||
|
systemctl restart "$unit"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_systemd_active() {
|
||||||
|
local unit="$1"
|
||||||
|
local timeout_seconds="${2:-60}"
|
||||||
|
local i
|
||||||
|
|
||||||
|
for ((i=0; i<timeout_seconds; i++)); do
|
||||||
|
if systemctl is-active --quiet "$unit"; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
verify_installation() {
|
||||||
|
log "Verifying services"
|
||||||
|
|
||||||
|
wait_for_systemd_active dronedetector-compose.service 30 || die "dronedetector-compose.service is not active"
|
||||||
|
for unit in "${SDR_UNITS[@]}"; do
|
||||||
|
wait_for_systemd_active "$unit" 45 || die "$unit is not active"
|
||||||
|
done
|
||||||
|
|
||||||
|
docker compose -f "$COMPOSE_FILE" ps
|
||||||
|
|
||||||
|
local running_services
|
||||||
|
running_services="$(docker compose -f "$COMPOSE_FILE" ps --status running --services || true)"
|
||||||
|
|
||||||
|
printf '%s\n' "$running_services" | grep -Fxq "dronedetector-server-to-master" || die "server_to_master is not running"
|
||||||
|
printf '%s\n' "$running_services" | grep -Fxq "dronedetector-nn-server" || die "NN_server is not running"
|
||||||
|
|
||||||
|
log "Verification completed"
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
require_root "$@"
|
||||||
|
|
||||||
|
log "Project root: ${PROJECT_ROOT}"
|
||||||
|
log "Runtime user: ${RUN_USER}:${RUN_GROUP}"
|
||||||
|
|
||||||
|
preflight
|
||||||
|
install_host_non_python_deps
|
||||||
|
setup_sdr_python_env
|
||||||
|
install_docker_if_needed
|
||||||
|
install_nvidia_container_toolkit
|
||||||
|
build_and_run_compose
|
||||||
|
install_systemd_units
|
||||||
|
verify_installation
|
||||||
|
|
||||||
|
log "SUCCESS: DroneDetector installation completed"
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
@ -0,0 +1,114 @@
|
|||||||
|
from common.runtime import load_root_env, validate_env, as_float, as_int, as_str
|
||||||
|
import numpy as np
|
||||||
|
import requests
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
validate_env("orange_scripts/compose_send_data_1200.py", {
|
||||||
|
"POROG_1200": as_float,
|
||||||
|
"SERVER_IP_2": as_str,
|
||||||
|
"SERVER_PORT_2": as_int,
|
||||||
|
})
|
||||||
|
porog = float(os.getenv('POROG_1200'))
|
||||||
|
server_ip_1 = os.getenv('SERVER_IP_1')
|
||||||
|
server_port_1 = os.getenv('SERVER_PORT_1')
|
||||||
|
server_ip_2 = os.getenv('SERVER_IP_2')
|
||||||
|
server_port_2 = os.getenv('SERVER_PORT_2')
|
||||||
|
PARAMS = {'split_size': 400_000, 'point_amount': 100_000}
|
||||||
|
PARAMS['show_amount'] = 0.8 * PARAMS['point_amount']
|
||||||
|
token = 0
|
||||||
|
channel = 1
|
||||||
|
flag = 0
|
||||||
|
|
||||||
|
##############################
|
||||||
|
# HYPERPARAMETERS
|
||||||
|
##############################
|
||||||
|
f_base = 1.1e9
|
||||||
|
f_step = 20e6
|
||||||
|
f_roof = 1.3e9
|
||||||
|
##############################
|
||||||
|
# Variables
|
||||||
|
##############################
|
||||||
|
f = f_base
|
||||||
|
EOCF = 0
|
||||||
|
signal_arr = []
|
||||||
|
|
||||||
|
|
||||||
|
class NumpyArrayEncoder(json.JSONEncoder):
|
||||||
|
def default(self, obj):
|
||||||
|
if isinstance(obj, np.integer):
|
||||||
|
return int(obj)
|
||||||
|
elif isinstance(obj, np.ndarray):
|
||||||
|
return obj.tolist()
|
||||||
|
else:
|
||||||
|
return super(NumpyArrayEncoder, self).default(obj)
|
||||||
|
|
||||||
|
|
||||||
|
def send_data(sig):
|
||||||
|
try:
|
||||||
|
global token
|
||||||
|
print('#' * 10)
|
||||||
|
print('\nОтправка пакета ' + str(token+1))
|
||||||
|
data_to_send = {
|
||||||
|
"freq": 1200,
|
||||||
|
"channel": int(channel),
|
||||||
|
"token": int(token+1),
|
||||||
|
"data_real": np.asarray(np.array(sig, dtype=np.complex64).real, dtype=np.float32),
|
||||||
|
"data_imag": np.asarray(np.array(sig, dtype=np.complex64).imag, dtype=np.float32)
|
||||||
|
}
|
||||||
|
mod_data_to_send = json.dumps(data_to_send, cls=NumpyArrayEncoder)
|
||||||
|
response = requests.post("http://{0}:{1}/receive_data".format(server_ip_2, server_port_2), json=mod_data_to_send)
|
||||||
|
if response.status_code == 200:
|
||||||
|
token += 1
|
||||||
|
print(response.text)
|
||||||
|
print('#' * 10)
|
||||||
|
else:
|
||||||
|
print("Ошибка при отправке данных: ", response.status_code)
|
||||||
|
print('#' * 10)
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
def median(sig):
|
||||||
|
global flag
|
||||||
|
median = abs(float(np.median(sorted(np.asarray(np.abs(np.array(sig, dtype=np.complex64)), dtype=np.float32))[int(PARAMS['show_amount']):])))
|
||||||
|
flag = 0 if porog > median else 1
|
||||||
|
print(channel, median, flag)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
global flag
|
||||||
|
global channel
|
||||||
|
global f_base
|
||||||
|
global f_step
|
||||||
|
global f_roof
|
||||||
|
global f
|
||||||
|
global EOCF
|
||||||
|
global signal_arr
|
||||||
|
|
||||||
|
y = np.array(lvl).ravel()
|
||||||
|
signal_arr = np.concatenate((signal_arr, y), axis=None)
|
||||||
|
|
||||||
|
if f >= f_roof:
|
||||||
|
f = f_base
|
||||||
|
signal_arr = []
|
||||||
|
channel = 1
|
||||||
|
return f, EOCF
|
||||||
|
else:
|
||||||
|
if flag == 0 and len(signal_arr) >= PARAMS['point_amount']:
|
||||||
|
median(signal_arr[:PARAMS['point_amount']])
|
||||||
|
signal_arr = []
|
||||||
|
if flag == 0:
|
||||||
|
f += f_step
|
||||||
|
channel += 1
|
||||||
|
if len(signal_arr) >= PARAMS['split_size']:
|
||||||
|
send_data(signal_arr[:PARAMS['split_size']])
|
||||||
|
flag = 0
|
||||||
|
signal_arr = []
|
||||||
|
channel += 1
|
||||||
|
f += f_step
|
||||||
|
return f, EOCF
|
||||||
@ -0,0 +1,115 @@
|
|||||||
|
|
||||||
|
from common.runtime import load_root_env, validate_env, as_float, as_int, as_str
|
||||||
|
import numpy as np
|
||||||
|
import requests
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
validate_env("orange_scripts/compose_send_data_2400.py", {
|
||||||
|
"POROG_2400": as_float,
|
||||||
|
"SERVER_IP_2": as_str,
|
||||||
|
"SERVER_PORT_2": as_int,
|
||||||
|
})
|
||||||
|
porog = float(os.getenv('POROG_2400'))
|
||||||
|
server_ip_1 = os.getenv('SERVER_IP_1')
|
||||||
|
server_port_1 = os.getenv('SERVER_PORT_1')
|
||||||
|
server_ip_2 = os.getenv('SERVER_IP_2')
|
||||||
|
server_port_2 = os.getenv('SERVER_PORT_2')
|
||||||
|
PARAMS = {'split_size': 400_000, 'point_amount': 100_000}
|
||||||
|
PARAMS['show_amount'] = 0.8 * PARAMS['point_amount']
|
||||||
|
token = 0
|
||||||
|
channel = 1
|
||||||
|
flag = 0
|
||||||
|
|
||||||
|
##############################
|
||||||
|
# HYPERPARAMETERS
|
||||||
|
##############################
|
||||||
|
f_base = 2.4e9
|
||||||
|
f_step = 20e6
|
||||||
|
f_roof = 2.5e9
|
||||||
|
##############################
|
||||||
|
# Variables
|
||||||
|
##############################
|
||||||
|
f = f_base
|
||||||
|
EOCF = 0
|
||||||
|
signal_arr = []
|
||||||
|
|
||||||
|
|
||||||
|
class NumpyArrayEncoder(json.JSONEncoder):
|
||||||
|
def default(self, obj):
|
||||||
|
if isinstance(obj, np.integer):
|
||||||
|
return int(obj)
|
||||||
|
elif isinstance(obj, np.ndarray):
|
||||||
|
return obj.tolist()
|
||||||
|
else:
|
||||||
|
return super(NumpyArrayEncoder, self).default(obj)
|
||||||
|
|
||||||
|
|
||||||
|
def send_data(sig):
|
||||||
|
try:
|
||||||
|
global token
|
||||||
|
print('#' * 10)
|
||||||
|
print('\nОтправка пакета ' + str(token+1))
|
||||||
|
data_to_send = {
|
||||||
|
"freq": 2400,
|
||||||
|
"channel": int(channel),
|
||||||
|
"token": int(token+1),
|
||||||
|
"data_real": np.asarray(np.array(sig, dtype=np.complex64).real, dtype=np.float32),
|
||||||
|
"data_imag": np.asarray(np.array(sig, dtype=np.complex64).imag, dtype=np.float32)
|
||||||
|
}
|
||||||
|
mod_data_to_send = json.dumps(data_to_send, cls=NumpyArrayEncoder)
|
||||||
|
response = requests.post("http://{0}:{1}/receive_data".format(server_ip_2, server_port_2), json=mod_data_to_send)
|
||||||
|
if response.status_code == 200:
|
||||||
|
token += 1
|
||||||
|
print(response.text)
|
||||||
|
print('#' * 10)
|
||||||
|
else:
|
||||||
|
print("Ошибка при отправке данных: ", response.status_code)
|
||||||
|
print('#' * 10)
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
def median(sig):
|
||||||
|
global flag
|
||||||
|
median = abs(float(np.median(sorted(np.asarray(np.abs(np.array(sig, dtype=np.complex64)), dtype=np.float32))[int(PARAMS['show_amount']):])))
|
||||||
|
flag = 0 if porog > median else 1
|
||||||
|
print(channel, median, flag)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
global flag
|
||||||
|
global channel
|
||||||
|
global f_base
|
||||||
|
global f_step
|
||||||
|
global f_roof
|
||||||
|
global f
|
||||||
|
global EOCF
|
||||||
|
global signal_arr
|
||||||
|
|
||||||
|
y = np.array(lvl).ravel()
|
||||||
|
signal_arr = np.concatenate((signal_arr, y), axis=None)
|
||||||
|
|
||||||
|
if f >= f_roof:
|
||||||
|
f = f_base
|
||||||
|
signal_arr = []
|
||||||
|
channel = 1
|
||||||
|
return f, EOCF
|
||||||
|
else:
|
||||||
|
if flag == 0 and len(signal_arr) >= PARAMS['point_amount']:
|
||||||
|
median(signal_arr[:PARAMS['point_amount']])
|
||||||
|
signal_arr = []
|
||||||
|
if flag == 0:
|
||||||
|
f += f_step
|
||||||
|
channel += 1
|
||||||
|
if len(signal_arr) >= PARAMS['split_size']:
|
||||||
|
send_data(signal_arr[:PARAMS['split_size']])
|
||||||
|
flag = 0
|
||||||
|
signal_arr = []
|
||||||
|
channel += 1
|
||||||
|
f += f_step
|
||||||
|
return f, EOCF
|
||||||
@ -0,0 +1,115 @@
|
|||||||
|
|
||||||
|
from common.runtime import load_root_env, validate_env, as_float, as_int, as_str
|
||||||
|
import numpy as np
|
||||||
|
import requests
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
validate_env("orange_scripts/compose_send_data_915.py", {
|
||||||
|
"POROG_915": as_float,
|
||||||
|
"SERVER_IP_1": as_str,
|
||||||
|
"SERVER_PORT_1": as_int,
|
||||||
|
})
|
||||||
|
porog = float(os.getenv('POROG_915'))
|
||||||
|
server_ip_1 = os.getenv('SERVER_IP_1')
|
||||||
|
server_port_1 = os.getenv('SERVER_PORT_1')
|
||||||
|
server_ip_2 = os.getenv('SERVER_IP_2')
|
||||||
|
server_port_2 = os.getenv('SERVER_PORT_2')
|
||||||
|
PARAMS = {'split_size': 400_000, 'point_amount': 100_000}
|
||||||
|
PARAMS['show_amount'] = 0.8 * PARAMS['point_amount']
|
||||||
|
token = 0
|
||||||
|
channel = 1
|
||||||
|
flag = 0
|
||||||
|
|
||||||
|
##############################
|
||||||
|
# HYPERPARAMETERS
|
||||||
|
##############################
|
||||||
|
f_base = 0.91e9
|
||||||
|
f_step = 20e6
|
||||||
|
f_roof = 0.98e9
|
||||||
|
##############################
|
||||||
|
# Variables
|
||||||
|
##############################
|
||||||
|
f = f_base
|
||||||
|
EOCF = 0
|
||||||
|
signal_arr = []
|
||||||
|
|
||||||
|
|
||||||
|
class NumpyArrayEncoder(json.JSONEncoder):
|
||||||
|
def default(self, obj):
|
||||||
|
if isinstance(obj, np.integer):
|
||||||
|
return int(obj)
|
||||||
|
elif isinstance(obj, np.ndarray):
|
||||||
|
return obj.tolist()
|
||||||
|
else:
|
||||||
|
return super(NumpyArrayEncoder, self).default(obj)
|
||||||
|
|
||||||
|
|
||||||
|
def send_data(sig):
|
||||||
|
try:
|
||||||
|
global token
|
||||||
|
print('#' * 10)
|
||||||
|
print('\nОтправка пакета ' + str(token+1))
|
||||||
|
data_to_send = {
|
||||||
|
"freq": 915,
|
||||||
|
"channel": int(channel),
|
||||||
|
"token": int(token+1),
|
||||||
|
"data_real": np.asarray(np.array(sig, dtype=np.complex64).real, dtype=np.float32),
|
||||||
|
"data_imag": np.asarray(np.array(sig, dtype=np.complex64).imag, dtype=np.float32)
|
||||||
|
}
|
||||||
|
mod_data_to_send = json.dumps(data_to_send, cls=NumpyArrayEncoder)
|
||||||
|
response = requests.post("http://{0}:{1}/receive_data".format(server_ip_1, server_port_1), json=mod_data_to_send)
|
||||||
|
if response.status_code == 200:
|
||||||
|
token += 1
|
||||||
|
print(response.text)
|
||||||
|
print('#' * 10)
|
||||||
|
else:
|
||||||
|
print("Ошибка при отправке данных: ", response.status_code)
|
||||||
|
print('#' * 10)
|
||||||
|
except Exception as exc:
|
||||||
|
print(str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
def median(sig):
|
||||||
|
global flag
|
||||||
|
median = abs(float(np.median(sorted(np.asarray(np.abs(np.array(sig, dtype=np.complex64)), dtype=np.float32))[int(PARAMS['show_amount']):])))
|
||||||
|
flag = 0 if porog > median else 1
|
||||||
|
print(channel, median, flag)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
global flag
|
||||||
|
global channel
|
||||||
|
global f_base
|
||||||
|
global f_step
|
||||||
|
global f_roof
|
||||||
|
global f
|
||||||
|
global EOCF
|
||||||
|
global signal_arr
|
||||||
|
|
||||||
|
y = np.array(lvl).ravel()
|
||||||
|
signal_arr = np.concatenate((signal_arr, y), axis=None)
|
||||||
|
|
||||||
|
if f >= f_roof:
|
||||||
|
f = f_base
|
||||||
|
signal_arr = []
|
||||||
|
channel = 1
|
||||||
|
return f, EOCF
|
||||||
|
else:
|
||||||
|
if flag == 0 and len(signal_arr) >= PARAMS['point_amount']:
|
||||||
|
median(signal_arr[:PARAMS['point_amount']])
|
||||||
|
signal_arr = []
|
||||||
|
if flag == 0:
|
||||||
|
f += f_step
|
||||||
|
channel += 1
|
||||||
|
if len(signal_arr) >= PARAMS['split_size']:
|
||||||
|
send_data(signal_arr[:PARAMS['split_size']])
|
||||||
|
flag = 0
|
||||||
|
signal_arr = []
|
||||||
|
channel += 1
|
||||||
|
f += f_step
|
||||||
|
return f, EOCF
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_3300').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_3300').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_3300').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_433').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_433').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_433').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_4500').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_4500').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_4500').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_5200').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_5200').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_5200').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_5800').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_5800').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_5800').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
@ -0,0 +1,123 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_750').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_750').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_750').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
print(1)
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
print(num_chs, circle_buffer)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
print(3)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from common.runtime import load_root_env, validate_env, as_bool, as_str
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
load_root_env(__file__)
|
||||||
|
freq_suffix = os.path.splitext(os.path.basename(__file__))[0].split("_")[-1]
|
||||||
|
validate_env(__file__, {
|
||||||
|
"send_to_module_flag": as_bool,
|
||||||
|
"save_data_flag": as_bool,
|
||||||
|
"elems_to_save": as_str,
|
||||||
|
"file_types_to_save": as_str,
|
||||||
|
"lochost": as_str,
|
||||||
|
"locport": as_str,
|
||||||
|
"freq_endpoint": as_str,
|
||||||
|
"path_to_save_medians": as_str,
|
||||||
|
"path_to_save_alarms": as_str,
|
||||||
|
"module_name": as_str,
|
||||||
|
f"f_step_{freq_suffix}": as_str,
|
||||||
|
f"f_bases_{freq_suffix}": as_str,
|
||||||
|
f"f_roofs_{freq_suffix}": as_str,
|
||||||
|
})
|
||||||
|
|
||||||
|
debug_flag = as_bool(os.getenv('debug_flag', '0'))
|
||||||
|
send_to_module_flag = as_bool(os.getenv('send_to_module_flag', '0'))
|
||||||
|
save_data_flag = as_bool(os.getenv('save_data_flag', '0'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_868').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_868').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_868').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
freq_endpoint = os.getenv('freq_endpoint')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median = tmp_signal.fill_signal(lvl, signal_length)
|
||||||
|
|
||||||
|
if median:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport, freq_endpoint)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, tmp_signal.get_signal())
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
tmp_signal.clear()
|
||||||
|
|
||||||
|
return f
|
||||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,108 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from DroneScanner.utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from DroneScanner.core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from DroneScanner.core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
dotenv_path = os.path.join(os.path.dirname(__file__), '../../.env')
|
||||||
|
if os.path.exists(dotenv_path):
|
||||||
|
load_dotenv(dotenv_path)
|
||||||
|
|
||||||
|
debug_flag = bool(os.getenv('debug_flag'))
|
||||||
|
send_to_module_flag = bool(os.getenv('send_to_module_flag'))
|
||||||
|
save_data_flag = bool(os.getenv('save_data_flag'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_1200').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_1200').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_1200').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median, signal, abs_signal = tmp_signal.fill_sig(lvl, signal_length)
|
||||||
|
|
||||||
|
if median != -1:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
|
||||||
|
#print(f, freq, num_chs, signal_length)
|
||||||
|
#print(median)
|
||||||
|
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
# print(circle_buffer.get_buffer())
|
||||||
|
# print(circle_buffer.get_medians())
|
||||||
|
# print(circle_buffer.get_alarms())
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, signal, abs_signal)
|
||||||
|
#print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
#else:
|
||||||
|
#print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
return f
|
||||||
@ -0,0 +1,276 @@
|
|||||||
|
|
||||||
|
# this module will be imported in the into your flowgraph
|
||||||
|
import numpy as np
|
||||||
|
import os
|
||||||
|
|
||||||
|
import platform
|
||||||
|
from rknnlite.api import RKNNLite
|
||||||
|
|
||||||
|
import wiringpi as wpi
|
||||||
|
from wiringpi import GPIO
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
||||||
|
dotenv_path = os.path.join(os.path.dirname(__file__), '../../.env')
|
||||||
|
load_dotenv(dotenv_path)
|
||||||
|
##############################
|
||||||
|
# wiringPi
|
||||||
|
##############################
|
||||||
|
|
||||||
|
wpi.wiringPiSetup()
|
||||||
|
|
||||||
|
##############################
|
||||||
|
# RKNN
|
||||||
|
##############################
|
||||||
|
|
||||||
|
DEVICE_COMPATIBLE_NODE = '/proc/device-tree/compatible'
|
||||||
|
|
||||||
|
RK3588_MODEL = {
|
||||||
|
'path': os.getenv('path_to_NN'),
|
||||||
|
'model': None,
|
||||||
|
'split_size': 50_000,
|
||||||
|
'N_predictions': 40,
|
||||||
|
'N_samples_confidence_threshold': 0.65,
|
||||||
|
}
|
||||||
|
|
||||||
|
RK3588_MODEL['model'] = RKNNLite()
|
||||||
|
|
||||||
|
try:
|
||||||
|
ret1 = RK3588_MODEL['model'].load_rknn(RK3588_MODEL['path'])
|
||||||
|
assert(ret1 == 0)
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
|
||||||
|
ret2 = RK3588_MODEL['model'].init_runtime(core_mask=RKNNLite.NPU_CORE_0)
|
||||||
|
assert(ret2 == 0)
|
||||||
|
|
||||||
|
##############################
|
||||||
|
# HYPERPARAMETERS
|
||||||
|
##############################
|
||||||
|
|
||||||
|
f_base = 2.48e9
|
||||||
|
f_step = -10e6
|
||||||
|
f_roof = 2.4e9
|
||||||
|
|
||||||
|
signal_num = 10
|
||||||
|
#signal_dir = '/home/orangepi/CDD/Complex_DroneDetection/gnuradio/signal/'
|
||||||
|
#if not os.path.exists(signal_dir):
|
||||||
|
# os.mkdir(signal_dir)
|
||||||
|
|
||||||
|
|
||||||
|
reading_signal_delay = 0
|
||||||
|
iterations = 3 # read signal iterations
|
||||||
|
height_threshold = 100
|
||||||
|
|
||||||
|
weak_avg_amount = 70
|
||||||
|
weak_samples_confidence = 0.50
|
||||||
|
#classes = {0: 'noise', 1: 'DJI', 2: 'other', 3: 'for weak'}
|
||||||
|
classes = {0: 'noise', 1: 'DJI_video', 2: 'DJI_control', 3: 'WIFI'}
|
||||||
|
|
||||||
|
#pins = [11, 4, 3, 14, 12, 0, 1, 2, 5, 7]
|
||||||
|
pins = [11, 4, 3, 14, 12, 0, 1, 2, 5, 7]
|
||||||
|
|
||||||
|
on_state = 0
|
||||||
|
off_state = 1
|
||||||
|
p2p_border = np.array([0.05, 0.065, 0.08, 0.95, 0.115, 0.125, 0.135, 0.185, 0.25, 0.3])
|
||||||
|
amp_border = np.array([0, 0.06, 0.07, 0.075, 0.08, 0.085, 0.09, 0.095, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.20])
|
||||||
|
#amp_decays = np.array([0, -0.15, -0.14, -0.13, -0.12, -0.11, -0.10,-0.09,-0.08,-0.07,-0.06,-0.05,-0.04,-0.03,-0.02,-0.01, -0.009, -0.008, -0.007])
|
||||||
|
amp_decays = np.array([0, -0.07, -0.0675, -0.065, -0.0625, -0.06, -0.05,-0.045,-0.04,-0.035,-0.03,-0.025,-0.02,-0.015,-0.01,-0.008, -0.004, -0.002, -0.001])
|
||||||
|
|
||||||
|
assert(len(amp_border) == len(amp_decays))
|
||||||
|
amp_slice_size = 50000
|
||||||
|
pred_amps = []
|
||||||
|
##############################
|
||||||
|
# Variables
|
||||||
|
##############################
|
||||||
|
|
||||||
|
running_amp = 0
|
||||||
|
|
||||||
|
weak_detected = 0
|
||||||
|
counter = 0
|
||||||
|
ctrs = {0: 0, 1: 0, 2: 0, 3: 0}
|
||||||
|
avg_probs = {0: 0., 1: 0., 2: 0., 3: 0.}
|
||||||
|
avg_amps = {0: 0., 1: 0., 2: 0., 3: 0.}
|
||||||
|
max_amp = 0
|
||||||
|
|
||||||
|
max_freq = 0
|
||||||
|
it = 0 # current reading flag
|
||||||
|
f = f_base # local frequency
|
||||||
|
EOCF = 0 # End of changing frequency flag
|
||||||
|
signal_arr = []
|
||||||
|
|
||||||
|
weak_avg_ctr = 0
|
||||||
|
weak_ctr = 0
|
||||||
|
avg_confidence = 0
|
||||||
|
strong_confidence_threshold = 0.6
|
||||||
|
weak_confidence_threshold = 0.85
|
||||||
|
current_pin = 0
|
||||||
|
|
||||||
|
vals = []
|
||||||
|
############################### support functions
|
||||||
|
##############################
|
||||||
|
|
||||||
|
def calc_running_amp(sig):
|
||||||
|
global amp_slice_size
|
||||||
|
running_amp = np.average(np.sort(np.abs(sig).flatten())[::-1][:amp_slice_size])
|
||||||
|
#print(running_amp)
|
||||||
|
return running_amp
|
||||||
|
|
||||||
|
def softmax(x):
|
||||||
|
"""Compute softmax values for each sets of scores in x."""
|
||||||
|
e_x = np.exp(x - np.max(x))
|
||||||
|
return e_x / e_x.sum()
|
||||||
|
|
||||||
|
|
||||||
|
def compute_signal_distance(signal: np.array) -> float:
|
||||||
|
"""
|
||||||
|
Computes a peak to peak distanse of the input signal.
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
signal, np.array - an array of complex points of the input signal
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
sig_dist, float - peak to peak amplitude signal distance
|
||||||
|
"""
|
||||||
|
# sig_dist = np.max(np.abs(signal)) - np.min(np.abs(signal))
|
||||||
|
sig_dist = np.abs(np.max(signal) - np.min(signal))
|
||||||
|
return sig_dist
|
||||||
|
|
||||||
|
|
||||||
|
def send_data(sig_dist):
|
||||||
|
len_threshold = int(os.getenv('len_threshold'))
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
length = int(np.sum(np.where(p2p_border <= sig_dist, 1, 0)))
|
||||||
|
|
||||||
|
if length >= len_threshold:
|
||||||
|
trigger = True
|
||||||
|
else:
|
||||||
|
trigger = False
|
||||||
|
|
||||||
|
data_to_send = {
|
||||||
|
"freq": '2400',
|
||||||
|
"amplitude": length
|
||||||
|
# "triggered": trigger,
|
||||||
|
# "light_len": length
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post("http://{0}:{1}/send-freq/".format(localhost, localport), json=data_to_send)
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
print("Данные успешно отправлены и приняты!")
|
||||||
|
else:
|
||||||
|
print("Ошибка при отправке данных: ", response.status_code)
|
||||||
|
|
||||||
|
|
||||||
|
##############################
|
||||||
|
# main function
|
||||||
|
##############################
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
global f_base
|
||||||
|
global f_step
|
||||||
|
global f_roof
|
||||||
|
|
||||||
|
global signal_tag
|
||||||
|
|
||||||
|
global reading_signal_delay
|
||||||
|
global iterations
|
||||||
|
|
||||||
|
global max_amp
|
||||||
|
global max_freq
|
||||||
|
global it
|
||||||
|
|
||||||
|
global f
|
||||||
|
|
||||||
|
global EOCF
|
||||||
|
global strong_model
|
||||||
|
global weak_model
|
||||||
|
|
||||||
|
global weak_ctr
|
||||||
|
global weak_avg_ctr
|
||||||
|
global avg_confidence
|
||||||
|
global strong_confidence_threshold
|
||||||
|
global weak_confidence_threshold
|
||||||
|
global weak_samples_confidence
|
||||||
|
global height_threshold
|
||||||
|
global signal_arr
|
||||||
|
global ctrs
|
||||||
|
global avg_probs
|
||||||
|
global avg_amps
|
||||||
|
global amp_border
|
||||||
|
global amp_decays
|
||||||
|
global classes
|
||||||
|
global pred_amps
|
||||||
|
global weak_detected
|
||||||
|
global vals
|
||||||
|
outputs = []
|
||||||
|
|
||||||
|
|
||||||
|
y = np.array(lvl).ravel()
|
||||||
|
signal_arr = np.concatenate((signal_arr, y), axis=None)
|
||||||
|
|
||||||
|
if f <= f_roof:
|
||||||
|
f = f_base
|
||||||
|
signal_arr = []
|
||||||
|
send_data(np.max(np.array(vals)))
|
||||||
|
vals = []
|
||||||
|
return f, EOCF
|
||||||
|
else:
|
||||||
|
label = None
|
||||||
|
if len(signal_arr) >= RK3588_MODEL['split_size']: # the signal length `soft` constraint
|
||||||
|
|
||||||
|
sig = np.array([signal_arr.real[0:RK3588_MODEL['split_size']], signal_arr.imag[0:RK3588_MODEL['split_size']]], dtype=np.float32)
|
||||||
|
running_amp = calc_running_amp(sig)
|
||||||
|
# feeds the input signal into weak classifier
|
||||||
|
outputs = RK3588_MODEL['model'].inference(inputs=[sig])
|
||||||
|
signal_arr = []
|
||||||
|
|
||||||
|
label = np.argmax(outputs, axis=2)[0][0]
|
||||||
|
probability = softmax(outputs[0][0])[label]
|
||||||
|
|
||||||
|
#print(classes[label], round(probability, 2), int(f))
|
||||||
|
|
||||||
|
weak_ctr += 1
|
||||||
|
if (label != 0) and (label != 3) and probability > weak_confidence_threshold:
|
||||||
|
weak_avg_ctr += 1
|
||||||
|
ctrs[label] += 1
|
||||||
|
avg_probs[label] += probability
|
||||||
|
avg_amps[label] += running_amp
|
||||||
|
if weak_ctr == RK3588_MODEL['N_predictions']:
|
||||||
|
prob = round(softmax(outputs[0][0])[label], 2)
|
||||||
|
#print('Detected: ', classes[label], ' Probability: ' , prob, 'Frequency: ', str(f))
|
||||||
|
print('---------> Frequency: ', f)
|
||||||
|
for key in avg_probs.keys():
|
||||||
|
avg_probs[key] = float(avg_probs[key] / max(1, ctrs[key]))
|
||||||
|
avg_amps[key] = float(avg_amps[key] / max(1, ctrs[key]))
|
||||||
|
|
||||||
|
for key in ctrs.keys():
|
||||||
|
print("avg prob: ", "%.4f" % avg_probs[key],"avg_amp: ", "%.4f" % avg_amps[key],"ctr: ", ctrs[key],"class: ", classes[key])
|
||||||
|
#sfm = softmax(list(avg_probs.values()))
|
||||||
|
#print(sfm)
|
||||||
|
label = np.argmax(list(ctrs.values()))
|
||||||
|
weak_avg_ctr = ctrs[label]
|
||||||
|
weak_avg_prob = avg_probs[label] # / max(1, ctrs[label])
|
||||||
|
weak_avg_amp = avg_amps[label]
|
||||||
|
amp_decay = 0 #amp_decays[min(np.sum(np.where(amp_border <= weak_avg_amp, 1, 0)), len(amp_border) - 1)]
|
||||||
|
final_confidence_threshold = weak_confidence_threshold + amp_decay
|
||||||
|
print('-' * 50, classes[label], weak_avg_ctr,"%.4f" % float(weak_avg_prob), '/', "%.4f" % final_confidence_threshold)
|
||||||
|
#print(classes[label] , ': ', sfm[label])
|
||||||
|
avg_probs = {0: 0., 1: 0., 2: 0., 3: 0.}
|
||||||
|
avg_amps = {0: 0., 1: 0., 2: 0., 3: 0.}
|
||||||
|
ctrs = {0: 0, 1: 0, 2: 0, 3: 0}
|
||||||
|
if weak_avg_ctr >= RK3588_MODEL['N_predictions'] * RK3588_MODEL['N_samples_confidence_threshold'] and label != 0 and weak_avg_prob > final_confidence_threshold:
|
||||||
|
print('!!!' * 30, f)
|
||||||
|
vals.append(weak_avg_amp)
|
||||||
|
else:
|
||||||
|
vals.append(0)
|
||||||
|
f += f_step
|
||||||
|
|
||||||
|
weak_ctr = 0
|
||||||
|
weak_avg_ctr = 0
|
||||||
|
return f, EOCF
|
||||||
@ -0,0 +1,109 @@
|
|||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
from smb.SMBConnection import SMBConnection
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from DroneScanner.utils.datas_processing import pack_elems, agregator, send_data, save_data, remote_save_data
|
||||||
|
from DroneScanner.core.sig_n_medi_collect import Signal, SignalsArray, get_signal_length
|
||||||
|
from DroneScanner.core.multichannelswitcher import MultiChannel, get_centre_freq
|
||||||
|
|
||||||
|
dotenv_path = os.path.join(os.path.dirname(__file__), '../../.env')
|
||||||
|
if os.path.exists(dotenv_path):
|
||||||
|
load_dotenv(dotenv_path)
|
||||||
|
|
||||||
|
debug_flag = bool(os.getenv('debug_flag'))
|
||||||
|
send_to_module_flag = bool(os.getenv('send_to_module_flag'))
|
||||||
|
save_data_flag = bool(os.getenv('save_data_flag'))
|
||||||
|
module_name = os.getenv('module_name')
|
||||||
|
elems_to_save = os.getenv('elems_to_save')
|
||||||
|
file_types_to_save = os.getenv('file_types_to_save')
|
||||||
|
localhost = os.getenv('lochost')
|
||||||
|
localport = os.getenv('locport')
|
||||||
|
f_step = [*map(float, os.getenv('f_step_915').split())]
|
||||||
|
f_bases = [*map(float, os.getenv('f_bases_915').split())]
|
||||||
|
f_roofs = [*map(float, os.getenv('f_roofs_915').split())]
|
||||||
|
path_to_save_medians = os.getenv('path_to_save_medians')
|
||||||
|
path_to_save_alarms = os.getenv('path_to_save_alarms')
|
||||||
|
smb_host = os.getenv('smb_host')
|
||||||
|
smb_port = os.getenv('smb_port')
|
||||||
|
smb_user = os.getenv('smb_user')
|
||||||
|
smb_pass = os.getenv('smb_pass')
|
||||||
|
shared_folder = os.getenv('shared_folder')
|
||||||
|
the_pc_name = os.getenv('the_pc_name')
|
||||||
|
remote_pc_name = os.getenv('remote_pc_name')
|
||||||
|
smb_domain = os.getenv('smb_domain')
|
||||||
|
|
||||||
|
elems_to_save = elems_to_save.split(',')
|
||||||
|
file_types_to_save = file_types_to_save.split(',')
|
||||||
|
|
||||||
|
tmp_signal = Signal()
|
||||||
|
tmp_sigs_array = SignalsArray()
|
||||||
|
multi_channel = MultiChannel(f_step, f_bases, f_roofs)
|
||||||
|
f = multi_channel.init_f()
|
||||||
|
multi_channel.fill_DB()
|
||||||
|
|
||||||
|
if debug_flag:
|
||||||
|
conn = SMBConnection(smb_user, smb_pass, the_pc_name, remote_pc_name, use_ntlm_v2=True)
|
||||||
|
conn.connect(smb_host, 139)
|
||||||
|
filelist = conn.listPath(shared_folder, '/')
|
||||||
|
print(filelist)
|
||||||
|
|
||||||
|
|
||||||
|
def work(lvl):
|
||||||
|
|
||||||
|
f = multi_channel.get_cur_channel()
|
||||||
|
freq = get_centre_freq(f)
|
||||||
|
signal_length = get_signal_length(freq)
|
||||||
|
median, signal, abs_signal = tmp_signal.fill_sig(lvl, signal_length)
|
||||||
|
|
||||||
|
if median != -1:
|
||||||
|
try:
|
||||||
|
num_chs, circle_buffer = multi_channel.check_f(f)
|
||||||
|
|
||||||
|
#print(f, freq, num_chs)
|
||||||
|
#print(median)
|
||||||
|
|
||||||
|
cur_channel, sigs_array = tmp_sigs_array.fill_sig_arr(median, num_chs)
|
||||||
|
|
||||||
|
if sigs_array:
|
||||||
|
print('Значения на {0}: {1}'.format(freq, sigs_array))
|
||||||
|
print('Пороги: ', circle_buffer.get_medians())
|
||||||
|
alarm = circle_buffer.check_alarm(sigs_array)
|
||||||
|
|
||||||
|
if alarm:
|
||||||
|
print('----ALARM---- ', freq)
|
||||||
|
multi_channel.db_alarms_zeros(circle_buffer)
|
||||||
|
else:
|
||||||
|
circle_buffer.update(sigs_array)
|
||||||
|
|
||||||
|
if send_to_module_flag:
|
||||||
|
send_data(agregator(freq, alarm), localhost, localport)
|
||||||
|
|
||||||
|
if save_data_flag:
|
||||||
|
if not circle_buffer.check_init() and circle_buffer.current_column - 1 == 0:
|
||||||
|
save_data(path_to_save_medians, freq, 'DateTime', 'ALARM', 'max signal', list(range(num_chs)),
|
||||||
|
list(range(num_chs)))
|
||||||
|
if circle_buffer.check_init():
|
||||||
|
save_data(path_to_save_medians, freq, datetime.datetime.now(), alarm, max(sigs_array), sigs_array,
|
||||||
|
circle_buffer.get_medians())
|
||||||
|
# print(circle_buffer.get_buffer())
|
||||||
|
# print(circle_buffer.get_medians())
|
||||||
|
# print(circle_buffer.get_alarms())
|
||||||
|
if debug_flag:
|
||||||
|
single_alarm = circle_buffer.check_single_alarm(median, cur_channel)
|
||||||
|
print(cur_channel, single_alarm)
|
||||||
|
if single_alarm:
|
||||||
|
data = pack_elems(elems_to_save, file_types_to_save, signal, abs_signal)
|
||||||
|
print('SAVE CURRENT SIGNAL SROCHNO TI MENYA SLISHISH?!?!?!?')
|
||||||
|
try:
|
||||||
|
remote_save_data(conn, data, module_name, freq, shared_folder, path_to_save_alarms)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка: {e}")
|
||||||
|
else:
|
||||||
|
print('VSE OKI DOKI SIGNAL SOKHRANYAT NE NUZHNO!!!')
|
||||||
|
|
||||||
|
f = multi_channel.change_channel()
|
||||||
|
except Exception as e:
|
||||||
|
print(str(e))
|
||||||
|
print(".", end='')
|
||||||
|
|
||||||
|
return f
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue