Skip to content

Commit

Permalink
Merge pull request #964 from DLR-RM/pylint_fixes
Browse files Browse the repository at this point in the history
Some pylint fixes
  • Loading branch information
cornerfarmer authored Aug 22, 2023
2 parents 3c2cc1f + c01949a commit 5bc7468
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 119 deletions.
5 changes: 2 additions & 3 deletions blenderproc/command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def cli():
elif args.mode in ["run", "debug", "quickstart"]:

# Install blender, if not already done
determine_result = InstallUtility.determine_blender_install_path(args, unknown_args)
determine_result = InstallUtility.determine_blender_install_path(args)
custom_blender_path, blender_install_path = determine_result
blender_run_path, major_version = InstallUtility.make_sure_blender_is_installed(custom_blender_path,
blender_install_path,
Expand Down Expand Up @@ -233,8 +233,7 @@ def handle_sigterm(_signum, _frame):
current_cli()
elif args.mode == "pip":
# Install blender, if not already done
custom_blender_path, blender_install_path = InstallUtility.determine_blender_install_path(args,
unknown_args)
custom_blender_path, blender_install_path = InstallUtility.determine_blender_install_path(args)
blender_bin, major_version = InstallUtility.make_sure_blender_is_installed(custom_blender_path,
blender_install_path)
blender_path = os.path.dirname(blender_bin)
Expand Down
1 change: 0 additions & 1 deletion blenderproc/debug_startup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
""" This script allows the use of the debug mode in BlenderProc. """

import sys
from pathlib import Path
import os

import bpy
Expand Down
2 changes: 1 addition & 1 deletion blenderproc/python/loader/BopLoader.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def load_bop_objs(bop_dataset_path: str, model_type: str = "", obj_ids: Optional
f"Supported are 'm', 'dm', 'cm', 'mm'")
scale = {'m': 1., 'dm': 0.1, 'cm': 0.01, 'mm': 0.001}[object_model_unit]
if mm2m is not None:
warnings.warn(f"WARNING: `mm2m` is deprecated, please use `object_model_unit='mm'` instead!")
warnings.warn("WARNING: `mm2m` is deprecated, please use `object_model_unit='mm'` instead!")
scale = 0.001

if obj_ids is None:
Expand Down
17 changes: 10 additions & 7 deletions blenderproc/python/loader/HavenEnvironmentLoader.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,27 @@
import glob
import os
import random
from typing import Union

import numpy as np
from mathutils import Euler
from typing import Union

import bpy

from blenderproc.python.utility.Utility import Utility


def set_world_background_hdr_img(path_to_hdr_file: str, strength: float = 1.0,
rotation_euler: Union[list, Euler, np.ndarray] = [0.0, 0.0, 0.0]):
def set_world_background_hdr_img(path_to_hdr_file: str, strength: float = 1.0,
rotation_euler: Union[list, Euler, np.ndarray] = None):
"""
Sets the world background to the given hdr_file.
:param path_to_hdr_file: Path to the .hdr file
:param strength: The brightness of the background.
:param rotation_euler: The euler angles of the background.
"""
if rotation_euler is None:
rotation_euler = [0.0, 0.0, 0.0]

if not os.path.exists(path_to_hdr_file):
raise FileNotFoundError(f"The given path does not exists: {path_to_hdr_file}")
Expand All @@ -41,17 +44,17 @@ def set_world_background_hdr_img(path_to_hdr_file: str, strength: float = 1.0,

# Set the brightness of the background
background_node.inputs["Strength"].default_value = strength

# add a mapping node and a texture coordinate node
mapping_node = nodes.new("ShaderNodeMapping")
mapping_node = nodes.new("ShaderNodeMapping")
tex_coords_node = nodes.new("ShaderNodeTexCoord")

#link the texture coordinate node to mapping node
links.new(tex_coords_node.outputs["Generated"], mapping_node.inputs["Vector"])

#link the mapping node to the texture node
links.new(mapping_node.outputs["Vector"], texture_node.inputs["Vector"])

mapping_node.inputs["Rotation"].default_value = rotation_euler

def get_random_world_background_hdr_img_path_from_haven(data_path: str) -> str:
Expand Down
30 changes: 15 additions & 15 deletions blenderproc/python/utility/GlobalStorage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
""" This module provides functions to store global data. """

from typing import Any, Dict, Optional


class GlobalStorage(object):
class GlobalStorage:
"""
The GlobalStorage has two functions:
1. It can store data over the boundaries of modules with the add(), set() and get() functions
Expand All @@ -10,7 +12,8 @@ class GlobalStorage(object):
To 1. you can save your own keys in the GlobalStorage to access them in a later module.
For example you have a personal renderer or loader, which has attributes, which are independent of the scene and
the objects so custom properties for those are not the way to go. In these instances you can use these functions.
the objects so custom properties for those are not the way to go. In these instances you can use these
functions.
Here is a list of all used global_storage_keys to avoid that your key is clashing with existing keys:
Expand Down Expand Up @@ -60,8 +63,8 @@ def init_global(global_config: "Config"):
if not GlobalStorage._global_config.has_param(key):
GlobalStorage._global_config.data[key] = value
else:
raise RuntimeError("This key was already found in the global config: {} it is also used internally, "
"please use another key!".format(key))
raise RuntimeError(f"This key was already found in the global config: {key} it is "
"also used internally, please use another key!")

@staticmethod
def add_to_config_before_init(key: str, value: Any):
Expand All @@ -76,8 +79,8 @@ def add_to_config_before_init(key: str, value: Any):
if key not in GlobalStorage._add_to_global_config_at_init:
GlobalStorage._add_to_global_config_at_init[key] = value
else:
raise RuntimeError("This key: {} was added before to the list of "
"add_to_global_config_at_init!".format(key))
raise RuntimeError(f"This key: {key} was added before to the list of "
"add_to_global_config_at_init!")
else:
raise RuntimeError("This fct. should only be called before the GlobalStorage was inited!")

Expand All @@ -95,11 +98,11 @@ def add(key: str, value: Any):
:param key: which is added to the GlobalStorage
:param value: which can be accessed by this key over the get() fct.
"""
if key not in GlobalStorage._storage_dict.keys():
if key not in GlobalStorage._storage_dict:
GlobalStorage._storage_dict[key] = value
else:
raise RuntimeError("The key: {} was already set before with this value: {}".format(key,
GlobalStorage._storage_dict[key]))
raise RuntimeError(f"The key: {key} was already set before with "
f"this value: {GlobalStorage._storage_dict[key]}")

@staticmethod
def set(key: str, value: Any):
Expand Down Expand Up @@ -127,8 +130,7 @@ def get(key: str) -> Any:
"""
if key in GlobalStorage._storage_dict:
return GlobalStorage._storage_dict[key]
else:
raise RuntimeError("The key: {} is not in the global storage!".format(key))
raise RuntimeError(f"The key: {key} is not in the global storage!")

@staticmethod
def is_in_storage(key: str) -> bool:
Expand All @@ -150,8 +152,7 @@ def has_param(key: str) -> bool:
"""
if GlobalStorage._global_config is not None:
return GlobalStorage._global_config.has_param(key)
else:
return False
return False

@staticmethod
def get_global_config() -> "Config":
Expand All @@ -165,5 +166,4 @@ def get_global_config() -> "Config":
"""
if GlobalStorage._global_config is not None:
return GlobalStorage._global_config
else:
raise RuntimeError("The global config was not initialized!")
raise RuntimeError("The global config was not initialized!")
6 changes: 2 additions & 4 deletions blenderproc/python/utility/InstallUtility.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from sys import platform, version_info
import ssl
from platform import machine
from typing import List, Union, Tuple
from typing import Union, Tuple

if version_info.major == 3:
from urllib.request import urlretrieve
Expand All @@ -29,12 +29,10 @@ class InstallUtility:
"""

@staticmethod
def determine_blender_install_path(used_args: "argparse.NameSpace",
user_args: List[str]) -> Union[str, str]:
def determine_blender_install_path(used_args: "argparse.NameSpace") -> Union[str, str]:
""" Determines the path of the blender installation
:param used_args: The given command line arguments.
:param user_args: The arguments that will be forwarded to the users script.
:return:
- The path to an already existing blender installation that should be used, otherwise None
- The path to where blender should be installed.
Expand Down
43 changes: 24 additions & 19 deletions blenderproc/python/utility/MaterialGetter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
""" This module provides functions to filter materials. """

import re

import mathutils
Expand All @@ -7,7 +9,8 @@


class MaterialGetter:

""" Filters materials. """

@staticmethod
def perform_and_condition_check(and_condition, materials, used_materials_to_check=None):
""" Checks for all materials in the scene if all given conditions are true, collects them in the return list.
Expand Down Expand Up @@ -51,25 +54,27 @@ def perform_and_condition_check(and_condition, materials, used_materials_to_chec
new_value = mathutils.Color(value)
# raise an exception if it is none of them
else:
raise Exception("Types are not matching: %s and %s !"
% (type(getattr(material, key)), type(value)))
raise Exception(f"Types are not matching: {type(getattr(material, key))} "
"and {type(value)} !")
# or check for equality
if not ((isinstance(getattr(material, key), str) and re.fullmatch(value, getattr(material, key)) is not None)
if not ((isinstance(getattr(material, key), str) and
re.fullmatch(value, getattr(material, key)) is not None)
or getattr(material, key) == new_value):
select_material = False
break
# check if a custom property with this name exists
elif key in material and requested_custom_property:
# check if the type of the value of such custom property matches desired
if isinstance(material[key], type(value)) or (isinstance(material[key], int) and isinstance(value, bool)):
if isinstance(material[key], type(value)) or (isinstance(material[key], int)
and isinstance(value, bool)):
# if it is a string and if the whole string matches the given pattern
if not ((isinstance(material[key], str) and re.fullmatch(value, material[key]) is not None) or
material[key] == value):
select_material = False
break
else:
# raise an exception if not
raise Exception("Types are not matching: {} and {} !".format(type(material[key]), type(value)))
raise Exception(f"Types are not matching: {type(material[key])} and {type(value)} !")
elif requested_custom_function:
if key.startswith("texture_amount_"):
if material.use_nodes:
Expand All @@ -78,19 +83,19 @@ def perform_and_condition_check(and_condition, materials, used_materials_to_chec
texture_nodes = Utility.get_nodes_with_type(nodes, "TexImage")
amount_of_texture_nodes = len(texture_nodes) if texture_nodes is not None else 0
if "min" in key:
if not (amount_of_texture_nodes >= value):
if not amount_of_texture_nodes >= value:
select_material = False
break
elif "max" in key:
if not (amount_of_texture_nodes <= value):
if not amount_of_texture_nodes <= value:
select_material = False
break
elif "eq" in key:
if not (amount_of_texture_nodes == value):
if not amount_of_texture_nodes == value:
select_material = False
break
else:
raise Exception("This type of key is unknown: {}".format(key))
raise Exception(f"This type of key is unknown: {key}")
else:
select_material = False
break
Expand All @@ -101,19 +106,19 @@ def perform_and_condition_check(and_condition, materials, used_materials_to_chec
principled = Utility.get_nodes_with_type(nodes, "BsdfPrincipled")
amount_of_principled_bsdf_nodes = len(principled) if principled is not None else 0
if "min" in key:
if not (amount_of_principled_bsdf_nodes >= value):
if not amount_of_principled_bsdf_nodes >= value:
select_material = False
break
elif "max" in key:
if not (amount_of_principled_bsdf_nodes <= value):
if not amount_of_principled_bsdf_nodes <= value:
select_material = False
break
elif "eq" in key:
if not (amount_of_principled_bsdf_nodes == value):
if not amount_of_principled_bsdf_nodes == value:
select_material = False
break
else:
raise Exception("This type of key is unknown: {}".format(key))
raise Exception(f"This type of key is unknown: {key}")
else:
select_material = False
break
Expand All @@ -136,7 +141,7 @@ def perform_and_condition_check(and_condition, materials, used_materials_to_chec
# check if this key exists, else throw an error
if extracted_input_name not in principled.inputs:
raise Exception("Only valid inputs of a principled node are allowed: "
"{} in: {}".format(extracted_input_name, key))
f"{extracted_input_name} in: {key}")
# extract this input value
used_value = principled.inputs[extracted_input_name]
# if this input value is not a default value it will be connected via the links
Expand All @@ -147,19 +152,19 @@ def perform_and_condition_check(and_condition, materials, used_materials_to_chec
used_value = used_value.default_value
# compare the given value to the default value
if key.endswith("min"):
if not (used_value >= value):
if not used_value >= value:
select_material = False
break
elif key.endswith("max"):
if not (used_value <= value):
if not used_value <= value:
select_material = False
break
elif key.endswith("eq"):
if not (used_value == value):
if not used_value == value:
select_material = False
break
else:
raise Exception("This type of key is unknown: {}".format(key))
raise Exception(f"This type of key is unknown: {key}")
else:
select_material = False
break
Expand Down
1 change: 0 additions & 1 deletion blenderproc/python/utility/Utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from pathlib import Path
import time
import inspect
import importlib
import json
from contextlib import contextmanager

Expand Down
Loading

0 comments on commit 5bc7468

Please sign in to comment.