Skip to content

Commit

Permalink
Added info about variables type, return type. Make signle code style …
Browse files Browse the repository at this point in the history
…for everything. zero sum commit. QMessage box bug fix
  • Loading branch information
raik199x committed Apr 13, 2024
1 parent 4cb562e commit a7a2831
Show file tree
Hide file tree
Showing 27 changed files with 283 additions and 282 deletions.
4 changes: 2 additions & 2 deletions CloudStorages/abstract_cloud_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ def __init__(self):
self.cloud_storage_name = str()

# Flags (only one of 2 must be set to true in child class)
self.isAuthViaToken = False
self.isAuthViaCredentials = False
self.is_auth_via_token = False
self.is_auth_via_credentials = False

def checkDataFolderExistence(self) -> bool:
raise NotImplementedError("checkProjectFolderExistence is not implemented for current class")
Expand Down
14 changes: 8 additions & 6 deletions CloudStorages/cloud_storage_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(self):

def checkAuthFields(self, cloud_class, email: str, password: str, token: str) -> str:
return_result = str()
if cloud_class.isAuthViaCredentials:
if cloud_class.is_auth_via_credentials:
return_result = return_result + "Empty email field\n" if len(email) == 0 else ""
return_result = return_result + "Empty password field\n" if len(password) == 0 else ""
return_result = (
Expand All @@ -27,7 +27,7 @@ def checkAuthFields(self, cloud_class, email: str, password: str, token: str) ->
else ""
)
return_result = return_result + "Ambiguous email format, no @ symbol\n" if email.find("@") == -1 else ""
if cloud_class.isAuthViaToken:
if cloud_class.is_auth_via_token:
return_result = return_result + "Empty token\n" if len(token) == 0 else ""

if len(return_result) == 0:
Expand All @@ -43,9 +43,9 @@ def tryLogin(self, cloud_class, email: str, password: str, token: str) -> str:
signal.alarm(self.timeout_duration)

try:
if cloud_class.isAuthViaCredentials:
if cloud_class.is_auth_via_credentials:
result = cloud_class.loginViaCredentials(email, password)
elif cloud_class.isAuthViaToken:
elif cloud_class.is_auth_via_token:
result = cloud_class.loginViaToken(token)
except TimeoutError:
return self.function_timeout_code
Expand All @@ -55,13 +55,15 @@ def tryLogin(self, cloud_class, email: str, password: str, token: str) -> str:
return result

def getAuthFields(self, cloud_class, email: str, password: str, token: str) -> dict:
if cloud_class.isAuthViaCredentials:
if cloud_class.is_auth_via_credentials:
return {"email": email, "password": password}
if cloud_class.isAuthViaToken:
if cloud_class.is_auth_via_token:
return {"token": token}
return self.fail_code

def getStorageInstance(self, cloud_provider: str):
if cloud_provider == self.mega_cloud_name:
return MegaCloud()
return self.unknown_code


2 changes: 1 addition & 1 deletion CloudStorages/mega.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def __init__(self):
self.deleted_file_name = "trashed.zip"

# Setting up vars
self.isAuthViaCredentials = True
self.is_auth_via_credentials = True
self.cloud_storage_name = "Mega"

def loginViaToken(self, token) -> str:
Expand Down
40 changes: 20 additions & 20 deletions DeepLearning/dataset_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def __init__(self, value: list, emotion: str, expected: list):
class DatasetParser:
def __init__(self, path_to_dataset_folder: str):
self.dataset_path = path_to_dataset_folder
self.isParserLoaded = False
self.is_parser_loaded = False

# Dataset constants
self.angry = "angry"
Expand All @@ -37,8 +37,8 @@ def __init__(self, path_to_dataset_folder: str):
} # fmt: skip

# Dataset info
self.forTesting = "test/"
self.forLearning = "train/"
self.for_testing = "test/"
self.for_learning = "train/"

# Interactions options
self.shuffled = "Shuffled full dataset (default strategy)"
Expand All @@ -50,24 +50,24 @@ def __init__(self, path_to_dataset_folder: str):
self.learning_set_dict = dict()
self.testing_set_dict = dict()

def GetAmountOfFilesInFolder(self, path: str) -> int:
def getAmountOfFilesInFolder(self, path: str) -> int:
return len(os.listdir(path))

def ReloadEmotion(self, forWhat: str, emotion_type: str) -> None:
full_path = os.path.join(self.dataset_path, forWhat, emotion_type)
def reloadEmotion(self, for_what: str, emotion_type: str) -> None:
full_path = os.path.join(self.dataset_path, for_what, emotion_type)
# Reading emotion
current_emotion_list = list() # Preparing list for all images in this emotion
files_in_folder = os.listdir(full_path)
for file in files_in_folder:
image = cv2.imread(os.path.join(full_path, file), cv2.IMREAD_GRAYSCALE)
current_emotion_list.append(image)

if forWhat == self.forLearning:
if for_what == self.for_learning:
self.learning_set_dict[emotion_type] = current_emotion_list
elif forWhat == self.forTesting:
elif for_what == self.for_testing:
self.testing_set_dict[emotion_type] = current_emotion_list

def ParseFolderWithEmotions(self, folder_with_emotions: str) -> dict():
def parseFolderWithEmotions(self, folder_with_emotions: str) -> dict():
"""Parses a folder of emotions and returns a dictionary of emotions to lists of images.
This function iterates over every emotion in the folder, checks if the emotion exists, and if so,
Expand Down Expand Up @@ -95,7 +95,7 @@ def ParseFolderWithEmotions(self, folder_with_emotions: str) -> dict():
emotions_dict[emotion] = current_emotion_list # saving list to dict
return emotions_dict

def LoadDatasetIntoRam(self) -> int:
def loadDatasetIntoRam(self) -> int:
"""Loads the dataset into RAM.
This function checks if the dataset folder exists and is a directory.
Expand All @@ -113,32 +113,32 @@ def LoadDatasetIntoRam(self) -> int:
return -1

# Loading learning set
path_to_learning = os.path.join(self.dataset_path, self.forLearning)
path_to_learning = os.path.join(self.dataset_path, self.for_learning)
if os.path.exists(path_to_learning) and os.path.isdir(path_to_learning):
self.learning_set_dict = self.ParseFolderWithEmotions(path_to_learning)
self.learning_set_dict = self.parseFolderWithEmotions(path_to_learning)

# Loading testing set
path_to_testing = os.path.join(self.dataset_path, self.forTesting)
path_to_testing = os.path.join(self.dataset_path, self.for_testing)
if os.path.exists(path_to_testing) and os.path.isdir(path_to_testing):
self.testing_set_dict = self.ParseFolderWithEmotions(path_to_testing)
self.testing_set_dict = self.parseFolderWithEmotions(path_to_testing)

self.isParserLoaded = True
self.is_parser_loaded = True
return 0

def getDatasetData(self, forWhat: str, needToShuffle: bool) -> DatasetData:
if not self.isParserLoaded:
def getDatasetData(self, for_what: str, need_to_shuffle: bool) -> DatasetData:
if not self.is_parser_loaded:
return None
if forWhat != self.forLearning and forWhat != self.forTesting:
if for_what != self.for_learning and for_what != self.for_testing:
return None

target_dict = self.learning_set_dict if forWhat == self.forLearning else self.testing_set_dict
target_dict = self.learning_set_dict if for_what == self.for_learning else self.testing_set_dict
result_list = list()

for emotion in self.emotion_list:
for data in target_dict[emotion]:
result_list.append(DatasetData(data, emotion, self.emotion_expected_dict[emotion]))

if needToShuffle:
if need_to_shuffle:
random.shuffle(result_list)

return result_list
14 changes: 7 additions & 7 deletions DeepLearning/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ def __init__(self):
)

self.loss_fn = torch.nn.CrossEntropyLoss() # Multi class classification, includes nn.LogSoftmax and nn.NLLLoss
self.optimizer = self.CreateOptimizer()
self.optimizer = self.createOptimizer()

def CreateOptimizer(self): # To stop messing optimizers after load and creation
def createOptimizer(self): # To stop messing optimizers after load and creation
# return torch.optim.Adam(self.parameters(), lr=learning_rate) # Most effective Adam and SGD
return torch.optim.SGD(self.parameters(), lr=learning_rate)

def TrainEpoch(self, tensor: torch.tensor, expected_tensor: torch.tensor) -> torch.Tensor:
def trainEpoch(self, tensor: torch.tensor, expected_tensor: torch.tensor) -> torch.Tensor:
self.train()

# 1. Forward pass
Expand All @@ -66,7 +66,7 @@ def TrainEpoch(self, tensor: torch.tensor, expected_tensor: torch.tensor) -> tor

return classification_result

def TestingEpoch(self, tensor: torch.tensor, expected_tensor: torch.tensor) -> dict[str:int, str:int]:
def testingEpoch(self, tensor: torch.tensor, expected_tensor: torch.tensor) -> dict[str:int, str:int]:
self.eval()
with torch.inference_mode():
classification_result = self(tensor)
Expand All @@ -78,15 +78,15 @@ def TestingEpoch(self, tensor: torch.tensor, expected_tensor: torch.tensor) -> d
"IsPredictedRight": torch.argmax(classification_result) == torch.argmax(expected_tensor),
}

def BackupModel(self, folder_path: str, file_name: str) -> None:
def backupModel(self, folder_path: str, file_name: str) -> None:
MODEL_PATH = Path(folder_path)
MODEL_PATH.mkdir(parents=True, exist_ok=True)
torch.save(self.state_dict(), os.path.join(folder_path, file_name))

def LoadModel(self, path_to_model: str) -> None:
def loadModel(self, path_to_model: str) -> None:
self.load_state_dict(torch.load(path_to_model, map_location=torch.device(pytorch_device)))
self.eval()
self.optimizer = self.CreateOptimizer() # optimizer must be recreated after load
self.optimizer = self.createOptimizer() # optimizer must be recreated after load

def accuracy(self, expected_result: torch.Tensor, model_result: torch.Tensor) -> int:
correct = torch.eq(expected_result, model_result).sum().item()
Expand Down
8 changes: 4 additions & 4 deletions ImageProcessing/face_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ def __init__(self, pretrained_face_detector_path: str, image_improvement_level:
self.detector = dlib.cnn_face_detection_model_v1(pretrained_face_detector_path)
self.image_improvement_level = image_improvement_level

def DetectFaces(self, image: np.array) -> dlib.mmod_rectangles:
def detectFaces(self, image: np.array) -> dlib.mmod_rectangles:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return self.detector(gray, self.image_improvement_level)

def ConvertDlibToList(
def convertDlibToList(
self, face: dlib.mmod_rectangle, original_image: np.array
) -> list[tuple[int, int], tuple[int, int]]:
# extract the starting and ending (x, y)-coordinates of the
Expand All @@ -34,7 +34,7 @@ def ConvertDlibToList(
face_coordinates.append((endX, endY))
return face_coordinates

def DrawFaceBox(self, image: np.array, face: list[tuple[int, int], tuple[int, int]]) -> np.array:
def drawFaceBox(self, image: np.array, face: list[tuple[int, int], tuple[int, int]]) -> np.array:
if len(face) != 2:
print("face coordinates is messed up") #! use logging system
return None
Expand All @@ -47,7 +47,7 @@ def DrawFaceBox(self, image: np.array, face: list[tuple[int, int], tuple[int, in
)
return result_image

def CropFaceBox(self, image: np.array, face: list[tuple[int, int], tuple[int, int]]) -> np.array:
def cropFaceBox(self, image: np.array, face: list[tuple[int, int], tuple[int, int]]) -> np.array:
if len(face) != 2:
print("face coordinates is messed up") #! use logging system
return None
Expand Down
10 changes: 5 additions & 5 deletions camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,20 @@ def listPorts(self) -> list:
index += 1
return camera_indexes

def readImage(self, path_to_image) -> np.array:
def readImage(self, path_to_image: str) -> np.array:
return cv2.imread(path_to_image)

def resizeImage(self, image: np.array, new_size: tuple[int, int]) -> np.array:
return cv2.resize(image, new_size)

def getImageRGB(self, image):
def getImageRGB(self, image: np.array) -> np.array:
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

def putText(
self,
image,
text,
position,
image: np.array,
text: str,
position: int,
font=default_text_font,
font_scale=default_text_font_scale,
color=default_text_color,
Expand Down
12 changes: 6 additions & 6 deletions config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ def __init__(self):
self.poe_lat_cookie = "lat_cookie"
self.poe_chat_id = "chatId"

def saveConfig(self):
def saveConfig(self) -> None:
with open(self.config_name, "w") as config_file:
self.config.write(config_file)

def deletePoeCredentials(self):
def deletePoeCredentials(self) -> None:
self.config.remove_section(self.poe_index)
self.saveConfig()

Expand All @@ -40,7 +40,7 @@ def removeFieldFromSection(self, section: str, field: str):
self.config.remove_option(section, field)
self.saveConfig()

def isEntryExist(self, section_name) -> bool:
def isEntryExist(self, section_name: str) -> bool:
isExist = True
try:
self.config[section_name]
Expand All @@ -59,7 +59,7 @@ def addPoeAccount(self, token_dict: dict) -> None:
self.config[self.poe_index] = token_dict
self.saveConfig()

def setPoeChatId(self, chatId: str or int):
def setPoeChatId(self, chatId: str or int) -> None:
self.config[self.poe_index][self.poe_chat_id] = str(chatId)
self.saveConfig()

Expand Down Expand Up @@ -101,11 +101,11 @@ def getStorageEntrees(self) -> list[list]:
if cloud_instance == cloud_interface.unknown_code:
continue

if cloud_instance.isAuthViaCredentials:
if cloud_instance.is_auth_via_credentials:
result = cloud_instance.loginViaCredentials(
self.config[each_section]["email"], self.config[each_section]["password"]
)
elif cloud_instance.isAuthViaToken:
elif cloud_instance.is_auth_via_token:
result = cloud_instance.loginViaToken(each_section["token"])

if result == cloud_instance.success_code:
Expand Down
16 changes: 8 additions & 8 deletions connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@

class Connector:
def __init__(self):
self.Parser = DatasetParser("stub") # Empty parser
self.parser = DatasetParser("stub") # Empty parser

def IsGrayscale(self, image: np.array) -> bool:
def isGrayscale(self, image: np.array) -> bool:
# Check the number of channels in the image
return image.ndim == 2 or (image.ndim == 3 and image.shape[2] == 1)

def ImageIntoTensor(self, original_image: np.array) -> torch.tensor:
def imageIntoTensor(self, original_image: np.array) -> torch.tensor:
# Checking if image is already gray
image = original_image.copy()
if not self.IsGrayscale(image):
if not self.isGrayscale(image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Now checking if image is suitable size
Expand All @@ -28,13 +28,13 @@ def ImageIntoTensor(self, original_image: np.array) -> torch.tensor:
# Converting to tensor
return torch.from_numpy(image).to(torch.float32).to(pytorch_device)

def ClassificationResultIntoEmotion(self, class_result: torch.tensor) -> str:
def classificationResultIntoEmotion(self, class_result: torch.tensor) -> str:
result_index = torch.argmax(class_result)
for emotion in self.Parser.emotion_list:
expect = self.Parser.emotion_expected_dict[emotion]
for emotion in self.parser.emotion_list:
expect = self.parser.emotion_expected_dict[emotion]
if expect.index(max(expect)) == result_index:
return emotion
raise IndexError("Tensor list is bigger than expected list, so could not find emotion")

def expectListIntoTensor(self, expect_list) -> torch.tensor:
def expectListIntoTensor(self, expect_list: list) -> torch.tensor:
return torch.from_numpy(np.array(expect_list)).to(torch.float32).to(pytorch_device)
Loading

0 comments on commit a7a2831

Please sign in to comment.